From 1239cbeefcb52dc436daa37e3ccee57236581597 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:20:17 +0530 Subject: [PATCH 01/41] fix(presets): recompose surviving skills when a lower preset layer is removed Removing a preset that is the base (or a middle layer) of another preset's prepend/append/wrap composition left the removed preset's content in the active agent's SKILL.md (Claude, Codex, Copilot with --skills, ...), while command-file agents such as Gemini were recomposed onto the new stack. The composed skill is owned by the surviving preset at the top of the chain, so _unregister_skills() restores nothing for the removed preset, and _reconcile_skills() only revisited the active skills directory when that restore had touched it. The recomposed .composed/.md that _reconcile_composed_commands() writes was therefore never rendered into the skill, and `specify preset resolve` disagreed with what the agent ran. After a removal, also reconcile active-directory skills for commands whose winning layer composes, as long as the skill still carries the winning preset's source marker. A hand-edited skill is left alone, matching the existing protection for non-owned skills during removal. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 45 +++++++-- .../presets/test_manager_skills.py | 91 +++++++++++++++++++ 2 files changed, 130 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 5a4a4fb739..f58beef2af 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -151,6 +151,7 @@ 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] = {} non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() @@ -195,6 +196,8 @@ 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": + composed_winners[cmd_name] = pack_id found_preset = True break if not found_preset: @@ -394,16 +397,21 @@ 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 + ) + 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(): @@ -418,6 +426,31 @@ 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): + skill_file = skills_dir / skill_name / "SKILL.md" + if not self._validate_skill_subdir( + skill_file.parent, create=False, skills_root=skills_dir + ) or not skill_file.is_file(): + continue + try: + content = skill_file.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + 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 diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 7ae833bfb9..31387b80bf 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1897,6 +1897,97 @@ 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 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_shared_skills_dir_restored_once_using_active_agent( self, project_dir, temp_dir ): From 8c0328f1132f275351c575e94f6cbeb35dac3485 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 19 Oct 2026 18:53:32 +0530 Subject: [PATCH 02/41] fix(presets): limit removal recomposition to owned skill names When both the modern (speckit-specify) and legacy (speckit.specify) skill directories exist, the active-directory recomposition added for lower-layer removal selected the command because the modern skill kept the winning preset's marker, and _register_skills() then rewrote both directories, overwriting a user-owned legacy skill. Give _register_skills() an optional only_skill_names filter and pass the directory's managed names on removal, so only names that are still preset-owned are written. Install and rescaffold calls pass None and keep writing every existing directory, as before. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 15 ++++++++++- .../presets/test_manager_skills.py | 25 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index f58beef2af..b170f4ecdc 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -365,7 +365,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, @@ -659,6 +664,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. @@ -684,6 +690,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 @@ -769,6 +778,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 31387b80bf..9c89ade670 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1988,6 +1988,31 @@ def test_remove_base_preset_preserves_hand_edited_composed_skill( 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 57bdfc9b9d8cd250c76569d6163af180957591f5 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:48:40 +0530 Subject: [PATCH 03/41] fix(presets): retire a composed skill whose only base was removed When the removed preset was the only replace base of a composing command, with no core or extension fallback, resolution returns None. Command-file agents unregister that command, but the survivor's stale .composed/.md stayed behind, and the removal recomposition rendered it back into the skill, so the removed preset's instructions stayed active. Track composing winners whose stack no longer resolves, delete their stale composed cache, and on removal delete the active skill only while it still carries the winning preset's source marker. Hand-edited skills are kept, matching the existing ownership protection. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 23 ++++++++- .../presets/test_manager_skills.py | 49 +++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index b170f4ecdc..ea4d23720a 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -152,6 +152,9 @@ 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. + unresolved_winners: Dict[str, str] = {} non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() @@ -197,7 +200,15 @@ def _reconcile_skills( if top_path.is_relative_to(pack_dir): preset_cmds.setdefault(pack_id, []).append(cmd_name) if layers[0]["strategy"] != "replace": - composed_winners[cmd_name] = pack_id + 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 + stale = pack_dir / ".composed" / f"{cmd_name}.md" + if stale.is_file() and not stale.is_symlink(): + stale.unlink() + else: + composed_winners[cmd_name] = pack_id found_preset = True break if not found_preset: @@ -411,6 +422,16 @@ def apply_to_dir( 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 + ): + shutil.rmtree(stale_dir) if active_names is None or active_names: apply_to_dir( active_skills_dir, diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 9c89ade670..01601459c1 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1918,6 +1918,55 @@ def _install_composed_specify_stack(self, project_dir, temp_dir, layers): 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 ): From c184e1a5345f388e1a2204873ccd64cf49b1bd20 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 19 Oct 2026 20:28:29 +0530 Subject: [PATCH 04/41] fix(presets): guard, widen and journal stale composed-cache deletion Round-3 review of the no-base removal fix: - Delete a cache only when no path component below the project root is a symlink, so a symlinked .composed directory can't redirect the deletion to a file outside the project. - Drop every surviving preset's .composed/.md for an uncomposable command, not only the winner's: a middle preset's stale cache could be rendered back into the skill by a later rescaffold. - Delete through the journal-aware unlink helper, as the cache writes already do, so a failing integration lifecycle can restore the cache. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 38 +++++++++- .../presets/test_manager_skills.py | 70 ++++++++++++++++++- 2 files changed, 102 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index ea4d23720a..d7a2ec323f 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -204,9 +204,9 @@ def _reconcile_skills( # 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 - stale = pack_dir / ".composed" / f"{cmd_name}.md" - if stale.is_file() and not stale.is_symlink(): - stale.unlink() + self._drop_stale_composed_caches( + cmd_name, presets_by_priority + ) else: composed_winners[cmd_name] = pack_id found_preset = True @@ -452,6 +452,38 @@ def apply_to_dir( return reconciled_skill_commands + def _drop_stale_composed_caches( + self, cmd_name: str, presets_by_priority: List[Any] + ) -> None: + """Delete every preset's ``.composed/.md`` for an uncomposable command. + + With no base left, any preset's cached composition of ``cmd_name`` + still holds the removed layer and could be rendered back by a later + registration. A cache reached through a symlinked ancestor below the + project root is skipped, so nothing outside the project is deleted; + the deletion is journaled like the cache writes. + """ + from ..integrations._file_changes import unlink as _unlink_file + + for pack_id, _meta in presets_by_priority: + stale = self.presets_dir / pack_id / ".composed" / f"{cmd_name}.md" + if not stale.is_file() or not self._has_no_symlink_below_project(stale): + continue + _unlink_file(stale) + + def _has_no_symlink_below_project(self, path: Path) -> bool: + """True if ``path`` is under the project root with no symlinked component.""" + try: + path.relative_to(self.project_root) + except ValueError: + return False + current = path + while current != self.project_root: + if current.is_symlink(): + return False + current = current.parent + return True + def _skills_owned_by_preset( self, skills_dir: Path, owners: Dict[str, str] ) -> Set[str]: diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 01601459c1..86dea134ff 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1918,12 +1918,12 @@ def _install_composed_specify_stack(self, project_dir, temp_dir, layers): 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.""" + def _install_unbacked_custom_stack(self, project_dir, temp_dir, layers=None): + """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 [ + for preset_id, body, strategy, priority in layers or [ ("base-preset", "Base preset body", "replace", 10), ("append-preset", "Appended body", "append", 5), ]: @@ -1967,6 +1967,70 @@ def test_remove_sole_base_preset_keeps_hand_edited_skill( assert skill_file.read_text(encoding="utf-8") == edited + def test_remove_sole_base_preset_keeps_cache_behind_symlinked_dir( + self, project_dir, temp_dir + ): + """A ``.composed`` directory that links outside the project is not + followed when stale caches are deleted.""" + manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) + composed = manager.presets_dir / "append-preset" / ".composed" + external = temp_dir / "external-composed" + shutil.move(str(composed), str(external)) + composed.symlink_to(external, target_is_directory=True) + target = external / "speckit.custom.md" + assert target.is_file() + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert target.is_file() + + def test_remove_sole_base_under_two_composers_survives_rescaffold( + self, project_dir, temp_dir + ): + """Every surviving preset's stale cache is dropped, so a later + rescaffold cannot render the removed base back into the skill.""" + manager, skill_file = self._install_unbacked_custom_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("middle-preset", "Middle body", "append", 7), + ("top-preset", "Top body", "append", 5), + ], + ) + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + manager.register_enabled_presets_for_agent("claude") + + for preset_id in ("middle-preset", "top-preset"): + assert not ( + manager.presets_dir / preset_id / ".composed" / "speckit.custom.md" + ).exists() + assert not skill_file.exists() or "Base preset body" not in skill_file.read_text( + encoding="utf-8" + ) + + def test_stale_cache_deletion_is_journaled(self, project_dir, temp_dir): + """The cache deletion is reported to the lifecycle file-change journal.""" + from specify_cli.integrations._file_changes import file_change_observer + + manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) + cache = manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" + events = [] + token = file_change_observer.set( + lambda path, before, removal: events.append((path, before, removal)) + ) + try: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + finally: + file_change_observer.reset(token) + + assert (cache, True, True) in events + assert not cache.exists() + def test_remove_base_preset_recomposes_surviving_composed_skill( self, project_dir, temp_dir ): From b9a2c359ccac538fef80b8a60e635f39ef60f76d Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 19 Oct 2026 22:52:52 +0530 Subject: [PATCH 05/41] fix(presets): harden no-base cleanup against unsafe keys and read failures Round-4 review of the no-base removal fix: - Skip registry keys (and command names) that are not a single plain path segment, so a malformed key such as "../../../outside" cannot steer cache cleanup outside the project. - Invalidate stale caches for every installed preset, disabled ones included: re-enabling a disabled composer and rescaffolding could otherwise render its stale cache back. - Retire output only when the stack has no replace layer left. resolve_content() also returns None when a surviving layer can't be read; that keeps the existing cache and skill instead of deleting them. - Journal the stale skill-directory removal like the other skill deletions, so a failing lifecycle can restore it. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 53 +++++++++---- .../presets/test_manager_skills.py | 78 ++++++++++++++++++- 2 files changed, 115 insertions(+), 16 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index d7a2ec323f..7c408468db 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -20,6 +20,16 @@ from ._resolver import PresetResolver +def _is_plain_path_segment(name: Any) -> bool: + """True for a single, non-traversing path component.""" + return ( + isinstance(name, str) + and name not in ("", ".", "..") + and "/" not in name + and "\\" not in name + ) + + class _PresetSkillMethods: """Skill artifact methods shared through PresetManager's lifecycle state.""" @@ -200,15 +210,17 @@ def _reconcile_skills( 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: + if resolver.resolve_content(cmd_name, "command") is not None: + composed_winners[cmd_name] = pack_id + elif 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. + # caches so they can't be rendered back into a + # skill. A None from an unreadable layer, with a + # base still present, keeps existing output. unresolved_winners[cmd_name] = pack_id - self._drop_stale_composed_caches( - cmd_name, presets_by_priority - ) - else: - composed_winners[cmd_name] = pack_id + self._drop_stale_composed_caches(cmd_name) found_preset = True break if not found_preset: @@ -431,7 +443,14 @@ def apply_to_dir( if self._validate_skill_subdir( stale_dir, create=False, skills_root=active_skills_dir ): + from ..integrations._file_changes import ( + after_file_change, + before_file_change, + ) + + before_file_change(stale_dir, removal=True) shutil.rmtree(stale_dir) + after_file_change(stale_dir) if active_names is None or active_names: apply_to_dir( active_skills_dir, @@ -452,20 +471,24 @@ def apply_to_dir( return reconciled_skill_commands - def _drop_stale_composed_caches( - self, cmd_name: str, presets_by_priority: List[Any] - ) -> None: - """Delete every preset's ``.composed/.md`` for an uncomposable command. + def _drop_stale_composed_caches(self, cmd_name: str) -> None: + """Delete every installed preset's ``.composed/.md`` for an + uncomposable command, disabled presets included. With no base left, any preset's cached composition of ``cmd_name`` still holds the removed layer and could be rendered back by a later - registration. A cache reached through a symlinked ancestor below the - project root is skipped, so nothing outside the project is deleted; - the deletion is journaled like the cache writes. + registration. A registry key or command name with a path separator or + ``..`` component is skipped, as is a cache reached through a symlinked + ancestor below the project root, so nothing outside the project is + deleted; the deletion is journaled like the cache writes. """ from ..integrations._file_changes import unlink as _unlink_file - for pack_id, _meta in presets_by_priority: + for pack_id in self.registry.list(): + if not _is_plain_path_segment(pack_id) or not _is_plain_path_segment( + f"{cmd_name}.md" + ): + continue stale = self.presets_dir / pack_id / ".composed" / f"{cmd_name}.md" if not stale.is_file() or not self._has_no_symlink_below_project(stale): continue diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 86dea134ff..098d19ce9a 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1937,7 +1937,8 @@ def _install_unbacked_custom_stack(self, project_dir, temp_dir, layers=None): 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") + if layers is None: + 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( @@ -2030,6 +2031,81 @@ def test_stale_cache_deletion_is_journaled(self, project_dir, temp_dir): assert (cache, True, True) in events assert not cache.exists() + skill_dir = project_dir / ".claude" / "skills" / "speckit-custom" + assert (skill_dir, True, True) in events + assert not skill_dir.exists() + + def test_stale_cache_cleanup_ignores_traversing_registry_key( + self, project_dir, temp_dir + ): + """A malformed registry key with ``..`` must not reach outside the project.""" + manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) + outside = (manager.presets_dir / "../../../outside").resolve() + target = outside / ".composed" / "speckit.custom.md" + target.parent.mkdir(parents=True) + target.write_text("external\n", encoding="utf-8") + manager.registry.add("../../../outside", {"version": "1.0.0", "enabled": True, "priority": 20}) + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert target.read_text(encoding="utf-8") == "external\n" + + def test_remove_sole_base_drops_disabled_preset_cache( + self, project_dir, temp_dir + ): + """A disabled composer's stale cache is dropped too, so re-enabling it + and rescaffolding cannot render the removed base back.""" + manager, skill_file = self._install_unbacked_custom_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("middle-preset", "Middle body", "append", 7), + ("top-preset", "Top body", "append", 5), + ], + ) + manager.registry.update("middle-preset", {"enabled": False}) + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + manager.registry.update("middle-preset", {"enabled": True}) + manager.register_enabled_presets_for_agent("claude") + + assert not ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" + ).exists() + assert not skill_file.exists() or "Base preset body" not in skill_file.read_text( + encoding="utf-8" + ) + + def test_unreadable_surviving_base_keeps_composed_output( + self, project_dir, temp_dir + ): + """Resolution also fails when a surviving base can't be decoded; that + must not be treated as a missing base that retires the output.""" + manager, skill_file = self._install_unbacked_custom_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("other-base", "Other base body", "replace", 8), + ("append-preset", "Appended body", "append", 5), + ], + ) + cache = manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" + skill_before = skill_file.read_text(encoding="utf-8") + assert cache.is_file() and "Other base body" in skill_before + manifest = yaml.safe_load( + (manager.presets_dir / "other-base" / "preset.yml").read_text() + ) + command_file = manager.presets_dir / "other-base" / manifest["provides"]["templates"][0]["file"] + command_file.write_bytes(b"---\ndescription: x\n---\n\xff\xfe broken\n") + + manager.remove("base-preset") + + assert cache.is_file() + assert skill_file.read_text(encoding="utf-8") == skill_before def test_remove_base_preset_recomposes_surviving_composed_skill( self, project_dir, temp_dir From b38ba5317d85852f1d61a75fac21fccf0e61f49f Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 19 Oct 2026 23:39:48 +0530 Subject: [PATCH 06/41] fix(presets): reject junctions in cache cleanup, filter historical writes Round-5 review of the removal reconciliation: - Treat Windows reparse points (directory junctions, which Path.is_symlink() misses) like symlinks when checking a stale cache's ancestors, mirroring FileHelper._entry_mode. - Pass the directory's managed names to _register_skills() for historical (inactive) agent directories too, so a user-owned modern/legacy sibling there is not overwritten. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 19 +++++- .../presets/test_manager_skills.py | 64 +++++++++++++++++++ 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 7c408468db..982242453a 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -3,6 +3,7 @@ import copy import os import shutil +import stat from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union @@ -20,6 +21,21 @@ from ._resolver import PresetResolver +def _is_link_or_reparse_point(path: Path) -> bool: + """True for a symlink or a Windows reparse point such as a directory junction. + + ``Path.is_symlink()`` does not report junctions; mirror the check in + ``FileHelper._entry_mode``. + """ + try: + entry = path.lstat() + except OSError: + return False + return stat.S_ISLNK(entry.st_mode) or bool( + getattr(entry, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT + ) + + def _is_plain_path_segment(name: Any) -> bool: """True for a single, non-traversing path component.""" return ( @@ -398,6 +414,7 @@ def apply_to_dir( written = self._register_skills( filtered_manifest, pack_dir, target_dir=skills_dir, target_agent=dir_agent or "", + only_skill_names=managed_names, ) if target_agent is None: written_names = { @@ -502,7 +519,7 @@ def _has_no_symlink_below_project(self, path: Path) -> bool: return False current = path while current != self.project_root: - if current.is_symlink(): + if _is_link_or_reparse_point(current): return False current = current.parent return True diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 098d19ce9a..dd2385b046 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2035,6 +2035,34 @@ def test_stale_cache_deletion_is_journaled(self, project_dir, temp_dir): assert (skill_dir, True, True) in events assert not skill_dir.exists() + def test_stale_cache_cleanup_rejects_junctioned_composed_dir( + self, project_dir, temp_dir, monkeypatch + ): + """A ``.composed`` directory reported as a Windows reparse point (a + junction, which ``is_symlink()`` misses) is not followed.""" + from types import SimpleNamespace + + manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) + composed = manager.presets_dir / "append-preset" / ".composed" + cache = composed / "speckit.custom.md" + lstat = Path.lstat + + def junction_lstat(path, **kwargs): + result = lstat(path, **kwargs) + if path == composed: + return SimpleNamespace( + st_mode=result.st_mode, + st_file_attributes=0x400, + st_reparse_tag=0xA0000003, + ) + return result + + monkeypatch.setattr(Path, "lstat", junction_lstat) + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert cache.is_file() + def test_stale_cache_cleanup_ignores_traversing_registry_key( self, project_dir, temp_dir ): @@ -2408,6 +2436,42 @@ def test_remove_reconciles_skill_for_every_historical_agent( "the currently active agent" ) + def test_remove_keeps_user_owned_legacy_skill_in_historical_dir( + self, project_dir, temp_dir + ): + """Reconciling an inactive agent's directory writes only the managed + skill name, not a user-owned legacy sibling beside it.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skills_dir = project_dir / ".claude" / "skills" + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "specify.md").write_text( + "---\ndescription: Core specify command\n---\n\nCore specify body\n", + encoding="utf-8", + ) + preset_b_dir = self._create_command_preset( + temp_dir, "hist-legacy-b", "speckit.specify", "Preset B", "preset B body", + ) + preset_a_dir = self._create_command_preset( + temp_dir, "hist-legacy-a", "speckit.specify", "Preset A", "preset A body", + ) + manager = PresetManager(project_dir) + manager.install_from_directory(preset_b_dir, "0.1.5", priority=10) + manager.install_from_directory(preset_a_dir, "0.1.5", priority=1) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + legacy_file = claude_skills_dir / "speckit.specify" / "SKILL.md" + legacy_file.parent.mkdir(parents=True) + legacy = "---\nname: speckit.specify\n---\n\nUser-owned legacy body\n" + legacy_file.write_text(legacy, encoding="utf-8") + + assert manager.remove("hist-legacy-a") is True + + assert legacy_file.read_text(encoding="utf-8") == legacy + assert "preset:hist-legacy-b" in ( + claude_skills_dir / "speckit-specify" / "SKILL.md" + ).read_text() + def test_skill_reconciliation_preserves_per_directory_names( self, project_dir, temp_dir ): From 3738814214c781fc750172d343f8f0899503d9ed Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 20 Oct 2026 00:56:39 +0530 Subject: [PATCH 07/41] fix(presets): reconcile composed skills on every path, historical dirs and aliases Round-6 review ("previously missed" items): - Never render a cached composition whose stack has no base, even when the cache file exists: with the sole composer disabled during removal its stale cache survived, and re-enabling it rendered the removed base. Retirement of still-owned skills for an uncomposable command now runs on every reconciliation (activation and rescaffold), not only removal. - On removal, also recompose or retire a surviving composer's still-owned skills in its recorded historical (inactive) agent directories, resolved through _safe_skills_dir_for_agent(). - Treat a command's manifest aliases as part of its skills: ownership accepts the registrar's ":" alias marker as well as "preset:", targeted reconciliation re-renders owned alias skills, and retirement removes them. Hand-edited aliases are kept. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 131 ++++++++++++++---- .../presets/test_manager_skills.py | 107 ++++++++++++++ 2 files changed, 214 insertions(+), 24 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 982242453a..0ffc8d4d22 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -366,7 +366,7 @@ def apply_to_dir( for cmd in cmds if any( name in dir_managed_names - for name in self._skill_names_for_command(cmd) + for name in self._command_skill_names(cmd, pack_id) ) ] if not dir_cmds: @@ -390,7 +390,7 @@ def apply_to_dir( # the same symlink guard — or the surviving preset's # override would be silently skipped (#2948). for cmd_name in dir_cmds: - for skill_name in self._skill_names_for_command(cmd_name): + for skill_name in self._command_skill_names(cmd_name, pack_id): if skill_name not in dir_managed_names: continue skill_subdir = skills_dir / skill_name @@ -439,8 +439,24 @@ def apply_to_dir( # reconciliation just wrote to on its behalf (#2948). self._merge_pack_registered_skills(pack_id, written) - extra_dirs = extra_skills_dirs or {} + extra_dirs = dict(extra_skills_dirs or {}) + if extra_skills_dirs is not None: + # Removal restores only what the removed preset still owned. A + # surviving composer's skills in historical (inactive) agent + # directories are its own, so recompose or retire them there too. + for dir_path, agent, owned_composed in self._historical_owned_skills( + composed_winners, unresolved_winners, active_ai, active_skills_dir + ): + prior_agent, prior_names = extra_dirs.get(dir_path, (agent, [])) + extra_dirs[dir_path] = ( + prior_agent, list(dict.fromkeys([*prior_names, *owned_composed])) + ) if active_skills_dir: + # Command-file agents unregister an uncomposable command; retire + # its skills too while they still carry the composer's marker. + # This runs on every reconciliation (activation and rescaffold + # too), so a stale skill can't outlive its base. + self._retire_owned_skills(active_skills_dir, unresolved_winners) active_provenance = extra_dirs.get(active_skills_dir) active_names: Optional[Set[str]] = None if extra_skills_dirs is not None: @@ -451,23 +467,6 @@ def apply_to_dir( 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 - ): - from ..integrations._file_changes import ( - after_file_change, - before_file_change, - ) - - before_file_change(stale_dir, removal=True) - shutil.rmtree(stale_dir) - after_file_change(stale_dir) if active_names is None or active_names: apply_to_dir( active_skills_dir, @@ -524,17 +523,85 @@ def _has_no_symlink_below_project(self, path: Path) -> bool: current = current.parent return True + def _command_skill_names(self, cmd_name: str, pack_id: str) -> List[str]: + """Modern and legacy skill names for ``cmd_name`` and its aliases in ``pack_id``.""" + names = list(self._skill_names_for_command(cmd_name)) + manifest_path = self.presets_dir / pack_id / "preset.yml" + try: + manifest = PresetManifest(manifest_path) + except (PresetValidationError, OSError): + return names + for tmpl in manifest.templates: + if tmpl.get("name") == cmd_name and tmpl.get("type") == "command": + for alias in tmpl.get("aliases") or []: + if isinstance(alias, str): + names.extend(self._skill_names_for_command(alias)) + break + return list(dict.fromkeys(names)) + + def _retire_owned_skills(self, skills_dir: Path, owners: Dict[str, str]) -> None: + """Delete skills in ``skills_dir`` still owned by their composer (journaled).""" + from ..integrations._file_changes import after_file_change, before_file_change + + for stale_skill in self._skills_owned_by_preset(skills_dir, owners): + stale_dir = skills_dir / stale_skill + if self._validate_skill_subdir( + stale_dir, create=False, skills_root=skills_dir + ): + before_file_change(stale_dir, removal=True) + shutil.rmtree(stale_dir) + after_file_change(stale_dir) + + def _historical_owned_skills( + self, + composed_winners: Dict[str, str], + unresolved_winners: Dict[str, str], + active_ai: Optional[str], + active_skills_dir: Optional[Path], + ) -> List[tuple]: + """Recompose targets in surviving composers' historical skill directories. + + Retires the composers' still-owned skills for uncomposable commands in + those directories, and returns ``(dir, agent, owned_names)`` for each + directory holding still-owned skills of composable commands. + """ + targets: List[tuple] = [] + for pack_id in dict.fromkeys( + [*composed_winners.values(), *unresolved_winners.values()] + ): + meta = self.registry.get(pack_id) or {} + recorded = meta.get("registered_skills") + if not isinstance(recorded, dict): + continue + for agent in recorded: + if not isinstance(agent, str) or agent == active_ai: + continue + skills_dir = self._safe_skills_dir_for_agent(agent) + if skills_dir is None or skills_dir == active_skills_dir: + continue + self._retire_owned_skills(skills_dir, { + cmd: pid for cmd, pid in unresolved_winners.items() if pid == pack_id + }) + owned = self._skills_owned_by_preset(skills_dir, { + cmd: pid for cmd, pid in composed_winners.items() if pid == pack_id + }) + if owned: + targets.append((skills_dir, agent, sorted(owned))) + return targets + 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. + ``owners`` maps command names to the expected owning preset id. Alias + skills count too; the registrar marks those ``:`` rather + than ``preset:``. """ 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): + for skill_name in self._command_skill_names(cmd_name, pack_id): skill_file = skills_dir / skill_name / "SKILL.md" if not self._validate_skill_subdir( skill_file.parent, create=False, skills_root=skills_dir @@ -545,7 +612,10 @@ def _skills_owned_by_preset( except (OSError, UnicodeDecodeError): continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") - if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}": + source = metadata.get("source") if isinstance(metadata, dict) else None + if isinstance(source, str) and ( + source == f"preset:{pack_id}" or source.startswith(f"{pack_id}:") + ): owned.add(skill_name) return owned @@ -872,6 +942,17 @@ def _register_skills( if not missing_skill_dir.exists(): target_skill_names.append(skill_name) if only_skill_names is not None: + # Targeted reconciliation also refreshes the command's alias + # skills it may manage, so they don't keep a removed layer. + for alias in cmd_tmpl.get("aliases") or []: + if not isinstance(alias, str): + continue + for alias_skill in self._skill_names_for_command(alias): + if ( + alias_skill not in target_skill_names + and (skills_dir / alias_skill).is_dir() + ): + target_skill_names.append(alias_skill) target_skill_names = [ name for name in target_skill_names if name in only_skill_names ] @@ -898,9 +979,11 @@ def _register_skills( or frontmatter.get("strategy") or "replace" ) + # A cached composition is not proof of a base either: it can be a + # stale leftover of a removed base (e.g. while its composer was + # disabled), so check resolution even when the cache exists. if ( effective_strategy != "replace" - and not composed_file.exists() and resolver.resolve_content(cmd_name, "command") is None ): continue diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index dd2385b046..34f7aed758 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2063,6 +2063,113 @@ def junction_lstat(path, **kwargs): assert cache.is_file() + def _install_custom_layers(self, project_dir, temp_dir, *, core=False, alias=None): + """Base (replace) + append presets for ``speckit.custom`` under Claude.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if core: + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + 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 + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + if alias and strategy != "replace": + manifest["provides"]["templates"][0]["aliases"] = [alias] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + return manager + + def test_reenabled_sole_composer_does_not_render_removed_base( + self, project_dir, temp_dir + ): + """The only composer is disabled while its base is removed; re-enabling + and rescaffolding must not render its stale cache, and the old skill is + retired once nothing is left to compose onto.""" + manager = self._install_custom_layers(project_dir, temp_dir) + skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + manager.registry.update("append-preset", {"enabled": False}) + manager.remove("base-preset") + manager.registry.update("append-preset", {"enabled": True}) + + with pytest.warns(UserWarning, match="no base layer"): + manager.register_enabled_presets_for_agent("claude") + + assert not skill.exists() or "Base preset body" not in skill.read_text( + encoding="utf-8" + ) + assert not ( + manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" + ).exists() + + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_reconciles_historical_agent_skill( + self, project_dir, temp_dir, core + ): + """A composer's skill in a historical (inactive) agent directory is + recomposed onto the fallback, or retired when there is none.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=core) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + + if core: + assert manager.remove("base-preset") is True + content = claude_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + else: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not claude_skill.exists() + + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_reconciles_native_alias_skill( + self, project_dir, temp_dir, core + ): + """A composer's alias skill is recomposed or retired with the primary.""" + manager = self._install_custom_layers( + project_dir, temp_dir, core=core, alias="speckit.custom-alias" + ) + alias_skill = project_dir / ".claude" / "skills" / "speckit-custom-alias" / "SKILL.md" + assert "Base preset body" in alias_skill.read_text(encoding="utf-8") + + if core: + assert manager.remove("base-preset") is True + content = alias_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + else: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not alias_skill.exists() + + def test_remove_sole_base_keeps_hand_edited_alias_skill( + self, project_dir, temp_dir + ): + manager = self._install_custom_layers( + project_dir, temp_dir, alias="speckit.custom-alias" + ) + alias_skill = project_dir / ".claude" / "skills" / "speckit-custom-alias" / "SKILL.md" + edited = "---\nname: speckit-custom-alias\n---\n\nUser-owned alias\n" + alias_skill.write_text(edited, encoding="utf-8") + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert alias_skill.read_text(encoding="utf-8") == edited + def test_stale_cache_cleanup_ignores_traversing_registry_key( self, project_dir, temp_dir ): From a9a200021188d2c2b9e921bba8533bdbbdac4718 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:09:35 +0530 Subject: [PATCH 08/41] refactor(presets): rework removal reconciliation around registration records Rework the fix as requested in review: reconcile the destinations the registry already tracks instead of adding removal-specific cases. - On removal, _unregister_skills() only restores what the removed preset owned. Also collect the affected commands' skill destinations from the surviving presets' registered_skills (inferring per-agent provenance for legacy flat lists), keep those whose SKILL.md still carries that preset's marker, and pass them through the existing extra_skills_dirs reconciliation, so active and historical directories are refreshed from the remaining stack. - When a composing winner's stack has no replace base left, nothing resolves: remove its preset-owned output (journaled) instead of rendering it. Ownership accepts both preset: and the registrar's : marker; anything else is preserved. - _register_skills() lets the resolver decide even when a .composed cache exists, so a stale cache is never rendered. This replaces the cache deletion and its path guards. - Keep the only_skill_names filter so a user-owned modern/legacy sibling is not overwritten. - Drop the alias handling added in an earlier round, which introduced the alias regressions; aliases behave as on main. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) Co-Authored-By: Claude Opus 5.5 --- src/specify_cli/presets/_manager_skills.py | 323 +++++++----------- .../presets/test_manager_skills.py | 211 +++++------- 2 files changed, 196 insertions(+), 338 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 0ffc8d4d22..cc4d516be3 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -3,7 +3,6 @@ import copy import os import shutil -import stat from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union @@ -21,31 +20,6 @@ from ._resolver import PresetResolver -def _is_link_or_reparse_point(path: Path) -> bool: - """True for a symlink or a Windows reparse point such as a directory junction. - - ``Path.is_symlink()`` does not report junctions; mirror the check in - ``FileHelper._entry_mode``. - """ - try: - entry = path.lstat() - except OSError: - return False - return stat.S_ISLNK(entry.st_mode) or bool( - getattr(entry, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT - ) - - -def _is_plain_path_segment(name: Any) -> bool: - """True for a single, non-traversing path component.""" - return ( - isinstance(name, str) - and name not in ("", ".", "..") - and "/" not in name - and "\\" not in name - ) - - class _PresetSkillMethods: """Skill artifact methods shared through PresetManager's lifecycle state.""" @@ -177,10 +151,9 @@ 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] = {} + # Commands won by a composing preset whose stack no longer has any + # replace base: nothing resolves, so their owned output is removed. + unresolvable_cmds: Set[str] = set() non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() @@ -225,18 +198,11 @@ 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 not None: - composed_winners[cmd_name] = pack_id - elif not any( - layer["strategy"] == "replace" for layer in layers - ): - # Nothing left to compose onto: drop the stale - # caches so they can't be rendered back into a - # skill. A None from an unreadable layer, with a - # base still present, keeps existing output. - unresolved_winners[cmd_name] = pack_id - self._drop_stale_composed_caches(cmd_name) + if ( + all(layer["strategy"] != "replace" for layer in layers) + and resolver.resolve_content(cmd_name, "command") is None + ): + unresolvable_cmds.add(cmd_name) found_preset = True break if not found_preset: @@ -366,9 +332,21 @@ def apply_to_dir( for cmd in cmds if any( name in dir_managed_names - for name in self._command_skill_names(cmd, pack_id) + for name in self._skill_names_for_command(cmd) ) ] + stale_cmds = [cmd for cmd in dir_cmds if cmd in unresolvable_cmds] + if stale_cmds: + self._remove_owned_skills( + skills_dir, + [ + name + for cmd in stale_cmds + for name in self._skill_names_for_command(cmd) + if name in dir_managed_names + ], + ) + dir_cmds = [cmd for cmd in dir_cmds if cmd not in unresolvable_cmds] if not dir_cmds: continue pack_dir = self.presets_dir / pack_id @@ -390,7 +368,7 @@ def apply_to_dir( # the same symlink guard — or the surviving preset's # override would be silently skipped (#2948). for cmd_name in dir_cmds: - for skill_name in self._command_skill_names(cmd_name, pack_id): + for skill_name in self._skill_names_for_command(cmd_name): if skill_name not in dir_managed_names: continue skill_subdir = skills_dir / skill_name @@ -404,9 +382,6 @@ 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). - # 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, ) @@ -441,38 +416,28 @@ def apply_to_dir( extra_dirs = dict(extra_skills_dirs or {}) if extra_skills_dirs is not None: - # Removal restores only what the removed preset still owned. A - # surviving composer's skills in historical (inactive) agent - # directories are its own, so recompose or retire them there too. - for dir_path, agent, owned_composed in self._historical_owned_skills( - composed_winners, unresolved_winners, active_ai, active_skills_dir - ): - prior_agent, prior_names = extra_dirs.get(dir_path, (agent, [])) - extra_dirs[dir_path] = ( - prior_agent, list(dict.fromkeys([*prior_names, *owned_composed])) + # _unregister_skills only restored what the removed preset owned. + # Skills a surviving preset rendered on top of it are its own, so + # refresh those recorded destinations from the remaining stack too. + for skills_dir, (agent, names) in self._surviving_owned_skills( + command_names, presets_by_priority, active_ai, active_skills_dir + ).items(): + prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) + extra_dirs[skills_dir] = ( + prior_agent, list(dict.fromkeys([*prior_names, *names])) ) if active_skills_dir: - # Command-file agents unregister an uncomposable command; retire - # its skills too while they still carry the composer's marker. - # This runs on every reconciliation (activation and rescaffold - # too), so a stale skill can't outlive its base. - self._retire_owned_skills(active_skills_dir, unresolved_winners) active_provenance = extra_dirs.get(active_skills_dir) - 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 - ) - if active_names is None or active_names: + if extra_skills_dirs is None or active_provenance: apply_to_dir( active_skills_dir, active_ai, is_active=True, - managed_names=active_names, + managed_names=( + set(active_provenance[1]) + if active_provenance + else None + ), ) for extra_dir, (extra_agent, extra_names) in extra_dirs.items(): @@ -487,137 +452,96 @@ def apply_to_dir( return reconciled_skill_commands - def _drop_stale_composed_caches(self, cmd_name: str) -> None: - """Delete every installed preset's ``.composed/.md`` for an - uncomposable command, disabled presets included. - - With no base left, any preset's cached composition of ``cmd_name`` - still holds the removed layer and could be rendered back by a later - registration. A registry key or command name with a path separator or - ``..`` component is skipped, as is a cache reached through a symlinked - ancestor below the project root, so nothing outside the project is - deleted; the deletion is journaled like the cache writes. - """ - from ..integrations._file_changes import unlink as _unlink_file - - for pack_id in self.registry.list(): - if not _is_plain_path_segment(pack_id) or not _is_plain_path_segment( - f"{cmd_name}.md" - ): - continue - stale = self.presets_dir / pack_id / ".composed" / f"{cmd_name}.md" - if not stale.is_file() or not self._has_no_symlink_below_project(stale): - continue - _unlink_file(stale) - - def _has_no_symlink_below_project(self, path: Path) -> bool: - """True if ``path`` is under the project root with no symlinked component.""" - try: - path.relative_to(self.project_root) - except ValueError: - return False - current = path - while current != self.project_root: - if _is_link_or_reparse_point(current): - return False - current = current.parent - return True - - def _command_skill_names(self, cmd_name: str, pack_id: str) -> List[str]: - """Modern and legacy skill names for ``cmd_name`` and its aliases in ``pack_id``.""" - names = list(self._skill_names_for_command(cmd_name)) - manifest_path = self.presets_dir / pack_id / "preset.yml" - try: - manifest = PresetManifest(manifest_path) - except (PresetValidationError, OSError): - return names - for tmpl in manifest.templates: - if tmpl.get("name") == cmd_name and tmpl.get("type") == "command": - for alias in tmpl.get("aliases") or []: - if isinstance(alias, str): - names.extend(self._skill_names_for_command(alias)) - break - return list(dict.fromkeys(names)) - - def _retire_owned_skills(self, skills_dir: Path, owners: Dict[str, str]) -> None: - """Delete skills in ``skills_dir`` still owned by their composer (journaled).""" - from ..integrations._file_changes import after_file_change, before_file_change - - for stale_skill in self._skills_owned_by_preset(skills_dir, owners): - stale_dir = skills_dir / stale_skill - if self._validate_skill_subdir( - stale_dir, create=False, skills_root=skills_dir - ): - before_file_change(stale_dir, removal=True) - shutil.rmtree(stale_dir) - after_file_change(stale_dir) - - def _historical_owned_skills( + def _surviving_owned_skills( self, - composed_winners: Dict[str, str], - unresolved_winners: Dict[str, str], + command_names: List[str], + presets_by_priority: List[Any], active_ai: Optional[str], active_skills_dir: Optional[Path], - ) -> List[tuple]: - """Recompose targets in surviving composers' historical skill directories. + ) -> Dict[Path, tuple[Optional[str], List[str]]]: + """Recorded skill destinations of ``command_names`` still owned by a survivor. - Retires the composers' still-owned skills for uncomposable commands in - those directories, and returns ``(dir, agent, owned_names)`` for each - directory holding still-owned skills of composable commands. + Reads each remaining preset's ``registered_skills`` (inferring per-agent + provenance for legacy flat lists) and keeps the names whose ``SKILL.md`` + still carries that preset's ``preset:`` marker. """ - targets: List[tuple] = [] - for pack_id in dict.fromkeys( - [*composed_winners.values(), *unresolved_winners.values()] - ): - meta = self.registry.get(pack_id) or {} + registrar = self._command_registrar() + affected = { + name + for cmd_name in command_names + for name in self._skill_names_for_command(cmd_name) + } + found: Dict[Path, tuple[Optional[str], List[str]]] = {} + for pack_id, meta in presets_by_priority: + if not isinstance(meta, dict): + continue recorded = meta.get("registered_skills") + if isinstance(recorded, list) and active_ai: + recorded = self._infer_legacy_skill_provenance( + [n for n in recorded if isinstance(n, str)], pack_id, active_ai + ) if not isinstance(recorded, dict): continue - for agent in recorded: - if not isinstance(agent, str) or agent == active_ai: + for agent, names in recorded.items(): + if not isinstance(agent, str) or not isinstance(names, list): continue - skills_dir = self._safe_skills_dir_for_agent(agent) - if skills_dir is None or skills_dir == active_skills_dir: + skills_dir = ( + active_skills_dir + if agent == active_ai + else self._safe_skills_dir_for_agent(agent) + ) + if skills_dir is None: continue - self._retire_owned_skills(skills_dir, { - cmd: pid for cmd, pid in unresolved_winners.items() if pid == pack_id - }) - owned = self._skills_owned_by_preset(skills_dir, { - cmd: pid for cmd, pid in composed_winners.items() if pid == pack_id - }) - if owned: - targets.append((skills_dir, agent, sorted(owned))) - return targets - - 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. Alias - skills count too; the registrar marks those ``:`` rather - than ``preset:``. + for name in names: + if name not in affected: + continue + skill_file = skills_dir / name / "SKILL.md" + if not self._validate_skill_subdir( + skill_file.parent, create=False, skills_root=skills_dir + ) or not skill_file.is_file(): + continue + try: + content = skill_file.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + continue + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}": + dir_agent, dir_names = found.get(skills_dir, (agent, [])) + found[skills_dir] = (dir_agent, [*dir_names, name]) + return found + + def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None: + """Delete preset-owned skills among ``skill_names`` (journaled). + + A skill is preset-owned when its ``SKILL.md`` source marker names an + installed preset, either as ``preset:`` (skill registration) or + ``:`` (command registration for native skill agents); + anything else is left untouched. """ + from ..integrations._file_changes import after_file_change, before_file_change + registrar = self._command_registrar() - owned: Set[str] = set() - for cmd_name, pack_id in owners.items(): - for skill_name in self._command_skill_names(cmd_name, pack_id): - skill_file = skills_dir / skill_name / "SKILL.md" - if not self._validate_skill_subdir( - skill_file.parent, create=False, skills_root=skills_dir - ) or not skill_file.is_file(): - continue - try: - content = skill_file.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): - continue - metadata = registrar.parse_frontmatter(content)[0].get("metadata") - source = metadata.get("source") if isinstance(metadata, dict) else None - if isinstance(source, str) and ( - source == f"preset:{pack_id}" or source.startswith(f"{pack_id}:") - ): - owned.add(skill_name) - return owned + pack_ids = list(self.registry.list()) + for name in dict.fromkeys(skill_names): + skill_dir = skills_dir / name + skill_file = skill_dir / "SKILL.md" + if not self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ) or not skill_file.is_file(): + continue + try: + content = skill_file.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + continue + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + source = metadata.get("source") if isinstance(metadata, dict) else None + if isinstance(source, str) and any( + source == f"preset:{pack_id}" or source.startswith(f"{pack_id}:") + for pack_id in pack_ids + ): + before_file_change(skill_dir, removal=True) + shutil.rmtree(skill_dir) + after_file_change(skill_dir) def _resolve_agent_skills_dir(self, agent_name: str) -> Path: """Resolve the real skill output directory for an integration.""" @@ -942,17 +866,6 @@ def _register_skills( if not missing_skill_dir.exists(): target_skill_names.append(skill_name) if only_skill_names is not None: - # Targeted reconciliation also refreshes the command's alias - # skills it may manage, so they don't keep a removed layer. - for alias in cmd_tmpl.get("aliases") or []: - if not isinstance(alias, str): - continue - for alias_skill in self._skill_names_for_command(alias): - if ( - alias_skill not in target_skill_names - and (skills_dir / alias_skill).is_dir() - ): - target_skill_names.append(alias_skill) target_skill_names = [ name for name in target_skill_names if name in only_skill_names ] @@ -979,9 +892,9 @@ def _register_skills( or frontmatter.get("strategy") or "replace" ) - # A cached composition is not proof of a base either: it can be a - # stale leftover of a removed base (e.g. while its composer was - # disabled), so check resolution even when the cache exists. + # A cached composition can outlive its base (e.g. one removed + # while its composer was disabled), so the resolver decides even + # when the cache exists. if ( effective_strategy != "replace" and resolver.resolve_content(cmd_name, "command") is None diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 34f7aed758..647895ee45 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1945,16 +1945,15 @@ 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.""" + nothing to compose onto: the composer's skill is removed, and a later + rescaffold does not render its stale cached composition back.""" 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 + manager.register_enabled_presets_for_agent("claude") assert not skill_file.exists() - assert not cache.exists() def test_remove_sole_base_preset_keeps_hand_edited_skill( self, project_dir, temp_dir @@ -1968,29 +1967,11 @@ def test_remove_sole_base_preset_keeps_hand_edited_skill( assert skill_file.read_text(encoding="utf-8") == edited - def test_remove_sole_base_preset_keeps_cache_behind_symlinked_dir( - self, project_dir, temp_dir - ): - """A ``.composed`` directory that links outside the project is not - followed when stale caches are deleted.""" - manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) - composed = manager.presets_dir / "append-preset" / ".composed" - external = temp_dir / "external-composed" - shutil.move(str(composed), str(external)) - composed.symlink_to(external, target_is_directory=True) - target = external / "speckit.custom.md" - assert target.is_file() - - with pytest.warns(UserWarning, match="no base layer"): - assert manager.remove("base-preset") is True - - assert target.is_file() - def test_remove_sole_base_under_two_composers_survives_rescaffold( self, project_dir, temp_dir ): - """Every surviving preset's stale cache is dropped, so a later - rescaffold cannot render the removed base back into the skill.""" + """With two composers and no base left, the skill is removed and a + rescaffold does not render either composer's stale cache back.""" manager, skill_file = self._install_unbacked_custom_stack( project_dir, temp_dir, @@ -2005,20 +1986,13 @@ def test_remove_sole_base_under_two_composers_survives_rescaffold( assert manager.remove("base-preset") is True manager.register_enabled_presets_for_agent("claude") - for preset_id in ("middle-preset", "top-preset"): - assert not ( - manager.presets_dir / preset_id / ".composed" / "speckit.custom.md" - ).exists() - assert not skill_file.exists() or "Base preset body" not in skill_file.read_text( - encoding="utf-8" - ) + assert not skill_file.exists() - def test_stale_cache_deletion_is_journaled(self, project_dir, temp_dir): - """The cache deletion is reported to the lifecycle file-change journal.""" + def test_stale_skill_removal_is_journaled(self, project_dir, temp_dir): + """Removing the composer's stale skill is reported to the lifecycle journal.""" from specify_cli.integrations._file_changes import file_change_observer manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) - cache = manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" events = [] token = file_change_observer.set( lambda path, before, removal: events.append((path, before, removal)) @@ -2029,40 +2003,10 @@ def test_stale_cache_deletion_is_journaled(self, project_dir, temp_dir): finally: file_change_observer.reset(token) - assert (cache, True, True) in events - assert not cache.exists() skill_dir = project_dir / ".claude" / "skills" / "speckit-custom" assert (skill_dir, True, True) in events assert not skill_dir.exists() - def test_stale_cache_cleanup_rejects_junctioned_composed_dir( - self, project_dir, temp_dir, monkeypatch - ): - """A ``.composed`` directory reported as a Windows reparse point (a - junction, which ``is_symlink()`` misses) is not followed.""" - from types import SimpleNamespace - - manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) - composed = manager.presets_dir / "append-preset" / ".composed" - cache = composed / "speckit.custom.md" - lstat = Path.lstat - - def junction_lstat(path, **kwargs): - result = lstat(path, **kwargs) - if path == composed: - return SimpleNamespace( - st_mode=result.st_mode, - st_file_attributes=0x400, - st_reparse_tag=0xA0000003, - ) - return result - - monkeypatch.setattr(Path, "lstat", junction_lstat) - with pytest.warns(UserWarning, match="no base layer"): - assert manager.remove("base-preset") is True - - assert cache.is_file() - def _install_custom_layers(self, project_dir, temp_dir, *, core=False, alias=None): """Base (replace) + append presets for ``speckit.custom`` under Claude.""" self._write_init_options(project_dir, ai="claude", ai_skills=True) @@ -2091,12 +2035,75 @@ def _install_custom_layers(self, project_dir, temp_dir, *, core=False, alias=Non manager.install_from_directory(preset_dir, "0.1.5", priority=priority) return manager + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_reconciles_skill_owned_by_lower_survivor_in_historical_dir( + self, project_dir, temp_dir, core + ): + """Claude's skill was rendered by ``middle``; ``top`` was installed later + under Codex only. Removing the base must still refresh Claude's skill, + whose recorded owner is ``middle``, not the current winner ``top``.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if core: + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + def install(preset_id, body, strategy, priority): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + 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) + + install("base-preset", "Base preset body", "replace", 10) + install("middle-preset", "Middle body", "append", 7) + assert "preset:middle-preset" in claude_skill.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + + if core: + assert manager.remove("base-preset") is True + content = claude_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + else: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not claude_skill.exists() + + def test_remove_base_reconciles_survivor_with_legacy_flat_skill_record( + self, project_dir, temp_dir + ): + """A surviving composer whose ``registered_skills`` is still a legacy + flat list gets its inactive agent's skill refreshed too.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=True) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + manager.registry.update("append-preset", {"registered_skills": ["speckit-custom"]}) + + assert manager.remove("base-preset") is True + + content = claude_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + def test_reenabled_sole_composer_does_not_render_removed_base( self, project_dir, temp_dir ): """The only composer is disabled while its base is removed; re-enabling - and rescaffolding must not render its stale cache, and the old skill is - retired once nothing is left to compose onto.""" + and rescaffolding neither renders its stale cache nor keeps its old + skill, since nothing is left to compose onto.""" manager = self._install_custom_layers(project_dir, temp_dir) skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" manager.registry.update("append-preset", {"enabled": False}) @@ -2106,12 +2113,7 @@ def test_reenabled_sole_composer_does_not_render_removed_base( with pytest.warns(UserWarning, match="no base layer"): manager.register_enabled_presets_for_agent("claude") - assert not skill.exists() or "Base preset body" not in skill.read_text( - encoding="utf-8" - ) - assert not ( - manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" - ).exists() + assert not skill.exists() @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) def test_remove_base_reconciles_historical_agent_skill( @@ -2134,63 +2136,11 @@ def test_remove_base_reconciles_historical_agent_skill( assert manager.remove("base-preset") is True assert not claude_skill.exists() - @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) - def test_remove_base_reconciles_native_alias_skill( - self, project_dir, temp_dir, core - ): - """A composer's alias skill is recomposed or retired with the primary.""" - manager = self._install_custom_layers( - project_dir, temp_dir, core=core, alias="speckit.custom-alias" - ) - alias_skill = project_dir / ".claude" / "skills" / "speckit-custom-alias" / "SKILL.md" - assert "Base preset body" in alias_skill.read_text(encoding="utf-8") - - if core: - assert manager.remove("base-preset") is True - content = alias_skill.read_text(encoding="utf-8") - assert "Base preset body" not in content - assert "Core custom body" in content and "Appended body" in content - else: - with pytest.warns(UserWarning, match="no base layer"): - assert manager.remove("base-preset") is True - assert not alias_skill.exists() - - def test_remove_sole_base_keeps_hand_edited_alias_skill( + def test_remove_sole_base_with_disabled_composer_survives_rescaffold( self, project_dir, temp_dir ): - manager = self._install_custom_layers( - project_dir, temp_dir, alias="speckit.custom-alias" - ) - alias_skill = project_dir / ".claude" / "skills" / "speckit-custom-alias" / "SKILL.md" - edited = "---\nname: speckit-custom-alias\n---\n\nUser-owned alias\n" - alias_skill.write_text(edited, encoding="utf-8") - - with pytest.warns(UserWarning, match="no base layer"): - assert manager.remove("base-preset") is True - - assert alias_skill.read_text(encoding="utf-8") == edited - - def test_stale_cache_cleanup_ignores_traversing_registry_key( - self, project_dir, temp_dir - ): - """A malformed registry key with ``..`` must not reach outside the project.""" - manager, _skill = self._install_unbacked_custom_stack(project_dir, temp_dir) - outside = (manager.presets_dir / "../../../outside").resolve() - target = outside / ".composed" / "speckit.custom.md" - target.parent.mkdir(parents=True) - target.write_text("external\n", encoding="utf-8") - manager.registry.add("../../../outside", {"version": "1.0.0", "enabled": True, "priority": 20}) - - with pytest.warns(UserWarning, match="no base layer"): - assert manager.remove("base-preset") is True - - assert target.read_text(encoding="utf-8") == "external\n" - - def test_remove_sole_base_drops_disabled_preset_cache( - self, project_dir, temp_dir - ): - """A disabled composer's stale cache is dropped too, so re-enabling it - and rescaffolding cannot render the removed base back.""" + """A composer disabled during the removal can't bring the removed base + back through its stale cache once it is re-enabled and rescaffolded.""" manager, skill_file = self._install_unbacked_custom_stack( project_dir, temp_dir, @@ -2207,12 +2157,7 @@ def test_remove_sole_base_drops_disabled_preset_cache( manager.registry.update("middle-preset", {"enabled": True}) manager.register_enabled_presets_for_agent("claude") - assert not ( - manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" - ).exists() - assert not skill_file.exists() or "Base preset body" not in skill_file.read_text( - encoding="utf-8" - ) + assert not skill_file.exists() def test_unreadable_surviving_base_keeps_composed_output( self, project_dir, temp_dir From cf44847838ade6ac5e15909ee5be06bf11ebb53b Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:32:30 +0000 Subject: [PATCH 09/41] fix(presets): reconcile native-skill aliases of composed commands For native skill agents (e.g. Claude) a preset's command aliases are written by command registration and recorded in registered_commands, so the skill reconciliation pass never saw them. When a layer under a composing preset changed, the alias kept the old composition: removing the only base deleted the primary skill but left the alias running the removed base's text, and a core fallback recomposed the primary but not the alias until the next rescaffold. After skill reconciliation, read each surviving preset's registered_commands for native skill agents, map aliases to their primary through the preset manifest, and for aliases whose SKILL.md still carries the preset's `:` marker: re-render from the current stack, or remove (journaled) when nothing is left to compose onto. On install/rescaffold passes a recorded alias missing from the active agent is rendered again, so an alias retired with its base comes back when a new base makes the command composable. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 141 ++++++++++++++++++ .../presets/test_manager_skills.py | 82 ++++++++++ 2 files changed, 223 insertions(+) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index cc4d516be3..ca86fbfcd2 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -14,6 +14,7 @@ from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter from ..integrations.base import IntegrationBase +from ..integrations._file_changes import write_text as _write_text from ..integrations._registration import project_registration from ._manager_commands import _substitute_core_template from ._manifest import PresetManifest, PresetValidationError @@ -450,8 +451,148 @@ def apply_to_dir( managed_names=set(extra_names), ) + self._reconcile_preset_aliases( + command_names, + presets_by_priority, + active_ai, + active_skills_dir, + create_missing=extra_skills_dirs is None, + ) + return reconciled_skill_commands + def _reconcile_preset_aliases( + self, + command_names: List[str], + presets_by_priority: List[Any], + active_ai: Optional[str], + active_skills_dir: Optional[Path], + *, + create_missing: bool = False, + ) -> None: + """Re-render, retire or restore native-skill aliases of composed commands. + + For native skill agents, a preset's command aliases are written by + command registration (``:`` source marker) and recorded in + its ``registered_commands``, not in ``registered_skills``, so the + skill pass above never sees them. When a layer under a composing + preset is added or removed, its aliases would otherwise keep the old + composition. Rewrite each from the current stack, or remove it when + nothing is left to compose onto, the same as its primary skill. Only + outputs still carrying the preset's marker are touched. + + Args: + create_missing: Also render a recorded alias that is missing from + the active agent's directory (e.g. one retired when its base + was removed, once a new base makes it composable again). Like + the primary skill, this only happens for the active agent. + """ + from ..integrations._file_changes import after_file_change, before_file_change + + try: + registrar = self._command_registrar() + except ImportError: + return + registrar._ensure_configs() + resolver = PresetResolver(self.project_root) + wanted = set(command_names) + + for pack_id, meta in presets_by_priority: + if not isinstance(meta, dict): + continue + recorded = meta.get("registered_commands") + if not isinstance(recorded, dict): + continue + pack_dir = self.presets_dir / pack_id + manifest = resolver._get_manifest(pack_dir) + if not manifest: + continue + alias_to_tmpl: Dict[str, Dict[str, Any]] = {} + for tmpl in manifest.templates: + if tmpl.get("type") != "command" or tmpl.get("name") not in wanted: + continue + if tmpl.get("strategy", "replace") == "replace": + # A replace layer's own file did not change. + continue + for alias in tmpl.get("aliases") or []: + if isinstance(alias, str): + alias_to_tmpl[alias] = tmpl + if not alias_to_tmpl: + continue + + for agent, names in recorded.items(): + agent_config = registrar.AGENT_CONFIGS.get(agent) + if ( + not isinstance(names, list) + or not agent_config + or agent_config.get("extension") != "/SKILL.md" + ): + continue + skills_dir = ( + active_skills_dir + if agent == active_ai + else self._safe_skills_dir_for_agent(agent) + ) + if skills_dir is None: + continue + for alias in names: + tmpl = alias_to_tmpl.get(alias) if isinstance(alias, str) else None + if tmpl is None: + continue + skill_name = registrar._compute_output_name(agent, alias, agent_config) + skill_dir = skills_dir / skill_name + skill_file = skill_dir / "SKILL.md" + missing = not skill_dir.exists() and not skill_dir.is_symlink() + if missing: + if not (create_missing and agent == active_ai): + continue + else: + if not self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ) or not skill_file.is_file(): + continue + try: + content = skill_file.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + continue + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + source = ( + metadata.get("source") if isinstance(metadata, dict) else None + ) + if not ( + isinstance(source, str) and source.startswith(f"{pack_id}:") + ): + continue + + primary = tmpl["name"] + layers = resolver.collect_all_layers(primary, "command") + if not layers or not layers[0]["path"].is_relative_to(pack_dir): + # Another layer wins now; this alias is not ours to render. + continue + composed = resolver.resolve_content(primary, "command") + if composed is None: + if missing: + continue + before_file_change(skill_dir, removal=True) + shutil.rmtree(skill_dir) + after_file_change(skill_dir) + continue + if missing and not self._validate_skill_subdir( + skill_dir, create=True, skills_root=skills_dir + ): + continue + composed_file = pack_dir / ".composed" / f"{primary}.md" + composed_file.parent.mkdir(parents=True, exist_ok=True) + _write_text(composed_file, composed, encoding="utf-8") + registrar.register_commands( + agent, + [{"name": alias, "file": f".composed/{primary}.md"}], + pack_id, + pack_dir, + self.project_root, + _resolved_dir=skills_dir, + ) + def _surviving_owned_skills( self, command_names: List[str], diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 647895ee45..7476365547 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2035,6 +2035,88 @@ def _install_custom_layers(self, project_dir, temp_dir, *, core=False, alias=Non manager.install_from_directory(preset_dir, "0.1.5", priority=priority) return manager + _ALIAS = "speckit.custom-short" + + def _alias_skill(self, project_dir): + return project_dir / ".claude" / "skills" / "speckit-custom-short" / "SKILL.md" + + def test_remove_sole_base_retires_composer_alias_skill(self, project_dir, temp_dir): + """A composer's native alias goes with its primary when no base is left, + and a rescaffold does not render the removed base's text back into it.""" + from specify_cli.integrations._file_changes import file_change_observer + + manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) + alias_file = self._alias_skill(project_dir) + assert "Base preset body" in alias_file.read_text(encoding="utf-8") + events = [] + token = file_change_observer.set( + lambda path, before, removal: events.append((path, before, removal)) + ) + try: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + finally: + file_change_observer.reset(token) + + assert not alias_file.parent.exists() + assert (alias_file.parent, True, True) in events + with pytest.warns(UserWarning, match="no base layer"): + manager.register_enabled_presets_for_agent("claude") + assert not alias_file.parent.exists() + + def test_remove_base_recomposes_composer_alias_skill(self, project_dir, temp_dir): + """With a core fallback, the alias is recomposed on removal exactly as a + rescaffold would render it.""" + manager = self._install_custom_layers( + project_dir, temp_dir, core=True, alias=self._ALIAS + ) + alias_file = self._alias_skill(project_dir) + + assert manager.remove("base-preset") is True + + after_remove = alias_file.read_text(encoding="utf-8") + assert "Base preset body" not in after_remove + assert "Core custom body" in after_remove + assert "Appended body" in after_remove + manager.register_enabled_presets_for_agent("claude") + assert alias_file.read_text(encoding="utf-8") == after_remove + + # The alias stays tracked as the composer's command output, so + # removing the composer after the rescaffold still cleans it up. + assert manager.remove("append-preset") is True + assert not alias_file.parent.exists() + + def test_new_base_restores_retired_composer_alias_skill(self, project_dir, temp_dir): + """An alias retired with its base comes back with its primary once a new + base makes the command composable again.""" + manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) + alias_file = self._alias_skill(project_dir) + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not alias_file.parent.exists() + + new_base = self._create_command_preset( + temp_dir, "new-base", "speckit.custom", "new-base", "New base body" + ) + manager.install_from_directory(new_base, "0.1.5", priority=10) + + restored = alias_file.read_text(encoding="utf-8") + assert "New base body" in restored and "Appended body" in restored + assert "Base preset body" not in restored + assert "source: append-preset:" in restored + + def test_remove_sole_base_keeps_hand_edited_alias_skill(self, project_dir, temp_dir): + manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) + alias_file = self._alias_skill(project_dir) + edited = "---\nname: speckit-custom-short\n---\n\nUser-owned body\n" + alias_file.write_text(edited, encoding="utf-8") + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert alias_file.read_text(encoding="utf-8") == edited + + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) def test_remove_base_reconciles_skill_owned_by_lower_survivor_in_historical_dir( self, project_dir, temp_dir, core From 960f9023075ebd20d2946c5b08cea3029bd43ad5 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:26:52 +0000 Subject: [PATCH 10/41] fix(presets): keep alias reconciliation active-only and failure-safe Follow-up to the Nov 2 review of the alias reconciliation: - Outside a removal pass, render and restore aliases only in the active agent's directory (single-active rule, #2948). Retiring an alias that is no longer composable is still allowed wherever it is recorded. - Group recorded agents by resolved skills directory and render each shared directory once with the active agent's renderer, as _unregister_skills does, so codex/agy sharing .agents/skills keep the active agent's command-reference syntax. - Retire an alias only when no replace layer remains. When a replace base is still present but resolve_content() fails (e.g. an undecodable layer), keep the alias, matching the primary-skill path. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 45 ++++++++- .../presets/test_manager_skills.py | 97 +++++++++++++++++++ 2 files changed, 139 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index ca86fbfcd2..034900d038 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -457,6 +457,7 @@ def apply_to_dir( active_ai, active_skills_dir, create_missing=extra_skills_dirs is None, + removal_pass=extra_skills_dirs is not None, ) return reconciled_skill_commands @@ -469,6 +470,7 @@ def _reconcile_preset_aliases( active_skills_dir: Optional[Path], *, create_missing: bool = False, + removal_pass: bool = False, ) -> None: """Re-render, retire or restore native-skill aliases of composed commands. @@ -486,6 +488,12 @@ def _reconcile_preset_aliases( the active agent's directory (e.g. one retired when its base was removed, once a new base makes it composable again). Like the primary skill, this only happens for the active agent. + removal_pass: True when called after a preset was removed, where + the primary-skill pass also repairs historical agents' + directories. On install/activation passes, rendering stays + active-only (the single-active rule of #2948); an alias that + is no longer composable is still retired wherever it is + recorded, mirroring stale-output retirement. """ from ..integrations._file_changes import after_file_change, before_file_change @@ -520,6 +528,14 @@ def _reconcile_preset_aliases( if not alias_to_tmpl: continue + # Several native skill agents can resolve to one physical + # directory (agy/codex/zed all use ``.agents/skills``). Rendering + # it once per recorded agent would let whichever agent is iterated + # last win, writing another agent's command-reference syntax over + # the active one's. Group by resolved directory and render with + # the active agent when it shares that directory, exactly as + # ``_unregister_skills`` does. + groups: Dict[Path, Dict[str, Any]] = {} for agent, names in recorded.items(): agent_config = registrar.AGENT_CONFIGS.get(agent) if ( @@ -535,7 +551,22 @@ def _reconcile_preset_aliases( ) if skills_dir is None: continue - for alias in names: + group = groups.setdefault(skills_dir, {"agents": [], "aliases": []}) + group["agents"].append(agent) + for name in names: + if isinstance(name, str) and name not in group["aliases"]: + group["aliases"].append(name) + + for skills_dir, group in groups.items(): + agents = group["agents"] + agent = ( + active_ai if active_ai in agents else sorted(agents)[0] + ) + agent_config = registrar.AGENT_CONFIGS[agent] + # Rendering follows the single-active rule outside a removal + # pass; retiring an uncomposable alias is allowed anywhere. + may_render = removal_pass or skills_dir == active_skills_dir + for alias in group["aliases"]: tmpl = alias_to_tmpl.get(alias) if isinstance(alias, str) else None if tmpl is None: continue @@ -544,7 +575,7 @@ def _reconcile_preset_aliases( skill_file = skill_dir / "SKILL.md" missing = not skill_dir.exists() and not skill_dir.is_symlink() if missing: - if not (create_missing and agent == active_ai): + if not (create_missing and skills_dir == active_skills_dir): continue else: if not self._validate_skill_subdir( @@ -571,12 +602,20 @@ def _reconcile_preset_aliases( continue composed = resolver.resolve_content(primary, "command") if composed is None: - if missing: + if missing or any( + layer["strategy"] == "replace" for layer in layers + ): + # A replace base is still there, so this is a + # resolution failure (e.g. an unreadable layer), + # not a missing base: keep the alias, as the + # primary-skill path keeps its output. continue before_file_change(skill_dir, removal=True) shutil.rmtree(skill_dir) after_file_change(skill_dir) continue + if not may_render: + continue if missing and not self._validate_skill_subdir( skill_dir, create=True, skills_root=skills_dir ): diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 7476365547..15207383c2 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2105,6 +2105,103 @@ def test_new_base_restores_retired_composer_alias_skill(self, project_dir, temp_ assert "Base preset body" not in restored assert "source: append-preset:" in restored + def test_unreadable_surviving_base_keeps_alias_skill(self, project_dir, temp_dir): + """A surviving replace base that cannot be decoded makes resolution + fail; that is not a missing base, so the alias is kept like the + primary skill's output.""" + manager = self._install_custom_layers( + project_dir, temp_dir, alias=self._ALIAS + ) + other = self._create_command_preset( + temp_dir, "other-base", "speckit.custom", "other-base", "Other base body" + ) + # Lower-priority than base-preset, so it only becomes the base once + # base-preset is removed. + manager.install_from_directory(other, "0.1.5", priority=12) + alias_file = self._alias_skill(project_dir) + before = alias_file.read_text(encoding="utf-8") + assert "Base preset body" in before + manifest = yaml.safe_load( + (manager.presets_dir / "other-base" / "preset.yml").read_text() + ) + command_file = ( + manager.presets_dir / "other-base" + / manifest["provides"]["templates"][0]["file"] + ) + command_file.write_bytes(b"---\ndescription: x\n---\n\xff\xfe broken\n") + + assert manager.remove("base-preset") is True + + assert alias_file.read_text(encoding="utf-8") == before + + def test_install_does_not_rewrite_inactive_agent_alias_skill( + self, project_dir, temp_dir + ): + """Installing a new base while another agent is active must not write + an inactive agent's alias: registration is active-only (#2948).""" + manager = self._install_custom_layers( + project_dir, temp_dir, alias=self._ALIAS + ) + claude_alias = self._alias_skill(project_dir) + before = claude_alias.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + + new_base = self._create_command_preset( + temp_dir, "new-base", "speckit.custom", "new-base", "New base body" + ) + manager.install_from_directory(new_base, "0.1.5", priority=8) + + assert claude_alias.read_text(encoding="utf-8") == before + + def test_shared_dir_alias_rendered_once_with_active_renderer( + self, project_dir, temp_dir + ): + """Codex and agy share ``.agents/skills``. A shared alias must be + rendered once, with the active agent's command-reference syntax.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + shared = project_dir / ".agents" / "skills" + self._create_skill(shared, "speckit-custom") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + for preset_id, body, strategy, priority in [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Run `__SPECKIT_COMMAND_PLAN__`.", "append", 5), + ]: + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + if strategy != "replace": + manifest["provides"]["templates"][0]["aliases"] = [self._ALIAS] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + + # `integration use agy` then back to codex records both agent keys + # against the one shared directory. + self._write_init_options(project_dir, ai="agy", ai_skills=True) + manager.register_enabled_presets_for_agent("agy") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + recorded = manager.registry.get("append-preset").get("registered_commands", {}) + assert {"codex", "agy"} <= set(recorded) + + assert manager.remove("base-preset") is True + + alias_text = (shared / "speckit-custom-short" / "SKILL.md").read_text( + encoding="utf-8" + ) + assert "Core custom body" in alias_text + # Codex is active, so references use its "$" prefix, not agy's "/". + assert "$speckit-plan" in alias_text + assert "/speckit-plan" not in alias_text + def test_remove_sole_base_keeps_hand_edited_alias_skill(self, project_dir, temp_dir): manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) alias_file = self._alias_skill(project_dir) From a0defa5d0db2b6471f414dd6ef1fd864711b895f Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:08:54 +0530 Subject: [PATCH 11/41] fix(presets): refresh survivor-owned skills from the owner's layer Removing a lower preset refreshed every skill a survivor still owned by rendering the global winner into it. When a higher preset was installed later under another agent, that wrote its content and ownership marker into an integration it never registered in (#2948, active-only). Each survivor-owned destination is now handled by its owner's layer: - a replace owner never depended on the removed layer, so the skill is left untouched; - a composing owner that is also the winner is rendered as before; - a composing owner below the winner is rendered from its own layer and the layers under it (resolve_content() takes an optional layers slice, _register_skills() takes the resolved text), and retired when nothing is left under it to compose onto. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 108 +++++++++++++++--- src/specify_cli/presets/_resolver.py | 8 +- .../presets/test_manager_skills.py | 32 ++++++ 3 files changed, 132 insertions(+), 16 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 034900d038..6627dd67e5 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -158,11 +158,13 @@ def _reconcile_skills( non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() + cmd_layers: Dict[str, List[Dict[str, Any]]] = {} for cmd_name in command_names: layers = resolver.collect_all_layers(cmd_name, "command") if not layers: continue + cmd_layers[cmd_name] = layers skill_name, legacy_skill_name = self._skill_names_for_command( cmd_name @@ -416,17 +418,40 @@ def apply_to_dir( self._merge_pack_registered_skills(pack_id, written) extra_dirs = dict(extra_skills_dirs or {}) + # {(skills_dir, agent, owner_id): {cmd_name: [skill_name, ...]}} + owner_refreshes: Dict[tuple, Dict[str, List[str]]] = {} if extra_skills_dirs is not None: # _unregister_skills only restored what the removed preset owned. - # Skills a surviving preset rendered on top of it are its own, so - # refresh those recorded destinations from the remaining stack too. - for skills_dir, (agent, names) in self._surviving_owned_skills( + # Skills a surviving preset composed on top of it are its own, so + # refresh those recorded destinations from that owner's layer and + # the layers below it. A replace owner never depended on lower + # layers, and a higher preset that never registered there must + # not be rendered into it (#2948), so the global winner is used + # only when it is the owner. + for skills_dir, agent, owner_id, cmd_name, name in self._surviving_owned_skills( command_names, presets_by_priority, active_ai, active_skills_dir - ).items(): - prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) - extra_dirs[skills_dir] = ( - prior_agent, list(dict.fromkeys([*prior_names, *names])) + ): + layers = cmd_layers.get(cmd_name, []) + owner_dir = self.presets_dir / owner_id + owner_idx = next( + ( + idx + for idx, layer in enumerate(layers) + if layer["path"].is_relative_to(owner_dir) + ), + None, ) + if owner_idx is None or layers[owner_idx]["strategy"] == "replace": + continue + if owner_idx == 0: + prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) + extra_dirs[skills_dir] = ( + prior_agent, list(dict.fromkeys([*prior_names, name])) + ) + continue + owner_refreshes.setdefault( + (skills_dir, agent, owner_id), {} + ).setdefault(cmd_name, []).append(name) if active_skills_dir: active_provenance = extra_dirs.get(active_skills_dir) if extra_skills_dirs is None or active_provenance: @@ -451,6 +476,50 @@ def apply_to_dir( managed_names=set(extra_names), ) + for (skills_dir, agent, owner_id), owned in owner_refreshes.items(): + owner_dir = self.presets_dir / owner_id + try: + manifest = PresetManifest(owner_dir / "preset.yml") + except PresetValidationError: + continue + overrides: Dict[str, str] = {} + for cmd_name, names in owned.items(): + layers = cmd_layers[cmd_name] + owner_idx = next( + idx + for idx, layer in enumerate(layers) + if layer["path"].is_relative_to(owner_dir) + ) + composed = resolver.resolve_content( + cmd_name, "command", layers=layers[owner_idx:] + ) + if composed is None: + # Nothing left under the owner to compose onto. + self._remove_owned_skills(skills_dir, names) + else: + overrides[cmd_name] = composed + if not overrides: + continue + written = self._register_skills( + self._FilteredManifest(manifest, set(overrides)), + owner_dir, + target_dir=skills_dir, + target_agent=agent or "", + only_skill_names={ + name + for cmd_name in overrides + for name in owned[cmd_name] + }, + content_overrides=overrides, + ) + if target_agent is None or agent == target_agent: + written_names = {n for names in written.values() for n in names} + reconciled_skill_commands.update( + cmd_name + for cmd_name, names in owned.items() + if written_names.intersection(names) + ) + self._reconcile_preset_aliases( command_names, presets_by_priority, @@ -638,20 +707,21 @@ def _surviving_owned_skills( presets_by_priority: List[Any], active_ai: Optional[str], active_skills_dir: Optional[Path], - ) -> Dict[Path, tuple[Optional[str], List[str]]]: + ) -> List[tuple[Path, Optional[str], str, str, str]]: """Recorded skill destinations of ``command_names`` still owned by a survivor. Reads each remaining preset's ``registered_skills`` (inferring per-agent provenance for legacy flat lists) and keeps the names whose ``SKILL.md`` - still carries that preset's ``preset:`` marker. + still carries that preset's ``preset:`` marker, as + ``(skills_dir, agent, owner_id, command_name, skill_name)`` tuples. """ registrar = self._command_registrar() affected = { - name + name: cmd_name for cmd_name in command_names for name in self._skill_names_for_command(cmd_name) } - found: Dict[Path, tuple[Optional[str], List[str]]] = {} + found: List[tuple[Path, Optional[str], str, str, str]] = [] for pack_id, meta in presets_by_priority: if not isinstance(meta, dict): continue @@ -686,8 +756,7 @@ def _surviving_owned_skills( continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}": - dir_agent, dir_names = found.get(skills_dir, (agent, [])) - found[skills_dir] = (dir_agent, [*dir_names, name]) + found.append((skills_dir, agent, pack_id, affected[name], name)) return found def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None: @@ -932,6 +1001,7 @@ def _register_skills( target_dir: Optional[Path] = None, target_agent: Optional[str] = None, only_skill_names: Optional[Set[str]] = None, + content_overrides: Optional[Dict[str, str]] = None, ) -> Dict[str, List[str]]: """Generate SKILL.md files for preset command overrides. @@ -960,6 +1030,9 @@ def _register_skills( 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. + content_overrides: ``{command_name: content}`` to render instead + of the preset's command file or ``.composed`` cache, for a + composition that has already been resolved by the caller. Returns: ``{agent_name: [skill_name, ...]}`` for the single active @@ -1053,7 +1126,11 @@ def _register_skills( continue # Parse the command file - content = source_file.read_text(encoding="utf-8") + override = (content_overrides or {}).get(cmd_name) + content = ( + override if override is not None + else source_file.read_text(encoding="utf-8") + ) frontmatter, body = registrar.parse_frontmatter(content) # A composition-strategy command (wrap/prepend/append) needs a @@ -1076,7 +1153,8 @@ def _register_skills( # while its composer was disabled), so the resolver decides even # when the cache exists. if ( - effective_strategy != "replace" + override is None + and effective_strategy != "replace" and resolver.resolve_content(cmd_name, "command") is None ): continue diff --git a/src/specify_cli/presets/_resolver.py b/src/specify_cli/presets/_resolver.py index ea1c4e03f9..22c2499719 100644 --- a/src/specify_cli/presets/_resolver.py +++ b/src/specify_cli/presets/_resolver.py @@ -736,6 +736,8 @@ def resolve_content( self, template_name: str, template_type: str = "template", + *, + layers: Optional[List[Dict[str, Any]]] = None, ) -> Optional[str]: """Resolve a template name and return composed content. @@ -751,11 +753,15 @@ def resolve_content( Args: template_name: Template name (e.g., "spec-template") template_type: Template type ("template", "command", or "script") + layers: Compose this slice of the stack (highest priority first, + as returned by :meth:`collect_all_layers`) instead of the + whole stack, e.g. one preset's layer and everything below it. Returns: Composed content string, or None if not found """ - layers = self.collect_all_layers(template_name, template_type) + if layers is None: + layers = self.collect_all_layers(template_name, template_type) if not layers: return None diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 15207383c2..a498a443b1 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2255,11 +2255,43 @@ def install(preset_id, body, strategy, priority): content = claude_skill.read_text(encoding="utf-8") assert "Base preset body" not in content assert "Core custom body" in content and "Middle body" in content + # top-preset was never registered under Claude. + assert "Top body" not in content + assert "preset:middle-preset" in content else: with pytest.warns(UserWarning, match="no base layer"): assert manager.remove("base-preset") is True assert not claude_skill.exists() + def test_remove_shadowed_base_leaves_replace_survivor_in_historical_dir( + self, project_dir, temp_dir + ): + """``middle`` replaces ``base`` in Claude's skill; ``top`` is installed + later under Codex only. Removing the shadowed base must not touch + Claude's skill, and must not render ``top`` into it.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + + def install(preset_id, body, priority): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + + install("base-preset", "Base preset body", 10) + install("middle-preset", "Middle body", 7) + before = claude_skill.read_text(encoding="utf-8") + assert "preset:middle-preset" in before + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", 5) + + assert manager.remove("base-preset") is True + + assert claude_skill.read_text(encoding="utf-8") == before + def test_remove_base_reconciles_survivor_with_legacy_flat_skill_record( self, project_dir, temp_dir ): From d44bee08b332f9720c33c2f1f479c4b4717d884d Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:05:06 +0530 Subject: [PATCH 12/41] fix(presets): keep a lower survivor's skill when its base is unreadable resolve_content() also returns None when a surviving layer cannot be read, so retire the owned skill only when the owner's layer slice has no replace base left. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 11 +++--- .../presets/test_manager_skills.py | 36 +++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 6627dd67e5..b5bdc6a452 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -490,14 +490,17 @@ def apply_to_dir( for idx, layer in enumerate(layers) if layer["path"].is_relative_to(owner_dir) ) + owner_layers = layers[owner_idx:] composed = resolver.resolve_content( - cmd_name, "command", layers=layers[owner_idx:] + cmd_name, "command", layers=owner_layers ) - if composed is None: + if composed is not None: + overrides[cmd_name] = composed + elif all(layer["strategy"] != "replace" for layer in owner_layers): # Nothing left under the owner to compose onto. self._remove_owned_skills(skills_dir, names) - else: - overrides[cmd_name] = composed + # Otherwise a surviving layer is unreadable: keep the + # existing output rather than deleting it. if not overrides: continue written = self._register_skills( diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index a498a443b1..4fda5b7285 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2292,6 +2292,42 @@ def install(preset_id, body, priority): assert claude_skill.read_text(encoding="utf-8") == before + def test_remove_base_keeps_lower_survivor_skill_when_core_base_is_unreadable( + self, project_dir, temp_dir + ): + """The core base under ``middle`` exists but is not UTF-8, so its + composition fails. That is not "no base left": Claude's skill, owned by + ``middle``, must be kept rather than deleted.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_bytes(b"---\ndescription: x\n---\n\n\xff\xfe\n") + manager = PresetManager(project_dir) + + def install(preset_id, body, strategy, priority): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + 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) + + install("base-preset", "Base preset body", "replace", 10) + install("middle-preset", "Middle body", "append", 7) + before = claude_skill.read_text(encoding="utf-8") + assert "preset:middle-preset" in before + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + + assert manager.remove("base-preset") is True + + assert claude_skill.read_text(encoding="utf-8") == before + def test_remove_base_reconciles_survivor_with_legacy_flat_skill_record( self, project_dir, temp_dir ): From 5f24cd362c879ea9da224cd1936ee72da2b6b911 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:05:06 +0530 Subject: [PATCH 13/41] fix(presets): refresh shadowed survivors' aliases from the owner's layer The removal pass rendered a historical alias only when its preset won the whole stack, so an alias owned by a lower composing survivor kept the removed base's body. Refresh it from the owner's layer down, as the primary skill already is, and retire it when that slice has no base. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 24 +++++++-- .../presets/test_manager_skills.py | 51 +++++++++++++++++++ 2 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index b5bdc6a452..a75f7e601a 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -669,13 +669,29 @@ def _reconcile_preset_aliases( primary = tmpl["name"] layers = resolver.collect_all_layers(primary, "command") - if not layers or not layers[0]["path"].is_relative_to(pack_dir): - # Another layer wins now; this alias is not ours to render. + owner_idx = next( + ( + idx + for idx, layer in enumerate(layers) + if layer["path"].is_relative_to(pack_dir) + ), + None, + ) + if owner_idx is None or ( + owner_idx > 0 and (missing or not removal_pass) + ): + # Another layer wins now; this alias is not ours to + # render. On a removal pass an existing alias of a + # shadowed preset is still refreshed from its own + # layer down, as its primary skill is. continue - composed = resolver.resolve_content(primary, "command") + owner_layers = layers[owner_idx:] + composed = resolver.resolve_content( + primary, "command", layers=owner_layers + ) if composed is None: if missing or any( - layer["strategy"] == "replace" for layer in layers + layer["strategy"] == "replace" for layer in owner_layers ): # A replace base is still there, so this is a # resolution failure (e.g. an unreadable layer), diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 4fda5b7285..7adb162415 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2292,6 +2292,57 @@ def install(preset_id, body, priority): assert claude_skill.read_text(encoding="utf-8") == before + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_reconciles_alias_owned_by_lower_survivor_in_historical_dir( + self, project_dir, temp_dir, core + ): + """Like the primary skill, Claude's alias skill rendered by ``middle`` + must drop the removed base's body even though ``top`` (Codex only) + now wins, and must not pick up ``top``'s body.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + skills = project_dir / ".claude" / "skills" + self._create_skill(skills, "speckit-custom") + alias_file = self._alias_skill(project_dir) + if core: + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + def install(preset_id, body, strategy, priority): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + if strategy != "replace": + manifest["provides"]["templates"][0]["aliases"] = [self._ALIAS] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + + install("base-preset", "Base preset body", "replace", 10) + install("middle-preset", "Middle body", "append", 7) + assert "Base preset body" in alias_file.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + + if core: + assert manager.remove("base-preset") is True + content = alias_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + assert "Top body" not in content + assert "middle-preset:" in content + else: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not alias_file.exists() + def test_remove_base_keeps_lower_survivor_skill_when_core_base_is_unreadable( self, project_dir, temp_dir ): From 25979c78b3042497775cc064d1f7d1786baadad5 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:12:18 +0000 Subject: [PATCH 14/41] fix(presets): validate the composed cache path before refreshing an alias Run the shared_infra directory and destination guards on the .composed cache before writing a historical alias refresh, so a symlinked .composed directory or cache file cannot redirect the write outside the project. Skip the alias when the path is unsafe. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 20 ++++++- .../presets/test_manager_skills.py | 56 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index a75f7e601a..21f375ef64 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -568,6 +568,10 @@ def _reconcile_preset_aliases( recorded, mirroring stale-output retirement. """ from ..integrations._file_changes import after_file_change, before_file_change + from ..shared_infra import ( + _ensure_safe_shared_destination, + _ensure_safe_shared_directory, + ) try: registrar = self._command_registrar() @@ -709,7 +713,21 @@ def _reconcile_preset_aliases( ): continue composed_file = pack_dir / ".composed" / f"{primary}.md" - composed_file.parent.mkdir(parents=True, exist_ok=True) + try: + # Every ancestor and the cache file itself must stay + # inside the project and off symlinks, so a planted + # ``.composed`` link cannot redirect this write. + _ensure_safe_shared_directory( + self.project_root, + composed_file.parent, + create=True, + context="preset composed cache directory", + ) + _ensure_safe_shared_destination( + self.project_root, composed_file + ) + except (ValueError, OSError): + continue _write_text(composed_file, composed, encoding="utf-8") registrar.register_commands( agent, diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 7adb162415..6d14f5150a 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2343,6 +2343,62 @@ def install(preset_id, body, strategy, priority): assert manager.remove("base-preset") is True assert not alias_file.exists() + @pytest.mark.parametrize("link", ["cache-file", "cache-dir"]) + def test_historical_alias_refresh_does_not_write_through_symlinked_cache( + self, project_dir, temp_dir, link + ): + """Refreshing a shadowed survivor's historical alias writes its + ``.composed`` cache; a symlinked cache directory or file must not + redirect that write outside the project.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + def install(preset_id, body, strategy, priority): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + if strategy != "replace": + manifest["provides"]["templates"][0]["aliases"] = [self._ALIAS] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + + install("base-preset", "Base preset body", "replace", 10) + install("middle-preset", "Middle body", "append", 7) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + + outside = temp_dir / "outside" + outside.mkdir() + target = outside / "speckit.custom.md" + target.write_text("external\n", encoding="utf-8") + cache_dir = manager.presets_dir / "middle-preset" / ".composed" + if link == "cache-dir": + if cache_dir.exists(): + shutil.rmtree(cache_dir) + cache_dir.symlink_to(outside, target_is_directory=True) + else: + cache_dir.mkdir(exist_ok=True) + cache_file = cache_dir / "speckit.custom.md" + if cache_file.exists(): + cache_file.unlink() + cache_file.symlink_to(target) + + assert manager.remove("base-preset") is True + + assert target.read_text(encoding="utf-8") == "external\n" + assert sorted(p.name for p in outside.iterdir()) == ["speckit.custom.md"] + def test_remove_base_keeps_lower_survivor_skill_when_core_base_is_unreadable( self, project_dir, temp_dir ): From cd5296a78d4cc305624d4327490956d7a58d6830 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:12:44 +0000 Subject: [PATCH 15/41] fix(presets): keep survivor aliases and retire baseless shadowed ones Address three review findings in native-skill alias reconciliation: - Write the .composed cache with the atomic, journaled shared-infra writer, so a hard link to a file outside the project is replaced rather than written through. - When the removed preset and a survivor declare the same alias, leave the survivor-owned file out of the removed preset's cleanup so reconciliation recomposes it instead of losing it. - Let a shadowed composer's alias reach the retirement check, so a rescaffold cannot leave a baseless raw fragment executable. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager.py | 4 + src/specify_cli/presets/_manager_skills.py | 95 ++++++++++++--- .../presets/test_manager_skills.py | 108 ++++++++++++++++++ 3 files changed, 189 insertions(+), 18 deletions(-) diff --git a/src/specify_cli/presets/_manager.py b/src/specify_cli/presets/_manager.py index 963bb5c640..09eec18ba4 100644 --- a/src/specify_cli/presets/_manager.py +++ b/src/specify_cli/presets/_manager.py @@ -891,6 +891,10 @@ def remove(self, pack_id: str) -> bool: registered_commands = commands_to_unregister # Unregister non-skill command files from AI agents. + if registered_commands: + registered_commands = self._drop_survivor_owned_aliases( + pack_id, registered_commands + ) if registered_commands: self._unregister_commands(registered_commands) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 21f375ef64..86c548ced8 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -14,7 +14,6 @@ from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter from ..integrations.base import IntegrationBase -from ..integrations._file_changes import write_text as _write_text from ..integrations._registration import project_registration from ._manager_commands import _substitute_core_template from ._manifest import PresetManifest, PresetValidationError @@ -568,10 +567,7 @@ def _reconcile_preset_aliases( recorded, mirroring stale-output retirement. """ from ..integrations._file_changes import after_file_change, before_file_change - from ..shared_infra import ( - _ensure_safe_shared_destination, - _ensure_safe_shared_directory, - ) + from ..shared_infra import _ensure_safe_shared_directory, _write_shared_text try: registrar = self._command_registrar() @@ -681,14 +677,16 @@ def _reconcile_preset_aliases( ), None, ) - if owner_idx is None or ( - owner_idx > 0 and (missing or not removal_pass) - ): - # Another layer wins now; this alias is not ours to - # render. On a removal pass an existing alias of a - # shadowed preset is still refreshed from its own - # layer down, as its primary skill is. + if owner_idx is None or (owner_idx > 0 and missing): continue + # Another layer wins now, so outside a removal pass this + # alias is not ours to render. It still goes through the + # retirement check below: a rescaffold re-registers it + # from the raw fragment, which must not stay executable + # once nothing is left to compose onto. On a removal pass + # an existing shadowed alias is refreshed from its own + # layer down, as its primary skill is. + shadowed = owner_idx > 0 and not removal_pass owner_layers = layers[owner_idx:] composed = resolver.resolve_content( primary, "command", layers=owner_layers @@ -706,7 +704,7 @@ def _reconcile_preset_aliases( shutil.rmtree(skill_dir) after_file_change(skill_dir) continue - if not may_render: + if shadowed or not may_render: continue if missing and not self._validate_skill_subdir( skill_dir, create=True, skills_root=skills_dir @@ -716,19 +714,19 @@ def _reconcile_preset_aliases( try: # Every ancestor and the cache file itself must stay # inside the project and off symlinks, so a planted - # ``.composed`` link cannot redirect this write. + # ``.composed`` link cannot redirect this write. The + # entry is replaced atomically rather than written in + # place, so a hard link to an outside file is broken, + # not written through. _ensure_safe_shared_directory( self.project_root, composed_file.parent, create=True, context="preset composed cache directory", ) - _ensure_safe_shared_destination( - self.project_root, composed_file - ) + _write_shared_text(self.project_root, composed_file, composed) except (ValueError, OSError): continue - _write_text(composed_file, composed, encoding="utf-8") registrar.register_commands( agent, [{"name": alias, "file": f".composed/{primary}.md"}], @@ -738,6 +736,67 @@ def _reconcile_preset_aliases( _resolved_dir=skills_dir, ) + def _drop_survivor_owned_aliases( + self, pack_id: str, registered_commands: Dict[str, List[str]] + ) -> Dict[str, List[str]]: + """Leave out native-skill outputs another installed preset now owns. + + Two presets can declare the same command alias. For native skill + agents both record it in ``registered_commands``, but only one file + exists, carrying the ``:`` marker of whichever registered + it last. Deleting it with the preset being removed would drop a + survivor's alias that post-removal reconciliation (which does not + create missing outputs on a removal pass) cannot bring back, so keep + those names out of the unregister list and let reconciliation + recompose them. + """ + try: + registrar = self._command_registrar() + except ImportError: + return registered_commands + registrar._ensure_configs() + survivors = [pid for pid in self.registry.list() if pid != pack_id] + if not survivors: + return registered_commands + result: Dict[str, List[str]] = {} + for agent, names in registered_commands.items(): + agent_config = registrar.AGENT_CONFIGS.get(agent) + if ( + not isinstance(names, list) + or not agent_config + or agent_config.get("extension") != "/SKILL.md" + ): + result[agent] = names + continue + skills_dir = self._safe_skills_dir_for_agent(agent) + kept: List[str] = [] + for name in names: + if skills_dir is not None and isinstance(name, str): + skill_dir = skills_dir / registrar._compute_output_name( + agent, name, agent_config + ) + skill_file = skill_dir / "SKILL.md" + source = None + if self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ) and skill_file.is_file(): + try: + metadata = registrar.parse_frontmatter( + skill_file.read_text(encoding="utf-8") + )[0].get("metadata") + except (OSError, UnicodeDecodeError): + metadata = None + if isinstance(metadata, dict): + source = metadata.get("source") + if isinstance(source, str) and any( + source.startswith(f"{other}:") for other in survivors + ): + continue + kept.append(name) + if kept: + result[agent] = kept + return result + def _surviving_owned_skills( self, command_names: List[str], diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 6d14f5150a..77631511f5 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1,5 +1,7 @@ """Tests for preset skill artifacts in specify_cli.presets._manager_skills.""" +import functools +import os import shutil from pathlib import Path @@ -2399,6 +2401,112 @@ def install(preset_id, body, strategy, priority): assert target.read_text(encoding="utf-8") == "external\n" assert sorted(p.name for p in outside.iterdir()) == ["speckit.custom.md"] + def _install_alias_layer( + self, manager, temp_dir, preset_id, body, strategy, priority, *, alias=True + ): + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + if alias: + manifest["provides"]["templates"][0]["aliases"] = [self._ALIAS] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + + def _write_core_custom(self, project_dir): + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + + def test_historical_alias_refresh_does_not_write_through_hardlinked_cache( + self, project_dir, temp_dir + ): + """A ``.composed`` cache file hard-linked to a file outside the project + passes the symlink and containment checks; the refresh must replace + the entry rather than write through the shared inode.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + + outside = temp_dir / "outside" + outside.mkdir() + target = outside / "speckit.custom.md" + target.write_text("external\n", encoding="utf-8") + cache_dir = manager.presets_dir / "middle-preset" / ".composed" + cache_dir.mkdir(exist_ok=True) + cache_file = cache_dir / "speckit.custom.md" + cache_file.unlink(missing_ok=True) + try: + os.link(target, cache_file) + except OSError as exc: # pragma: no cover - filesystem without hard links + pytest.skip(f"hard links unsupported: {exc}") + + assert manager.remove("base-preset") is True + + assert target.read_text(encoding="utf-8") == "external\n" + assert "Core custom body" in self._alias_skill(project_dir).read_text( + encoding="utf-8" + ) + + def test_remove_base_keeps_survivor_alias_both_layers_declare( + self, project_dir, temp_dir + ): + """When the removed base and the surviving composer declare the same + alias, the file on disk is the composer's; removing the base must not + delete it while the core fallback keeps the command composable.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + alias_file = self._alias_skill(project_dir) + assert "source: append-preset:" in alias_file.read_text(encoding="utf-8") + + assert manager.remove("base-preset") is True + + content = alias_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + assert "source: append-preset:" in content + manager.register_enabled_presets_for_agent("claude") + assert alias_file.read_text(encoding="utf-8") == content + + def test_baseless_lower_composer_alias_stays_retired_after_rescaffold( + self, project_dir, temp_dir + ): + """With two composers and no base left, a rescaffold re-registers the + lower composer's alias from its raw fragment; reconciliation must + retire it again rather than skip it because another layer wins.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + install("top-preset", "Top body", "append", 5, alias=False) + alias_file = self._alias_skill(project_dir) + assert alias_file.is_file() + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + manager.register_enabled_presets_for_agent("claude") + + assert not alias_file.parent.exists() + def test_remove_base_keeps_lower_survivor_skill_when_core_base_is_unreadable( self, project_dir, temp_dir ): From 50c62a0a280dd1688a24471c2fc4243e07c278fe Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 5 Nov 2026 23:19:03 +0530 Subject: [PATCH 16/41] fix(presets): replace alias output instead of writing it in place An alias SKILL.md hard-linked to a file outside the project passes the ownership checks, and the registrar then wrote the recomposed text through the shared inode. Write a sibling temp file and rename it over the destination instead, for the direct write, the dev-mode cache file and the copy fallback; the file-change journaling is unchanged. The write-error tests that simulated a failing artifact write by patching Path.write_text now also patch the registrar helper, so the simulated failure still lands on the artifact write. --- src/specify_cli/agents.py | 26 ++++++++++++-- .../integrations/test_integration_generic.py | 25 +++++++++++++- .../presets/test_manager_skills.py | 34 +++++++++++++++++++ tests/test_extensions.py | 12 ++++--- 4 files changed, 89 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index 72966998a5..7d5d2d2d17 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -9,6 +9,7 @@ import hashlib import os import re +import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, Iterable, List, Optional @@ -1016,6 +1017,25 @@ def register_commands( return registered + @staticmethod + def _replace_file_text(dest: Path, content: str) -> None: + """Write ``content`` to ``dest`` by replacing its directory entry. + + An in-place write reaches every hard link of the file, so an alias + linked to a file outside the project would carry the new text there + too. Writing a sibling temp file and renaming it over ``dest`` only + changes what ``dest`` names. + """ + fd, temp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=dest.parent) + temp_path = Path(temp_name) + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + temp_path.chmod(0o644) + os.replace(temp_path, dest) + finally: + temp_path.unlink(missing_ok=True) + @staticmethod def _write_registered_output( dest_file: Path, @@ -1038,7 +1058,7 @@ def _write_registered_output( if not link_outputs or (agent_config or {}).get("dev_no_symlink"): if dest_file.is_symlink(): dest_file.unlink() - dest_file.write_text(content, encoding="utf-8") + CommandRegistrar._replace_file_text(dest_file, content) after_file_change(dest_file) return @@ -1050,7 +1070,7 @@ def _write_registered_output( try: before_file_change(cache_file) cache_file.parent.mkdir(parents=True, exist_ok=True) - cache_file.write_text(content, encoding="utf-8") + CommandRegistrar._replace_file_text(cache_file, content) after_file_change(cache_file) if dest_file.exists() or dest_file.is_symlink(): dest_file.unlink() @@ -1062,7 +1082,7 @@ def _write_registered_output( # functional by falling back to a copy. if dest_file.is_symlink(): dest_file.unlink() - dest_file.write_text(content, encoding="utf-8") + CommandRegistrar._replace_file_text(dest_file, content) after_file_change(dest_file) @staticmethod diff --git a/tests/integrations/test_integration_generic.py b/tests/integrations/test_integration_generic.py index c2eabfcaa7..1e19ee26a0 100644 --- a/tests/integrations/test_integration_generic.py +++ b/tests/integrations/test_integration_generic.py @@ -11,6 +11,7 @@ import pytest import yaml +from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar from specify_cli.integrations import get_integration from specify_cli.integrations.base import MarkdownIntegration from specify_cli.integrations.manifest import IntegrationManifest @@ -876,16 +877,29 @@ def test_generic_refresh_write_error_restores_artifacts_and_registry( second.parent.rmdir() source = manager.extensions_dir / "sample/commands/run.md" source.write_text(source.read_text(encoding="utf-8") + "\nupdated source\n", encoding="utf-8") + # Skills-mode generic artifacts are written through Path.write_text; the + # command-file path replaces the entry via the registrar helper. original_write = Path.write_text + original_replace = AgentCommandRegistrar._replace_file_text - def fail_second_write(path, *args, **kwargs): + def fail_second(path): if path == second: if partial_second: original_write(path, "partial generated output", encoding="utf-8") raise OSError("simulated refresh write error") + + def fail_second_write(path, *args, **kwargs): + fail_second(path) return original_write(path, *args, **kwargs) + def fail_second_replace(path, content): + fail_second(path) + return original_replace(path, content) + monkeypatch.setattr(Path, "write_text", fail_second_write) + monkeypatch.setattr( + AgentCommandRegistrar, "_replace_file_text", staticmethod(fail_second_replace) + ) manager.register_enabled_extensions_for_agent("generic", force=skills) monkeypatch.undo() @@ -1105,13 +1119,22 @@ def test_generic_registration_write_error_rolls_back_partial_install( "speckit-sample-other/SKILL.md" if skills else "speckit.sample.other.md" ) original_write = Path.write_text + original_replace = AgentCommandRegistrar._replace_file_text def fail_second_write(path, *args, **kwargs): if path == second: raise OSError("simulated artifact write error") return original_write(path, *args, **kwargs) + def fail_second_replace(path, content): + if path == second: + raise OSError("simulated artifact write error") + return original_replace(path, content) + monkeypatch.setattr(Path, "write_text", fail_second_write) + monkeypatch.setattr( + AgentCommandRegistrar, "_replace_file_text", staticmethod(fail_second_replace) + ) with pytest.raises(OSError, match="simulated artifact write error"): manager.install_from_directory(generic_extension, "1.0.0") monkeypatch.undo() diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 77631511f5..997cf4774d 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2460,6 +2460,40 @@ def test_historical_alias_refresh_does_not_write_through_hardlinked_cache( encoding="utf-8" ) + def test_alias_refresh_does_not_write_through_hardlinked_skill( + self, project_dir, temp_dir + ): + """An alias ``SKILL.md`` hard-linked to a file outside the project + carries the preset's own source marker, so the ownership checks pass; + the refresh on removal must replace the directory entry rather than + write through the shared inode.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + alias_file = self._alias_skill(project_dir) + before = alias_file.read_text(encoding="utf-8") + assert "Base preset body" in before + + outside = temp_dir / "outside" + outside.mkdir() + target = outside / "SKILL.md" + try: + os.link(alias_file, target) + except OSError as exc: # pragma: no cover - filesystem without hard links + pytest.skip(f"hard links unsupported: {exc}") + + assert manager.remove("base-preset") is True + + assert target.read_text(encoding="utf-8") == before + after = alias_file.read_text(encoding="utf-8") + assert "Base preset body" not in after + assert "Core custom body" in after and "Appended body" in after + assert alias_file.stat().st_nlink == 1 + def test_remove_base_keeps_survivor_alias_both_layers_declare( self, project_dir, temp_dir ): diff --git a/tests/test_extensions.py b/tests/test_extensions.py index b512742389..81d5eb4c45 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -4760,14 +4760,18 @@ def test_dev_register_commands_falls_back_to_copy_when_cache_write_fails( """Dev-mode registration stays functional when the dev cache is unwritable.""" agents_dir = project_dir / ".github" / "agents" agents_dir.mkdir(parents=True) - original_write_text = Path.write_text + from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar + + original_write = AgentCommandRegistrar._replace_file_text - def raise_cache_write_error(path, *args, **kwargs): + def raise_cache_write_error(path, content): if ".specify-dev" in path.parts: raise OSError("cache is not writable") - return original_write_text(path, *args, **kwargs) + return original_write(path, content) - monkeypatch.setattr(Path, "write_text", raise_cache_write_error) + monkeypatch.setattr( + AgentCommandRegistrar, "_replace_file_text", staticmethod(raise_cache_write_error) + ) manifest = ExtensionManifest(extension_dir / "extension.yml") registrar = CommandRegistrar() From f956449c7714d5f7f121ed3a4b20c5d31be2734a Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:17:10 +0000 Subject: [PATCH 17/41] fix(agents): keep output permissions when replacing a registered file The atomic replace in _replace_file_text set every temp file to 0644 before renaming it over the destination, so a private (0600) command or skill output became world-readable on refresh and new outputs ignored a restrictive umask. Keep an existing regular file's mode, and give a new file 0666 under the process umask, as an in-place write would. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/agents.py | 18 +++++++- .../presets/test_manager_skills.py | 41 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index 7d5d2d2d17..b1d29e6b98 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -9,6 +9,7 @@ import hashlib import os import re +import stat import tempfile from copy import deepcopy from pathlib import Path @@ -1025,13 +1026,28 @@ def _replace_file_text(dest: Path, content: str) -> None: linked to a file outside the project would carry the new text there too. Writing a sibling temp file and renaming it over ``dest`` only changes what ``dest`` names. + + The replacement keeps an existing file's permission bits, and a new + file gets the default creation mode under the process umask, the + same as an in-place write would leave them. """ + try: + dest_stat = os.lstat(dest) + except FileNotFoundError: + dest_stat = None + if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode): + mode = stat.S_IMODE(dest_stat.st_mode) + else: + # ``os.umask`` has no read-only form; set and restore it at once. + umask = os.umask(0) + os.umask(umask) + mode = 0o666 & ~umask fd, temp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=dest.parent) temp_path = Path(temp_name) try: with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(content) - temp_path.chmod(0o644) + temp_path.chmod(mode) os.replace(temp_path, dest) finally: temp_path.unlink(missing_ok=True) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 997cf4774d..55d616660c 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3,6 +3,7 @@ import functools import os import shutil +import stat from pathlib import Path import pytest @@ -2460,6 +2461,46 @@ def test_historical_alias_refresh_does_not_write_through_hardlinked_cache( encoding="utf-8" ) + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_alias_refresh_preserves_existing_output_mode( + self, project_dir, temp_dir + ): + """Replacing the alias entry must keep a private (0600) output private + rather than resetting it to a fixed world-readable mode.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + alias_file = self._alias_skill(project_dir) + alias_file.chmod(0o600) + + assert manager.remove("base-preset") is True + + assert "Core custom body" in alias_file.read_text(encoding="utf-8") + assert stat.S_IMODE(alias_file.stat().st_mode) == 0o600 + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_new_alias_output_honors_umask(self, project_dir, temp_dir): + """A newly created alias output gets the default creation mode under + the process umask, as an ordinary file write would.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + old_umask = os.umask(0o077) + try: + install("append-preset", "Appended body", "append", 5) + finally: + os.umask(old_umask) + + alias_file = self._alias_skill(project_dir) + assert "Appended body" in alias_file.read_text(encoding="utf-8") + assert stat.S_IMODE(alias_file.stat().st_mode) == 0o600 + def test_alias_refresh_does_not_write_through_hardlinked_skill( self, project_dir, temp_dir ): From 586db130b60f57e8d2270c9458f004be9538aade Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:18:30 +0000 Subject: [PATCH 18/41] fix(presets): key alias ownership on its declarer; keep modes without umask Address four review findings: - _replace_file_text no longer reads the umask by setting it to 0. It creates the temp file with mode 0666 so the kernel applies the umask, and restores an existing file's own bits. - The temp name is a fixed short .speckit-.tmp, so a destination name near the filesystem limit stays writable. - The .composed cache refresh goes through the path guards, journaling and _replace_file_text, so an existing cache keeps its mode. - An alias belongs to the highest layer that declares it, not to the primary command's winning layer, so a lower declarer recomposes it on rescaffold and restores it when a new base arrives. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/agents.py | 45 +++++++---- src/specify_cli/presets/_manager_skills.py | 63 +++++++++++++--- .../presets/test_manager_skills.py | 74 +++++++++++++++++++ .../test_agents_replace_file_text.py | 46 ++++++++++++ 4 files changed, 203 insertions(+), 25 deletions(-) create mode 100644 tests/specify_cli/test_agents_replace_file_text.py diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index b1d29e6b98..5c1adf6e0a 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -9,8 +9,8 @@ import hashlib import os import re +import secrets import stat -import tempfile from copy import deepcopy from pathlib import Path from typing import Any, Dict, Iterable, List, Optional @@ -1027,27 +1027,46 @@ def _replace_file_text(dest: Path, content: str) -> None: too. Writing a sibling temp file and renaming it over ``dest`` only changes what ``dest`` names. - The replacement keeps an existing file's permission bits, and a new - file gets the default creation mode under the process umask, the - same as an in-place write would leave them. + The replacement keeps an existing file's permission bits. A new file + is created with mode 0666 so the kernel applies the process umask, + the same as an in-place write; the umask itself is never changed. + The temp name has a fixed short length, so any name valid for + ``dest`` stays writable. """ try: dest_stat = os.lstat(dest) except FileNotFoundError: dest_stat = None - if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode): - mode = stat.S_IMODE(dest_stat.st_mode) + keep_mode = ( + stat.S_IMODE(dest_stat.st_mode) + if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode) + else None + ) + # O_BINARY (Windows) leaves newline translation to the text wrapper + # below, as ``tempfile.mkstemp`` and ``Path.write_text`` do. + flags = ( + os.O_WRONLY + | os.O_CREAT + | os.O_EXCL + | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_BINARY", 0) + ) + for _attempt in range(100): + temp_path = dest.parent / f".speckit-{secrets.token_hex(8)}.tmp" + try: + fd = os.open(temp_path, flags, 0o666) + except FileExistsError: + continue + break else: - # ``os.umask`` has no read-only form; set and restore it at once. - umask = os.umask(0) - os.umask(umask) - mode = 0o666 & ~umask - fd, temp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=dest.parent) - temp_path = Path(temp_name) + raise FileExistsError( + f"Could not create a temporary file next to {dest}" + ) try: with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(content) - temp_path.chmod(mode) + if keep_mode is not None: + os.chmod(temp_path, keep_mode) os.replace(temp_path, dest) finally: temp_path.unlink(missing_ok=True) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 86c548ced8..d42d654771 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -567,7 +567,10 @@ def _reconcile_preset_aliases( recorded, mirroring stale-output retirement. """ from ..integrations._file_changes import after_file_change, before_file_change - from ..shared_infra import _ensure_safe_shared_directory, _write_shared_text + from ..shared_infra import ( + _ensure_safe_shared_destination, + _ensure_safe_shared_directory, + ) try: registrar = self._command_registrar() @@ -677,16 +680,26 @@ def _reconcile_preset_aliases( ), None, ) - if owner_idx is None or (owner_idx > 0 and missing): + if owner_idx is None: continue - # Another layer wins now, so outside a removal pass this - # alias is not ours to render. It still goes through the - # retirement check below: a rescaffold re-registers it - # from the raw fragment, which must not stay executable - # once nothing is left to compose onto. On a removal pass - # an existing shadowed alias is refreshed from its own - # layer down, as its primary skill is. - shadowed = owner_idx > 0 and not removal_pass + # The alias belongs to the highest layer that declares + # it, not to whichever layer wins the primary command: a + # higher preset that does not declare this alias leaves + # it to us. Only a higher declarer shadows it. + alias_shadowed = any( + self._layer_declares_alias(resolver, layer, primary, alias) + for layer in layers[:owner_idx] + ) + if alias_shadowed and missing: + continue + # A shadowed alias is not ours to render outside a + # removal pass. It still goes through the retirement + # check below: a rescaffold re-registers it from the raw + # fragment, which must not stay executable once nothing + # is left to compose onto. On a removal pass an existing + # shadowed alias is refreshed from its own layer down, as + # its primary skill is. + shadowed = alias_shadowed and not removal_pass owner_layers = layers[owner_idx:] composed = resolver.resolve_content( primary, "command", layers=owner_layers @@ -717,14 +730,20 @@ def _reconcile_preset_aliases( # ``.composed`` link cannot redirect this write. The # entry is replaced atomically rather than written in # place, so a hard link to an outside file is broken, - # not written through. + # not written through, and an existing cache keeps + # its permission bits. _ensure_safe_shared_directory( self.project_root, composed_file.parent, create=True, context="preset composed cache directory", ) - _write_shared_text(self.project_root, composed_file, composed) + _ensure_safe_shared_destination( + self.project_root, composed_file + ) + before_file_change(composed_file) + registrar._replace_file_text(composed_file, composed) + after_file_change(composed_file) except (ValueError, OSError): continue registrar.register_commands( @@ -736,6 +755,26 @@ def _reconcile_preset_aliases( _resolved_dir=skills_dir, ) + def _layer_declares_alias( + self, resolver: Any, layer: Dict[str, Any], primary: str, alias: str + ) -> bool: + """Whether ``layer`` comes from a preset declaring ``alias`` for ``primary``.""" + try: + rel = layer["path"].relative_to(self.presets_dir) + except (KeyError, TypeError, ValueError): + return False + if not rel.parts: + return False + manifest = resolver._get_manifest(self.presets_dir / rel.parts[0]) + if not manifest: + return False + return any( + tmpl.get("type") == "command" + and tmpl.get("name") == primary + and alias in (tmpl.get("aliases") or []) + for tmpl in manifest.templates + ) + def _drop_survivor_owned_aliases( self, pack_id: str, registered_commands: Dict[str, List[str]] ) -> Dict[str, List[str]]: diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 55d616660c..9c7cd564e0 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2501,6 +2501,80 @@ def test_new_alias_output_honors_umask(self, project_dir, temp_dir): assert "Appended body" in alias_file.read_text(encoding="utf-8") assert stat.S_IMODE(alias_file.stat().st_mode) == 0o600 + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_historical_alias_refresh_preserves_cache_mode( + self, project_dir, temp_dir + ): + """Refreshing a shadowed survivor's ``.composed`` cache keeps a private + (0600) cache file private.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + cache_file = ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" + ) + cache_file.parent.mkdir(exist_ok=True) + cache_file.write_text("stale\n", encoding="utf-8") + cache_file.chmod(0o600) + + assert manager.remove("base-preset") is True + + assert "Core custom body" in cache_file.read_text(encoding="utf-8") + assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 + + def test_rescaffold_recomposes_alias_declared_only_by_lower_preset( + self, project_dir, temp_dir + ): + """``top`` wins the primary command but does not declare the alias, so + ``middle`` still owns it: a rescaffold must recompose it onto the base + instead of leaving the raw fragment it re-registers.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + install("top-preset", "Top body", "append", 5, alias=False) + alias_file = self._alias_skill(project_dir) + + manager.register_enabled_presets_for_agent("claude") + + content = alias_file.read_text(encoding="utf-8") + assert "Base preset body" in content and "Middle body" in content + assert "Top body" not in content + assert "source: middle-preset:" in content + + def test_new_base_restores_alias_declared_only_by_lower_preset( + self, project_dir, temp_dir + ): + """An alias retired with its base comes back when a new base arrives, + even though a higher preset (which does not declare the alias) wins + the primary command.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + install("top-preset", "Top body", "append", 5, alias=False) + alias_file = self._alias_skill(project_dir) + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not alias_file.parent.exists() + + install("new-base", "New base body", "replace", 10, alias=False) + + content = alias_file.read_text(encoding="utf-8") + assert "New base body" in content and "Middle body" in content + assert "Top body" not in content + def test_alias_refresh_does_not_write_through_hardlinked_skill( self, project_dir, temp_dir ): diff --git a/tests/specify_cli/test_agents_replace_file_text.py b/tests/specify_cli/test_agents_replace_file_text.py new file mode 100644 index 0000000000..6a45ffa179 --- /dev/null +++ b/tests/specify_cli/test_agents_replace_file_text.py @@ -0,0 +1,46 @@ +"""Tests for ``CommandRegistrar._replace_file_text`` (atomic artifact writes).""" + +import os +import stat + +import pytest + +from specify_cli.agents import CommandRegistrar + + +def test_replace_keeps_long_valid_filename_writable(tmp_path): + """The temp entry must not be longer than the destination allows: a + 250-byte name is valid and an in-place write accepted it.""" + dest = tmp_path / ("a" * 247 + ".md") + dest.write_text("old\n", encoding="utf-8") + + CommandRegistrar._replace_file_text(dest, "new\n") + + assert dest.read_text(encoding="utf-8") == "new\n" + assert sorted(p.name for p in tmp_path.iterdir()) == [dest.name] + + +def test_replace_creates_long_valid_filename(tmp_path): + dest = tmp_path / ("b" * 247 + ".md") + + CommandRegistrar._replace_file_text(dest, "new\n") + + assert dest.read_text(encoding="utf-8") == "new\n" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") +def test_replace_does_not_touch_process_umask(tmp_path, monkeypatch): + """Reading the umask by setting it to 0 is process-wide and racy; a new + file must get the creation mode from the kernel instead.""" + old_umask = os.umask(0o027) + calls = [] + monkeypatch.setattr(os, "umask", lambda mask: calls.append(mask) or 0o027) + try: + dest = tmp_path / "new.md" + CommandRegistrar._replace_file_text(dest, "new\n") + finally: + monkeypatch.undo() + os.umask(old_umask) + + assert calls == [] + assert stat.S_IMODE(dest.stat().st_mode) == 0o640 From 53a373e03898e41b40f29a4e923b9d6c9d78c670 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:15:58 +0000 Subject: [PATCH 19/41] fix(agents): never expose replacement text through a wider temp file Replacing a 0600 file under a 022 umask created a 0644 temp file and wrote the new content before the final chmod restored the private mode. Create the temp file with the destination's own bits and set them before writing, so the content is never readable more widely than the destination. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/agents.py | 20 +++++++++----- .../test_agents_replace_file_text.py | 27 +++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index 5c1adf6e0a..fce93dd821 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -1027,9 +1027,12 @@ def _replace_file_text(dest: Path, content: str) -> None: too. Writing a sibling temp file and renaming it over ``dest`` only changes what ``dest`` names. - The replacement keeps an existing file's permission bits. A new file - is created with mode 0666 so the kernel applies the process umask, - the same as an in-place write; the umask itself is never changed. + The replacement keeps an existing file's permission bits, and the + temp file is created with (at most) those bits and set to them before + any content is written, so the new text is never readable more widely + than the destination. A new file is created with mode 0666 so the + kernel applies the process umask, the same as an in-place write; the + umask itself is never changed. The temp name has a fixed short length, so any name valid for ``dest`` stays writable. """ @@ -1054,7 +1057,9 @@ def _replace_file_text(dest: Path, content: str) -> None: for _attempt in range(100): temp_path = dest.parent / f".speckit-{secrets.token_hex(8)}.tmp" try: - fd = os.open(temp_path, flags, 0o666) + fd = os.open( + temp_path, flags, 0o666 if keep_mode is None else keep_mode + ) except FileExistsError: continue break @@ -1063,10 +1068,13 @@ def _replace_file_text(dest: Path, content: str) -> None: f"Could not create a temporary file next to {dest}" ) try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(content) if keep_mode is not None: + # The umask may have cleared some of the destination's bits; + # restore them before writing. This never widens the mode + # beyond the destination's own. os.chmod(temp_path, keep_mode) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) os.replace(temp_path, dest) finally: temp_path.unlink(missing_ok=True) diff --git a/tests/specify_cli/test_agents_replace_file_text.py b/tests/specify_cli/test_agents_replace_file_text.py index 6a45ffa179..3ede1f5517 100644 --- a/tests/specify_cli/test_agents_replace_file_text.py +++ b/tests/specify_cli/test_agents_replace_file_text.py @@ -44,3 +44,30 @@ def test_replace_does_not_touch_process_umask(tmp_path, monkeypatch): assert calls == [] assert stat.S_IMODE(dest.stat().st_mode) == 0o640 + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") +def test_replace_writes_private_content_only_into_private_temp(tmp_path, monkeypatch): + """Replacing a 0600 file under a 022 umask must not expose the new + content through a 0644 temp file before the final chmod.""" + dest = tmp_path / "private.md" + dest.write_text("old\n", encoding="utf-8") + dest.chmod(0o600) + modes_at_write = [] + real_fdopen = os.fdopen + + def recording_fdopen(fd, *args, **kwargs): + modes_at_write.append(stat.S_IMODE(os.fstat(fd).st_mode)) + return real_fdopen(fd, *args, **kwargs) + + old_umask = os.umask(0o022) + try: + monkeypatch.setattr(os, "fdopen", recording_fdopen) + CommandRegistrar._replace_file_text(dest, "secret\n") + finally: + monkeypatch.undo() + os.umask(old_umask) + + assert modes_at_write == [0o600] + assert dest.read_text(encoding="utf-8") == "secret\n" + assert stat.S_IMODE(dest.stat().st_mode) == 0o600 From a6a344fad4d3338af846e7554580b46e96979252 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 9 Nov 2026 01:39:56 +0530 Subject: [PATCH 20/41] fix(agents): close the temp descriptor when restoring its mode fails _replace_file_text restored the destination's permission bits on the temp file before wrapping the descriptor, so a failing os.chmod left the descriptor open; only the temp entry was removed. Registration catches write errors and continues, so the leak accumulated. Enter the file context first and restore the mode inside it, still before any content is written. Assisted-by: Claude Code (model: Claude Mythos 5.1, autonomous) --- src/specify_cli/agents.py | 12 ++++--- .../test_agents_replace_file_text.py | 31 +++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index fce93dd821..c57cff5836 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -1068,12 +1068,14 @@ def _replace_file_text(dest: Path, content: str) -> None: f"Could not create a temporary file next to {dest}" ) try: - if keep_mode is not None: - # The umask may have cleared some of the destination's bits; - # restore them before writing. This never widens the mode - # beyond the destination's own. - os.chmod(temp_path, keep_mode) + # Wrap the descriptor first so a failing ``chmod`` cannot leak it: + # registration catches write errors and carries on. with os.fdopen(fd, "w", encoding="utf-8") as fh: + if keep_mode is not None: + # The umask may have cleared some of the destination's + # bits; restore them before writing. This never widens + # the mode beyond the destination's own. + os.chmod(temp_path, keep_mode) fh.write(content) os.replace(temp_path, dest) finally: diff --git a/tests/specify_cli/test_agents_replace_file_text.py b/tests/specify_cli/test_agents_replace_file_text.py index 3ede1f5517..881c7039bb 100644 --- a/tests/specify_cli/test_agents_replace_file_text.py +++ b/tests/specify_cli/test_agents_replace_file_text.py @@ -71,3 +71,34 @@ def recording_fdopen(fd, *args, **kwargs): assert modes_at_write == [0o600] assert dest.read_text(encoding="utf-8") == "secret\n" assert stat.S_IMODE(dest.stat().st_mode) == 0o600 + + +def test_replace_closes_descriptor_when_chmod_fails(tmp_path, monkeypatch): + """A failing ``chmod`` must not leak the temp file's descriptor: callers + catch registration errors and continue, so a leak would accumulate.""" + dest = tmp_path / "owned.md" + dest.write_text("old\n", encoding="utf-8") + opened = [] + real_open = os.open + + def recording_open(path, *args, **kwargs): + fd = real_open(path, *args, **kwargs) + opened.append(fd) + return fd + + def failing_chmod(path, mode, *args, **kwargs): + raise PermissionError(f"chmod denied: {path}") + + monkeypatch.setattr(os, "open", recording_open) + monkeypatch.setattr(os, "chmod", failing_chmod) + try: + with pytest.raises(PermissionError): + CommandRegistrar._replace_file_text(dest, "new\n") + finally: + monkeypatch.undo() + + assert len(opened) == 1 + with pytest.raises(OSError): + os.fstat(opened[0]) + assert dest.read_text(encoding="utf-8") == "old\n" + assert sorted(p.name for p in tmp_path.iterdir()) == [dest.name] From daac3359213c26abf33d91ad4f1b7cb54a6fff2c Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:16:32 +0000 Subject: [PATCH 21/41] fix(presets): keep a refreshed SKILL.md's permission bits The skill writes in the preset skills manager went through _write_shared_text, which always set 0644, so recomposing or restoring a private (0600) SKILL.md on preset removal made it world-readable. Add an opt-in preserve_mode to _write_shared_text that keeps an existing regular file's bits (new files still get 0644) and use it for every SKILL.md write there. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 11 ++++-- src/specify_cli/shared_infra.py | 23 ++++++++++- .../presets/test_manager_skills.py | 39 +++++++++++++++++++ 3 files changed, 68 insertions(+), 5 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index d42d654771..5457cef863 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -312,6 +312,7 @@ def apply_to_dir( skills_dir, skill_subdir / "SKILL.md", skill_content, + preserve_mode=True, ) wrote_override = True if ( @@ -1348,7 +1349,7 @@ def _register_skills( skill_file = skill_subdir / "SKILL.md" _write_shared_text( - skills_dir, skill_file, skill_content + skills_dir, skill_file, skill_content, preserve_mode=True ) written.append(target_skill_name) self._merge_pack_registered_skills( @@ -2008,7 +2009,9 @@ def _unregister_skills_in_dir( skill_content = integration.post_process_skill_content( skill_content ) - _write_shared_text(skills_dir, skill_file, skill_content) + _write_shared_text( + skills_dir, skill_file, skill_content, preserve_mode=True + ) mutated_names.append(skill_name) continue @@ -2066,7 +2069,9 @@ def _unregister_skills_in_dir( skill_content = integration.post_process_skill_content( skill_content ) - _write_shared_text(skills_dir, skill_file, skill_content) + _write_shared_text( + skills_dir, skill_file, skill_content, preserve_mode=True + ) mutated_names.append(skill_name) else: # No core or extension template — remove the skill entirely diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index 134e329758..67ae5ddeb1 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -8,6 +8,7 @@ import logging import os import re +import stat import tempfile from pathlib import Path from typing import Any @@ -317,8 +318,26 @@ def _ensure_safe_shared_destination( raise ValueError(f"Shared infrastructure destination escapes project root: {label}") from None -def _write_shared_text(project_path: Path, dest: Path, content: str) -> None: - _write_shared_bytes(project_path, dest, content.encode("utf-8")) +def _write_shared_text( + project_path: Path, dest: Path, content: str, *, preserve_mode: bool = False +) -> None: + """Atomically write ``content`` to ``dest`` (see ``_write_shared_bytes``). + + With ``preserve_mode``, an existing regular file keeps its permission + bits instead of being reset to 0644, so refreshing a private output + does not widen it; a new file still gets 0644. The content is written + into a 0600 temp file, so it is never readable more widely than that + before the final mode is applied. + """ + mode = 0o644 + if preserve_mode: + try: + dest_stat = os.lstat(dest) + except FileNotFoundError: + dest_stat = None + if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode): + mode = stat.S_IMODE(dest_stat.st_mode) + _write_shared_bytes(project_path, dest, content.encode("utf-8"), mode=mode) def _write_shared_bytes( diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 9c7cd564e0..1717b8d13b 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2575,6 +2575,45 @@ def test_new_base_restores_alias_declared_only_by_lower_preset( assert "New base body" in content and "Middle body" in content assert "Top body" not in content + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_skill_refresh_on_removal_preserves_skill_mode( + self, project_dir, temp_dir + ): + """Recomposing a surviving preset's skill keeps a private (0600) + ``SKILL.md`` private instead of resetting it to 0644.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=True) + skill_file = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + skill_file.chmod(0o600) + + assert manager.remove("base-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Core custom body" in content and "Appended body" in content + assert stat.S_IMODE(skill_file.stat().st_mode) == 0o600 + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_skill_restore_on_removal_preserves_skill_mode( + self, project_dir, temp_dir + ): + """Restoring the core skill when the last preset goes keeps the + existing ``SKILL.md`` mode.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + self._install_alias_layer( + manager, temp_dir, "base-preset", "Base preset body", "replace", 10, + alias=False, + ) + skill_file = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + assert "Base preset body" in skill_file.read_text(encoding="utf-8") + skill_file.chmod(0o600) + + assert manager.remove("base-preset") is True + + assert "Base preset body" not in skill_file.read_text(encoding="utf-8") + assert stat.S_IMODE(skill_file.stat().st_mode) == 0o600 + def test_alias_refresh_does_not_write_through_hardlinked_skill( self, project_dir, temp_dir ): From 1b81d0ac841d3b92180d3c712bc8a24aec98d0ae Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:44:18 +0530 Subject: [PATCH 22/41] fix(presets): remove only SKILL.md when retiring a stale preset skill main now keeps user files next to a generated SKILL.md when a preset skill is removed (#5233) and dropped the shutil import. Use the same unlink_in_directory() helper for the stale composed skills and aliases this branch retires, instead of removing the whole skill directory. --- src/specify_cli/presets/_manager_skills.py | 23 ++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 64e9999c11..63d6bb4cf6 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -566,7 +566,11 @@ def _reconcile_preset_aliases( is no longer composable is still retired wherever it is recorded, mirroring stale-output retirement. """ - from ..integrations._file_changes import after_file_change, before_file_change + from ..integrations._file_changes import ( + after_file_change, + before_file_change, + unlink_in_directory, + ) from ..shared_infra import ( _ensure_safe_shared_destination, _ensure_safe_shared_directory, @@ -713,9 +717,11 @@ def _reconcile_preset_aliases( # not a missing base: keep the alias, as the # primary-skill path keeps its output. continue - before_file_change(skill_dir, removal=True) - shutil.rmtree(skill_dir) - after_file_change(skill_dir) + alias_file = skill_dir / "SKILL.md" + unlink_in_directory( + alias_file, + root=self.project_root if alias_file.is_relative_to(self.project_root) else skills_dir, + ) continue if shadowed or not may_render: continue @@ -902,7 +908,7 @@ def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None ``:`` (command registration for native skill agents); anything else is left untouched. """ - from ..integrations._file_changes import after_file_change, before_file_change + from ..integrations._file_changes import unlink_in_directory registrar = self._command_registrar() pack_ids = list(self.registry.list()) @@ -923,9 +929,10 @@ def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None source == f"preset:{pack_id}" or source.startswith(f"{pack_id}:") for pack_id in pack_ids ): - before_file_change(skill_dir, removal=True) - shutil.rmtree(skill_dir) - after_file_change(skill_dir) + unlink_in_directory( + skill_file, + root=self.project_root if skill_file.is_relative_to(self.project_root) else skills_dir, + ) def _resolve_agent_skills_dir(self, agent_name: str) -> Path: """Resolve the real skill output directory for an integration.""" From 729c799c2fef6aa32689243f1cb1deb06b978d52 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 10 Nov 2026 16:20:30 +0000 Subject: [PATCH 23/41] fix(presets): keep alias refresh in place; compose only layers registered there Address four review findings: - Restore a retired alias when its directory still exists. Retiring removes only SKILL.md, so a directory holding other files stays; the missing check now looks at the file, not the directory. - When a survivor's skill or alias in a historical agent's directory is recomposed after a removal, use only layers registered in that directory. A preset installed while another agent was active is no longer composed into it. - Drop CommandRegistrar._replace_file_text. The alias is written in place by command registration again, so the same inode keeps its owner, ACL and mode, and no temp entry is renamed over it. agents.py and the tests patched for the helper are back to main. - An alias SKILL.md with more than one link is left alone instead of being replaced, as other generated artifacts with extra links are. The .composed cache goes through _write_shared_text(preserve_mode). Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/agents.py | 71 +--------- src/specify_cli/presets/_manager_skills.py | 126 +++++++++++++++--- .../integrations/test_integration_generic.py | 25 +--- .../presets/test_manager_skills.py | 114 +++++++++++++++- .../test_agents_replace_file_text.py | 104 --------------- tests/test_extensions.py | 12 +- 6 files changed, 219 insertions(+), 233 deletions(-) delete mode 100644 tests/specify_cli/test_agents_replace_file_text.py diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index 57c8cc9011..8f3668812f 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -9,8 +9,6 @@ import hashlib import os import re -import secrets -import stat from copy import deepcopy from pathlib import Path from typing import Any, Dict, Iterable, List, Optional @@ -992,69 +990,6 @@ def register_commands( return registered - @staticmethod - def _replace_file_text(dest: Path, content: str) -> None: - """Write ``content`` to ``dest`` by replacing its directory entry. - - An in-place write reaches every hard link of the file, so an alias - linked to a file outside the project would carry the new text there - too. Writing a sibling temp file and renaming it over ``dest`` only - changes what ``dest`` names. - - The replacement keeps an existing file's permission bits, and the - temp file is created with (at most) those bits and set to them before - any content is written, so the new text is never readable more widely - than the destination. A new file is created with mode 0666 so the - kernel applies the process umask, the same as an in-place write; the - umask itself is never changed. - The temp name has a fixed short length, so any name valid for - ``dest`` stays writable. - """ - try: - dest_stat = os.lstat(dest) - except FileNotFoundError: - dest_stat = None - keep_mode = ( - stat.S_IMODE(dest_stat.st_mode) - if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode) - else None - ) - # O_BINARY (Windows) leaves newline translation to the text wrapper - # below, as ``tempfile.mkstemp`` and ``Path.write_text`` do. - flags = ( - os.O_WRONLY - | os.O_CREAT - | os.O_EXCL - | getattr(os, "O_NOFOLLOW", 0) - | getattr(os, "O_BINARY", 0) - ) - for _attempt in range(100): - temp_path = dest.parent / f".speckit-{secrets.token_hex(8)}.tmp" - try: - fd = os.open( - temp_path, flags, 0o666 if keep_mode is None else keep_mode - ) - except FileExistsError: - continue - break - else: - raise FileExistsError( - f"Could not create a temporary file next to {dest}" - ) - try: - # Wrap the descriptor first so a failing ``chmod`` cannot leak it: - # registration catches write errors and carries on. - with os.fdopen(fd, "w", encoding="utf-8") as fh: - if keep_mode is not None: - # The umask may have cleared some of the destination's - # bits; restore them before writing. This never widens - # the mode beyond the destination's own. - os.chmod(temp_path, keep_mode) - fh.write(content) - os.replace(temp_path, dest) - finally: - temp_path.unlink(missing_ok=True) - @staticmethod def _write_registered_output( dest_file: Path, @@ -1077,7 +1012,7 @@ def _write_registered_output( if not link_outputs or (agent_config or {}).get("dev_no_symlink"): if dest_file.is_symlink(): dest_file.unlink() - CommandRegistrar._replace_file_text(dest_file, content) + dest_file.write_text(content, encoding="utf-8") after_file_change(dest_file) return @@ -1089,7 +1024,7 @@ def _write_registered_output( try: before_file_change(cache_file) cache_file.parent.mkdir(parents=True, exist_ok=True) - CommandRegistrar._replace_file_text(cache_file, content) + cache_file.write_text(content, encoding="utf-8") after_file_change(cache_file) if dest_file.exists() or dest_file.is_symlink(): dest_file.unlink() @@ -1101,7 +1036,7 @@ def _write_registered_output( # functional by falling back to a copy. if dest_file.is_symlink(): dest_file.unlink() - CommandRegistrar._replace_file_text(dest_file, content) + dest_file.write_text(content, encoding="utf-8") after_file_change(dest_file) @staticmethod diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 63d6bb4cf6..c861772855 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -442,7 +442,16 @@ def apply_to_dir( ) if owner_idx is None or layers[owner_idx]["strategy"] == "replace": continue - if owner_idx == 0: + # A layer under the owner that was never registered in this + # destination (a preset installed while another agent was + # active) must not be composed into it either. The global + # winner's own composition is only right when nothing is + # filtered out; otherwise compose from the owner's layers + # that belong here. + registered_here = self._layers_registered_in( + layers[owner_idx:], skills_dir, active_ai, active_skills_dir + ) + if owner_idx == 0 and len(registered_here) == len(layers): prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) extra_dirs[skills_dir] = ( prior_agent, list(dict.fromkeys([*prior_names, name])) @@ -489,7 +498,9 @@ def apply_to_dir( for idx, layer in enumerate(layers) if layer["path"].is_relative_to(owner_dir) ) - owner_layers = layers[owner_idx:] + owner_layers = self._layers_registered_in( + layers[owner_idx:], skills_dir, active_ai, active_skills_dir + ) composed = resolver.resolve_content( cmd_name, "command", layers=owner_layers ) @@ -566,15 +577,8 @@ def _reconcile_preset_aliases( is no longer composable is still retired wherever it is recorded, mirroring stale-output retirement. """ - from ..integrations._file_changes import ( - after_file_change, - before_file_change, - unlink_in_directory, - ) - from ..shared_infra import ( - _ensure_safe_shared_destination, - _ensure_safe_shared_directory, - ) + from ..integrations._file_changes import unlink_in_directory + from ..shared_infra import _ensure_safe_shared_directory, _write_shared_text try: registrar = self._command_registrar() @@ -652,7 +656,11 @@ def _reconcile_preset_aliases( skill_name = registrar._compute_output_name(agent, alias, agent_config) skill_dir = skills_dir / skill_name skill_file = skill_dir / "SKILL.md" - missing = not skill_dir.exists() and not skill_dir.is_symlink() + # Retiring an alias removes only ``SKILL.md``; its + # directory stays when it holds other files. So "missing" + # is about the file, not the directory. + missing = not skill_file.exists() and not skill_file.is_symlink() + hard_linked = False if missing: if not (create_missing and skills_dir == active_skills_dir): continue @@ -663,6 +671,7 @@ def _reconcile_preset_aliases( continue try: content = skill_file.read_text(encoding="utf-8") + hard_linked = skill_file.stat().st_nlink > 1 except (OSError, UnicodeDecodeError): continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") @@ -704,7 +713,9 @@ def _reconcile_preset_aliases( # shadowed alias is refreshed from its own layer down, as # its primary skill is. shadowed = alias_shadowed and not removal_pass - owner_layers = layers[owner_idx:] + owner_layers = self._layers_registered_in( + layers[owner_idx:], skills_dir, active_ai, active_skills_dir + ) composed = resolver.resolve_content( primary, "command", layers=owner_layers ) @@ -725,6 +736,12 @@ def _reconcile_preset_aliases( continue if shadowed or not may_render: continue + if hard_linked: + # Command registration writes the alias in place, + # which would reach every other link of the file. + # As elsewhere for generated artifacts with extra + # links, it is not ours to rewrite: leave it. + continue if missing and not self._validate_skill_subdir( skill_dir, create=True, skills_root=skills_dir ): @@ -734,22 +751,23 @@ def _reconcile_preset_aliases( # Every ancestor and the cache file itself must stay # inside the project and off symlinks, so a planted # ``.composed`` link cannot redirect this write. The - # entry is replaced atomically rather than written in - # place, so a hard link to an outside file is broken, - # not written through, and an existing cache keeps - # its permission bits. + # shared writer validates the destination, journals + # the change and replaces the entry atomically, so a + # hard link to an outside file is broken, not written + # through; an existing cache keeps its permission + # bits. _ensure_safe_shared_directory( self.project_root, composed_file.parent, create=True, context="preset composed cache directory", ) - _ensure_safe_shared_destination( - self.project_root, composed_file + _write_shared_text( + self.project_root, + composed_file, + composed, + preserve_mode=True, ) - before_file_change(composed_file) - registrar._replace_file_text(composed_file, composed) - after_file_change(composed_file) except (ValueError, OSError): continue registrar.register_commands( @@ -761,6 +779,70 @@ def _reconcile_preset_aliases( _resolved_dir=skills_dir, ) + def _layers_registered_in( + self, + layers: List[Dict[str, Any]], + skills_dir: Path, + active_ai: Optional[str], + active_skills_dir: Optional[Path], + ) -> List[Dict[str, Any]]: + """Drop preset layers that were never registered in ``skills_dir``. + + Presets are registered for the active agent only (#2948), so a preset + installed while another agent was active has no output in a + historical agent's directory and must not be composed into one. A + preset counts as registered here when its ``registered_skills`` or + ``registered_commands`` names an agent that resolves to this + directory. The active directory is never filtered, non-preset layers + (core, extensions, project overrides) always stay, and so does a + preset whose provenance is unknown (a legacy flat list). + """ + if active_skills_dir is not None and skills_dir == active_skills_dir: + return layers + registered: Dict[str, bool] = {} + + def resolves_here(agent: Any) -> bool: + if not isinstance(agent, str): + return False + agent_dir = ( + active_skills_dir + if agent == active_ai + else self._safe_skills_dir_for_agent(agent) + ) + return agent_dir is not None and agent_dir == skills_dir + + def is_registered(pack_id: str) -> bool: + meta = self.registry.get(pack_id) + if not isinstance(meta, dict): + return True + if isinstance(meta.get("registered_skills"), list): + return True + for key in ("registered_skills", "registered_commands"): + recorded = meta.get(key) + if isinstance(recorded, dict) and any( + names and resolves_here(agent) + for agent, names in recorded.items() + ): + return True + return False + + kept: List[Dict[str, Any]] = [] + for layer in layers: + try: + rel = layer["path"].relative_to(self.presets_dir) + except (KeyError, TypeError, ValueError): + kept.append(layer) + continue + if not rel.parts: + kept.append(layer) + continue + pack_id = rel.parts[0] + if pack_id not in registered: + registered[pack_id] = is_registered(pack_id) + if registered[pack_id]: + kept.append(layer) + return kept + def _layer_declares_alias( self, resolver: Any, layer: Dict[str, Any], primary: str, alias: str ) -> bool: diff --git a/tests/integrations/test_integration_generic.py b/tests/integrations/test_integration_generic.py index 99e109403f..3ea10f7b11 100644 --- a/tests/integrations/test_integration_generic.py +++ b/tests/integrations/test_integration_generic.py @@ -11,7 +11,6 @@ import pytest import yaml -from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar from specify_cli.integrations import get_integration from specify_cli.integrations.base import MarkdownIntegration from specify_cli.integrations.manifest import IntegrationManifest @@ -877,29 +876,16 @@ def test_generic_refresh_write_error_restores_artifacts_and_registry( second.parent.rmdir() source = manager.extensions_dir / "sample/commands/run.md" source.write_text(source.read_text(encoding="utf-8") + "\nupdated source\n", encoding="utf-8") - # Skills-mode generic artifacts are written through Path.write_text; the - # command-file path replaces the entry via the registrar helper. original_write = Path.write_text - original_replace = AgentCommandRegistrar._replace_file_text - def fail_second(path): + def fail_second_write(path, *args, **kwargs): if path == second: if partial_second: original_write(path, "partial generated output", encoding="utf-8") raise OSError("simulated refresh write error") - - def fail_second_write(path, *args, **kwargs): - fail_second(path) return original_write(path, *args, **kwargs) - def fail_second_replace(path, content): - fail_second(path) - return original_replace(path, content) - monkeypatch.setattr(Path, "write_text", fail_second_write) - monkeypatch.setattr( - AgentCommandRegistrar, "_replace_file_text", staticmethod(fail_second_replace) - ) manager.register_enabled_extensions_for_agent("generic", force=skills) monkeypatch.undo() @@ -1119,22 +1105,13 @@ def test_generic_registration_write_error_rolls_back_partial_install( "speckit-sample-other/SKILL.md" if skills else "speckit.sample.other.md" ) original_write = Path.write_text - original_replace = AgentCommandRegistrar._replace_file_text def fail_second_write(path, *args, **kwargs): if path == second: raise OSError("simulated artifact write error") return original_write(path, *args, **kwargs) - def fail_second_replace(path, content): - if path == second: - raise OSError("simulated artifact write error") - return original_replace(path, content) - monkeypatch.setattr(Path, "write_text", fail_second_write) - monkeypatch.setattr( - AgentCommandRegistrar, "_replace_file_text", staticmethod(fail_second_replace) - ) with pytest.raises(OSError, match="simulated artifact write error"): manager.install_from_directory(generic_extension, "1.0.0") monkeypatch.undo() diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 2badc9ec03..78f45a4c5c 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2614,13 +2614,115 @@ def test_skill_restore_on_removal_preserves_skill_mode( assert "Base preset body" not in skill_file.read_text(encoding="utf-8") assert stat.S_IMODE(skill_file.stat().st_mode) == 0o600 + def test_new_base_restores_retired_outputs_beside_companion_files( + self, project_dir, temp_dir + ): + """Retiring a stale skill removes only ``SKILL.md``, so a directory + holding a user's companion file stays behind. A new base must still + bring the primary skill and its alias back, next to those files.""" + manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) + alias_file = self._alias_skill(project_dir) + skill_file = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + for skill in (alias_file, skill_file): + (skill.parent / "notes.md").write_text("mine\n", encoding="utf-8") + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + for skill in (alias_file, skill_file): + assert not skill.exists() + assert (skill.parent / "notes.md").read_text(encoding="utf-8") == "mine\n" + + self._install_alias_layer( + manager, temp_dir, "new-base", "New base body", "replace", 10, alias=False + ) + + for skill in (alias_file, skill_file): + restored = skill.read_text(encoding="utf-8") + assert "New base body" in restored and "Appended body" in restored + assert (skill.parent / "notes.md").read_text(encoding="utf-8") == "mine\n" + + def test_new_base_does_not_restore_alias_through_symlinked_dir( + self, project_dir, temp_dir + ): + """A retired alias whose directory was swapped for a symlink has no + ``SKILL.md`` either, but restoring it must not write through the link.""" + manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) + alias_dir = self._alias_skill(project_dir).parent + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not alias_dir.exists() + outside = temp_dir / "outside" + outside.mkdir() + try: + alias_dir.symlink_to(outside, target_is_directory=True) + except OSError as exc: # pragma: no cover - symlinks unavailable + pytest.skip(f"symlinks unsupported: {exc}") + + self._install_alias_layer( + manager, temp_dir, "new-base", "New base body", "replace", 10, alias=False + ) + + assert list(outside.iterdir()) == [] + + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( + self, project_dir, temp_dir, core + ): + """``low`` is installed while Codex is active, so it was never + registered for Claude. When the base under Claude's composing owner + is removed, Claude's skill and alias must be recomposed only from + layers registered there (single-active, #2948), not onto ``low``.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if core: + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + claude_alias = self._alias_skill(project_dir) + assert "Base preset body" in claude_alias.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("low-preset", "Low body", "replace", 12, alias=False) + + assert manager.remove("base-preset") is True + + codex_skill = project_dir / ".agents" / "skills" / "speckit-custom" / "SKILL.md" + codex = codex_skill.read_text(encoding="utf-8") + assert "Low body" in codex and "Middle body" in codex + for output in (claude_skill, claude_alias): + if not core: + assert not output.exists() + continue + content = output.read_text(encoding="utf-8") + assert "Low body" not in content and "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): + """The alias is refreshed in place, as command registration always + wrote it: the same inode keeps its owner, ACL and mode.""" + manager = self._install_custom_layers( + project_dir, temp_dir, core=True, alias=self._ALIAS + ) + alias_file = self._alias_skill(project_dir) + before = alias_file.stat() + + assert manager.remove("base-preset") is True + + assert "Core custom body" in alias_file.read_text(encoding="utf-8") + after = alias_file.stat() + assert (after.st_ino, after.st_dev) == (before.st_ino, before.st_dev) + assert sorted(p.name for p in alias_file.parent.iterdir()) == ["SKILL.md"] + def test_alias_refresh_does_not_write_through_hardlinked_skill( self, project_dir, temp_dir ): """An alias ``SKILL.md`` hard-linked to a file outside the project - carries the preset's own source marker, so the ownership checks pass; - the refresh on removal must replace the directory entry rather than - write through the shared inode.""" + carries the preset's own source marker, so the marker check passes. + Like other generated artifacts with extra links, it is not ours to + rewrite: the refresh on removal leaves it, and the file it is linked + to, untouched.""" self._write_init_options(project_dir, ai="claude", ai_skills=True) self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") self._write_core_custom(project_dir) @@ -2643,10 +2745,8 @@ def test_alias_refresh_does_not_write_through_hardlinked_skill( assert manager.remove("base-preset") is True assert target.read_text(encoding="utf-8") == before - after = alias_file.read_text(encoding="utf-8") - assert "Base preset body" not in after - assert "Core custom body" in after and "Appended body" in after - assert alias_file.stat().st_nlink == 1 + assert alias_file.read_text(encoding="utf-8") == before + assert os.path.samefile(alias_file, target) def test_remove_base_keeps_survivor_alias_both_layers_declare( self, project_dir, temp_dir diff --git a/tests/specify_cli/test_agents_replace_file_text.py b/tests/specify_cli/test_agents_replace_file_text.py deleted file mode 100644 index 881c7039bb..0000000000 --- a/tests/specify_cli/test_agents_replace_file_text.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Tests for ``CommandRegistrar._replace_file_text`` (atomic artifact writes).""" - -import os -import stat - -import pytest - -from specify_cli.agents import CommandRegistrar - - -def test_replace_keeps_long_valid_filename_writable(tmp_path): - """The temp entry must not be longer than the destination allows: a - 250-byte name is valid and an in-place write accepted it.""" - dest = tmp_path / ("a" * 247 + ".md") - dest.write_text("old\n", encoding="utf-8") - - CommandRegistrar._replace_file_text(dest, "new\n") - - assert dest.read_text(encoding="utf-8") == "new\n" - assert sorted(p.name for p in tmp_path.iterdir()) == [dest.name] - - -def test_replace_creates_long_valid_filename(tmp_path): - dest = tmp_path / ("b" * 247 + ".md") - - CommandRegistrar._replace_file_text(dest, "new\n") - - assert dest.read_text(encoding="utf-8") == "new\n" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") -def test_replace_does_not_touch_process_umask(tmp_path, monkeypatch): - """Reading the umask by setting it to 0 is process-wide and racy; a new - file must get the creation mode from the kernel instead.""" - old_umask = os.umask(0o027) - calls = [] - monkeypatch.setattr(os, "umask", lambda mask: calls.append(mask) or 0o027) - try: - dest = tmp_path / "new.md" - CommandRegistrar._replace_file_text(dest, "new\n") - finally: - monkeypatch.undo() - os.umask(old_umask) - - assert calls == [] - assert stat.S_IMODE(dest.stat().st_mode) == 0o640 - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") -def test_replace_writes_private_content_only_into_private_temp(tmp_path, monkeypatch): - """Replacing a 0600 file under a 022 umask must not expose the new - content through a 0644 temp file before the final chmod.""" - dest = tmp_path / "private.md" - dest.write_text("old\n", encoding="utf-8") - dest.chmod(0o600) - modes_at_write = [] - real_fdopen = os.fdopen - - def recording_fdopen(fd, *args, **kwargs): - modes_at_write.append(stat.S_IMODE(os.fstat(fd).st_mode)) - return real_fdopen(fd, *args, **kwargs) - - old_umask = os.umask(0o022) - try: - monkeypatch.setattr(os, "fdopen", recording_fdopen) - CommandRegistrar._replace_file_text(dest, "secret\n") - finally: - monkeypatch.undo() - os.umask(old_umask) - - assert modes_at_write == [0o600] - assert dest.read_text(encoding="utf-8") == "secret\n" - assert stat.S_IMODE(dest.stat().st_mode) == 0o600 - - -def test_replace_closes_descriptor_when_chmod_fails(tmp_path, monkeypatch): - """A failing ``chmod`` must not leak the temp file's descriptor: callers - catch registration errors and continue, so a leak would accumulate.""" - dest = tmp_path / "owned.md" - dest.write_text("old\n", encoding="utf-8") - opened = [] - real_open = os.open - - def recording_open(path, *args, **kwargs): - fd = real_open(path, *args, **kwargs) - opened.append(fd) - return fd - - def failing_chmod(path, mode, *args, **kwargs): - raise PermissionError(f"chmod denied: {path}") - - monkeypatch.setattr(os, "open", recording_open) - monkeypatch.setattr(os, "chmod", failing_chmod) - try: - with pytest.raises(PermissionError): - CommandRegistrar._replace_file_text(dest, "new\n") - finally: - monkeypatch.undo() - - assert len(opened) == 1 - with pytest.raises(OSError): - os.fstat(opened[0]) - assert dest.read_text(encoding="utf-8") == "old\n" - assert sorted(p.name for p in tmp_path.iterdir()) == [dest.name] diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 91097c4a09..8f370b1a64 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -4794,18 +4794,14 @@ def test_dev_register_commands_falls_back_to_copy_when_cache_write_fails( """Dev-mode registration stays functional when the dev cache is unwritable.""" agents_dir = project_dir / ".github" / "agents" agents_dir.mkdir(parents=True) - from specify_cli.agents import CommandRegistrar as AgentCommandRegistrar - - original_write = AgentCommandRegistrar._replace_file_text + original_write_text = Path.write_text - def raise_cache_write_error(path, content): + def raise_cache_write_error(path, *args, **kwargs): if ".specify-dev" in path.parts: raise OSError("cache is not writable") - return original_write(path, content) + return original_write_text(path, *args, **kwargs) - monkeypatch.setattr( - AgentCommandRegistrar, "_replace_file_text", staticmethod(raise_cache_write_error) - ) + monkeypatch.setattr(Path, "write_text", raise_cache_write_error) manifest = ExtensionManifest(extension_dir / "extension.yml") registrar = CommandRegistrar() From b14ca0d78536b515fd01dae9a8874d3099aa123a Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:15:22 +0000 Subject: [PATCH 24/41] fix(presets): create a missing alias cache entry under the umask The alias refresh wrote its .composed cache through _write_shared_text(preserve_mode=True). With no existing entry there is no mode to preserve, so the new file got the writer's fixed 0644 even under a restrictive umask. Create a missing entry exclusively instead, so the kernel applies the process umask as it does for the other .composed writes; an existing entry still goes through the shared writer and keeps its bits. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 60 ++++++++++++------- .../presets/test_manager_skills.py | 34 +++++++++++ 2 files changed, 73 insertions(+), 21 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index c861772855..55a3037571 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -578,7 +578,6 @@ def _reconcile_preset_aliases( recorded, mirroring stale-output retirement. """ from ..integrations._file_changes import unlink_in_directory - from ..shared_infra import _ensure_safe_shared_directory, _write_shared_text try: registrar = self._command_registrar() @@ -748,26 +747,7 @@ def _reconcile_preset_aliases( continue composed_file = pack_dir / ".composed" / f"{primary}.md" try: - # Every ancestor and the cache file itself must stay - # inside the project and off symlinks, so a planted - # ``.composed`` link cannot redirect this write. The - # shared writer validates the destination, journals - # the change and replaces the entry atomically, so a - # hard link to an outside file is broken, not written - # through; an existing cache keeps its permission - # bits. - _ensure_safe_shared_directory( - self.project_root, - composed_file.parent, - create=True, - context="preset composed cache directory", - ) - _write_shared_text( - self.project_root, - composed_file, - composed, - preserve_mode=True, - ) + self._write_alias_composed_cache(composed_file, composed) except (ValueError, OSError): continue registrar.register_commands( @@ -779,6 +759,44 @@ def _reconcile_preset_aliases( _resolved_dir=skills_dir, ) + def _write_alias_composed_cache(self, composed_file: Path, composed: str) -> None: + """Write a preset's ``.composed`` cache entry for an alias refresh. + + Every ancestor and the cache file itself must stay inside the project + and off symlinks, so a planted ``.composed`` link cannot redirect the + write. An existing entry goes through the shared writer, which + replaces it atomically (a hard link to an outside file is broken, not + written through) and keeps its permission bits. A missing entry is + created exclusively, so the kernel applies the process umask, as it + does for the other ``.composed`` writes, and nothing planted at the + path in the meantime is opened or followed. + + Raises: + ValueError, OSError: The path is unsafe or the write failed. + """ + from ..integrations._file_changes import changing_file + from ..shared_infra import ( + _ensure_safe_shared_destination, + _ensure_safe_shared_directory, + _write_shared_text, + ) + + _ensure_safe_shared_directory( + self.project_root, + composed_file.parent, + create=True, + context="preset composed cache directory", + ) + if composed_file.exists() or composed_file.is_symlink(): + _write_shared_text( + self.project_root, composed_file, composed, preserve_mode=True + ) + return + _ensure_safe_shared_destination(self.project_root, composed_file) + with changing_file(composed_file): + with open(composed_file, "x", encoding="utf-8") as cache: + cache.write(composed) + def _layers_registered_in( self, layers: List[Dict[str, Any]], diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 78f45a4c5c..2cecc11a91 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2529,6 +2529,40 @@ def test_historical_alias_refresh_preserves_cache_mode( assert "Core custom body" in cache_file.read_text(encoding="utf-8") assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_historical_alias_refresh_creates_cache_under_umask( + self, project_dir, temp_dir + ): + """When the survivor has no ``.composed`` cache yet, the refresh + creates one. Like the other ``.composed`` writes, the new file must + get its mode from the process umask, not a fixed 0644.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + install("top-preset", "Top body", "append", 5) + cache_dir = manager.presets_dir / "middle-preset" / ".composed" + if cache_dir.exists(): + shutil.rmtree(cache_dir) + cache_file = cache_dir / "speckit.custom.md" + + old_umask = os.umask(0o077) + try: + assert manager.remove("base-preset") is True + finally: + os.umask(old_umask) + + assert "Core custom body" in cache_file.read_text(encoding="utf-8") + assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 + assert "Core custom body" in self._alias_skill(project_dir).read_text( + encoding="utf-8" + ) + def test_rescaffold_recomposes_alias_declared_only_by_lower_preset( self, project_dir, temp_dir ): From 4ddbcb84475ff860c128ad093e9fb2c33ad5be91 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:13:45 +0000 Subject: [PATCH 25/41] fix(presets): count command registrations only for native skill agents When a base is removed, a historical agent's skills are recomposed only from layers registered in that directory. A preset counted as registered there when its registered_commands named any agent resolving to it. For a command-backed agent that entry records command files, and its skills directory can be another agent's: Amp writes .agents/commands while its skills directory resolves to .agents/skills, Codex's native one. A preset installed under Amp was therefore composed into Codex's skill and alias. Count registered_commands only for native skill agents, where a registered command is a file in the skills directory. registered_skills counts for any agent, as before. Also pin that an alias of a composer whose strategy is declared only in frontmatter never carries a preset base: registration writes it from the preset's own file, so removing the base leaves it as a rescaffold renders it. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 29 ++++-- .../presets/test_manager_skills.py | 94 +++++++++++++++++++ 2 files changed, 117 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 55a3037571..2bb19f5ebf 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -809,15 +809,30 @@ def _layers_registered_in( Presets are registered for the active agent only (#2948), so a preset installed while another agent was active has no output in a historical agent's directory and must not be composed into one. A - preset counts as registered here when its ``registered_skills`` or - ``registered_commands`` names an agent that resolves to this - directory. The active directory is never filtered, non-preset layers - (core, extensions, project overrides) always stay, and so does a - preset whose provenance is unknown (a legacy flat list). + preset counts as registered here when its ``registered_skills`` names + an agent that resolves to this directory, or its + ``registered_commands`` names a native skill agent that does: only + for those is a registered command a file in the skills directory. A + command-backed agent's entry records command files elsewhere, and + its skills directory can be another agent's (Amp's resolves to + Codex's ``.agents/skills``). The active directory is never filtered, + non-preset layers (core, extensions, project overrides) always stay, + and so does a preset whose provenance is unknown (a legacy flat + list). """ if active_skills_dir is not None and skills_dir == active_skills_dir: return layers registered: Dict[str, bool] = {} + try: + registrar = self._command_registrar() + registrar._ensure_configs() + agent_configs = registrar.AGENT_CONFIGS + except ImportError: + agent_configs = {} + + def writes_skills(agent: Any) -> bool: + config = agent_configs.get(agent) if isinstance(agent, str) else None + return bool(config) and config.get("extension") == "/SKILL.md" def resolves_here(agent: Any) -> bool: if not isinstance(agent, str): @@ -838,7 +853,9 @@ def is_registered(pack_id: str) -> bool: for key in ("registered_skills", "registered_commands"): recorded = meta.get(key) if isinstance(recorded, dict) and any( - names and resolves_here(agent) + names + and (key == "registered_skills" or writes_skills(agent)) + and resolves_here(agent) for agent, names in recorded.items() ): return True diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 2cecc11a91..fa5ae7acd9 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2733,6 +2733,100 @@ def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( assert "Low body" not in content and "Base preset body" not in content assert "Core custom body" in content and "Middle body" in content + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_does_not_compose_command_mode_layer_into_shared_skills_dir( + self, project_dir, temp_dir, core + ): + """Amp is command-backed (``.agents/commands``), yet its skills + directory resolves to ``.agents/skills``, which is Codex's native + one. ``low`` is installed while Amp is active in command mode, so it + only ever wrote an Amp command file. Its ``registered_commands`` + entry must not make it count as registered in Codex's skills.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + skills_dir = project_dir / ".agents" / "skills" + self._create_skill(skills_dir, "speckit-custom") + if core: + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + codex_skill = skills_dir / "speckit-custom" / "SKILL.md" + codex_alias = skills_dir / "speckit-custom-short" / "SKILL.md" + assert "Base preset body" in codex_skill.read_text(encoding="utf-8") + assert "Base preset body" in codex_alias.read_text(encoding="utf-8") + (project_dir / ".agents" / "commands").mkdir() + self._write_init_options(project_dir, ai="amp", ai_skills=False) + install("low-preset", "Low body", "replace", 12, alias=False) + low = manager.registry.get("low-preset") + assert low["registered_commands"] == {"amp": ["speckit.custom"]} + assert not low.get("registered_skills") + # Amp is historical too once another agent becomes active. + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager.register_enabled_presets_for_agent("claude") + + assert manager.remove("base-preset") is True + + for output in (codex_skill, codex_alias): + if not core: + assert not output.exists() + continue + content = output.read_text(encoding="utf-8") + assert "Low body" not in content and "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + + @pytest.mark.parametrize( + "strategy,body", + [("append", "Appended body"), ("wrap", "Pre\n\n{CORE_TEMPLATE}\n\nPost")], + ) + def test_frontmatter_strategy_alias_never_carries_a_preset_base( + self, project_dir, temp_dir, strategy, body + ): + """A composer may declare its strategy only in the command file's + frontmatter. Command registration composes an alias onto preset + layers only for a manifest strategy, so this alias is the preset's + own file (wrap: around the core template) and holds nothing of the + base preset. Removing the base therefore leaves it exactly as a + rescaffold renders it, while the primary skill is recomposed.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + self._install_alias_layer( + manager, temp_dir, "base-preset", "Base preset body", "replace", 10, + alias=False, + ) + preset_dir = self._create_command_preset( + temp_dir, "fm-preset", "speckit.custom", "fm-preset", "unused" + ) + (preset_dir / "commands" / "speckit.custom.md").write_text( + f"---\ndescription: fm-preset\nstrategy: {strategy}\n---\n\n{body}\n", + encoding="utf-8", + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + assert "strategy" not in manifest["provides"]["templates"][0] + manifest["provides"]["templates"][0]["aliases"] = [self._ALIAS] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + alias_file = self._alias_skill(project_dir) + assert "Base preset body" in skill.read_text(encoding="utf-8") + installed = alias_file.read_text(encoding="utf-8") + assert "Base preset body" not in installed + assert "source: fm-preset:commands/speckit.custom.md" in installed + + assert manager.remove("base-preset") is True + + recomposed = skill.read_text(encoding="utf-8") + assert "Base preset body" not in recomposed + assert "Core custom body" in recomposed + assert alias_file.read_text(encoding="utf-8") == installed + manager.register_enabled_presets_for_agent("claude") + assert alias_file.read_text(encoding="utf-8") == installed + assert skill.read_text(encoding="utf-8") == recomposed + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From 8f476093ea289b0a42a37c940550bd53b039733e Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:08:38 +0000 Subject: [PATCH 26/41] fix(presets): honor a project override and the alias's own command on removal Two removal-pass cases rendered something a rescaffold would not: - A project override added after the presets were installed wins the command, but a surviving composer's skill was recomposed from the composer's layer down (or retired when no base was left) as if the override were not there. Route such a skill to the winner pass, which renders the override. - An alias name declared by two commands of one preset is a single file, registered for the last of them. Reconciling the other command matched the file on the preset id alone and wrote its composition over it. Require the marker of this command's own file (raw or composed). Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 21 ++++- .../presets/test_manager_skills.py | 82 +++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 2bb19f5ebf..153767cf29 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -451,7 +451,13 @@ def apply_to_dir( registered_here = self._layers_registered_in( layers[owner_idx:], skills_dir, active_ai, active_skills_dir ) - if owner_idx == 0 and len(registered_here) == len(layers): + # A project override wins the command for every agent, so the + # owner's composition is not what belongs there: let the + # winner pass below render the override, as a rescaffold does. + overridden = layers[0]["source"] == "project override" + if overridden or ( + owner_idx == 0 and len(registered_here) == len(layers) + ): prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) extra_dirs[skills_dir] = ( prior_agent, list(dict.fromkeys([*prior_names, name])) @@ -563,7 +569,8 @@ def _reconcile_preset_aliases( preset is added or removed, its aliases would otherwise keep the old composition. Rewrite each from the current stack, or remove it when nothing is left to compose onto, the same as its primary skill. Only - outputs still carrying the preset's marker are touched. + outputs still carrying the preset's marker for that command are + touched. Args: create_missing: Also render a recorded alias that is missing from @@ -677,8 +684,14 @@ def _reconcile_preset_aliases( source = ( metadata.get("source") if isinstance(metadata, dict) else None ) - if not ( - isinstance(source, str) and source.startswith(f"{pack_id}:") + # Command registration marks the alias with the file + # it was rendered from. Requiring this command's own + # file (raw or composed) leaves alone an alias name + # another command of the preset declares too and was + # registered for last. + if source not in ( + f"{pack_id}:{tmpl.get('file')}", + f"{pack_id}:.composed/{tmpl['name']}.md", ): continue diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index fa5ae7acd9..8b7e502a24 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2827,6 +2827,88 @@ def test_frontmatter_strategy_alias_never_carries_a_preset_base( assert alias_file.read_text(encoding="utf-8") == installed assert skill.read_text(encoding="utf-8") == recomposed + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) + def test_remove_base_renders_project_override_over_survivor_skill( + self, project_dir, temp_dir, core, historical + ): + """A project override added after the presets were installed wins the + command, but the composer's skill still shows the old composition + until something re-renders it. Removing the base must not recompose + (or retire) that skill from the composer's layer down as if the + override were not there: it renders the override, as a rescaffold + does.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=core) + skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + assert "source: preset:append-preset" in skill.read_text(encoding="utf-8") + overrides = project_dir / ".specify" / "templates" / "overrides" + overrides.mkdir(parents=True) + (overrides / "speckit.custom.md").write_text( + "---\ndescription: Override\n---\n\nOverride body\n", encoding="utf-8" + ) + if historical: + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + assert "Base preset body" in skill.read_text(encoding="utf-8") + + assert manager.remove("base-preset") is True + + removed = skill.read_text(encoding="utf-8") + assert "Override body" in removed and "source: override:speckit.custom" in removed + assert "Base preset body" not in removed and "Appended body" not in removed + self._write_init_options(project_dir, ai="claude", ai_skills=True) + manager.register_enabled_presets_for_agent("claude") + assert skill.read_text(encoding="utf-8") == removed + + def test_alias_refresh_leaves_alias_registered_for_another_command( + self, project_dir, temp_dir + ): + """Two commands of one preset declare the same alias, so the single + alias file belongs to whichever was registered last (``speckit.b``). + Reconciling ``speckit.a`` must not write its composition over it.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + skills_dir = project_dir / ".claude" / "skills" + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + manager = PresetManager(project_dir) + for name in ("a", "b"): + self._create_skill(skills_dir, f"speckit-{name}") + (core_cmds / f"{name}.md").write_text( + f"---\ndescription: Core {name}\n---\n\nCore {name} body\n", + encoding="utf-8", + ) + base = self._create_command_preset( + temp_dir, f"base-{name}", f"speckit.{name}", f"base-{name}", + f"Base {name} body", + ) + manager.install_from_directory(base, "0.1.5", priority=10) + preset_dir = self._create_multi_command_preset( + temp_dir, "multi", ["speckit.a", "speckit.b"] + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + for tmpl in manifest["provides"]["templates"]: + tmpl["strategy"] = "append" + tmpl["aliases"] = ["speckit.shared"] + (preset_dir / tmpl["file"]).write_text( + f"---\ndescription: multi\n---\n\nAppended {tmpl['name']}\n", + encoding="utf-8", + ) + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + alias_file = skills_dir / "speckit-shared" / "SKILL.md" + installed = alias_file.read_text(encoding="utf-8") + assert "source: multi:.composed/speckit.b.md" in installed + assert "Base b body" in installed and "Appended speckit.b" in installed + + assert manager.remove("base-a") is True + + assert alias_file.read_text(encoding="utf-8") == installed + primary = (skills_dir / "speckit-a" / "SKILL.md").read_text(encoding="utf-8") + assert "Core a body" in primary and "Base a body" not in primary + manager.register_enabled_presets_for_agent("claude") + assert alias_file.read_text(encoding="utf-8") == installed + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From a5429b36fa79aefb02c0f91717438c8eae307c7f Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:07:24 +0000 Subject: [PATCH 27/41] fix(presets): retire only the baseless command's own skill outputs When a composed command has no base left, its stale skill is deleted. The ownership check accepted any marker starting with an installed preset's id, so it also matched another preset's alias that uses the command's skill name: after speckit.custom lost its base, a rescaffold deleted an alias named speckit.custom that another preset registered for its own command, and nothing restored it. Match the markers a preset writes when it renders this command: preset:, or : with that preset's own file for the command, raw or composed. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 58 ++++++++++++------- .../presets/test_manager_skills.py | 32 ++++++++++ 2 files changed, 68 insertions(+), 22 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 153767cf29..547097058d 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -339,15 +339,16 @@ def apply_to_dir( ] stale_cmds = [cmd for cmd in dir_cmds if cmd in unresolvable_cmds] if stale_cmds: - self._remove_owned_skills( - skills_dir, - [ - name - for cmd in stale_cmds - for name in self._skill_names_for_command(cmd) - if name in dir_managed_names - ], - ) + for cmd in stale_cmds: + self._remove_owned_skills( + skills_dir, + cmd, + [ + name + for name in self._skill_names_for_command(cmd) + if name in dir_managed_names + ], + ) dir_cmds = [cmd for cmd in dir_cmds if cmd not in unresolvable_cmds] if not dir_cmds: continue @@ -514,7 +515,7 @@ def apply_to_dir( overrides[cmd_name] = composed elif all(layer["strategy"] != "replace" for layer in owner_layers): # Nothing left under the owner to compose onto. - self._remove_owned_skills(skills_dir, names) + self._remove_owned_skills(skills_dir, cmd_name, names) # Otherwise a surviving layer is unreadable: keep the # existing output rather than deleting it. if not overrides: @@ -1030,18 +1031,34 @@ def _surviving_owned_skills( found.append((skills_dir, agent, pack_id, affected[name], name)) return found - def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None: - """Delete preset-owned skills among ``skill_names`` (journaled). - - A skill is preset-owned when its ``SKILL.md`` source marker names an - installed preset, either as ``preset:`` (skill registration) or - ``:`` (command registration for native skill agents); - anything else is left untouched. + def _remove_owned_skills( + self, skills_dir: Path, cmd_name: str, skill_names: List[str] + ) -> None: + """Delete ``cmd_name``'s preset-rendered skills among ``skill_names`` (journaled). + + A skill is one when its ``SKILL.md`` source marker says an installed + preset rendered this command into it: ``preset:`` (skill + registration) or ``:`` with that preset's own file for the + command, raw or composed (command registration for native skill + agents). Anything else is left untouched, including another + command's alias that happens to use this skill's name. """ from ..integrations._file_changes import unlink_in_directory registrar = self._command_registrar() - pack_ids = list(self.registry.list()) + resolver = PresetResolver(self.project_root) + owned_sources: Set[str] = set() + for pack_id in self.registry.list(): + owned_sources.add(f"preset:{pack_id}") + owned_sources.add(f"{pack_id}:.composed/{cmd_name}.md") + manifest = resolver._get_manifest(self.presets_dir / pack_id) + for tmpl in manifest.templates if manifest else []: + if ( + tmpl.get("type") == "command" + and tmpl.get("name") == cmd_name + and isinstance(tmpl.get("file"), str) + ): + owned_sources.add(f"{pack_id}:{tmpl['file']}") for name in dict.fromkeys(skill_names): skill_dir = skills_dir / name skill_file = skill_dir / "SKILL.md" @@ -1055,10 +1072,7 @@ def _remove_owned_skills(self, skills_dir: Path, skill_names: List[str]) -> None continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None - if isinstance(source, str) and any( - source == f"preset:{pack_id}" or source.startswith(f"{pack_id}:") - for pack_id in pack_ids - ): + if isinstance(source, str) and source in owned_sources: unlink_in_directory( skill_file, root=self.project_root if skill_file.is_relative_to(self.project_root) else skills_dir, diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 8b7e502a24..c00ad889e8 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2909,6 +2909,38 @@ def test_alias_refresh_leaves_alias_registered_for_another_command( manager.register_enabled_presets_for_agent("claude") assert alias_file.read_text(encoding="utf-8") == installed + def test_rescaffold_keeps_other_presets_alias_named_like_baseless_command( + self, project_dir, temp_dir + ): + """``speckit.custom`` lost its base, so its skill is retired while its + composer stays installed. Another preset then registers an alias of + that name for its own command. A rescaffold still finds the command + uncomposable, but the file under its skill name is the other + preset's alias, not a stale output of the command.""" + manager = self._install_custom_layers(project_dir, temp_dir) + skills_dir = project_dir / ".claude" / "skills" + target = skills_dir / "speckit-custom" / "SKILL.md" + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + assert not target.exists() + self._create_skill(skills_dir, "speckit-other") + other = self._create_command_preset( + temp_dir, "other-preset", "speckit.other", "other", "Other body" + ) + manifest_path = other / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["aliases"] = ["speckit.custom"] + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(other, "0.1.5", priority=20) + installed = target.read_text(encoding="utf-8") + assert "source: other-preset:commands/speckit.other.md" in installed + assert "Other body" in installed + + with pytest.warns(UserWarning, match="no base layer"): + manager.register_enabled_presets_for_agent("claude") + + assert target.read_text(encoding="utf-8") == installed + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From 59a10c193f8126606c2dcf997f5a31aaed8e09b6 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 15 Nov 2026 05:23:46 +0530 Subject: [PATCH 28/41] fix(presets): filter unregistered extension bases from historical skills Honor native extension command registrations when recomposing a surviving preset for an inactive agent. Preserve extension layers whose legacy skill records cannot establish agent ownership. Assisted-by: Codex (model: GPT-6, autonomous) --- src/specify_cli/presets/_manager_skills.py | 31 ++++++-- .../presets/test_manager_skills.py | 72 +++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 547097058d..9f43949273 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -12,6 +12,7 @@ from .._init_options import is_ai_skills_enabled from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter +from ..extensions import ExtensionRegistry from ..integrations.base import IntegrationBase from ..integrations._registration import project_registration from ._manager_commands import _substitute_core_template @@ -818,7 +819,7 @@ def _layers_registered_in( active_ai: Optional[str], active_skills_dir: Optional[Path], ) -> List[Dict[str, Any]]: - """Drop preset layers that were never registered in ``skills_dir``. + """Drop pack layers that were never registered in ``skills_dir``. Presets are registered for the active agent only (#2948), so a preset installed while another agent was active has no output in a @@ -830,13 +831,15 @@ def _layers_registered_in( command-backed agent's entry records command files elsewhere, and its skills directory can be another agent's (Amp's resolves to Codex's ``.agents/skills``). The active directory is never filtered, - non-preset layers (core, extensions, project overrides) always stay, - and so does a preset whose provenance is unknown (a legacy flat - list). + core and project overrides always stay, and so do packs whose + provenance is unknown. Extensions record native skill commands per + agent, but their optional skill registrations are still a flat list. """ if active_skills_dir is not None and skills_dir == active_skills_dir: return layers registered: Dict[str, bool] = {} + extensions_dir = self.project_root / ".specify" / "extensions" + extension_registry = None try: registrar = self._command_registrar() registrar._ensure_configs() @@ -877,6 +880,26 @@ def is_registered(pack_id: str) -> bool: kept: List[Dict[str, Any]] = [] for layer in layers: + try: + ext_rel = layer["path"].relative_to(extensions_dir) + except (KeyError, TypeError, ValueError): + ext_rel = None + if ext_rel is not None and ext_rel.parts: + if extension_registry is None: + extension_registry = ExtensionRegistry(extensions_dir) + meta = extension_registry.get(ext_rel.parts[0]) + # A nonempty flat skill list cannot establish which agent + # owns those files. Preserve that legacy fallback, as well + # as extensions without registration metadata. + if isinstance(meta, dict) and not meta.get("registered_skills"): + commands = meta.get("registered_commands") + if isinstance(commands, dict) and not any( + names and writes_skills(agent) and resolves_here(agent) + for agent, names in commands.items() + ): + continue + kept.append(layer) + continue try: rel = layer["path"].relative_to(self.presets_dir) except (KeyError, TypeError, ValueError): diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index c00ad889e8..1a1f5bc135 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -9,6 +9,7 @@ import pytest import yaml +from specify_cli.extensions import ExtensionManager from specify_cli.presets import PresetManager from tests.specify_cli.presets._helpers import ( PresetArtifactTestHelpers, @@ -2733,6 +2734,77 @@ def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( assert "Low body" not in content and "Base preset body" not in content assert "Core custom body" in content and "Middle body" in content + @pytest.mark.parametrize("extension_agent", ["codex", "claude"]) + def test_historical_skill_uses_only_registered_extension( + self, project_dir, temp_dir, extension_agent + ): + """Removing a base must not introduce another agent's extension + into a historical skill or alias; a registered base must survive.""" + self._write_init_options(project_dir, ai=extension_agent, ai_skills=True) + for folder in (".agents", ".claude"): + (project_dir / folder / "skills").mkdir(parents=True) + extension = temp_dir / "foreign-extension" + (extension / "commands").mkdir(parents=True) + (extension / "commands" / "run.md").write_text( + "---\ndescription: Foreign command\n---\n\nFOREIGN EXTENSION BODY\n", + encoding="utf-8", + ) + manifest = { + "schema_version": "1.0", + "extension": { + "id": "foreign", "name": "Foreign", + "version": "1.0.0", "description": "Test", + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": {"commands": [{ + "name": "speckit.foreign.run", + "file": "commands/run.md", "description": "Run", + }]}, + } + (extension / "extension.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + extensions = ExtensionManager(project_dir) + extensions.install_from_directory(extension, "0.1.5") + assert extensions.registry.get("foreign")["registered_commands"] == { + extension_agent: ["speckit.foreign.run"] + } + assert extensions.registry.get("foreign")["registered_skills"] == [] + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-foreign-run") + manager = PresetManager(project_dir) + for preset_id, body, strategy, priority in [ + ("base-preset", "BASE BODY", "replace", 10), + ("append-preset", "APPEND BODY", "append", 5), + ]: + preset = self._create_command_preset( + temp_dir, preset_id, "speckit.foreign.run", preset_id, body + ) + path = preset / "preset.yml" + manifest = yaml.safe_load(path.read_text(encoding="utf-8")) + manifest["provides"]["templates"][0]["strategy"] = strategy + if strategy == "append": + manifest["provides"]["templates"][0]["aliases"] = ["speckit.foreign.short"] + path.write_text(yaml.safe_dump(manifest), encoding="utf-8") + manager.install_from_directory(preset, "0.1.5", priority=priority) + skill = project_dir / ".claude" / "skills" / "speckit-foreign-run" / "SKILL.md" + alias = project_dir / ".claude" / "skills" / "speckit-foreign-short" / "SKILL.md" + assert "BASE BODY" in skill.read_text(encoding="utf-8") + assert "FOREIGN EXTENSION BODY" not in skill.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + assert manager.remove("base-preset") + for output in (skill, alias): + if extension_agent == "codex": + assert not output.exists(), output.read_text(encoding="utf-8") + else: + content = output.read_text(encoding="utf-8") + assert "FOREIGN EXTENSION BODY" in content + assert "APPEND BODY" in content + assert "BASE BODY" not in content + active = project_dir / ".agents" / "skills" / "speckit-foreign-run" / "SKILL.md" + assert "FOREIGN EXTENSION BODY" in active.read_text(encoding="utf-8") + assert "APPEND BODY" in active.read_text(encoding="utf-8") + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) def test_remove_base_does_not_compose_command_mode_layer_into_shared_skills_dir( self, project_dir, temp_dir, core From 5f1fc6beb4388811feb52f97c50881a71354b94e Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:14:26 +0530 Subject: [PATCH 29/41] fix(presets): infer legacy layer registrations during removal Reuse skill ownership inference before filtering historical preset layers, so a legacy flat list does not register a preset in every agent directory. Assisted-by: Codex (model: GPT-6, autonomous) --- src/specify_cli/presets/_manager_skills.py | 11 ++++++++++- tests/specify_cli/presets/test_manager_skills.py | 5 ++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 9f43949273..3cf7b5a717 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -866,7 +866,16 @@ def is_registered(pack_id: str) -> bool: if not isinstance(meta, dict): return True if isinstance(meta.get("registered_skills"), list): - return True + if not active_ai: + return True + meta = { + **meta, + "registered_skills": self._infer_legacy_skill_provenance( + [n for n in meta["registered_skills"] if isinstance(n, str)], + pack_id, + active_ai, + ), + } for key in ("registered_skills", "registered_commands"): recorded = meta.get(key) if isinstance(recorded, dict) and any( diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 1a1f5bc135..25a6cac7db 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2699,8 +2699,9 @@ def test_new_base_does_not_restore_alias_through_symlinked_dir( assert list(outside.iterdir()) == [] @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + @pytest.mark.parametrize("legacy", [False, True], ids=["per-agent", "legacy"]) def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( - self, project_dir, temp_dir, core + self, project_dir, temp_dir, core, legacy ): """``low`` is installed while Codex is active, so it was never registered for Claude. When the base under Claude's composing owner @@ -2720,6 +2721,8 @@ def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( self._write_init_options(project_dir, ai="codex", ai_skills=True) manager.register_enabled_presets_for_agent("codex") install("low-preset", "Low body", "replace", 12, alias=False) + if legacy: + manager.registry.update("low-preset", {"registered_skills": ["speckit-custom"]}) assert manager.remove("base-preset") is True From 1bcd341f770f9e58f619857f67f9e959b932d502 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:18:43 +0530 Subject: [PATCH 30/41] fix(presets): preserve survivor skills after partial registration Recognize preset skill ownership markers when excluding surviving outputs from native command cleanup. Assisted-by: Codex (model: GPT-6, autonomous) --- src/specify_cli/presets/_manager_skills.py | 14 +++++--- .../presets/test_manager_skills.py | 34 +++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 3cf7b5a717..280b15dbe8 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -949,12 +949,15 @@ def _drop_survivor_owned_aliases( ) -> Dict[str, List[str]]: """Leave out native-skill outputs another installed preset now owns. - Two presets can declare the same command alias. For native skill + Two presets can declare the same command or alias. For native skill agents both record it in ``registered_commands``, but only one file exists, carrying the ``:`` marker of whichever registered - it last. Deleting it with the preset being removed would drop a - survivor's alias that post-removal reconciliation (which does not - create missing outputs on a removal pass) cannot bring back, so keep + it last, or a ``preset:`` marker after skill registration. + A partial skill registration can leave a primary command in this + cleanup list too. Deleting either output with the preset being + removed would drop a survivor's skill that post-removal + reconciliation (which does not create missing outputs on a removal + pass) cannot bring back, so keep those names out of the unregister list and let reconciliation recompose them. """ @@ -997,7 +1000,8 @@ def _drop_survivor_owned_aliases( if isinstance(metadata, dict): source = metadata.get("source") if isinstance(source, str) and any( - source.startswith(f"{other}:") for other in survivors + source == f"preset:{other}" or source.startswith(f"{other}:") + for other in survivors ): continue kept.append(name) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 25a6cac7db..153fe3264b 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3090,6 +3090,40 @@ def test_remove_base_keeps_survivor_alias_both_layers_declare( manager.register_enabled_presets_for_agent("claude") assert alias_file.read_text(encoding="utf-8") == content + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) + def test_remove_base_keeps_native_survivor_after_partial_skill_registration( + self, project_dir, temp_dir, monkeypatch, historical + ): + """A failed base skill phase must not let command cleanup delete + the surviving composer's successfully registered native skill.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=True) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + original = manager._register_skills + + def fail_base(manifest, *args, **kwargs): + if manifest.id == "base-preset": + raise RuntimeError("simulated base skills phase failure") + return original(manifest, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_register_skills", fail_base) + manager.register_enabled_presets_for_agent("codex") + + skill = project_dir / ".agents" / "skills" / "speckit-custom" / "SKILL.md" + assert "preset:append-preset" in skill.read_text(encoding="utf-8") + base = manager.registry.get("base-preset") + assert "speckit.custom" in base["registered_commands"]["codex"] + assert not base["registered_skills"].get("codex") + if historical: + self._write_init_options(project_dir, ai="claude", ai_skills=True) + + assert manager.remove("base-preset") is True + + content = skill.read_text(encoding="utf-8") + assert "Core custom body" in content and "Appended body" in content + assert "Base preset body" not in content + def test_baseless_lower_composer_alias_stays_retired_after_rescaffold( self, project_dir, temp_dir ): From ce821bb2ec46ab901da858aa0ebbc13128d10687 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:51:58 +0530 Subject: [PATCH 31/41] fix(presets): distinguish skill ownership from preset command prefixes A surviving preset named preset must not claim the removed preset ownership marker during partial-registration cleanup. Assisted-by: Codex (model: GPT-6, autonomous) --- src/specify_cli/presets/_manager_skills.py | 10 +++-- .../presets/test_manager_skills.py | 40 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 280b15dbe8..d1b92c1e7b 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -999,9 +999,13 @@ def _drop_survivor_owned_aliases( metadata = None if isinstance(metadata, dict): source = metadata.get("source") - if isinstance(source, str) and any( - source == f"preset:{other}" or source.startswith(f"{other}:") - for other in survivors + if ( + isinstance(source, str) + and source != f"preset:{pack_id}" + and any( + source == f"preset:{other}" or source.startswith(f"{other}:") + for other in survivors + ) ): continue kept.append(name) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 153fe3264b..84319f07f2 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3124,6 +3124,46 @@ def fail_base(manifest, *args, **kwargs): assert "Core custom body" in content and "Appended body" in content assert "Base preset body" not in content + @pytest.mark.parametrize("survivor_id", ["unrelated", "preset"]) + def test_remove_native_skill_with_survivor_named_preset( + self, project_dir, temp_dir, monkeypatch, survivor_id + ): + """A preset named ``preset`` must not own every ``preset:`` + marker when command cleanup handles a partial skills record.""" + 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, command in [ + ("base-preset", "speckit.custom"), + (survivor_id, "speckit.other"), + ]: + preset = self._create_command_preset(temp_dir, preset_id, command, preset_id, preset_id) + manager.install_from_directory(preset, "0.1.5") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + original = manager._merge_pack_registered_skills + + def fail_base_record(pack_id, written): + if pack_id == "base-preset" and written and "codex" in written: + raise OSError("simulated skill registry write failure") + return original(pack_id, written) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_merge_pack_registered_skills", fail_base_record) + with pytest.warns(UserWarning, match="simulated skill registry write failure"): + manager.register_enabled_presets_for_agent("codex") + + skill = project_dir / ".agents" / "skills" / "speckit-custom" / "SKILL.md" + assert "preset:base-preset" in skill.read_text(encoding="utf-8") + base = manager.registry.get("base-preset") + assert "speckit.custom" in base["registered_commands"]["codex"] + assert not base["registered_skills"].get("codex") + + assert manager.remove("base-preset") is True + + assert not skill.exists() + assert manager.registry.is_installed(survivor_id) + def test_baseless_lower_composer_alias_stays_retired_after_rescaffold( self, project_dir, temp_dir ): From 977a3291f25d770fedd7aa210cdabecae040428e Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:11:06 +0000 Subject: [PATCH 32/41] fix(presets): render shared skill dirs once; match the command's registration Two findings from the review of 1bcd341: - A surviving composer can record several agents for one physical skills directory (codex and agy share .agents/skills). Its primary skill was refreshed once per recorded agent on the owner route, so the last one's renderer won, and the winner route kept the first recorded one. Group the survivor's destinations by directory and pick the renderer once: the active agent when it uses that directory, otherwise the first recorded agent in sorted order. The alias pass uses the same rule, so a primary skill and its alias agree. - A layer under the owner counted as registered in a historical directory when its pack had any record for an agent resolving there. After a partial registration, another command's record admitted a layer of this command that was never written there. Require this command's skill name in registered_skills, or its command name in a native skill agent's registered_commands; the same for extensions. The legacy fallbacks are unchanged. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 73 +++++++-- .../presets/test_manager_skills.py | 155 +++++++++++++++++- 2 files changed, 212 insertions(+), 16 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index d1b92c1e7b..34085f6834 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -451,7 +451,8 @@ def apply_to_dir( # filtered out; otherwise compose from the owner's layers # that belong here. registered_here = self._layers_registered_in( - layers[owner_idx:], skills_dir, active_ai, active_skills_dir + layers[owner_idx:], skills_dir, active_ai, active_skills_dir, + cmd_name, ) # A project override wins the command for every agent, so the # owner's composition is not what belongs there: let the @@ -507,7 +508,8 @@ def apply_to_dir( if layer["path"].is_relative_to(owner_dir) ) owner_layers = self._layers_registered_in( - layers[owner_idx:], skills_dir, active_ai, active_skills_dir + layers[owner_idx:], skills_dir, active_ai, active_skills_dir, + cmd_name, ) composed = resolver.resolve_content( cmd_name, "command", layers=owner_layers @@ -650,8 +652,15 @@ def _reconcile_preset_aliases( for skills_dir, group in groups.items(): agents = group["agents"] + # Same choice as the primary skill of that directory. agent = ( - active_ai if active_ai in agents else sorted(agents)[0] + active_ai + if active_ai in agents + or ( + skills_dir == active_skills_dir + and active_ai in registrar.AGENT_CONFIGS + ) + else sorted(agents)[0] ) agent_config = registrar.AGENT_CONFIGS[agent] # Rendering follows the single-active rule outside a removal @@ -728,7 +737,8 @@ def _reconcile_preset_aliases( # its primary skill is. shadowed = alias_shadowed and not removal_pass owner_layers = self._layers_registered_in( - layers[owner_idx:], skills_dir, active_ai, active_skills_dir + layers[owner_idx:], skills_dir, active_ai, active_skills_dir, + primary, ) composed = resolver.resolve_content( primary, "command", layers=owner_layers @@ -818,16 +828,19 @@ def _layers_registered_in( skills_dir: Path, active_ai: Optional[str], active_skills_dir: Optional[Path], + cmd_name: str, ) -> List[Dict[str, Any]]: - """Drop pack layers that were never registered in ``skills_dir``. + """Drop pack layers of ``cmd_name`` never registered in ``skills_dir``. Presets are registered for the active agent only (#2948), so a preset installed while another agent was active has no output in a historical agent's directory and must not be composed into one. A - preset counts as registered here when its ``registered_skills`` names - an agent that resolves to this directory, or its - ``registered_commands`` names a native skill agent that does: only - for those is a registered command a file in the skills directory. A + preset counts as registered here when its ``registered_skills`` lists + this command's skill for an agent that resolves to this directory, or + its ``registered_commands`` lists the command for a native skill + agent that does: only for those is a registered command a file in + the skills directory. Another command of the same pack recorded + there says nothing about this one (a registration can be partial). A command-backed agent's entry records command files elsewhere, and its skills directory can be another agent's (Amp's resolves to Codex's ``.agents/skills``). The active directory is never filtered, @@ -847,6 +860,16 @@ def _layers_registered_in( except ImportError: agent_configs = {} + wanted = { + "registered_skills": set(self._skill_names_for_command(cmd_name)), + "registered_commands": {cmd_name}, + } + + def lists_command(key: str, names: Any) -> bool: + return isinstance(names, list) and any( + isinstance(name, str) and name in wanted[key] for name in names + ) + def writes_skills(agent: Any) -> bool: config = agent_configs.get(agent) if isinstance(agent, str) else None return bool(config) and config.get("extension") == "/SKILL.md" @@ -879,7 +902,7 @@ def is_registered(pack_id: str) -> bool: for key in ("registered_skills", "registered_commands"): recorded = meta.get(key) if isinstance(recorded, dict) and any( - names + lists_command(key, names) and (key == "registered_skills" or writes_skills(agent)) and resolves_here(agent) for agent, names in recorded.items() @@ -903,7 +926,9 @@ def is_registered(pack_id: str) -> bool: if isinstance(meta, dict) and not meta.get("registered_skills"): commands = meta.get("registered_commands") if isinstance(commands, dict) and not any( - names and writes_skills(agent) and resolves_here(agent) + lists_command("registered_commands", names) + and writes_skills(agent) + and resolves_here(agent) for agent, names in commands.items() ): continue @@ -1026,6 +1051,12 @@ def _surviving_owned_skills( provenance for legacy flat lists) and keeps the names whose ``SKILL.md`` still carries that preset's ``preset:`` marker, as ``(skills_dir, agent, owner_id, command_name, skill_name)`` tuples. + + Several agents can record one physical directory (agy/codex/zed all + use ``.agents/skills``), so each file is returned once, with the + agent to render it: the active agent when it uses that directory, + otherwise the first recorded agent in sorted order, as + ``_unregister_skills`` and the alias pass choose. """ registrar = self._command_registrar() affected = { @@ -1044,6 +1075,7 @@ def _surviving_owned_skills( ) if not isinstance(recorded, dict): continue + groups: Dict[Path, Dict[str, List[str]]] = {} for agent, names in recorded.items(): if not isinstance(agent, str) or not isinstance(names, list): continue @@ -1054,9 +1086,24 @@ def _surviving_owned_skills( ) if skills_dir is None: continue + group = groups.setdefault(skills_dir, {"agents": [], "names": []}) + group["agents"].append(agent) for name in names: - if name not in affected: - continue + if ( + isinstance(name, str) + and name in affected + and name not in group["names"] + ): + group["names"].append(name) + for skills_dir, group in groups.items(): + agents = group["agents"] + agent = ( + active_ai + if active_ai + and (active_ai in agents or skills_dir == active_skills_dir) + else sorted(agents)[0] + ) + for name in group["names"]: skill_file = skills_dir / name / "SKILL.md" if not self._validate_skill_subdir( skill_file.parent, create=False, skills_root=skills_dir diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 84319f07f2..cf1c5de3fd 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2737,12 +2737,18 @@ def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( assert "Low body" not in content and "Base preset body" not in content assert "Core custom body" in content and "Middle body" in content - @pytest.mark.parametrize("extension_agent", ["codex", "claude"]) + @pytest.mark.parametrize( + "extension_agent,unrelated_claude_command", + [("codex", False), ("codex", True), ("claude", False)], + ids=["codex", "codex-unrelated-claude-command", "claude"], + ) def test_historical_skill_uses_only_registered_extension( - self, project_dir, temp_dir, extension_agent + self, project_dir, temp_dir, extension_agent, unrelated_claude_command ): """Removing a base must not introduce another agent's extension - into a historical skill or alias; a registered base must survive.""" + into a historical skill or alias; a registered base must survive. + Another command of the extension recorded for Claude (a partial + registration) does not register this one there.""" self._write_init_options(project_dir, ai=extension_agent, ai_skills=True) for folder in (".agents", ".claude"): (project_dir / folder / "skills").mkdir(parents=True) @@ -2771,6 +2777,16 @@ def test_historical_skill_uses_only_registered_extension( extension_agent: ["speckit.foreign.run"] } assert extensions.registry.get("foreign")["registered_skills"] == [] + if unrelated_claude_command: + extensions.registry.update( + "foreign", + { + "registered_commands": { + extension_agent: ["speckit.foreign.run"], + "claude": ["speckit.foreign.other"], + } + }, + ) self._write_init_options(project_dir, ai="claude", ai_skills=True) self._create_skill(project_dir / ".claude" / "skills", "speckit-foreign-run") @@ -3016,6 +3032,139 @@ def test_rescaffold_keeps_other_presets_alias_named_like_baseless_command( assert target.read_text(encoding="utf-8") == installed + @pytest.mark.parametrize( + "active,expected,unexpected", + [ + ("codex", "$speckit-plan", "/speckit-plan"), + ("agy", "/speckit-plan", "$speckit-plan"), + ("claude", "/speckit-plan", "$speckit-plan"), + ], + ids=["codex-active", "agy-active", "shared-dir-historical"], + ) + @pytest.mark.parametrize("middle", [False, True], ids=["winner", "owner-refresh"]) + def test_shared_dir_survivor_skill_rendered_once_per_directory( + self, project_dir, temp_dir, active, expected, unexpected, middle + ): + """Codex and agy share ``.agents/skills``, and the surviving composer + records both. Its primary skill is one file, so it is refreshed once: + with the active agent's renderer when that agent uses the directory, + otherwise with the first recorded agent in sorted order (agy), the + same choice the alias pass and preset removal make. ``middle`` adds a + higher preset registered only for another directory, which sends the + refresh through the owner route instead of the winner route.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + shared = project_dir / ".agents" / "skills" + self._create_skill(shared, "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Run `__SPECKIT_COMMAND_PLAN__`.", "append", 5) + self._write_init_options(project_dir, ai="agy", ai_skills=True) + manager.register_enabled_presets_for_agent("agy") + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + recorded = manager.registry.get("append-preset").get("registered_skills", {}) + assert {"codex", "agy"} <= set(recorded) + if middle or active == "claude": + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if middle: + install("top-preset", "Top body", "append", 3, alias=False) + self._write_init_options(project_dir, ai=active, ai_skills=True) + + assert manager.remove("base-preset") is True + + for name in ("speckit-custom", "speckit-custom-short"): + text = (shared / name / "SKILL.md").read_text(encoding="utf-8") + assert "Core custom body" in text and "Base preset body" not in text + assert "Top body" not in text + assert expected in text and unexpected not in text + + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + def test_remove_base_requires_this_commands_registration_in_historical_dir( + self, project_dir, temp_dir, core + ): + """``low`` provides ``speckit.custom`` and ``speckit.other`` and is + installed while Codex is active. A partial registration then records + only its unrelated ``speckit.other`` skill for Claude. That record + must not admit its ``speckit.custom`` layer into Claude's skill and + alias when the base under Claude's composer is removed.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if core: + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + claude_alias = self._alias_skill(project_dir) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + low = self._create_multi_command_preset( + temp_dir, "low-preset", ["speckit.custom", "speckit.other"] + ) + (low / "commands" / "speckit.custom.md").write_text( + "---\ndescription: low\n---\n\nLow body\n", encoding="utf-8" + ) + manager.install_from_directory(low, "0.1.5", priority=12) + meta = manager.registry.get("low-preset") + assert "claude" not in meta["registered_skills"] + assert "claude" not in meta["registered_commands"] + manager.registry.update( + "low-preset", + { + "registered_skills": { + **meta["registered_skills"], "claude": ["speckit-other"], + }, + "registered_commands": { + **meta["registered_commands"], "claude": ["speckit.other"], + }, + }, + ) + + assert manager.remove("base-preset") is True + + for output in (claude_skill, claude_alias): + if not core: + assert not output.exists() + continue + content = output.read_text(encoding="utf-8") + assert "Low body" not in content and "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + + def test_shared_dir_outputs_use_active_renderer_when_only_another_agent_recorded( + self, project_dir, temp_dir + ): + """The presets were registered while agy was active. Codex uses the + same ``.agents/skills`` and is active now, without having been + recorded. The primary skill and its alias are refreshed in Codex's + directory, so both use Codex's command-reference syntax.""" + self._write_init_options(project_dir, ai="agy", ai_skills=True) + shared = project_dir / ".agents" / "skills" + self._create_skill(shared, "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Run `__SPECKIT_COMMAND_PLAN__`.", "append", 5) + meta = manager.registry.get("append-preset") + assert set(meta["registered_skills"]) == {"agy"} + assert set(meta["registered_commands"]) == {"agy"} + for name in ("speckit-custom", "speckit-custom-short"): + assert "/speckit-plan" in (shared / name / "SKILL.md").read_text( + encoding="utf-8" + ) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + + assert manager.remove("base-preset") is True + + for name in ("speckit-custom", "speckit-custom-short"): + text = (shared / name / "SKILL.md").read_text(encoding="utf-8") + assert "Core custom body" in text and "Base preset body" not in text + assert "$speckit-plan" in text and "/speckit-plan" not in text + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From f47e7aa4bb35fa89f92b6e791f70cbaf96aa3e59 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:07:03 +0000 Subject: [PATCH 33/41] fix(presets): refresh a survivor skill left by command registration For native skill agents command registration writes a composer's primary skill first, marked :.composed/.md, and the skills phase then replaces it with a preset: one. When that phase fails during activation, the command registration is all there is: only registered_commands records it. Removing the base then refreshed or retired the alias but left the removed preset's text in the primary skill, because survivor ownership was read from registered_skills and the preset: marker alone. Also read a native skill agent's registered_commands for the primary command, and accept the marker command registration writes for the command's own file, raw or composed. The skill then goes through the same refresh as any survivor-owned one. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 80 ++++++++++++++----- .../presets/test_manager_skills.py | 60 ++++++++++++++ 2 files changed, 119 insertions(+), 21 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 34085f6834..8094bc26e1 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -1052,6 +1052,12 @@ def _surviving_owned_skills( still carries that preset's ``preset:`` marker, as ``(skills_dir, agent, owner_id, command_name, skill_name)`` tuples. + For native skill agents command registration writes the same file + first, marked ``:``, and records it in + ``registered_commands``. When the skills phase then fails, that is + all there is, so those records and that marker (for the command's own + file, raw or composed) count as well. + Several agents can record one physical directory (agy/codex/zed all use ``.agents/skills``), so each file is returned once, with the agent to render it: the active agent when it uses that directory, @@ -1059,6 +1065,8 @@ def _surviving_owned_skills( ``_unregister_skills`` and the alias pass choose. """ registrar = self._command_registrar() + registrar._ensure_configs() + resolver = PresetResolver(self.project_root) affected = { name: cmd_name for cmd_name in command_names @@ -1073,28 +1081,54 @@ def _surviving_owned_skills( recorded = self._infer_legacy_skill_provenance( [n for n in recorded if isinstance(n, str)], pack_id, active_ai ) - if not isinstance(recorded, dict): - continue + recorded_commands = meta.get("registered_commands") groups: Dict[Path, Dict[str, List[str]]] = {} - for agent, names in recorded.items(): - if not isinstance(agent, str) or not isinstance(names, list): - continue - skills_dir = ( - active_skills_dir - if agent == active_ai - else self._safe_skills_dir_for_agent(agent) - ) - if skills_dir is None: - continue - group = groups.setdefault(skills_dir, {"agents": [], "names": []}) - group["agents"].append(agent) - for name in names: - if ( - isinstance(name, str) - and name in affected - and name not in group["names"] + for from_commands, records in ( + (False, recorded if isinstance(recorded, dict) else {}), + (True, recorded_commands if isinstance(recorded_commands, dict) else {}), + ): + for agent, names in records.items(): + if not isinstance(agent, str) or not isinstance(names, list): + continue + agent_config = registrar.AGENT_CONFIGS.get(agent) + if from_commands and not ( + agent_config and agent_config.get("extension") == "/SKILL.md" ): - group["names"].append(name) + continue + skills_dir = ( + active_skills_dir + if agent == active_ai + else self._safe_skills_dir_for_agent(agent) + ) + if skills_dir is None: + continue + group = groups.setdefault(skills_dir, {"agents": [], "names": []}) + if agent not in group["agents"]: + group["agents"].append(agent) + for name in names: + if not isinstance(name, str): + continue + if from_commands: + # Only a primary command: aliases are reconciled + # by ``_reconcile_preset_aliases``. + output = registrar._compute_output_name( + agent, name, agent_config + ) + if affected.get(output) != name: + continue + name = output + if name in affected and name not in group["names"]: + group["names"].append(name) + manifest = resolver._get_manifest(self.presets_dir / pack_id) + # {command_name: markers command registration writes for it} + command_sources: Dict[str, Set[str]] = {} + for tmpl in manifest.templates if manifest else []: + if tmpl.get("type") == "command" and isinstance(tmpl.get("name"), str): + sources = command_sources.setdefault( + tmpl["name"], {f"{pack_id}:.composed/{tmpl['name']}.md"} + ) + if isinstance(tmpl.get("file"), str): + sources.add(f"{pack_id}:{tmpl['file']}") for skills_dir, group in groups.items(): agents = group["agents"] agent = ( @@ -1114,7 +1148,11 @@ def _surviving_owned_skills( except (OSError, UnicodeDecodeError): continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") - if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}": + source = metadata.get("source") if isinstance(metadata, dict) else None + if source == f"preset:{pack_id}" or ( + isinstance(source, str) + and source in command_sources.get(affected[name], ()) + ): found.append((skills_dir, agent, pack_id, affected[name], name)) return found diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index cf1c5de3fd..ee197f6306 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3165,6 +3165,66 @@ def test_shared_dir_outputs_use_active_renderer_when_only_another_agent_recorded assert "Core custom body" in text and "Base preset body" not in text assert "$speckit-plan" in text and "/speckit-plan" not in text + @pytest.mark.parametrize("core", [False, True], ids=["no-fallback", "core-fallback"]) + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) + def test_remove_base_refreshes_survivor_skill_left_by_command_registration( + self, project_dir, temp_dir, monkeypatch, core, historical + ): + """The composer's skills phase fails while Codex is activated, so its + primary skill there is the composed command registration + (``:.composed/.md``) and only ``registered_commands`` + records it. Removing the base must still recompose or retire that + skill, as it does the alias, instead of leaving the removed preset's + text in it.""" + manager = self._install_custom_layers( + project_dir, temp_dir, core=core, alias=self._ALIAS + ) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + shared = project_dir / ".agents" / "skills" + shared.mkdir(parents=True) + original = manager._register_skills + + def fail_composer(manifest, *args, **kwargs): + if manifest.id == "append-preset": + raise RuntimeError("simulated composer skills phase failure") + return original(manifest, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_register_skills", fail_composer) + with pytest.warns(UserWarning, match="simulated composer skills phase"): + manager.register_enabled_presets_for_agent("codex") + skill = shared / "speckit-custom" / "SKILL.md" + alias = shared / "speckit-custom-short" / "SKILL.md" + for output in (skill, alias): + content = output.read_text(encoding="utf-8") + assert "source: append-preset:.composed/speckit.custom.md" in content + assert "Base preset body" in content + composer = manager.registry.get("append-preset") + assert "speckit.custom" in composer["registered_commands"]["codex"] + assert not composer["registered_skills"].get("codex") + if historical: + self._write_init_options(project_dir, ai="claude", ai_skills=True) + + if core: + assert manager.remove("base-preset") is True + else: + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + for output in (skill, alias): + if not core: + assert not output.exists() + continue + content = output.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + if core: + removed = skill.read_text(encoding="utf-8") + assert "source: preset:append-preset" in removed + self._write_init_options(project_dir, ai="codex", ai_skills=True) + manager.register_enabled_presets_for_agent("codex") + assert skill.read_text(encoding="utf-8") == removed + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From a358c7f90cdd604a90f6e932568e070bfb4f2228 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:12:55 +0000 Subject: [PATCH 34/41] fix(presets): honor umask for new skills; finish cleanup after a failed write Two items from the review of f47e7aa. - With preserve_mode, _write_shared_text kept an existing file's permission bits but still gave a new file a fixed 0644. Removing the winning preset deletes its skill, and the next winner's skill is a new file there, so a skill that was 0600 under umask 077 came back as 0644. A new file now gets its mode from the process umask: the temp file is created exclusively with 0666, as _stage_workflow_file does, so the umask is never read or changed. Callers that do not pass preserve_mode keep 0644. - _reconcile_skills ran the active directory, the other directories, the survivor refreshes and the alias pass in sequence, and the first exception ended all of it. One SKILL.md that could not be written on removal left the removed preset's text in the other directories and in every alias. Attempt each destination on its own, and each alias in the alias pass, then raise the first failure so the caller warns as before. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 74 +++++++--- src/specify_cli/shared_infra.py | 33 +++-- .../presets/test_manager_skills.py | 129 ++++++++++++++++++ 3 files changed, 208 insertions(+), 28 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 8094bc26e1..1ccb5470e2 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -3,7 +3,7 @@ import copy import os from pathlib import Path -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Union if TYPE_CHECKING: from ..agents import CommandRegistrar @@ -469,10 +469,22 @@ def apply_to_dir( owner_refreshes.setdefault( (skills_dir, agent, owner_id), {} ).setdefault(cmd_name, []).append(name) + # A destination that cannot be written must not leave the others + # stale: finish the remaining directories and the alias pass, then + # raise the first failure so the caller still warns about it. + failures: List[Exception] = [] + + def attempt(step: Callable[..., None], *args: Any, **kwargs: Any) -> None: + try: + step(*args, **kwargs) + except Exception as exc: + failures.append(exc) + if active_skills_dir: active_provenance = extra_dirs.get(active_skills_dir) if extra_skills_dirs is None or active_provenance: - apply_to_dir( + attempt( + apply_to_dir, active_skills_dir, active_ai, is_active=True, @@ -486,19 +498,25 @@ def apply_to_dir( for extra_dir, (extra_agent, extra_names) in extra_dirs.items(): if extra_dir == active_skills_dir: continue # already reconciled above as the active directory - apply_to_dir( + attempt( + apply_to_dir, extra_dir, extra_agent, is_active=False, managed_names=set(extra_names), ) - for (skills_dir, agent, owner_id), owned in owner_refreshes.items(): + def refresh_owner( + skills_dir: Path, + agent: Optional[str], + owner_id: str, + owned: Dict[str, List[str]], + ) -> None: owner_dir = self.presets_dir / owner_id try: manifest = PresetManifest(owner_dir / "preset.yml") except PresetValidationError: - continue + return overrides: Dict[str, str] = {} for cmd_name, names in owned.items(): layers = cmd_layers[cmd_name] @@ -522,7 +540,7 @@ def apply_to_dir( # Otherwise a surviving layer is unreadable: keep the # existing output rather than deleting it. if not overrides: - continue + return written = self._register_skills( self._FilteredManifest(manifest, set(overrides)), owner_dir, @@ -543,7 +561,11 @@ def apply_to_dir( if written_names.intersection(names) ) - self._reconcile_preset_aliases( + for (skills_dir, agent, owner_id), owned in owner_refreshes.items(): + attempt(refresh_owner, skills_dir, agent, owner_id, owned) + + attempt( + self._reconcile_preset_aliases, command_names, presets_by_priority, active_ai, @@ -552,6 +574,8 @@ def apply_to_dir( removal_pass=extra_skills_dirs is not None, ) + if failures: + raise failures[0] return reconciled_skill_commands def _reconcile_preset_aliases( @@ -597,6 +621,9 @@ def _reconcile_preset_aliases( registrar._ensure_configs() resolver = PresetResolver(self.project_root) wanted = set(command_names) + # An alias that cannot be written or removed must not keep the + # others stale: go on, and raise the first failure at the end. + failures: List[Exception] = [] for pack_id, meta in presets_by_priority: if not isinstance(meta, dict): @@ -753,10 +780,13 @@ def _reconcile_preset_aliases( # primary-skill path keeps its output. continue alias_file = skill_dir / "SKILL.md" - unlink_in_directory( - alias_file, - root=self.project_root if alias_file.is_relative_to(self.project_root) else skills_dir, - ) + try: + unlink_in_directory( + alias_file, + root=self.project_root if alias_file.is_relative_to(self.project_root) else skills_dir, + ) + except (ValueError, OSError) as exc: + failures.append(exc) continue if shadowed or not may_render: continue @@ -775,14 +805,20 @@ def _reconcile_preset_aliases( self._write_alias_composed_cache(composed_file, composed) except (ValueError, OSError): continue - registrar.register_commands( - agent, - [{"name": alias, "file": f".composed/{primary}.md"}], - pack_id, - pack_dir, - self.project_root, - _resolved_dir=skills_dir, - ) + try: + registrar.register_commands( + agent, + [{"name": alias, "file": f".composed/{primary}.md"}], + pack_id, + pack_dir, + self.project_root, + _resolved_dir=skills_dir, + ) + except (ValueError, OSError) as exc: + failures.append(exc) + + if failures: + raise failures[0] def _write_alias_composed_cache(self, composed_file: Path, composed: str) -> None: """Write a preset's ``.composed`` cache entry for an alias refresh. diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index f1a19cb9c1..bc53089306 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -325,18 +325,20 @@ def _write_shared_text( With ``preserve_mode``, an existing regular file keeps its permission bits instead of being reset to 0644, so refreshing a private output - does not widen it; a new file still gets 0644. The content is written - into a 0600 temp file, so it is never readable more widely than that - before the final mode is applied. + does not widen it, and a new file gets the default creation mode under + the process umask, as an ordinary write would. The content of an + existing file is written into a 0600 temp file, so it is never readable + more widely than that before the final mode is applied. """ - mode = 0o644 + mode: int | None = 0o644 if preserve_mode: try: dest_stat = os.lstat(dest) except FileNotFoundError: - dest_stat = None - if dest_stat is not None and stat.S_ISREG(dest_stat.st_mode): - mode = stat.S_IMODE(dest_stat.st_mode) + mode = None + else: + if stat.S_ISREG(dest_stat.st_mode): + mode = stat.S_IMODE(dest_stat.st_mode) _write_shared_bytes(project_path, dest, content.encode("utf-8"), mode=mode) @@ -345,8 +347,14 @@ def _write_shared_bytes( dest: Path, content: bytes, *, - mode: int = 0o644, + mode: int | None = 0o644, ) -> None: + """Atomically replace ``dest`` with ``content``. + + ``mode`` is the permission bits of the result. ``None`` leaves them to + the process umask: the temp file is then created exclusively with 0666, + so the kernel applies the umask and no mode is set afterwards. + """ _ensure_safe_shared_destination(project_path, dest) from .integrations._file_changes import after_file_change, before_file_change @@ -354,9 +362,16 @@ def _write_shared_bytes( fd, temp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=dest.parent) temp_path = Path(temp_name) try: + if mode is None: + os.close(fd) + temp_path.unlink() + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + flags |= getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0) + fd = os.open(temp_path, flags, 0o666) with os.fdopen(fd, "wb") as fh: fh.write(content) - temp_path.chmod(mode) + if mode is not None: + temp_path.chmod(mode) _ensure_safe_shared_destination(project_path, dest) os.replace(temp_path, dest) after_file_change(dest) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index ee197f6306..544ec186fe 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3225,6 +3225,135 @@ def fail_composer(manifest, *args, **kwargs): manager.register_enabled_presets_for_agent("codex") assert skill.read_text(encoding="utf-8") == removed + @pytest.mark.parametrize( + "broken", ["claude-skill", "codex-skill", "claude-alias", "codex-alias"] + ) + def test_failed_write_in_one_destination_does_not_skip_the_others( + self, project_dir, temp_dir, monkeypatch, broken + ): + """One output that cannot be written on removal is reported, but the + other directories and the alias pass still run, so the removed + preset's text is left in that one file only.""" + import specify_cli.shared_infra as shared_infra + from specify_cli.agents import CommandRegistrar + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager.register_enabled_presets_for_agent("codex") + # Only Codex gets the top preset, so Claude's directory is refreshed + # from its own owner while Codex's takes the winner. + install("top-preset", "Top body", "append", 5) + outputs = { + f"{agent}-{kind}": project_dir / root / "skills" / name / "SKILL.md" + for agent, root in (("claude", ".claude"), ("codex", ".agents")) + for kind, name in ( + ("skill", "speckit-custom"), + ("alias", "speckit-custom-short"), + ) + } + for output in outputs.values(): + assert "Base preset body" in output.read_text(encoding="utf-8") + target = outputs[broken] + write_skill = shared_infra._write_shared_text + write_alias = CommandRegistrar._write_registered_output + + def failing_skill(project_path, dest, content, **kwargs): + if dest == target: + raise OSError("simulated write failure") + return write_skill(project_path, dest, content, **kwargs) + + def failing_alias(dest_file, *args, **kwargs): + if dest_file == target: + raise OSError("simulated write failure") + return write_alias(dest_file, *args, **kwargs) + + monkeypatch.setattr(shared_infra, "_write_shared_text", failing_skill) + monkeypatch.setattr( + CommandRegistrar, "_write_registered_output", staticmethod(failing_alias) + ) + + with pytest.warns(UserWarning, match="simulated write failure"): + assert manager.remove("base-preset") is True + + for key, output in outputs.items(): + content = output.read_text(encoding="utf-8") + if key == broken: + assert "Base preset body" in content + continue + assert "Base preset body" not in content, key + assert "Core custom body" in content, key + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + def test_skill_rewritten_for_next_winner_honors_umask( + self, project_dir, temp_dir + ): + """Removing the winner deletes its skill; the next winner's skill is a + new file there and must get its mode from the process umask, like the + one it replaces, not a fixed 0644.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + (project_dir / ".claude" / "skills").mkdir(parents=True) + manager = PresetManager(project_dir) + install = functools.partial( + self._install_alias_layer, manager, temp_dir, alias=False + ) + skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + old_umask = os.umask(0o077) + try: + install("low-preset", "Low body", "replace", 10) + install("top-preset", "Top body", "replace", 5) + assert stat.S_IMODE(skill.stat().st_mode) == 0o600 + assert manager.remove("top-preset") is True + finally: + os.umask(old_umask) + + assert "Low body" in skill.read_text(encoding="utf-8") + assert stat.S_IMODE(skill.stat().st_mode) == 0o600 + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + @pytest.mark.parametrize( + ("umask", "preserve_mode", "expected"), + [(0o077, True, 0o600), (0o022, True, 0o644), (0o077, False, 0o644)], + ids=["umask-077", "umask-022", "without-preserve-mode"], + ) + def test_shared_writer_creates_new_file_under_umask_with_preserve_mode( + self, project_dir, umask, preserve_mode, expected + ): + """``preserve_mode`` leaves a new file's mode to the umask; without it + the writer keeps its fixed 0644. An existing file keeps its bits.""" + from specify_cli.shared_infra import _write_shared_text + + new_file = project_dir / "new.md" + existing = project_dir / "existing.md" + existing.write_text("old\n", encoding="utf-8") + existing.chmod(0o640) + old_umask = os.umask(umask) + try: + for dest in (new_file, existing): + _write_shared_text( + project_dir, dest, "new\n", preserve_mode=preserve_mode + ) + finally: + os.umask(old_umask) + + assert new_file.read_text(encoding="utf-8") == "new\n" + assert stat.S_IMODE(new_file.stat().st_mode) == expected + assert existing.read_text(encoding="utf-8") == "new\n" + assert stat.S_IMODE(existing.stat().st_mode) == ( + 0o640 if preserve_mode else 0o644 + ) + assert sorted(p.name for p in project_dir.glob("*.md")) == [ + "existing.md", + "new.md", + ] + assert not list(project_dir.glob(".*.md.*")) + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" From 0b07d68ce90581ba77da745b88a333f056e33adb Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:12:48 +0000 Subject: [PATCH 35/41] fix(presets): keep a removed skill's mode for the next winner's skill Removing a preset deletes its skill when no core or extension command backs it, and reconciliation then writes the next winner's skill as a new file. A skill the user had made private (0600) came back with the umask default, 0644 under umask 022, although nothing but its content was meant to change. Take the permission bits of the removed preset's SKILL.md files before they are deleted and hand them to the writers that reconciliation uses, so a file written where one was deleted takes its bits. The content is still written into a 0600 temp file first. Skills created later are unaffected: the bits are passed for that one removal only. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager.py | 6 ++- src/specify_cli/presets/_manager_skills.py | 53 ++++++++++++++++++- src/specify_cli/shared_infra.py | 18 ++++--- .../presets/test_manager_skills.py | 38 +++++++++++++ 4 files changed, 107 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/presets/_manager.py b/src/specify_cli/presets/_manager.py index 2b4ad5c9e7..377e36e02b 100644 --- a/src/specify_cli/presets/_manager.py +++ b/src/specify_cli/presets/_manager.py @@ -789,7 +789,9 @@ def remove(self, pack_id: str) -> bool: affected_skill_dirs: Dict[ Path, tuple[Optional[str], List[str]] ] = {} + retired_skill_modes: Dict[Path, int] = {} if registered_skills: + retired_skill_modes = self._skill_file_modes(registered_skills) restorable_skills = registered_skills # A skill tracked for a command-backed agent whose ai_skills is # now off is a leftover from a partially failed skills→command @@ -915,7 +917,9 @@ def remove(self, pack_id: str) -> bool: list(removed_cmd_names), extra_agents=affected_command_agents ) self._reconcile_skills( - list(removed_cmd_names), extra_skills_dirs=affected_skill_dirs + list(removed_cmd_names), + extra_skills_dirs=affected_skill_dirs, + new_file_modes=retired_skill_modes, ) except Exception as exc: import warnings diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 1ccb5470e2..134190ffa0 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -2,6 +2,7 @@ import copy import os +import stat from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Union @@ -105,6 +106,7 @@ def _reconcile_skills( Dict[Path, tuple[Optional[str], List[str]]] ] = None, target_agent: Optional[str] = None, + new_file_modes: Optional[Dict[Path, int]] = None, ) -> Set[str]: """Re-register skills for commands whose winning layer changed. @@ -120,6 +122,9 @@ def _reconcile_skills( is limited to the names actually managed in each directory. target_agent: If set, report only command names written for this agent. Other callers receive the union of all written names. + new_file_modes: Permission bits of the ``SKILL.md`` files the + removed preset had, by path (:meth:`_skill_file_modes`). A + skill written where one of them was deleted takes its bits. Returns: Command names whose skill output was successfully written. @@ -313,6 +318,9 @@ def apply_to_dir( skill_subdir / "SKILL.md", skill_content, preserve_mode=True, + new_file_mode=(new_file_modes or {}).get( + skill_subdir / "SKILL.md" + ), ) wrote_override = True if ( @@ -388,12 +396,14 @@ def apply_to_dir( # brand-new skill subdirectories when ai_skills is on). written = self._register_skills( filtered_manifest, pack_dir, only_skill_names=managed_names, + new_file_modes=new_file_modes, ) else: written = self._register_skills( filtered_manifest, pack_dir, target_dir=skills_dir, target_agent=dir_agent or "", only_skill_names=managed_names, + new_file_modes=new_file_modes, ) if target_agent is None: written_names = { @@ -1449,6 +1459,7 @@ def _register_skills( target_agent: Optional[str] = None, only_skill_names: Optional[Set[str]] = None, content_overrides: Optional[Dict[str, str]] = None, + new_file_modes: Optional[Dict[Path, int]] = None, ) -> Dict[str, List[str]]: """Generate SKILL.md files for preset command overrides. @@ -1480,6 +1491,8 @@ def _register_skills( content_overrides: ``{command_name: content}`` to render instead of the preset's command file or ``.composed`` cache, for a composition that has already been resolved by the caller. + new_file_modes: ``{skill_file: permission bits}`` for skills that + stand in for a file deleted earlier in the same removal. Returns: ``{agent_name: [skill_name, ...]}`` for the single active @@ -1660,7 +1673,11 @@ def _register_skills( skill_file = skill_subdir / "SKILL.md" _write_shared_text( - skills_dir, skill_file, skill_content, preserve_mode=True + skills_dir, + skill_file, + skill_content, + preserve_mode=True, + new_file_mode=(new_file_modes or {}).get(skill_file), ) written.append(target_skill_name) self._merge_pack_registered_skills( @@ -1817,6 +1834,40 @@ def _normalize_registered_skills( return {fallback_agent: [n for n in value if isinstance(n, str)]} return {} + def _skill_file_modes( + self, registered_skills: Union[Dict[str, List[str]], List[str]] + ) -> Dict[Path, int]: + """Permission bits of the ``SKILL.md`` files a preset has registered. + + Removal deletes a preset's skill when no core or extension command + backs it, and reconciliation then writes the next winner's skill as + a new file. Taken before the deletion, these bits let that file + stay as private as the one it stands in for. + """ + if isinstance(registered_skills, dict): + entries = [ + (self._safe_skills_dir_for_agent(agent), names) + for agent, names in registered_skills.items() + if isinstance(agent, str) + ] + else: + entries = [(self._get_skills_dir(), registered_skills)] + modes: Dict[Path, int] = {} + for skills_dir, names in entries: + if skills_dir is None or not isinstance(names, list): + continue + for name in names: + if not self._is_safe_registry_skill_name(name): + continue + skill_file = skills_dir / name / "SKILL.md" + try: + skill_stat = os.lstat(skill_file) + except OSError: + continue + if stat.S_ISREG(skill_stat.st_mode): + modes[skill_file] = stat.S_IMODE(skill_stat.st_mode) + return modes + def _safe_skills_dir_for_agent(self, agent_name: str) -> Optional[Path]: """Resolve ``agent_name``'s skills directory, validated for safety. diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index bc53089306..586909ce2f 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -319,23 +319,29 @@ def _ensure_safe_shared_destination( def _write_shared_text( - project_path: Path, dest: Path, content: str, *, preserve_mode: bool = False + project_path: Path, + dest: Path, + content: str, + *, + preserve_mode: bool = False, + new_file_mode: int | None = None, ) -> None: """Atomically write ``content`` to ``dest`` (see ``_write_shared_bytes``). With ``preserve_mode``, an existing regular file keeps its permission bits instead of being reset to 0644, so refreshing a private output - does not widen it, and a new file gets the default creation mode under - the process umask, as an ordinary write would. The content of an - existing file is written into a 0600 temp file, so it is never readable - more widely than that before the final mode is applied. + does not widen it. A new file gets ``new_file_mode`` when the caller + knows the bits of the file it stands in for, otherwise the default + creation mode under the process umask, as an ordinary write would. + Content given explicit bits is written into a 0600 temp file, so it is + never readable more widely than that before the final mode is applied. """ mode: int | None = 0o644 if preserve_mode: try: dest_stat = os.lstat(dest) except FileNotFoundError: - mode = None + mode = new_file_mode else: if stat.S_ISREG(dest_stat.st_mode): mode = stat.S_IMODE(dest_stat.st_mode) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 544ec186fe..12e4caafd7 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3316,6 +3316,44 @@ def test_skill_rewritten_for_next_winner_honors_umask( assert "Low body" in skill.read_text(encoding="utf-8") assert stat.S_IMODE(skill.stat().st_mode) == 0o600 + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) + def test_private_skill_stays_private_when_next_winner_takes_over( + self, project_dir, temp_dir, historical + ): + """A preset-only skill made private (0600) is deleted with its preset + and rewritten for the next winner. The new file takes the old one's + bits instead of the umask default; a skill created later does not.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + (project_dir / ".claude" / "skills").mkdir(parents=True) + manager = PresetManager(project_dir) + install = functools.partial( + self._install_alias_layer, manager, temp_dir, alias=False + ) + skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + old_umask = os.umask(0o022) + try: + install("low-preset", "Low body", "replace", 10) + install("top-preset", "Top body", "replace", 5) + assert stat.S_IMODE(skill.stat().st_mode) == 0o644 + skill.chmod(0o600) + if historical: + self._write_init_options(project_dir, ai="codex", ai_skills=True) + + assert manager.remove("top-preset") is True + + assert "Low body" in skill.read_text(encoding="utf-8") + assert stat.S_IMODE(skill.stat().st_mode) == 0o600 + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + assert manager.remove("low-preset") is True + assert not skill.exists() + shutil.rmtree(temp_dir / "low-preset") + install("low-preset", "Low body", "replace", 10) + assert stat.S_IMODE(skill.stat().st_mode) == 0o644 + finally: + os.umask(old_umask) + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") @pytest.mark.parametrize( ("umask", "preserve_mode", "expected"), From f119122061402d3de96de329d8ba1c7fbf0d1071 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:06:51 +0000 Subject: [PATCH 36/41] fix(presets): report an alias left stale on reconciliation Two paths in the alias pass kept an alias on its old composition without saying so, so after a removal it could go on showing the removed preset's text with no warning: - The preset's .composed cache could not be written. The failure is now raised with the others once the pass is done, so the caller warns that reconciliation failed. - The alias SKILL.md has other hard links and is deliberately not rewritten. It is still left alone, with a warning that names the file. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 16 +++++++++-- .../presets/test_manager_skills.py | 28 ++++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 134190ffa0..d1d99c4dc1 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -804,7 +804,18 @@ def _reconcile_preset_aliases( # Command registration writes the alias in place, # which would reach every other link of the file. # As elsewhere for generated artifacts with extra - # links, it is not ours to rewrite: leave it. + # links, it is not ours to rewrite: leave it, and + # say that it no longer matches the preset stack. + import warnings + + warnings.warn( + f"Alias skill {skill_file} has other hard links " + f"and was not refreshed. It may still contain " + f"content from a preset that is no longer " + f"installed; delete it and reinstall the preset " + f"to regenerate it.", + stacklevel=2, + ) continue if missing and not self._validate_skill_subdir( skill_dir, create=True, skills_root=skills_dir @@ -813,7 +824,8 @@ def _reconcile_preset_aliases( composed_file = pack_dir / ".composed" / f"{primary}.md" try: self._write_alias_composed_cache(composed_file, composed) - except (ValueError, OSError): + except (ValueError, OSError) as exc: + failures.append(exc) continue try: registrar.register_commands( diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 12e4caafd7..13202db229 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3435,12 +3435,38 @@ def test_alias_refresh_does_not_write_through_hardlinked_skill( except OSError as exc: # pragma: no cover - filesystem without hard links pytest.skip(f"hard links unsupported: {exc}") - assert manager.remove("base-preset") is True + # It still holds the removed base's text, so the skip is reported. + with pytest.warns(UserWarning, match="has other hard links"): + assert manager.remove("base-preset") is True assert target.read_text(encoding="utf-8") == before assert alias_file.read_text(encoding="utf-8") == before assert os.path.samefile(alias_file, target) + def test_alias_left_stale_by_failed_cache_write_is_reported( + self, project_dir, temp_dir, monkeypatch + ): + """An alias is rendered from its preset's ``.composed`` cache. When + that cache cannot be written on removal, the alias keeps the removed + base's text; the removal must say so instead of passing silently.""" + manager = self._install_custom_layers( + project_dir, temp_dir, core=True, alias=self._ALIAS + ) + alias_file = self._alias_skill(project_dir) + skill_file = alias_file.parent.parent / "speckit-custom" / "SKILL.md" + + def failing_cache(composed_file, composed): + raise OSError("simulated cache failure") + + monkeypatch.setattr(manager, "_write_alias_composed_cache", failing_cache) + + with pytest.warns(UserWarning, match="simulated cache failure"): + assert manager.remove("base-preset") is True + + assert "Base preset body" in alias_file.read_text(encoding="utf-8") + skill = skill_file.read_text(encoding="utf-8") + assert "Base preset body" not in skill and "Core custom body" in skill + def test_remove_base_keeps_survivor_alias_both_layers_declare( self, project_dir, temp_dir ): From 7edcf2625b09eb669b55901d9c2d99b658614341 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:20:11 +0000 Subject: [PATCH 37/41] fix(presets): use FileHelper for new file I/O; settle alias ownership per file main now rejects new direct filesystem calls outside FileHelper (#5484), and the lint job failed on this branch. The review of 0b07d68 and 8adb423 also named four alias cases. FileHelper migration: - FileHelper.file_mode() returns a regular file's permission bits, or None when nothing is there, and never follows the leaf. _write_shared_text and the snapshot of a removed preset's skill modes read the bits through it instead of os.lstat. - _remove_owned_skills reads SKILL.md through FileHelper. - The alias composed cache goes through _write_shared_text for a new file too; the writer creates it under the umask since 8adb423. Alias reconciliation: - An agent in skills mode can share a skills directory while its registrar writes command files (Amp and .agents/skills). It was picked to render a Codex alias there, looked for it under the dotted name, left the real alias stale and could write a .md file into the skills directory. A recorded skill agent renders in that case. - Command cleanup removes an alias under its current name and under the dotted name older releases wrote. A survivor owning one of the two files kept both. Ownership is now decided per file. - Two commands of one preset can render one alias from one file, so the raw source marker does not say which command it was registered for. The alias is left to the command registered last, and is not retired while a command that replaces still renders it. - An alias refresh dropped metadata.version. It now passes the preset version, as command registration does. Tests: resolver tests for the layers argument, and the shared writer's mode tests move to tests/test_shared_infra_write_mode.py. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- design/file-helper.md | 6 + src/specify_cli/file_helper.py | 16 ++ src/specify_cli/presets/_manager_skills.py | 189 ++++++++++------ src/specify_cli/shared_infra.py | 14 +- .../presets/test_manager_skills.py | 205 ++++++++++++++---- tests/specify_cli/presets/test_resolver.py | 77 +++++++ tests/test_file_helper.py | 31 +++ tests/test_shared_infra_write_mode.py | 89 ++++++++ 8 files changed, 515 insertions(+), 112 deletions(-) create mode 100644 tests/test_shared_infra_write_mode.py diff --git a/design/file-helper.md b/design/file-helper.md index 15c600d7aa..3a1685ca61 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -244,6 +244,12 @@ descriptor-relative or change their documented concurrency limitations. with cleanup details attached as a note. The yielded path uses the same spelling rule as `iterdir`; cleanup uses the resolved staging location. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. +- `file_mode(path)` returns a regular file's permission bits, or `None` when + no entry exists at the path. It never follows the leaf: a link (even an + allowed one), a directory or any other non-regular entry is an error, so the + bits describe the entry an atomic write to the same path would replace. + Callers that keep an existing file's permissions across a rewrite pass the + result as the write's `mode`. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index c7b393fb58..6ba8dcf088 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -498,6 +498,22 @@ def read_bytes(self, path: Path | str) -> bytes: def read_text(self, path: Path | str, *, encoding: str = "utf-8") -> str: return self.read_bytes(path).decode(encoding) + def file_mode(self, path: Path | str) -> int | None: + """Return a regular file's permission bits, or ``None`` when no entry exists. + + The leaf is never followed: a link, a directory or any other + non-regular entry is refused, so the bits always describe the file a + scoped write to ``path`` would replace. + """ + destination = self._path(path, allow_missing=True, follow_leaf=False) + try: + mode = self._entry_mode(destination) + except FileNotFoundError: + return None + if not stat.S_ISREG(mode): + raise UnsupportedPathError(f"Expected a regular file: {destination}") + return stat.S_IMODE(mode) + @contextmanager def _posix_directory(self, directory: Path, *, unsupported_message: str) -> Iterator[int]: """Walk an already policy-resolved parent with bounded descriptor ownership.""" diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index ea01b00da7..b818bd50a1 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -2,7 +2,6 @@ import copy import os -import stat from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Union @@ -14,6 +13,7 @@ from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter from ..extensions import ExtensionRegistry +from ..file_helper import FileHelper from ..integrations.base import IntegrationBase from ..integrations._registration import project_registration from ._manager_commands import _substitute_core_template @@ -646,7 +646,8 @@ def _reconcile_preset_aliases( if not manifest: continue alias_to_tmpl: Dict[str, Dict[str, Any]] = {} - for tmpl in manifest.templates: + templates = list(manifest.templates) + for tmpl in templates: if tmpl.get("type") != "command" or tmpl.get("name") not in wanted: continue if tmpl.get("strategy", "replace") == "replace": @@ -689,13 +690,25 @@ def _reconcile_preset_aliases( for skills_dir, group in groups.items(): agents = group["agents"] - # Same choice as the primary skill of that directory. + # Same choice as the primary skill of that directory, as + # long as the active agent's registrar writes skills. An + # agent in skills mode can share this directory while its + # registrar still emits command files (Amp writes + # ``.agents/commands/*.md`` but uses ``.agents/skills``): it + # would look for the alias under the dotted command name and + # write a ``.md`` file here. A recorded agent renders then. + active_config = ( + registrar.AGENT_CONFIGS.get(active_ai) + if isinstance(active_ai, str) + else None + ) agent = ( active_ai if active_ai in agents or ( skills_dir == active_skills_dir - and active_ai in registrar.AGENT_CONFIGS + and active_config is not None + and active_config.get("extension") == "/SKILL.md" ) else sorted(agents)[0] ) @@ -715,6 +728,7 @@ def _reconcile_preset_aliases( # is about the file, not the directory. missing = not skill_file.exists() and not skill_file.is_symlink() hard_linked = False + standalone_twin = False if missing: if not (create_missing and skills_dir == active_skills_dir): continue @@ -737,10 +751,29 @@ def _reconcile_preset_aliases( # file (raw or composed) leaves alone an alias name # another command of the preset declares too and was # registered for last. - if source not in ( - f"{pack_id}:{tmpl.get('file')}", - f"{pack_id}:.composed/{tmpl['name']}.md", - ): + if source == f"{pack_id}:{tmpl.get('file')}": + # The raw marker names a file, not a command. + # Other commands of the preset can render this + # alias from the same file: registration writes + # them in manifest order, so the file belongs + # to the last one, and one that replaces is + # complete without a base. + position = templates.index(tmpl) + twins = [ + (idx, other) + for idx, other in enumerate(templates) + if other is not tmpl + and other.get("type") == "command" + and other.get("file") == tmpl.get("file") + and alias in (other.get("aliases") or []) + ] + if any(idx > position for idx, _ in twins): + continue + standalone_twin = any( + other.get("strategy", "replace") == "replace" + for _, other in twins + ) + elif source != f"{pack_id}:.composed/{tmpl['name']}.md": continue primary = tmpl["name"] @@ -781,13 +814,15 @@ def _reconcile_preset_aliases( primary, "command", layers=owner_layers ) if composed is None: - if missing or any( + if missing or standalone_twin or any( layer["strategy"] == "replace" for layer in owner_layers ): # A replace base is still there, so this is a # resolution failure (e.g. an unreadable layer), # not a missing base: keep the alias, as the - # primary-skill path keeps its output. + # primary-skill path keeps its output. So is an + # alias another command of the preset renders + # from this file without needing a base. continue alias_file = skill_dir / "SKILL.md" try: @@ -835,6 +870,7 @@ def _reconcile_preset_aliases( pack_dir, self.project_root, _resolved_dir=skills_dir, + version=manifest.version, ) except (ValueError, OSError) as exc: failures.append(exc) @@ -847,22 +883,16 @@ def _write_alias_composed_cache(self, composed_file: Path, composed: str) -> Non Every ancestor and the cache file itself must stay inside the project and off symlinks, so a planted ``.composed`` link cannot redirect the - write. An existing entry goes through the shared writer, which - replaces it atomically (a hard link to an outside file is broken, not - written through) and keeps its permission bits. A missing entry is - created exclusively, so the kernel applies the process umask, as it - does for the other ``.composed`` writes, and nothing planted at the - path in the meantime is opened or followed. + write. The shared writer replaces the entry atomically, so a hard + link to an outside file is broken, not written through, and nothing + planted at the path in the meantime is opened or followed. An + existing entry keeps its permission bits; a missing one is created + under the process umask, as the other ``.composed`` writes are. Raises: ValueError, OSError: The path is unsafe or the write failed. """ - from ..integrations._file_changes import changing_file - from ..shared_infra import ( - _ensure_safe_shared_destination, - _ensure_safe_shared_directory, - _write_shared_text, - ) + from ..shared_infra import _ensure_safe_shared_directory, _write_shared_text _ensure_safe_shared_directory( self.project_root, @@ -870,15 +900,9 @@ def _write_alias_composed_cache(self, composed_file: Path, composed: str) -> Non create=True, context="preset composed cache directory", ) - if composed_file.exists() or composed_file.is_symlink(): - _write_shared_text( - self.project_root, composed_file, composed, preserve_mode=True - ) - return - _ensure_safe_shared_destination(self.project_root, composed_file) - with changing_file(composed_file): - with open(composed_file, "x", encoding="utf-8") as cache: - cache.write(composed) + _write_shared_text( + self.project_root, composed_file, composed, preserve_mode=True + ) def _layers_registered_in( self, @@ -1043,7 +1067,16 @@ def _drop_survivor_owned_aliases( pass) cannot bring back, so keep those names out of the unregister list and let reconciliation recompose them. + + ``unregister_commands()`` removes a skill under its current name + and under the dotted name older releases wrote + (``speckit.custom-short/SKILL.md``). Ownership is decided for each + of the two files: when a survivor owns only one, the name is still + left out, and the other file is removed here, as the unregister + would have removed it. """ + from ..integrations._file_changes import unlink_in_directory + try: registrar = self._command_registrar() except ImportError: @@ -1052,6 +1085,29 @@ def _drop_survivor_owned_aliases( survivors = [pid for pid in self.registry.list() if pid != pack_id] if not survivors: return registered_commands + + def survivor_owned(skills_dir: Path, skill_dir: Path) -> bool: + if not self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ): + return False + try: + with FileHelper(skills_dir) as files: + content = files.read_text(skill_dir / "SKILL.md") + except (OSError, ValueError): + # Missing, unreadable, not a regular file or not UTF-8. + return False + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + source = metadata.get("source") if isinstance(metadata, dict) else None + return ( + isinstance(source, str) + and source != f"preset:{pack_id}" + and any( + source == f"preset:{other}" or source.startswith(f"{other}:") + for other in survivors + ) + ) + result: Dict[str, List[str]] = {} for agent, names in registered_commands.items(): agent_config = registrar.AGENT_CONFIGS.get(agent) @@ -1065,33 +1121,31 @@ def _drop_survivor_owned_aliases( skills_dir = self._safe_skills_dir_for_agent(agent) kept: List[str] = [] for name in names: - if skills_dir is not None and isinstance(name, str): - skill_dir = skills_dir / registrar._compute_output_name( - agent, name, agent_config - ) - skill_file = skill_dir / "SKILL.md" - source = None - if self._validate_skill_subdir( + if skills_dir is None or not isinstance(name, str): + kept.append(name) + continue + output = registrar._compute_output_name(agent, name, agent_config) + outputs = [output] + if output != name and registrar._is_safe_command_name(name): + outputs.append(name) + owned = [ + survivor_owned(skills_dir, skills_dir / candidate) + for candidate in outputs + ] + if not any(owned): + kept.append(name) + continue + for candidate, is_owned in zip(outputs, owned): + skill_dir = skills_dir / candidate + if is_owned or not self._validate_skill_subdir( skill_dir, create=False, skills_root=skills_dir - ) and skill_file.is_file(): - try: - metadata = registrar.parse_frontmatter( - skill_file.read_text(encoding="utf-8") - )[0].get("metadata") - except (OSError, UnicodeDecodeError): - metadata = None - if isinstance(metadata, dict): - source = metadata.get("source") - if ( - isinstance(source, str) - and source != f"preset:{pack_id}" - and any( - source == f"preset:{other}" or source.startswith(f"{other}:") - for other in survivors - ) ): continue - kept.append(name) + skill_file = skill_dir / "SKILL.md" + unlink_in_directory( + skill_file, + root=self.project_root if skill_file.is_relative_to(self.project_root) else skills_dir, + ) if kept: result[agent] = kept return result @@ -1247,11 +1301,13 @@ def _remove_owned_skills( skill_file = skill_dir / "SKILL.md" if not self._validate_skill_subdir( skill_dir, create=False, skills_root=skills_dir - ) or not skill_file.is_file(): + ): continue try: - content = skill_file.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + with FileHelper(skills_dir) as files: + content = files.read_text(skill_file) + except (OSError, ValueError): + # Missing, unreadable, not a regular file or not UTF-8. continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None @@ -1600,11 +1656,10 @@ def _register_skills( continue # Parse the command file + content = source_file.read_text(encoding="utf-8") override = (content_overrides or {}).get(cmd_name) - content = ( - override if override is not None - else source_file.read_text(encoding="utf-8") - ) + if override is not None: + content = override frontmatter, body = registrar.parse_frontmatter(content) # A composition-strategy command (wrap/prepend/append) needs a @@ -1876,11 +1931,13 @@ def _skill_file_modes( continue skill_file = skills_dir / name / "SKILL.md" try: - skill_stat = os.lstat(skill_file) - except OSError: + with FileHelper(skills_dir) as files: + mode = files.file_mode(skill_file) + except (OSError, ValueError): + # Unreadable, or not a regular file reached without links. continue - if stat.S_ISREG(skill_stat.st_mode): - modes[skill_file] = stat.S_IMODE(skill_stat.st_mode) + if mode is not None: + modes[skill_file] = mode return modes def _safe_skills_dir_for_agent(self, agent_name: str) -> Optional[Path]: diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index 145e1f8523..28969c1844 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -8,7 +8,6 @@ import logging import os import re -import stat from pathlib import Path from typing import Any @@ -360,13 +359,12 @@ def _write_shared_text( """ mode: int | None = 0o644 if preserve_mode: - try: - dest_stat = os.lstat(dest) - except FileNotFoundError: - mode = new_file_mode - else: - if stat.S_ISREG(dest_stat.st_mode): - mode = stat.S_IMODE(dest_stat.st_mode) + from .file_helper import FileHelper + + _ensure_safe_shared_destination(project_path, dest) + with FileHelper(project_path) as files: + existing_mode = files.file_mode(dest) + mode = new_file_mode if existing_mode is None else existing_mode _write_shared_bytes(project_path, dest, content.encode("utf-8"), mode=mode) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index c7ded689e4..bad718171b 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -4,6 +4,7 @@ import os import shutil import stat +import warnings from pathlib import Path import pytest @@ -2094,6 +2095,8 @@ def test_remove_base_recomposes_composer_alias_skill(self, project_dir, temp_dir project_dir, temp_dir, core=True, alias=self._ALIAS ) alias_file = self._alias_skill(project_dir) + # The refresh keeps the preset version command registration records. + assert " version: 1.0.0\n" in alias_file.read_text(encoding="utf-8") assert manager.remove("base-preset") is True @@ -2101,6 +2104,7 @@ def test_remove_base_recomposes_composer_alias_skill(self, project_dir, temp_dir assert "Base preset body" not in after_remove assert "Core custom body" in after_remove assert "Appended body" in after_remove + assert " version: 1.0.0\n" in after_remove manager.register_enabled_presets_for_agent("claude") assert alias_file.read_text(encoding="utf-8") == after_remove @@ -2225,6 +2229,42 @@ def test_shared_dir_alias_rendered_once_with_active_renderer( assert "$speckit-plan" in alias_text assert "/speckit-plan" not in alias_text + @pytest.mark.parametrize("core", [True, False], ids=["core", "no-core"]) + def test_alias_in_dir_shared_with_command_agent_in_skills_mode( + self, project_dir, temp_dir, core + ): + """Amp in skills mode uses ``.agents/skills`` like Codex, but its + registrar writes ``.md`` command files under the dotted name. A + Codex alias there must still be found under its hyphenated skill + name and rendered as a skill, with no command file beside it.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + shared = project_dir / ".agents" / "skills" + self._create_skill(shared, "speckit-custom") + if core: + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Appended body", "append", 5) + alias_file = shared / "speckit-custom-short" / "SKILL.md" + assert "Base preset body" in alias_file.read_text(encoding="utf-8") + self._write_init_options(project_dir, ai="amp", ai_skills=True) + assert manager._get_skills_dir() == shared + + with warnings.catch_warnings(): + if not core: + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-preset") is True + + if core: + content = alias_file.read_text(encoding="utf-8") + assert "Core custom body" in content and "Appended body" in content + assert "Base preset body" not in content + else: + assert not alias_file.parent.exists() + install("new-base", "New base body", "replace", 10, alias=False) + assert not list(shared.glob("speckit.custom-short*")) + def test_remove_sole_base_keeps_hand_edited_alias_skill(self, project_dir, temp_dir): manager = self._install_custom_layers(project_dir, temp_dir, alias=self._ALIAS) alias_file = self._alias_skill(project_dir) @@ -3019,6 +3059,89 @@ def test_alias_refresh_leaves_alias_registered_for_another_command( manager.register_enabled_presets_for_agent("claude") assert alias_file.read_text(encoding="utf-8") == installed + @pytest.mark.parametrize("core", [True, False], ids=["core", "no-core"]) + @pytest.mark.parametrize( + "order", + [("speckit.a", "speckit.b"), ("speckit.b", "speckit.a")], + ids=["replace-last", "append-last"], + ) + def test_alias_of_two_commands_sharing_one_source_file( + self, project_dir, temp_dir, order, core + ): + """``speckit.a`` (append) and ``speckit.b`` (replace) of one preset + declare the same alias and render it from the same file, so the raw + ``:`` marker does not say which command the alias was + registered for. Registration writes in manifest order: the alias + is ``speckit.b``'s when that comes last, and ``speckit.b`` renders + it without a base either way. Reconciling ``speckit.a`` must not + write its composition over the former or delete the latter.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + skills_dir = project_dir / ".claude" / "skills" + manager = PresetManager(project_dir) + for name in ("a", "b"): + self._create_skill(skills_dir, f"speckit-{name}") + if core: + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "a.md").write_text( + "---\ndescription: Core a\n---\n\nCore a body\n", encoding="utf-8" + ) + base = self._create_command_preset( + temp_dir, "base-a", "speckit.a", "base-a", "Base a body" + ) + manager.install_from_directory(base, "0.1.5", priority=10) + preset_dir = self._create_multi_command_preset(temp_dir, "multi", list(order)) + (preset_dir / "commands" / "shared.md").write_text( + "---\ndescription: multi\n---\n\nShared fragment\n", encoding="utf-8" + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + for tmpl in manifest["provides"]["templates"]: + tmpl["strategy"] = "append" if tmpl["name"] == "speckit.a" else "replace" + tmpl["aliases"] = ["speckit.shared"] + tmpl["file"] = "commands/shared.md" + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + alias_file = skills_dir / "speckit-shared" / "SKILL.md" + raw_marker = "source: multi:commands/shared.md" + installed = alias_file.read_text(encoding="utf-8") + + def remove_base_and_rescaffold(): + with warnings.catch_warnings(): + if not core: + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-a") is True + removed = ( + alias_file.read_text(encoding="utf-8") + if alias_file.exists() + else None + ) + manager.register_enabled_presets_for_agent("claude") + return removed, alias_file.read_text(encoding="utf-8") + + if order[-1] == "speckit.b": + # The alias is speckit.b's and stays exactly as registered. + assert raw_marker in installed and "Base a body" not in installed + removed, rescaffolded = remove_base_and_rescaffold() + assert removed == installed + assert rescaffolded == installed + else: + assert "source: multi:.composed/speckit.a.md" in installed + assert "Base a body" in installed + removed, rescaffolded = remove_base_and_rescaffold() + if core: + assert "Core a body" in removed and "Shared fragment" in removed + assert "Base a body" not in removed + assert rescaffolded == removed + else: + # speckit.a's composition is retired with its base. The + # rescaffold registers the alias for speckit.b from the raw + # file, and reconciling speckit.a leaves that in place. + assert removed is None + assert raw_marker in rescaffolded + assert "Shared fragment" in rescaffolded + assert "Base a body" not in rescaffolded + def test_rescaffold_keeps_other_presets_alias_named_like_baseless_command( self, project_dir, temp_dir ): @@ -3373,44 +3496,6 @@ def test_private_skill_stays_private_when_next_winner_takes_over( finally: os.umask(old_umask) - @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") - @pytest.mark.parametrize( - ("umask", "preserve_mode", "expected"), - [(0o077, True, 0o600), (0o022, True, 0o644), (0o077, False, 0o644)], - ids=["umask-077", "umask-022", "without-preserve-mode"], - ) - def test_shared_writer_creates_new_file_under_umask_with_preserve_mode( - self, project_dir, umask, preserve_mode, expected - ): - """``preserve_mode`` leaves a new file's mode to the umask; without it - the writer keeps its fixed 0644. An existing file keeps its bits.""" - from specify_cli.shared_infra import _write_shared_text - - new_file = project_dir / "new.md" - existing = project_dir / "existing.md" - existing.write_text("old\n", encoding="utf-8") - existing.chmod(0o640) - old_umask = os.umask(umask) - try: - for dest in (new_file, existing): - _write_shared_text( - project_dir, dest, "new\n", preserve_mode=preserve_mode - ) - finally: - os.umask(old_umask) - - assert new_file.read_text(encoding="utf-8") == "new\n" - assert stat.S_IMODE(new_file.stat().st_mode) == expected - assert existing.read_text(encoding="utf-8") == "new\n" - assert stat.S_IMODE(existing.stat().st_mode) == ( - 0o640 if preserve_mode else 0o644 - ) - assert sorted(p.name for p in project_dir.glob("*.md")) == [ - "existing.md", - "new.md", - ] - assert not list(project_dir.glob(".*.tmp")) - def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" @@ -3511,6 +3596,50 @@ def test_remove_base_keeps_survivor_alias_both_layers_declare( manager.register_enabled_presets_for_agent("claude") assert alias_file.read_text(encoding="utf-8") == content + @pytest.mark.parametrize("survivor_file", ["current", "dotted"]) + def test_remove_base_decides_alias_ownership_per_file( + self, project_dir, temp_dir, survivor_file + ): + """Command cleanup removes an alias under its current name and under + the dotted name older releases wrote. When the surviving composer + owns only one of the two files, that one stays and the removed + preset's file goes.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + current = self._alias_skill(project_dir) + dotted = current.parent.parent / self._ALIAS / "SKILL.md" + survivor_text = current.read_text(encoding="utf-8") + assert "source: append-preset:" in survivor_text + retiring_text = ( + "---\nname: speckit-custom-short\nmetadata:\n" + " source: base-preset:commands/speckit.custom.md\n---\n\n" + "Base preset body\n" + ) + dotted.parent.mkdir() + if survivor_file == "current": + dotted.write_text(retiring_text, encoding="utf-8") + kept, removed = current, dotted + else: + dotted.write_text(survivor_text, encoding="utf-8") + current.write_text(retiring_text, encoding="utf-8") + kept, removed = dotted, current + + assert manager.remove("base-preset") is True + + assert not removed.parent.exists() + content = kept.read_text(encoding="utf-8") + assert "source: append-preset:" in content + if survivor_file == "current": + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + else: + assert content == survivor_text + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) def test_remove_base_keeps_native_survivor_after_partial_skill_registration( self, project_dir, temp_dir, monkeypatch, historical diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index f052361c76..a6d05233d4 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -1959,3 +1959,80 @@ def _create_pack(temp_dir, valid_pack_data, pack_id, content, (subdir / f"{template_name}.md").write_text(content) return pack_dir + + +def _install_layer_stack(root): + """Core template, a replacing preset and an appending preset above it.""" + name = "layers-template" + templates = root / ".specify" / "templates" + templates.mkdir(parents=True) + (templates / f"{name}.md").write_text("core body\n", encoding="utf-8") + presets = root / ".specify" / "presets" + presets.mkdir() + registry = PresetRegistry(presets) + for preset_id, priority, strategy in [("base", 10, "replace"), ("extra", 5, "append")]: + directory = presets / preset_id + directory.mkdir() + manifest = { + "schema_version": "1.0", + "preset": { + "id": preset_id, + "name": preset_id, + "version": "1.0.0", + "description": "Test", + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": { + "templates": [ + { + "type": "template", + "name": name, + "file": "body.md", + "strategy": strategy, + } + ] + }, + } + (directory / "preset.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8") + (directory / "body.md").write_text(f"{preset_id} body\n", encoding="utf-8") + registry.add(preset_id, {"priority": priority, "enabled": True}) + return name + + +def test_resolve_content_composes_supplied_layers_instead_of_the_stack(tmp_path): + name = _install_layer_stack(tmp_path) + resolver = PresetResolver(tmp_path) + extra, base, core = resolver.collect_all_layers(name) + assert [layer["strategy"] for layer in (extra, base, core)] == [ + "append", "replace", "replace", + ] + whole = resolver.resolve_content(name) + assert "base body" in whole and "extra body" in whole and "core body" not in whole + + assert resolver.resolve_content(name, layers=[extra, base, core]) == whole + # One layer and everything below it. + below_extra = resolver.resolve_content(name, layers=[base, core]) + assert "base body" in below_extra and "extra body" not in below_extra + # A slice that leaves a layer out composes onto what the slice holds. + without_base = resolver.resolve_content(name, layers=[extra, core]) + assert "core body" in without_base and "extra body" in without_base + assert "base body" not in without_base + assert without_base.index("core body") < without_base.index("extra body") + + +def test_resolve_content_with_layers_that_have_no_replace_base(tmp_path): + name = _install_layer_stack(tmp_path) + resolver = PresetResolver(tmp_path) + extra = resolver.collect_all_layers(name)[0] + + # The stack has a base, but the supplied slice does not: nothing to + # compose onto, and the rest of the stack is not consulted. + assert resolver.resolve_content(name, layers=[extra]) is None + + +def test_resolve_content_with_empty_layers_does_not_fall_back_to_the_stack(tmp_path): + name = _install_layer_stack(tmp_path) + resolver = PresetResolver(tmp_path) + + assert resolver.resolve_content(name) is not None + assert resolver.resolve_content(name, layers=[]) is None diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 32a8dc8238..7b2820040d 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -137,6 +137,37 @@ def test_plain_operations(root, allow): assert list(root.iterdir()) == [] +@pytest.mark.parametrize("allow", [False, True]) +def test_file_mode_reports_regular_file_bits_and_absence(root, allow): + files = FileHelper(root, allow_symlinks=allow) + files.mkdir("nested") + files.create_bytes("nested/private", b"secret", mode=0o600) + if os.name != "nt": + assert files.file_mode("nested/private") == 0o600 + (root / "nested/private").chmod(0o640) + assert files.file_mode(root / "nested/private") == 0o640 + else: + assert files.file_mode("nested/private") is not None + assert files.file_mode("nested/missing") is None + assert files.file_mode("missing/parent/file") is None + with pytest.raises(UnsupportedPathError, match="Expected a regular file"): + files.file_mode("nested") + with pytest.raises(PathEscapeError): + files.file_mode(root.parent / "outside") + + +@pytest.mark.parametrize("kind", ["file", "dangling"]) +def test_file_mode_never_follows_a_leaf_link(root, link, kind): + target = root / "target" + if kind == "file": + target.write_bytes(b"data") + link(root / "alias", target) + with pytest.raises(SymlinkDeniedError): + FileHelper(root).file_mode("alias") + with pytest.raises(UnsupportedPathError, match="Expected a regular file"): + FileHelper(root, allow_symlinks=True).file_mode("alias") + + @pytest.mark.skipif(os.name == "nt", reason="POSIX shared directory traversal") @pytest.mark.parametrize("operation", ["read_bytes", "create_bytes", "overwrite_text"]) def test_posix_operations_share_parent_walk_and_preserve_leaf_flags(root, monkeypatch, operation): diff --git a/tests/test_shared_infra_write_mode.py b/tests/test_shared_infra_write_mode.py new file mode 100644 index 0000000000..58ab4acaf8 --- /dev/null +++ b/tests/test_shared_infra_write_mode.py @@ -0,0 +1,89 @@ +"""Unit tests for the mode the shared text writer leaves on a file.""" + +from __future__ import annotations + +import os +import stat + +import pytest + +from specify_cli.shared_infra import SymlinkedSharedPathError, _write_shared_text + +pytestmark = pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + + +def _mode(path): + return stat.S_IMODE(path.stat().st_mode) + + +@pytest.fixture +def umask(): + """Set the process umask for one test and restore it afterwards.""" + previous = os.umask(0o022) + + def set_umask(value): + os.umask(value) + + yield set_umask + os.umask(previous) + + +@pytest.mark.parametrize( + ("mask", "preserve_mode", "expected"), + [(0o077, True, 0o600), (0o022, True, 0o644), (0o077, False, 0o644)], + ids=["umask-077", "umask-022", "without-preserve-mode"], +) +def test_new_file_mode_follows_umask_only_with_preserve_mode( + tmp_path, umask, mask, preserve_mode, expected +): + """``preserve_mode`` leaves a new file's mode to the umask; without it + the writer keeps its fixed 0644. An existing file keeps its bits.""" + new_file = tmp_path / "new.md" + existing = tmp_path / "existing.md" + existing.write_text("old\n", encoding="utf-8") + existing.chmod(0o640) + umask(mask) + + for dest in (new_file, existing): + _write_shared_text(tmp_path, dest, "new\n", preserve_mode=preserve_mode) + + assert new_file.read_text(encoding="utf-8") == "new\n" + assert _mode(new_file) == expected + assert existing.read_text(encoding="utf-8") == "new\n" + assert _mode(existing) == (0o640 if preserve_mode else 0o644) + assert sorted(p.name for p in tmp_path.iterdir()) == ["existing.md", "new.md"] + + +@pytest.mark.parametrize("mask", [0o022, 0o077]) +def test_new_file_takes_the_mode_of_the_file_it_stands_in_for(tmp_path, umask, mask): + """``new_file_mode`` is exact for a new file, whatever the umask, and + never overrides the bits of a file that is already there.""" + new_file = tmp_path / "new.md" + existing = tmp_path / "existing.md" + existing.write_text("old\n", encoding="utf-8") + existing.chmod(0o640) + umask(mask) + + for dest in (new_file, existing): + _write_shared_text( + tmp_path, dest, "new\n", preserve_mode=True, new_file_mode=0o600 + ) + + assert _mode(new_file) == 0o600 + assert _mode(existing) == 0o640 + assert existing.read_text(encoding="utf-8") == "new\n" + + +def test_preserve_mode_does_not_read_or_write_through_a_link(tmp_path): + outside = tmp_path / "outside.md" + outside.write_text("outside\n", encoding="utf-8") + outside.chmod(0o600) + project = tmp_path / "project" + project.mkdir() + (project / "linked.md").symlink_to(outside) + + with pytest.raises(SymlinkedSharedPathError): + _write_shared_text(project, project / "linked.md", "new\n", preserve_mode=True) + + assert outside.read_text(encoding="utf-8") == "outside\n" + assert _mode(outside) == 0o600 From b3fe60a94db0f1e5764e0d668668bdeeb2c7cb4f Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:08:42 +0000 Subject: [PATCH 38/41] fix(presets): name FileHelper paths from the helper's root FileHelper resolves a relative path against its root, not the working directory. 7edcf26 handed it paths built from the project root, so with a relative project root the reads looked under the root twice and found nothing: a stale skill was not retired, a survivor's alias was treated as unowned and deleted, and a private file's mode was not seen and came back as the umask default. Pass the path below the helper's root instead (the skill name under the skills directory, the shared relative path under the project root). Tests: four reconciliation scenarios and the shared writer run under a relative project root. All five failed on 7edcf26 and passed on 8adb423. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 10 +++++-- src/specify_cli/shared_infra.py | 4 ++- .../presets/test_manager_skills.py | 30 +++++++++++++++++++ tests/test_shared_infra_write_mode.py | 21 +++++++++++++ 4 files changed, 61 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index b818bd50a1..fb20c18e3c 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -1092,8 +1092,11 @@ def survivor_owned(skills_dir: Path, skill_dir: Path) -> bool: ): return False try: + # FileHelper reads a relative path against its root, so + # name the file from the skills directory, not from a + # project root that may itself be relative. with FileHelper(skills_dir) as files: - content = files.read_text(skill_dir / "SKILL.md") + content = files.read_text(Path(skill_dir.name) / "SKILL.md") except (OSError, ValueError): # Missing, unreadable, not a regular file or not UTF-8. return False @@ -1304,8 +1307,9 @@ def _remove_owned_skills( ): continue try: + # Named from the helper's root: see _drop_survivor_owned_aliases. with FileHelper(skills_dir) as files: - content = files.read_text(skill_file) + content = files.read_text(Path(name) / "SKILL.md") except (OSError, ValueError): # Missing, unreadable, not a regular file or not UTF-8. continue @@ -1932,7 +1936,7 @@ def _skill_file_modes( skill_file = skills_dir / name / "SKILL.md" try: with FileHelper(skills_dir) as files: - mode = files.file_mode(skill_file) + mode = files.file_mode(Path(name) / "SKILL.md") except (OSError, ValueError): # Unreadable, or not a regular file reached without links. continue diff --git a/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index 28969c1844..6b4afa41d6 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -362,8 +362,10 @@ def _write_shared_text( from .file_helper import FileHelper _ensure_safe_shared_destination(project_path, dest) + # FileHelper reads a relative path against its root, so hand it the + # path below the project root: the two may both be relative. with FileHelper(project_path) as files: - existing_mode = files.file_mode(dest) + existing_mode = files.file_mode(_shared_relative_path(project_path, dest)) mode = new_file_mode if existing_mode is None else existing_mode _write_shared_bytes(project_path, dest, content.encode("utf-8"), mode=mode) diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index bad718171b..aba95709b1 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3496,6 +3496,36 @@ def test_private_skill_stays_private_when_next_winner_takes_over( finally: os.umask(old_umask) + _posix_bits = pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits") + + @pytest.mark.parametrize( + "scenario,args", + [ + ("test_remove_sole_base_preset_retires_stale_composed_skill", ()), + ("test_remove_base_keeps_survivor_alias_both_layers_declare", ()), + pytest.param( + "test_alias_refresh_preserves_existing_output_mode", (), + marks=_posix_bits, + ), + pytest.param( + "test_private_skill_stays_private_when_next_winner_takes_over", + (False,), + marks=_posix_bits, + ), + ], + ids=["retire-skill", "survivor-alias", "refresh-mode", "next-winner-mode"], + ) + def test_reconciliation_under_a_relative_project_root( + self, project_dir, temp_dir, monkeypatch, scenario, args + ): + """FileHelper reads a relative path against its own root, not the + working directory. A manager created with a relative project root + must still find the skills it reads before removing, keeping or + rewriting them: each scenario covers one of those reads.""" + monkeypatch.chdir(project_dir.parent) + + getattr(self, scenario)(Path(project_dir.name), temp_dir, *args) + def test_alias_refresh_rewrites_the_same_file(self, project_dir, temp_dir): """The alias is refreshed in place, as command registration always wrote it: the same inode keeps its owner, ACL and mode.""" diff --git a/tests/test_shared_infra_write_mode.py b/tests/test_shared_infra_write_mode.py index 58ab4acaf8..bcd7c21ea3 100644 --- a/tests/test_shared_infra_write_mode.py +++ b/tests/test_shared_infra_write_mode.py @@ -4,6 +4,7 @@ import os import stat +from pathlib import Path import pytest @@ -74,6 +75,26 @@ def test_new_file_takes_the_mode_of_the_file_it_stands_in_for(tmp_path, umask, m assert existing.read_text(encoding="utf-8") == "new\n" +def test_existing_file_keeps_its_bits_under_a_relative_project_root( + tmp_path, umask, monkeypatch +): + """The existing bits are read below the project root, not below the + working directory joined with a relative root a second time.""" + project = tmp_path / "project" + project.mkdir() + existing = project / "existing.md" + existing.write_text("old\n", encoding="utf-8") + existing.chmod(0o600) + monkeypatch.chdir(tmp_path) + + _write_shared_text( + Path("project"), Path("project") / "existing.md", "new\n", preserve_mode=True + ) + + assert existing.read_text(encoding="utf-8") == "new\n" + assert _mode(existing) == 0o600 + + def test_preserve_mode_does_not_read_or_write_through_a_link(tmp_path): outside = tmp_path / "outside.md" outside.write_text("outside\n", encoding="utf-8") From fdda0534b8804e8cb2196db3809863a007c3e846 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:29:16 +0530 Subject: [PATCH 39/41] fix(presets): tighten skill ownership checks, symlink guards, and cache bypass Address remaining Copilot review findings on preset removal reconciliation: - Require exact retiring-preset marker proof before unlinking an alternate alias spelling in _drop_survivor_owned_aliases; preserve unmarked, unreadable, or symlinked files. - Reject leaf SKILL.md symlinks via no-follow FileHelper reads before checking ownership in _reconcile_preset_aliases, _surviving_owned_skills, and _infer_legacy_skill_provenance. - Include primary-name (and normalized output-name) matches alongside alias declarations in _reconcile_preset_aliases twins matching. - Fall back to the validated registrar directory for native-skill agents when active_skills_dir is None (ai_skills false or absent). - Infer legacy flat registered_skills provenance with an empty fallback even when active_ai is None (missing or unreadable init-options.json). - Verify command-level ownership (supplying command, normalized-name collisions, and shared-file primary/alias collisions) in _remove_owned_skills, preserving ambiguous outputs. - Skip reading obsolete .composed caches in _register_skills when content_overrides already supplies the resolved composition. - Add positive regression tests for extension-filter legacy fallback paths (nonempty flat registered_skills and missing command metadata). Assisted-by: Antigravity (model: Gemini 4 Neon (XHigh), autonomous) --- src/specify_cli/presets/_manager_skills.py | 241 ++++++--- tests/specify_cli/presets/test_manager.py | 17 +- .../presets/test_manager_skills.py | 469 +++++++++++++++++- 3 files changed, 633 insertions(+), 94 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index fb20c18e3c..f64d4b3b4a 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -677,7 +677,7 @@ def _reconcile_preset_aliases( continue skills_dir = ( active_skills_dir - if agent == active_ai + if agent == active_ai and active_skills_dir is not None else self._safe_skills_dir_for_agent(agent) ) if skills_dir is None: @@ -735,12 +735,13 @@ def _reconcile_preset_aliases( else: if not self._validate_skill_subdir( skill_dir, create=False, skills_root=skills_dir - ) or not skill_file.is_file(): + ): continue try: - content = skill_file.read_text(encoding="utf-8") + with FileHelper(skills_dir) as files: + content = files.read_text(Path(skill_name) / "SKILL.md") hard_linked = skill_file.stat().st_nlink > 1 - except (OSError, UnicodeDecodeError): + except (OSError, ValueError): continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = ( @@ -754,10 +755,10 @@ def _reconcile_preset_aliases( if source == f"{pack_id}:{tmpl.get('file')}": # The raw marker names a file, not a command. # Other commands of the preset can render this - # alias from the same file: registration writes - # them in manifest order, so the file belongs - # to the last one, and one that replaces is - # complete without a base. + # skill (as primary or alias) from the same file: + # registration writes them in manifest order, so + # the file belongs to the last one, and one that + # replaces is complete without a base. position = templates.index(tmpl) twins = [ (idx, other) @@ -765,7 +766,20 @@ def _reconcile_preset_aliases( if other is not tmpl and other.get("type") == "command" and other.get("file") == tmpl.get("file") - and alias in (other.get("aliases") or []) + and any( + isinstance(candidate, str) + and ( + candidate == alias + or registrar._compute_output_name( + agent, candidate, agent_config + ) + == skill_name + ) + for candidate in ( + other.get("name"), + *(other.get("aliases") or []), + ) + ) ] if any(idx > position for idx, _ in twins): continue @@ -959,11 +973,14 @@ def writes_skills(agent: Any) -> bool: def resolves_here(agent: Any) -> bool: if not isinstance(agent, str): return False - agent_dir = ( - active_skills_dir - if agent == active_ai - else self._safe_skills_dir_for_agent(agent) - ) + if agent == active_ai: + agent_dir = ( + active_skills_dir + if active_skills_dir is not None or not writes_skills(agent) + else self._safe_skills_dir_for_agent(agent) + ) + else: + agent_dir = self._safe_skills_dir_for_agent(agent) return agent_dir is not None and agent_dir == skills_dir def is_registered(pack_id: str) -> bool: @@ -1086,11 +1103,33 @@ def _drop_survivor_owned_aliases( if not survivors: return registered_commands - def survivor_owned(skills_dir: Path, skill_dir: Path) -> bool: + retiring_manifest = PresetResolver(self.project_root)._get_manifest( + self.presets_dir / pack_id + ) + + def retiring_sources_for(cmd_name: str) -> Set[str]: + sources = {f"preset:{pack_id}"} + if retiring_manifest is None: + sources.add(f"{pack_id}:.composed/{cmd_name}.md") + return sources + for tmpl in retiring_manifest.templates: + if tmpl.get("type") != "command": + continue + primary = tmpl.get("name") + aliases = tmpl.get("aliases") or [] + if primary != cmd_name and cmd_name not in aliases: + continue + if isinstance(primary, str): + sources.add(f"{pack_id}:.composed/{primary}.md") + if isinstance(tmpl.get("file"), str): + sources.add(f"{pack_id}:{tmpl['file']}") + return sources + + def read_source(skills_dir: Path, skill_dir: Path) -> Optional[str]: if not self._validate_skill_subdir( skill_dir, create=False, skills_root=skills_dir ): - return False + return None try: # FileHelper reads a relative path against its root, so # name the file from the skills directory, not from a @@ -1098,10 +1137,13 @@ def survivor_owned(skills_dir: Path, skill_dir: Path) -> bool: with FileHelper(skills_dir) as files: content = files.read_text(Path(skill_dir.name) / "SKILL.md") except (OSError, ValueError): - # Missing, unreadable, not a regular file or not UTF-8. - return False + # Missing, unreadable, symlinked, not a regular file or not UTF-8. + return None metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None + return source if isinstance(source, str) else None + + def is_survivor_owned(source: Optional[str]) -> bool: return ( isinstance(source, str) and source != f"preset:{pack_id}" @@ -1131,20 +1173,19 @@ def survivor_owned(skills_dir: Path, skill_dir: Path) -> bool: outputs = [output] if output != name and registrar._is_safe_command_name(name): outputs.append(name) - owned = [ - survivor_owned(skills_dir, skills_dir / candidate) + sources = [ + read_source(skills_dir, skills_dir / candidate) for candidate in outputs ] + owned = [is_survivor_owned(src) for src in sources] if not any(owned): kept.append(name) continue - for candidate, is_owned in zip(outputs, owned): - skill_dir = skills_dir / candidate - if is_owned or not self._validate_skill_subdir( - skill_dir, create=False, skills_root=skills_dir - ): + retiring_sources = retiring_sources_for(name) + for candidate, src, is_owned in zip(outputs, sources, owned): + if is_owned or not (isinstance(src, str) and src in retiring_sources): continue - skill_file = skill_dir / "SKILL.md" + skill_file = skills_dir / candidate / "SKILL.md" unlink_in_directory( skill_file, root=self.project_root if skill_file.is_relative_to(self.project_root) else skills_dir, @@ -1192,9 +1233,11 @@ def _surviving_owned_skills( if not isinstance(meta, dict): continue recorded = meta.get("registered_skills") - if isinstance(recorded, list) and active_ai: + if isinstance(recorded, list): recorded = self._infer_legacy_skill_provenance( - [n for n in recorded if isinstance(n, str)], pack_id, active_ai + [n for n in recorded if isinstance(n, str)], + pack_id, + active_ai or "", ) recorded_commands = meta.get("registered_commands") groups: Dict[Path, Dict[str, List[str]]] = {} @@ -1206,15 +1249,19 @@ def _surviving_owned_skills( if not isinstance(agent, str) or not isinstance(names, list): continue agent_config = registrar.AGENT_CONFIGS.get(agent) - if from_commands and not ( + native_skill_agent = bool( agent_config and agent_config.get("extension") == "/SKILL.md" - ): - continue - skills_dir = ( - active_skills_dir - if agent == active_ai - else self._safe_skills_dir_for_agent(agent) ) + if from_commands and not native_skill_agent: + continue + if agent == active_ai: + skills_dir = ( + active_skills_dir + if active_skills_dir is not None or not native_skill_agent + else self._safe_skills_dir_for_agent(agent) + ) + else: + skills_dir = self._safe_skills_dir_for_agent(agent) if skills_dir is None: continue group = groups.setdefault(skills_dir, {"agents": [], "names": []}) @@ -1253,14 +1300,15 @@ def _surviving_owned_skills( else sorted(agents)[0] ) for name in group["names"]: - skill_file = skills_dir / name / "SKILL.md" + skill_dir = skills_dir / name if not self._validate_skill_subdir( - skill_file.parent, create=False, skills_root=skills_dir - ) or not skill_file.is_file(): + skill_dir, create=False, skills_root=skills_dir + ): continue try: - content = skill_file.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + with FileHelper(skills_dir) as files: + content = files.read_text(Path(name) / "SKILL.md") + except (OSError, ValueError): continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None @@ -1276,30 +1324,71 @@ def _remove_owned_skills( ) -> None: """Delete ``cmd_name``'s preset-rendered skills among ``skill_names`` (journaled). - A skill is one when its ``SKILL.md`` source marker says an installed - preset rendered this command into it: ``preset:`` (skill - registration) or ``:`` with that preset's own file for the - command, raw or composed (command registration for native skill - agents). Anything else is left untouched, including another - command's alias that happens to use this skill's name. + A skill is removed only when its ``SKILL.md`` source marker + unambiguously proves an installed preset rendered ``cmd_name`` into + that output directory: ``:.composed/.md`` (which names + the command explicitly), ``preset:`` (when the preset supplies + ``cmd_name`` and no other command of the preset maps to the same skill + directory), or ``:`` (when no other command's primary name + or alias in the preset shares that file and output directory). + Anything else or any ambiguous ownership is preserved. """ from ..integrations._file_changes import unlink_in_directory registrar = self._command_registrar() resolver = PresetResolver(self.project_root) - owned_sources: Set[str] = set() + target_names = list(dict.fromkeys(skill_names)) + cmd_skill_names = set(self._skill_names_for_command(cmd_name)) + owned_sources_by_name: Dict[str, Set[str]] = { + name: set() for name in target_names + } for pack_id in self.registry.list(): - owned_sources.add(f"preset:{pack_id}") - owned_sources.add(f"{pack_id}:.composed/{cmd_name}.md") manifest = resolver._get_manifest(self.presets_dir / pack_id) - for tmpl in manifest.templates if manifest else []: - if ( - tmpl.get("type") == "command" - and tmpl.get("name") == cmd_name - and isinstance(tmpl.get("file"), str) + if not manifest: + continue + cmd_templates = [ + tmpl + for tmpl in manifest.templates + if tmpl.get("type") == "command" + and isinstance(tmpl.get("name"), str) + ] + matching = [tmpl for tmpl in cmd_templates if tmpl["name"] == cmd_name] + if not matching: + continue + other_templates = [ + tmpl for tmpl in cmd_templates if tmpl["name"] != cmd_name + ] + for name in target_names: + if name not in cmd_skill_names: + continue + sources = owned_sources_by_name[name] + sources.add(f"{pack_id}:.composed/{cmd_name}.md") + if not any( + name in self._skill_names_for_command(other["name"]) + for other in other_templates ): - owned_sources.add(f"{pack_id}:{tmpl['file']}") - for name in dict.fromkeys(skill_names): + sources.add(f"preset:{pack_id}") + for tmpl in matching: + file_rel = tmpl.get("file") + if not isinstance(file_rel, str): + continue + if not any( + other.get("file") == file_rel + and any( + isinstance(candidate, str) + and name in self._skill_names_for_command(candidate) + for candidate in ( + other["name"], + *(other.get("aliases") or []), + ) + ) + for other in other_templates + ): + sources.add(f"{pack_id}:{file_rel}") + for name in target_names: + owned_sources = owned_sources_by_name[name] + if not owned_sources: + continue skill_dir = skills_dir / name skill_file = skill_dir / "SKILL.md" if not self._validate_skill_subdir( @@ -1622,15 +1711,21 @@ def _register_skills( for cmd_tmpl in command_templates: cmd_name = cmd_tmpl["name"] cmd_file_rel = cmd_tmpl["file"] - source_file = preset_dir / cmd_file_rel - if not source_file.exists(): - continue - - # Use composed content if available (written by _register_commands - # for commands with non-replace strategies), otherwise the original. - composed_file = preset_dir / ".composed" / f"{cmd_name}.md" - if composed_file.exists(): - source_file = composed_file + override = (content_overrides or {}).get(cmd_name) + source_rel = Path(cmd_file_rel) + if override is None: + with FileHelper(preset_dir) as files: + if files.file_mode(source_rel) is None: + continue + # Use composed content if available (written by + # _register_commands for commands with non-replace + # strategies), otherwise the original. + composed_rel = Path(".composed") / f"{cmd_name}.md" + try: + if files.file_mode(composed_rel) is not None: + source_rel = composed_rel + except (FileNotFoundError, NotADirectoryError): + pass # Derive the short command name (e.g. "specify" from "speckit.specify") raw_short_name = cmd_name @@ -1659,11 +1754,13 @@ def _register_skills( if not target_skill_names: continue - # Parse the command file - content = source_file.read_text(encoding="utf-8") - override = (content_overrides or {}).get(cmd_name) + # Parse the command file (skip obsolete .composed cache when + # caller already supplied the resolved composition). if override is not None: content = override + else: + with FileHelper(preset_dir) as files: + content = files.read_text(source_rel) frontmatter, body = registrar.parse_frontmatter(content) # A composition-strategy command (wrap/prepend/append) needs a @@ -1850,12 +1947,10 @@ def _infer_legacy_skill_provenance( skill_subdir, create=False, skills_root=resolved_dir ): continue - skill_file = skill_subdir / "SKILL.md" - if not skill_file.is_file(): - continue try: - content = skill_file.read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError): + with FileHelper(resolved_dir) as files: + content = files.read_text(Path(name) / "SKILL.md") + except (OSError, ValueError): continue frontmatter, _ = registrar.parse_frontmatter(content) skill_metadata = frontmatter.get("metadata") diff --git a/tests/specify_cli/presets/test_manager.py b/tests/specify_cli/presets/test_manager.py index ff1738ab4c..bdf296cd84 100644 --- a/tests/specify_cli/presets/test_manager.py +++ b/tests/specify_cli/presets/test_manager.py @@ -1493,7 +1493,7 @@ def test_remove_after_partial_skills_to_command_toggle_deletes_stale_skill( ) def test_partial_skill_install_failure_rolls_back_persisted_writes( - self, project_dir, temp_dir, monkeypatch + self, project_dir, temp_dir ): """Install rollback must reload partial skill ownership before removal.""" self._write_init_options(project_dir, ai="copilot", ai_skills=True) @@ -1504,18 +1504,7 @@ def test_partial_skill_install_failure_rolls_back_persisted_writes( ["speckit.specify", "speckit.plan"], ) manager = PresetManager(project_dir) - original_read_text = Path.read_text - - def fail_plan_source(path, *args, **kwargs): - if ( - path.name == "speckit.plan.md" - and path.parent.name == "commands" - and "partial-install-failure-preset" in path.parts - ): - raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid") - return original_read_text(path, *args, **kwargs) - - monkeypatch.setattr(Path, "read_text", fail_plan_source) + (preset_dir / "commands" / "speckit.plan.md").write_bytes(b"\xff") with pytest.raises(UnicodeDecodeError): manager.install_from_directory(preset_dir, "0.1.5") @@ -1532,7 +1521,7 @@ def fail_plan_source(path, *args, **kwargs): assert ( not skill_file.exists() or "preset:partial-install-failure-preset" - not in original_read_text(skill_file, encoding="utf-8") + not in skill_file.read_text(encoding="utf-8") ), "rollback must not orphan a skill written before the later failure" diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index aba95709b1..e66ffcb4d3 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2797,17 +2797,33 @@ def test_remove_base_does_not_compose_other_agents_layer_into_historical_dir( assert "Core custom body" in content and "Middle body" in content @pytest.mark.parametrize( - "extension_agent,unrelated_claude_command", - [("codex", False), ("codex", True), ("claude", False)], - ids=["codex", "codex-unrelated-claude-command", "claude"], + "extension_agent,mode,expect_kept", + [ + ("codex", "registered-codex-only", False), + ("codex", "unrelated-claude-command", False), + ("claude", "registered-claude", True), + ("codex", "legacy-flat-skills", True), + ("codex", "missing-command-metadata", True), + ("codex", "unregistered-extension", True), + ], + ids=[ + "codex", + "codex-unrelated-claude-command", + "claude", + "legacy-flat-skills", + "missing-command-metadata", + "unregistered-extension", + ], ) def test_historical_skill_uses_only_registered_extension( - self, project_dir, temp_dir, extension_agent, unrelated_claude_command + self, project_dir, temp_dir, extension_agent, mode, expect_kept ): """Removing a base must not introduce another agent's extension into a historical skill or alias; a registered base must survive. Another command of the extension recorded for Claude (a partial - registration) does not register this one there.""" + registration) does not register this one there. Legacy fallback paths + (nonempty flat ``registered_skills`` or missing command-registration + metadata) preserve the extension base.""" self._write_init_options(project_dir, ai=extension_agent, ai_skills=True) for folder in (".agents", ".claude"): (project_dir / folder / "skills").mkdir(parents=True) @@ -2836,7 +2852,7 @@ def test_historical_skill_uses_only_registered_extension( extension_agent: ["speckit.foreign.run"] } assert extensions.registry.get("foreign")["registered_skills"] == [] - if unrelated_claude_command: + if mode == "unrelated-claude-command": extensions.registry.update( "foreign", { @@ -2846,6 +2862,18 @@ def test_historical_skill_uses_only_registered_extension( } }, ) + elif mode == "legacy-flat-skills": + extensions.registry.update( + "foreign", + {"registered_skills": ["speckit-foreign-run"]}, + ) + elif mode == "missing-command-metadata": + meta = dict(extensions.registry.get("foreign")) + meta.pop("registered_commands", None) + extensions.registry.data["extensions"]["foreign"] = meta + extensions.registry._save() + elif mode == "unregistered-extension": + extensions.registry.remove("foreign") self._write_init_options(project_dir, ai="claude", ai_skills=True) self._create_skill(project_dir / ".claude" / "skills", "speckit-foreign-run") @@ -2872,7 +2900,7 @@ def test_historical_skill_uses_only_registered_extension( manager.register_enabled_presets_for_agent("codex") assert manager.remove("base-preset") for output in (skill, alias): - if extension_agent == "codex": + if not expect_kept: assert not output.exists(), output.read_text(encoding="utf-8") else: content = output.read_text(encoding="utf-8") @@ -3670,6 +3698,433 @@ def test_remove_base_decides_alias_ownership_per_file( else: assert content == survivor_text + @pytest.mark.parametrize("survivor_file", ["current", "dotted"]) + @pytest.mark.parametrize("alternate_kind", ["user-authored", "unreadable", "symlink"]) + def test_remove_base_preserves_unowned_alternate_alias_spelling( + self, project_dir, temp_dir, survivor_file, alternate_kind + ): + """When a survivor owns one alias spelling, removal must only delete + the other spelling if it carries an exact retiring-preset marker; a + user-authored, unreadable, or symlinked alternate file stays intact.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + current = self._alias_skill(project_dir) + dotted = current.parent.parent / self._ALIAS / "SKILL.md" + survivor_text = current.read_text(encoding="utf-8") + assert "source: append-preset:" in survivor_text + dotted.parent.mkdir() + + if survivor_file == "current": + kept, alternate = current, dotted + else: + dotted.write_text(survivor_text, encoding="utf-8") + current.unlink() + kept, alternate = dotted, current + + outside_target = temp_dir / "outside-alias.md" + if alternate_kind == "user-authored": + alt_bytes = b"---\nname: speckit-custom-short\n---\n\nUser custom alias\n" + alternate.write_bytes(alt_bytes) + elif alternate_kind == "unreadable": + alt_bytes = b"---\nname: speckit-custom-short\n---\n\n\xff\xfe\n" + alternate.write_bytes(alt_bytes) + else: + outside_target.write_text( + "---\nname: speckit-custom-short\nmetadata:\n" + " source: base-preset:commands/speckit.custom.md\n---\n\nOutside\n", + encoding="utf-8", + ) + try: + alternate.symlink_to(outside_target) + except OSError as exc: + pytest.skip(f"symlinks unavailable: {exc}") + + assert manager.remove("base-preset") is True + + if alternate_kind == "symlink": + assert alternate.is_symlink() + assert outside_target.read_text(encoding="utf-8").endswith("Outside\n") + else: + assert alternate.read_bytes() == alt_bytes + content = kept.read_text(encoding="utf-8") + assert "source: append-preset:" in content + + @pytest.mark.parametrize("core", [True, False], ids=["refresh", "retire"]) + def test_reconcile_preset_aliases_rejects_symlinked_skill_file( + self, project_dir, temp_dir, core + ): + """A symlinked alias SKILL.md pointing to a file with the composer's + ownership marker must neither be refreshed nor unlinked on removal.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + if core: + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Appended body", "append", 5) + alias_file = self._alias_skill(project_dir) + original = alias_file.read_text(encoding="utf-8") + assert "source: append-preset:" in original + + outside = temp_dir / "linked-alias.md" + outside.write_text(original, encoding="utf-8") + alias_file.unlink() + try: + alias_file.symlink_to(outside) + except OSError as exc: + pytest.skip(f"symlinks unavailable: {exc}") + + with warnings.catch_warnings(): + if not core: + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-preset") is True + + assert alias_file.is_symlink() + assert outside.read_text(encoding="utf-8") == original + + @pytest.mark.parametrize("core", [True, False], ids=["refresh", "retire"]) + def test_surviving_owned_skills_rejects_symlinked_primary_skill_file( + self, project_dir, temp_dir, core + ): + """A symlinked primary SKILL.md pointing to a file with the surviving + composer's ownership marker must neither be overwritten nor deleted.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=core) + skill_file = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + original = skill_file.read_text(encoding="utf-8") + assert "source: preset:append-preset" in original + + outside = temp_dir / "linked-primary.md" + outside.write_text(original, encoding="utf-8") + skill_file.unlink() + try: + skill_file.symlink_to(outside) + except OSError as exc: + pytest.skip(f"symlinks unavailable: {exc}") + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert manager.remove("base-preset") is True + + assert not any( + "symlinked" in str(w.message).lower() for w in caught + ), [str(w.message) for w in caught] + assert skill_file.is_symlink() + assert outside.read_text(encoding="utf-8") == original + + @pytest.mark.parametrize("core", [True, False], ids=["core", "no-core"]) + def test_alias_reconcile_preserves_later_replace_primary_sharing_source_file( + self, project_dir, temp_dir, monkeypatch, core + ): + """An append command aliasing a later replace command's primary name + with the same source file must not overwrite or delete that primary + skill when a skills-phase failure leaves the raw marker in place.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skills = project_dir / ".claude" / "skills" + for name in ("speckit-a", "speckit-b"): + self._create_skill(claude_skills, name) + if core: + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "a.md").write_text( + "---\ndescription: Core a\n---\n\nCore a body\n", encoding="utf-8" + ) + manager = PresetManager(project_dir) + base = self._create_command_preset( + temp_dir, "base-a", "speckit.a", "base-a", "Base a body" + ) + manager.install_from_directory(base, "0.1.5", priority=10) + + preset_dir = self._create_multi_command_preset( + temp_dir, "multi", ["speckit.a", "speckit.b"] + ) + (preset_dir / "commands" / "shared.md").write_text( + "---\ndescription: multi\n---\n\nShared fragment\n", encoding="utf-8" + ) + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + for tmpl in manifest["provides"]["templates"]: + tmpl["file"] = "commands/shared.md" + if tmpl["name"] == "speckit.a": + tmpl["strategy"] = "append" + tmpl["aliases"] = ["speckit.b"] + else: + tmpl["strategy"] = "replace" + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + + self._write_init_options(project_dir, ai="codex", ai_skills=True) + skills_dir = project_dir / ".agents" / "skills" + skills_dir.mkdir(parents=True) + original_register_skills = manager._register_skills + + def fail_multi_skills(m, *args, **kwargs): + if m.id == "multi": + raise RuntimeError("simulated skills failure") + return original_register_skills(m, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_register_skills", fail_multi_skills) + with pytest.warns(UserWarning, match="simulated skills failure"): + manager.register_enabled_presets_for_agent("codex") + + primary_b = skills_dir / "speckit-b" / "SKILL.md" + installed_b = primary_b.read_text(encoding="utf-8") + assert "source: multi:commands/shared.md" in installed_b + assert "Base a body" not in installed_b + + with warnings.catch_warnings(): + if not core: + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-a") is True + + assert primary_b.read_text(encoding="utf-8") == installed_b + + @pytest.mark.parametrize("ai_skills", [False, None], ids=["false", "absent"]) + def test_native_skill_agent_keeps_base_in_shared_dir_when_ai_skills_off( + self, project_dir, temp_dir, ai_skills + ): + """When Codex is active with ``ai_skills`` false or absent, its native + command registrations still live in ``.agents/skills`` shared with an + agy-owned composer. Removing a higher base must keep Codex's lower + base rather than retiring the composer's skill and alias.""" + import json + + shared = project_dir / ".agents" / "skills" + shared.mkdir(parents=True) + opts = {"ai": "codex"} if ai_skills is None else {"ai": "codex", "ai_skills": False} + (project_dir / ".specify" / "init-options.json").write_text( + json.dumps(opts), encoding="utf-8" + ) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("low-preset", "Low codex body", "replace", 12, alias=False) + assert manager.registry.get("low-preset")["registered_commands"] == { + "codex": ["speckit.custom"] + } + + self._write_init_options(project_dir, ai="agy", ai_skills=True) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Appended body", "append", 5) + for name in ("speckit-custom", "speckit-custom-short"): + before = (shared / name / "SKILL.md").read_text(encoding="utf-8") + assert "Base preset body" in before and "Appended body" in before + + (project_dir / ".specify" / "init-options.json").write_text( + json.dumps(opts), encoding="utf-8" + ) + + assert manager.remove("base-preset") is True + + for name in ("speckit-custom", "speckit-custom-short"): + text = (shared / name / "SKILL.md").read_text(encoding="utf-8") + assert "Low codex body" in text + assert "Appended body" in text + assert "Base preset body" not in text + + @pytest.mark.parametrize("init_state", ["missing", "corrupt"]) + @pytest.mark.parametrize("core", [True, False], ids=["core-fallback", "no-fallback"]) + def test_remove_base_reconciles_legacy_flat_survivor_without_active_ai( + self, project_dir, temp_dir, init_state, core + ): + """When init-options.json is missing or unreadable (``active_ai`` is + ``None``), a surviving composer with a legacy flat ``registered_skills`` + list must still have its on-disk skill discovered and reconciled.""" + manager = self._install_custom_layers(project_dir, temp_dir, core=core) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + assert "Base preset body" in claude_skill.read_text(encoding="utf-8") + manager.registry.update( + "append-preset", + {"registered_skills": ["speckit-custom"], "registered_commands": {}}, + ) + init_file = project_dir / ".specify" / "init-options.json" + if init_state == "missing": + init_file.unlink() + else: + init_file.write_text("{not valid json", encoding="utf-8") + + with warnings.catch_warnings(): + if not core: + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-preset") is True + + if core: + content = claude_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content + else: + assert not claude_skill.exists() + + def test_baseless_composer_preserves_other_presets_colliding_normalized_skill( + self, project_dir, temp_dir + ): + """Two distinct commands (``speckit.custom-short`` and + ``speckit.custom.short``) normalize to the same skill directory + ``speckit-custom-short``. Retiring a baseless composer for one must + not delete another preset's skill for the other command.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + skills_dir = project_dir / ".claude" / "skills" + self._create_skill(skills_dir, "speckit-custom-short") + manager = PresetManager(project_dir) + + base = self._create_command_preset( + temp_dir, "base-dash", "speckit.custom-short", "base-dash", "Base dash body" + ) + manager.install_from_directory(base, "0.1.5", priority=10) + append = self._create_command_preset( + temp_dir, "append-dash", "speckit.custom-short", "append-dash", "Append dash" + ) + path = append / "preset.yml" + data = yaml.safe_load(path.read_text(encoding="utf-8")) + data["provides"]["templates"][0]["strategy"] = "append" + path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(append, "0.1.5", priority=5) + + other = self._create_command_preset( + temp_dir, "other-dot", "speckit.custom.short", "other-dot", "Other dot body" + ) + manager.install_from_directory(other, "0.1.5", priority=20) + skill = skills_dir / "speckit-custom-short" / "SKILL.md" + other_content = skill.read_text(encoding="utf-8") + assert "source: preset:other-dot" in other_content + assert "Other dot body" in other_content + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-dash") is True + manager.register_enabled_presets_for_agent("claude") + + assert skill.is_file() + assert skill.read_text(encoding="utf-8") == other_content + + def test_baseless_composer_preserves_same_preset_colliding_normalized_skill( + self, project_dir, temp_dir + ): + """When one preset defines both a baseless append command + ``speckit.custom-short`` and a replace command ``speckit.custom.short`` + normalizing to ``speckit-custom-short``, the ``preset:`` marker is + ambiguous and must not be deleted on rescaffold.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + skills_dir = project_dir / ".claude" / "skills" + self._create_skill(skills_dir, "speckit-custom-short") + manager = PresetManager(project_dir) + + base = self._create_command_preset( + temp_dir, "base-dash", "speckit.custom-short", "base-dash", "Base dash body" + ) + manager.install_from_directory(base, "0.1.5", priority=10) + + preset_dir = self._create_multi_command_preset( + temp_dir, "multi", ["speckit.custom-short", "speckit.custom.short"] + ) + (preset_dir / "commands" / "speckit.custom.short.md").write_text( + "---\ndescription: multi dot\n---\n\nDot replace body\n", encoding="utf-8" + ) + manifest_path = preset_dir / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + for tmpl in data["provides"]["templates"]: + tmpl["strategy"] = ( + "append" if tmpl["name"] == "speckit.custom-short" else "replace" + ) + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + + skill = skills_dir / "speckit-custom-short" / "SKILL.md" + assert "Dot replace body" in skill.read_text(encoding="utf-8") + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-dash") is True + + assert skill.is_file() + assert "Dot replace body" in skill.read_text(encoding="utf-8") + + def test_baseless_composer_preserves_shared_file_replace_alias_after_rescaffold( + self, project_dir, temp_dir + ): + """A preset supplies both a baseless append command ``speckit.a`` and a + replace command ``speckit.b`` sharing one source file, where ``speckit.b`` + declares ``speckit.a`` as an alias. After rescaffolding, ``speckit.b``'s + valid alias skill shares the raw marker and must not be deleted.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + skills_dir = project_dir / ".agents" / "skills" + skills_dir.mkdir(parents=True) + manager = PresetManager(project_dir) + + base = self._create_command_preset( + temp_dir, "base-a", "speckit.a", "base-a", "Base a body" + ) + manager.install_from_directory(base, "0.1.5", priority=10) + + preset_dir = self._create_multi_command_preset( + temp_dir, "multi", ["speckit.a", "speckit.b"] + ) + (preset_dir / "commands" / "shared.md").write_text( + "---\ndescription: multi\n---\n\nShared replace body\n", encoding="utf-8" + ) + manifest_path = preset_dir / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + for tmpl in data["provides"]["templates"]: + tmpl["file"] = "commands/shared.md" + if tmpl["name"] == "speckit.a": + tmpl["strategy"] = "append" + else: + tmpl["strategy"] = "replace" + tmpl["aliases"] = ["speckit.a"] + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-a") is True + manager.register_enabled_presets_for_agent("codex") + + alias_skill = skills_dir / "speckit-a" / "SKILL.md" + assert alias_skill.is_file() + content = alias_skill.read_text(encoding="utf-8") + assert "source: multi:commands/shared.md" in content + assert "Shared replace body" in content + + def test_historical_owner_refresh_ignores_corrupt_obsolete_composed_cache( + self, project_dir, temp_dir + ): + """When removal resolves ``content_overrides`` for a historical owner + from surviving layers, an unreadable or invalid-UTF-8 obsolete + ``.composed`` cache must not block refreshing the skill.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skill = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("middle-preset", "Middle body", "append", 7, alias=False) + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager.register_enabled_presets_for_agent("codex") + # Only Codex gets top-preset, so Claude takes the refresh_owner path + # with content_overrides. + install("top-preset", "Top body", "append", 5, alias=False) + + obsolete_cache = ( + project_dir / ".specify" / "presets" / "middle-preset" + / ".composed" / "speckit.custom.md" + ) + obsolete_cache.parent.mkdir(parents=True, exist_ok=True) + obsolete_cache.write_bytes(b"\xff\xfeinvalid utf-8") + + assert manager.remove("base-preset") is True + + content = claude_skill.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core custom body" in content and "Middle body" in content + assert "Top body" not in content + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) def test_remove_base_keeps_native_survivor_after_partial_skill_registration( self, project_dir, temp_dir, monkeypatch, historical From 6c7f17e1aebab702b893ad5fc1d67e238b0bbed3 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:35:58 +0530 Subject: [PATCH 40/41] fix(presets): reconcile legacy aliases, restore removed survivor aliases, and require unambiguous ownership Address review feedback on preset removal and skill/alias reconciliation: - Reconcile both modern and legacy dotted alias spellings independently in _reconcile_preset_aliases, refreshing or retiring only owned files. - Track exact alias outputs deleted during removal (and their pre-deletion modes) so registered surviving owners restore them without recreating unrelated user-deleted files. - Handle disabled composing presets explicitly during removal instead of shielding stale dependent aliases while preserving independent disabled replace outputs. - Guard manifest loads against PresetValidationError (including PresetSectionValidationError) in _drop_survivor_owned_aliases and related skill reconciliation helpers. - Decide shared-alias cleanup per spelling using exact retiring sources and actual survivor registrations, preserving unowned/user-stripped files and preventing cross-preset marker collisions. - Keep all affected commands per normalized skill directory in _surviving_owned_skills and require unambiguous command ownership before refreshing skills. Assisted-by: Antigravity (model: Gemini 4 Neon (High), autonomous) --- src/specify_cli/presets/_manager.py | 8 +- src/specify_cli/presets/_manager_skills.py | 1264 ++++++++++++----- .../presets/test_manager_skills.py | 445 +++++- 3 files changed, 1394 insertions(+), 323 deletions(-) diff --git a/src/specify_cli/presets/_manager.py b/src/specify_cli/presets/_manager.py index 377e36e02b..865a8c8179 100644 --- a/src/specify_cli/presets/_manager.py +++ b/src/specify_cli/presets/_manager.py @@ -897,9 +897,14 @@ def remove(self, pack_id: str) -> bool: registered_commands = commands_to_unregister # Unregister non-skill command files from AI agents. + deleted_alias_outputs: Dict[Path, Set[str]] = {} if registered_commands: registered_commands = self._drop_survivor_owned_aliases( - pack_id, registered_commands + pack_id, + registered_commands, + deleted_outputs=deleted_alias_outputs, + retired_modes=retired_skill_modes, + removed_cmd_names=removed_cmd_names, ) if registered_commands: self._unregister_commands(registered_commands) @@ -920,6 +925,7 @@ def remove(self, pack_id: str) -> bool: list(removed_cmd_names), extra_skills_dirs=affected_skill_dirs, new_file_modes=retired_skill_modes, + removed_alias_outputs=deleted_alias_outputs, ) except Exception as exc: import warnings diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index f64d4b3b4a..a8aec851e9 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -107,6 +107,7 @@ def _reconcile_skills( ] = None, target_agent: Optional[str] = None, new_file_modes: Optional[Dict[Path, int]] = None, + removed_alias_outputs: Optional[Dict[Path, Set[str]]] = None, ) -> Set[str]: """Re-register skills for commands whose winning layer changed. @@ -125,6 +126,10 @@ def _reconcile_skills( new_file_modes: Permission bits of the ``SKILL.md`` files the removed preset had, by path (:meth:`_skill_file_modes`). A skill written where one of them was deleted takes its bits. + removed_alias_outputs: ``{skills_dir: {skill_name, ...}}`` for + outputs deleted during this removal pass so surviving owners + can restore only those outputs without recreating unrelated + user-deleted files. Returns: Command names whose skill output was successfully written. @@ -467,9 +472,23 @@ def apply_to_dir( # A project override wins the command for every agent, so the # owner's composition is not what belongs there: let the # winner pass below render the override, as a rescaffold does. + # When multiple affected commands share this skill directory + # name (e.g. ``speckit.custom-short`` and ``speckit.custom.short``), + # route through ``owner_refreshes`` so ``apply_to_dir`` cannot + # overwrite the file with a colliding command's winner. overridden = layers[0]["source"] == "project override" + collides_with_other_cmd = ( + sum( + 1 + for other_cmd in command_names + if name in self._skill_names_for_command(other_cmd) + ) + > 1 + ) if overridden or ( - owner_idx == 0 and len(registered_here) == len(layers) + owner_idx == 0 + and len(registered_here) == len(layers) + and not collides_with_other_cmd ): prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) extra_dirs[skills_dir] = ( @@ -574,6 +593,16 @@ def refresh_owner( for (skills_dir, agent, owner_id), owned in owner_refreshes.items(): attempt(refresh_owner, skills_dir, agent, owner_id, owned) + combined_removed_outputs: Dict[Path, Set[str]] = { + skills_dir: set(names) + for skills_dir, names in (removed_alias_outputs or {}).items() + if names + } + if extra_skills_dirs: + for skills_dir, (_agent, names) in extra_skills_dirs.items(): + if names: + combined_removed_outputs.setdefault(skills_dir, set()).update(names) + attempt( self._reconcile_preset_aliases, command_names, @@ -582,12 +611,71 @@ def refresh_owner( active_skills_dir, create_missing=extra_skills_dirs is None, removal_pass=extra_skills_dirs is not None, + removed_alias_outputs=combined_removed_outputs or None, + new_file_modes=new_file_modes, ) if failures: raise failures[0] return reconciled_skill_commands + def _render_alias_skill_text( + self, + registrar: "CommandRegistrar", + agent: str, + agent_config: Dict[str, Any], + alias: str, + skill_name: str, + raw_content: str, + pack_id: str, + source_rel: str, + version: Optional[str], + ) -> str: + """Render a native-skill alias ``SKILL.md`` for an explicit output dir.""" + from ..integrations import get_integration + + frontmatter, body = registrar.parse_frontmatter(raw_content) + if frontmatter.get("strategy") == "wrap": + body, core_frontmatter = _substitute_core_template( + body, alias, self.project_root, registrar + ) + frontmatter = dict(frontmatter) + for key in ("scripts", "agent_scripts"): + if key not in frontmatter and key in core_frontmatter: + frontmatter[key] = core_frontmatter[key] + frontmatter.pop("strategy", None) + frontmatter = registrar._adjust_script_paths(frontmatter) + for key in agent_config.get("strip_frontmatter_keys", []): + frontmatter.pop(key, None) + if agent_config.get("inject_name") and not frontmatter.get("name"): + format_name = agent_config.get("format_name") + frontmatter["name"] = format_name(alias) if format_name else alias + sep = agent_config.get("invoke_separator", ".") + try: + integration = get_integration(agent) + if integration is not None: + sep = integration.invoke_separator_for_mode(True) + frontmatter, body = integration.process_registered_command( + frontmatter, body, source_id=pack_id + ) + except (ImportError, ValueError, KeyError): + pass + prefix = get_invocation_prefix(agent, True) + body = registrar._convert_argument_placeholder( + body, "$ARGUMENTS", agent_config["args"] + ) + body = IntegrationBase.resolve_command_refs(body, sep, prefix) + return registrar.render_skill_command( + agent, + skill_name, + frontmatter, + body, + pack_id, + source_rel, + self.project_root, + version=version, + ) + def _reconcile_preset_aliases( self, command_names: List[str], @@ -597,6 +685,8 @@ def _reconcile_preset_aliases( *, create_missing: bool = False, removal_pass: bool = False, + removed_alias_outputs: Optional[Dict[Path, Set[str]]] = None, + new_file_modes: Optional[Dict[Path, int]] = None, ) -> None: """Re-render, retire or restore native-skill aliases of composed commands. @@ -621,8 +711,15 @@ def _reconcile_preset_aliases( active-only (the single-active rule of #2948); an alias that is no longer composable is still retired wherever it is recorded, mirroring stale-output retirement. + removed_alias_outputs: ``{skills_dir: {skill_name, ...}}`` for + outputs deleted during this removal so a registered surviving + owner can restore them without recreating unrelated + user-deleted files. + new_file_modes: Pre-deletion permission bits by path for restored + outputs. """ from ..integrations._file_changes import unlink_in_directory + from ..shared_infra import _write_shared_text try: registrar = self._command_registrar() @@ -635,37 +732,80 @@ def _reconcile_preset_aliases( # others stale: go on, and raise the first failure at the end. failures: List[Exception] = [] - for pack_id, meta in presets_by_priority: - if not isinstance(meta, dict): - continue - recorded = meta.get("registered_commands") - if not isinstance(recorded, dict): - continue - pack_dir = self.presets_dir / pack_id - manifest = resolver._get_manifest(pack_dir) - if not manifest: - continue - alias_to_tmpl: Dict[str, Dict[str, Any]] = {} - templates = list(manifest.templates) - for tmpl in templates: - if tmpl.get("type") != "command" or tmpl.get("name") not in wanted: - continue - if tmpl.get("strategy", "replace") == "replace": - # A replace layer's own file did not change. - continue - for alias in tmpl.get("aliases") or []: - if isinstance(alias, str): - alias_to_tmpl[alias] = tmpl - if not alias_to_tmpl: - continue + def probe_alias_file( + skills_dir: Path, skill_name: str + ) -> tuple[bool, Optional[str], bool]: + """Return ``(missing, content, skip)`` without following symlinks.""" + skill_dir = skills_dir / skill_name + try: + with FileHelper(skills_dir) as files: + mode = files.file_mode(Path(skill_name) / "SKILL.md") + if mode is None: + return True, None, False + if not self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ): + return False, None, True + content = files.read_text(Path(skill_name) / "SKILL.md") + return False, content, False + except FileNotFoundError: + return True, None, False + except (OSError, ValueError): + return False, None, True + + def check_alias_ownership( + pack_id: str, + tmpl: Dict[str, Any], + templates: List[Dict[str, Any]], + agent: str, + agent_config: Dict[str, Any], + alias: str, + skill_name: str, + content: str, + ) -> tuple[bool, bool]: + """Return ``(owned, standalone_twin)`` for an alias output file.""" + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + source = ( + metadata.get("source") if isinstance(metadata, dict) else None + ) + if source == f"{pack_id}:.composed/{tmpl['name']}.md": + return True, False + if source != f"{pack_id}:{tmpl.get('file')}": + return False, False + position = templates.index(tmpl) + twins = [ + (idx, other) + for idx, other in enumerate(templates) + if other is not tmpl + and other.get("type") == "command" + and other.get("file") == tmpl.get("file") + and any( + isinstance(candidate, str) + and ( + candidate == alias + or candidate == skill_name + or registrar._compute_output_name( + agent, candidate, agent_config + ) + == skill_name + ) + for candidate in ( + other.get("name"), + *(other.get("aliases") or []), + ) + ) + ] + if any(idx > position for idx, _ in twins): + return False, False + standalone_twin = any( + other.get("strategy", "replace") == "replace" + for _, other in twins + ) + return True, standalone_twin - # Several native skill agents can resolve to one physical - # directory (agy/codex/zed all use ``.agents/skills``). Rendering - # it once per recorded agent would let whichever agent is iterated - # last win, writing another agent's command-reference syntax over - # the active one's. Group by resolved directory and render with - # the active agent when it shares that directory, exactly as - # ``_unregister_skills`` does. + def group_recorded_agents( + recorded: Dict[str, Any], + ) -> Dict[Path, Dict[str, Any]]: groups: Dict[Path, Dict[str, Any]] = {} for agent, names in recorded.items(): agent_config = registrar.AGENT_CONFIGS.get(agent) @@ -687,207 +827,428 @@ def _reconcile_preset_aliases( for name in names: if isinstance(name, str) and name not in group["aliases"]: group["aliases"].append(name) + return groups - for skills_dir, group in groups.items(): - agents = group["agents"] - # Same choice as the primary skill of that directory, as - # long as the active agent's registrar writes skills. An - # agent in skills mode can share this directory while its - # registrar still emits command files (Amp writes - # ``.agents/commands/*.md`` but uses ``.agents/skills``): it - # would look for the alias under the dotted command name and - # write a ``.md`` file here. A recorded agent renders then. - active_config = ( - registrar.AGENT_CONFIGS.get(active_ai) - if isinstance(active_ai, str) - else None + def pick_renderer_agent(skills_dir: Path, agents: List[str]) -> str: + active_config = ( + registrar.AGENT_CONFIGS.get(active_ai) + if isinstance(active_ai, str) + else None + ) + return ( + active_ai + if active_ai in agents + or ( + skills_dir == active_skills_dir + and active_config is not None + and active_config.get("extension") == "/SKILL.md" ) - agent = ( - active_ai - if active_ai in agents - or ( - skills_dir == active_skills_dir - and active_config is not None - and active_config.get("extension") == "/SKILL.md" - ) - else sorted(agents)[0] + else sorted(agents)[0] + ) + + for pack_id, meta in presets_by_priority: + if not isinstance(meta, dict): + continue + recorded = meta.get("registered_commands") + if not isinstance(recorded, dict): + continue + pack_dir = self.presets_dir / pack_id + manifest = self._safe_get_manifest(resolver, pack_dir) + if not manifest: + continue + alias_to_tmpl: Dict[str, tuple[Dict[str, Any], bool]] = {} + templates = list(manifest.templates) + for tmpl in templates: + if tmpl.get("type") != "command": + continue + tmpl_aliases = [ + a for a in (tmpl.get("aliases") or []) if isinstance(a, str) + ] + primary_wanted = tmpl.get("name") in wanted + alias_wanted = bool(removed_alias_outputs) and any( + a in wanted for a in tmpl_aliases ) + if not primary_wanted and not alias_wanted: + continue + if tmpl.get("strategy", "replace") == "replace" and not removed_alias_outputs: + # A replace layer's own file did not change unless a + # retiring higher layer just deleted its shared output. + continue + for alias in tmpl_aliases: + if primary_wanted or alias in wanted: + alias_to_tmpl[alias] = (tmpl, primary_wanted) + if not alias_to_tmpl: + continue + + # Several native skill agents can resolve to one physical + # directory (agy/codex/zed all use ``.agents/skills``). Rendering + # it once per recorded agent would let whichever agent is iterated + # last win, writing another agent's command-reference syntax over + # the active one's. Group by resolved directory and render with + # the active agent when it shares that directory, exactly as + # ``_unregister_skills`` does. + groups = group_recorded_agents(recorded) + + for skills_dir, group in groups.items(): + agent = pick_renderer_agent(skills_dir, group["agents"]) agent_config = registrar.AGENT_CONFIGS[agent] # Rendering follows the single-active rule outside a removal # pass; retiring an uncomposable alias is allowed anywhere. may_render = removal_pass or skills_dir == active_skills_dir + removed_in_dir = (removed_alias_outputs or {}).get(skills_dir, set()) for alias in group["aliases"]: - tmpl = alias_to_tmpl.get(alias) if isinstance(alias, str) else None - if tmpl is None: + entry = alias_to_tmpl.get(alias) if isinstance(alias, str) else None + if entry is None: continue - skill_name = registrar._compute_output_name(agent, alias, agent_config) - skill_dir = skills_dir / skill_name - skill_file = skill_dir / "SKILL.md" - # Retiring an alias removes only ``SKILL.md``; its - # directory stays when it holds other files. So "missing" - # is about the file, not the directory. - missing = not skill_file.exists() and not skill_file.is_symlink() - hard_linked = False - standalone_twin = False - if missing: - if not (create_missing and skills_dir == active_skills_dir): + tmpl, primary_wanted = entry + modern_skill_name = registrar._compute_output_name( + agent, alias, agent_config + ) + candidate_skill_names = [modern_skill_name] + if ( + modern_skill_name != alias + and registrar._is_safe_command_name(alias) + ): + candidate_skill_names.append(alias) + + probed = [] + for skill_name in candidate_skill_names: + missing, content, skip = probe_alias_file( + skills_dir, skill_name + ) + owned = False + standalone_twin = False + if not missing and not skip and content is not None: + owned, standalone_twin = check_alias_ownership( + pack_id, + tmpl, + templates, + agent, + agent_config, + alias, + skill_name, + content, + ) + probed.append( + (skill_name, missing, skip, owned, standalone_twin) + ) + has_existing_owned = any( + not missing and owned + for _, missing, _, owned, _ in probed + ) + is_replace = tmpl.get("strategy", "replace") == "replace" + + for ( + skill_name, + missing, + skip, + owned, + standalone_twin, + ) in probed: + if skip: continue - else: - if not self._validate_skill_subdir( - skill_dir, create=False, skills_root=skills_dir - ): + is_legacy = skill_name != modern_skill_name + was_removed = skill_name in removed_in_dir + can_restore_removed = ( + was_removed and not has_existing_owned + ) + if missing: + can_create_active = ( + create_missing + and skills_dir == active_skills_dir + and not is_legacy + ) + if not (can_restore_removed or can_create_active): + continue + if (is_replace or not primary_wanted) and not can_restore_removed: + continue + else: + if is_replace or not primary_wanted or not owned: + continue + + skill_dir = skills_dir / skill_name + skill_file = skill_dir / "SKILL.md" + primary = tmpl["name"] + layers = resolver.collect_all_layers(primary, "command") + owner_idx = next( + ( + idx + for idx, layer in enumerate(layers) + if layer["path"].is_relative_to(pack_dir) + ), + None, + ) + if owner_idx is None: continue - try: - with FileHelper(skills_dir) as files: - content = files.read_text(Path(skill_name) / "SKILL.md") - hard_linked = skill_file.stat().st_nlink > 1 - except (OSError, ValueError): + # The alias belongs to the highest layer registered in + # this directory that declares it, not to whichever + # layer wins the primary command. + higher_layers = self._layers_registered_in( + layers[:owner_idx], + skills_dir, + active_ai, + active_skills_dir, + primary, + ) + alias_shadowed = any( + self._layer_declares_alias( + resolver, layer, primary, alias + ) + for layer in higher_layers + ) + if alias_shadowed and missing: continue - metadata = registrar.parse_frontmatter(content)[0].get("metadata") - source = ( - metadata.get("source") if isinstance(metadata, dict) else None + + if is_replace: + if not may_render: + continue + if not self._validate_skill_subdir( + skill_dir, create=True, skills_root=skills_dir + ): + continue + raw_rel = tmpl.get("file") + if not isinstance(raw_rel, str): + continue + try: + with FileHelper(pack_dir) as files: + raw_content = files.read_text(Path(raw_rel)) + rendered = self._render_alias_skill_text( + registrar, + agent, + agent_config, + alias, + skill_name, + raw_content, + pack_id, + raw_rel, + manifest.version, + ) + _write_shared_text( + skills_dir, + skill_file, + rendered, + preserve_mode=True, + new_file_mode=(new_file_modes or {}).get( + skill_file + ), + ) + except (ValueError, OSError) as exc: + failures.append(exc) + continue + + # A shadowed alias is not ours to render outside a + # removal pass. It still goes through the retirement + # check below: a rescaffold re-registers it from the raw + # fragment, which must not stay executable once nothing + # is left to compose onto. On a removal pass an existing + # shadowed alias is refreshed from its own layer down, as + # its primary skill is. + shadowed = alias_shadowed and not removal_pass + owner_layers = self._layers_registered_in( + layers[owner_idx:], + skills_dir, + active_ai, + active_skills_dir, + primary, ) - # Command registration marks the alias with the file - # it was rendered from. Requiring this command's own - # file (raw or composed) leaves alone an alias name - # another command of the preset declares too and was - # registered for last. - if source == f"{pack_id}:{tmpl.get('file')}": - # The raw marker names a file, not a command. - # Other commands of the preset can render this - # skill (as primary or alias) from the same file: - # registration writes them in manifest order, so - # the file belongs to the last one, and one that - # replaces is complete without a base. - position = templates.index(tmpl) - twins = [ - (idx, other) - for idx, other in enumerate(templates) - if other is not tmpl - and other.get("type") == "command" - and other.get("file") == tmpl.get("file") - and any( - isinstance(candidate, str) - and ( - candidate == alias - or registrar._compute_output_name( - agent, candidate, agent_config + composed = resolver.resolve_content( + primary, "command", layers=owner_layers + ) + if composed is None: + if ( + missing + or standalone_twin + or any( + layer["strategy"] == "replace" + for layer in owner_layers + ) + ): + # A replace base is still there, so this is a + # resolution failure (e.g. an unreadable layer), + # not a missing base: keep the alias, as the + # primary-skill path keeps its output. So is an + # alias another command of the preset renders + # from this file without needing a base. + continue + alias_file = skill_dir / "SKILL.md" + try: + unlink_in_directory( + alias_file, + root=( + self.project_root + if alias_file.is_relative_to( + self.project_root ) - == skill_name - ) - for candidate in ( - other.get("name"), - *(other.get("aliases") or []), - ) + else skills_dir + ), ) - ] - if any(idx > position for idx, _ in twins): + except (ValueError, OSError) as exc: + failures.append(exc) + continue + if shadowed or not may_render: + continue + hard_linked = False + if not missing: + try: + hard_linked = skill_file.stat().st_nlink > 1 + except OSError: continue - standalone_twin = any( - other.get("strategy", "replace") == "replace" - for _, other in twins + if hard_linked: + # Command registration writes the alias in place, + # which would reach every other link of the file. + # As elsewhere for generated artifacts with extra + # links, it is not ours to rewrite: leave it, and + # say that it no longer matches the preset stack. + import warnings + + warnings.warn( + f"Alias skill {skill_file} has other hard links " + f"and was not refreshed. It may still contain " + f"content from a preset that is no longer " + f"installed; delete it and reinstall the preset " + f"to regenerate it.", + stacklevel=2, ) - elif source != f"{pack_id}:.composed/{tmpl['name']}.md": continue - - primary = tmpl["name"] - layers = resolver.collect_all_layers(primary, "command") - owner_idx = next( - ( - idx - for idx, layer in enumerate(layers) - if layer["path"].is_relative_to(pack_dir) - ), - None, - ) - if owner_idx is None: - continue - # The alias belongs to the highest layer that declares - # it, not to whichever layer wins the primary command: a - # higher preset that does not declare this alias leaves - # it to us. Only a higher declarer shadows it. - alias_shadowed = any( - self._layer_declares_alias(resolver, layer, primary, alias) - for layer in layers[:owner_idx] - ) - if alias_shadowed and missing: - continue - # A shadowed alias is not ours to render outside a - # removal pass. It still goes through the retirement - # check below: a rescaffold re-registers it from the raw - # fragment, which must not stay executable once nothing - # is left to compose onto. On a removal pass an existing - # shadowed alias is refreshed from its own layer down, as - # its primary skill is. - shadowed = alias_shadowed and not removal_pass - owner_layers = self._layers_registered_in( - layers[owner_idx:], skills_dir, active_ai, active_skills_dir, - primary, - ) - composed = resolver.resolve_content( - primary, "command", layers=owner_layers - ) - if composed is None: - if missing or standalone_twin or any( - layer["strategy"] == "replace" for layer in owner_layers + if missing and not self._validate_skill_subdir( + skill_dir, create=True, skills_root=skills_dir ): - # A replace base is still there, so this is a - # resolution failure (e.g. an unreadable layer), - # not a missing base: keep the alias, as the - # primary-skill path keeps its output. So is an - # alias another command of the preset renders - # from this file without needing a base. continue - alias_file = skill_dir / "SKILL.md" + composed_file = pack_dir / ".composed" / f"{primary}.md" try: - unlink_in_directory( - alias_file, - root=self.project_root if alias_file.is_relative_to(self.project_root) else skills_dir, + self._write_alias_composed_cache( + composed_file, composed ) except (ValueError, OSError) as exc: failures.append(exc) - continue - if shadowed or not may_render: - continue - if hard_linked: - # Command registration writes the alias in place, - # which would reach every other link of the file. - # As elsewhere for generated artifacts with extra - # links, it is not ours to rewrite: leave it, and - # say that it no longer matches the preset stack. - import warnings - - warnings.warn( - f"Alias skill {skill_file} has other hard links " - f"and was not refreshed. It may still contain " - f"content from a preset that is no longer " - f"installed; delete it and reinstall the preset " - f"to regenerate it.", - stacklevel=2, + continue + saved_mode = ( + (new_file_modes or {}).get(skill_file) + if missing + else None ) - continue - if missing and not self._validate_skill_subdir( - skill_dir, create=True, skills_root=skills_dir + try: + if not is_legacy and saved_mode is None: + registrar.register_commands( + agent, + [ + { + "name": alias, + "file": f".composed/{primary}.md", + } + ], + pack_id, + pack_dir, + self.project_root, + _resolved_dir=skills_dir, + version=manifest.version, + ) + else: + rendered = self._render_alias_skill_text( + registrar, + agent, + agent_config, + alias, + skill_name, + composed, + pack_id, + f".composed/{primary}.md", + manifest.version, + ) + _write_shared_text( + skills_dir, + skill_file, + rendered, + preserve_mode=True, + new_file_mode=saved_mode, + ) + except (ValueError, OSError) as exc: + failures.append(exc) + + if removal_pass: + # Disabled composing presets are excluded from presets_by_priority, + # so any alias they previously composed onto the removed layer + # would otherwise stay executable with the removed layer's text. + # Retire only outputs still carrying the disabled composer's own + # marker for a command affected by this removal. + disabled_presets = [ + (pack_id, meta) + for pack_id, meta in self.registry.list_by_priority( + include_disabled=True + ) + if isinstance(meta, dict) and not meta.get("enabled", True) + ] + for pack_id, meta in disabled_presets: + recorded = meta.get("registered_commands") + if not isinstance(recorded, dict): + continue + pack_dir = self.presets_dir / pack_id + manifest = self._safe_get_manifest(resolver, pack_dir) + if not manifest: + continue + alias_to_tmpl = {} + templates = list(manifest.templates) + for tmpl in templates: + if ( + tmpl.get("type") != "command" + or tmpl.get("name") not in wanted + or tmpl.get("strategy", "replace") == "replace" ): continue - composed_file = pack_dir / ".composed" / f"{primary}.md" - try: - self._write_alias_composed_cache(composed_file, composed) - except (ValueError, OSError) as exc: - failures.append(exc) - continue - try: - registrar.register_commands( - agent, - [{"name": alias, "file": f".composed/{primary}.md"}], - pack_id, - pack_dir, - self.project_root, - _resolved_dir=skills_dir, - version=manifest.version, + for alias in tmpl.get("aliases") or []: + if isinstance(alias, str): + alias_to_tmpl[alias] = tmpl + if not alias_to_tmpl: + continue + groups = group_recorded_agents(recorded) + for skills_dir, group in groups.items(): + agent = pick_renderer_agent(skills_dir, group["agents"]) + agent_config = registrar.AGENT_CONFIGS[agent] + for alias in group["aliases"]: + tmpl = alias_to_tmpl.get(alias) + if tmpl is None: + continue + modern_skill_name = registrar._compute_output_name( + agent, alias, agent_config ) - except (ValueError, OSError) as exc: - failures.append(exc) + candidate_skill_names = [modern_skill_name] + if ( + modern_skill_name != alias + and registrar._is_safe_command_name(alias) + ): + candidate_skill_names.append(alias) + for skill_name in candidate_skill_names: + missing, content, skip = probe_alias_file( + skills_dir, skill_name + ) + if missing or skip or content is None: + continue + owned, standalone_twin = check_alias_ownership( + pack_id, + tmpl, + templates, + agent, + agent_config, + alias, + skill_name, + content, + ) + if not owned or standalone_twin: + continue + alias_file = skills_dir / skill_name / "SKILL.md" + try: + unlink_in_directory( + alias_file, + root=( + self.project_root + if alias_file.is_relative_to( + self.project_root + ) + else skills_dir + ), + ) + except (ValueError, OSError) as exc: + failures.append(exc) if failures: raise failures[0] @@ -1048,6 +1409,16 @@ def is_registered(pack_id: str) -> bool: kept.append(layer) return kept + @staticmethod + def _safe_get_manifest( + resolver: PresetResolver, pack_dir: Path + ) -> Optional["PresetManifest"]: + """Load a preset manifest, treating validation errors as unavailable.""" + try: + return resolver._get_manifest(pack_dir) + except PresetValidationError: + return None + def _layer_declares_alias( self, resolver: Any, layer: Dict[str, Any], primary: str, alias: str ) -> bool: @@ -1058,7 +1429,7 @@ def _layer_declares_alias( return False if not rel.parts: return False - manifest = resolver._get_manifest(self.presets_dir / rel.parts[0]) + manifest = self._safe_get_manifest(resolver, self.presets_dir / rel.parts[0]) if not manifest: return False return any( @@ -1069,29 +1440,41 @@ def _layer_declares_alias( ) def _drop_survivor_owned_aliases( - self, pack_id: str, registered_commands: Dict[str, List[str]] + self, + pack_id: str, + registered_commands: Dict[str, List[str]], + *, + deleted_outputs: Optional[Dict[Path, Set[str]]] = None, + retired_modes: Optional[Dict[Path, int]] = None, + removed_cmd_names: Optional[Set[str]] = None, ) -> Dict[str, List[str]]: - """Leave out native-skill outputs another installed preset now owns. + """Clean retiring native-skill outputs per spelling without harming survivors. Two presets can declare the same command or alias. For native skill agents both record it in ``registered_commands``, but only one file exists, carrying the ``:`` marker of whichever registered it last, or a ``preset:`` marker after skill registration. A partial skill registration can leave a primary command in this - cleanup list too. Deleting either output with the preset being - removed would drop a survivor's skill that post-removal - reconciliation (which does not create missing outputs on a removal - pass) cannot bring back, so keep - those names out of the unregister list and let reconciliation - recompose them. - - ``unregister_commands()`` removes a skill under its current name - and under the dotted name older releases wrote - (``speckit.custom-short/SKILL.md``). Ownership is decided for each - of the two files: when a survivor owns only one, the name is still - left out, and the other file is removed here, as the unregister - would have removed it. + cleanup list too. + + Ownership is decided per spelling (modern output name and legacy + dotted name) against the retiring preset's exact sources and each + survivor's actual registrations in that directory: + + - Outputs owned by an enabled survivor (or a disabled preset whose + command does not compose onto the retiring layer) are kept for + reconciliation or left untouched. + - Dependent outputs owned by a disabled composing preset are retired + here because post-removal reconciliation excludes disabled presets. + - Outputs carrying an exact retiring marker are unlinked here and + recorded in ``deleted_outputs`` (with their pre-deletion bits in + ``retired_modes``) so reconciliation can restore them for a + registered surviving owner without recreating unrelated + user-deleted files. + - Unowned, user-edited, unreadable, or symlinked files for a shared + output are preserved rather than forwarded to unconditional cleanup. """ + from .. import load_init_options from ..integrations._file_changes import unlink_in_directory try: @@ -1099,13 +1482,162 @@ def _drop_survivor_owned_aliases( except ImportError: return registered_commands registrar._ensure_configs() - survivors = [pid for pid in self.registry.list() if pid != pack_id] - if not survivors: + all_others = [pid for pid in self.registry.list() if pid != pack_id] + if not all_others: return registered_commands - retiring_manifest = PresetResolver(self.project_root)._get_manifest( - self.presets_dir / pack_id + resolver = PresetResolver(self.project_root) + retiring_manifest = self._safe_get_manifest( + resolver, self.presets_dir / pack_id ) + init_opts = load_init_options(self.project_root) + active_ai = init_opts.get("ai") if isinstance(init_opts, dict) else None + if not isinstance(active_ai, str) or not active_ai: + active_ai = None + active_skills_dir = self._get_skills_dir() + + def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: + if agent_name == active_ai: + return ( + active_skills_dir + if active_skills_dir is not None or not native_skill_agent + else self._safe_skills_dir_for_agent(agent_name) + ) + return self._safe_skills_dir_for_agent(agent_name) + + # {(skills_dir, candidate_name): [(other_id, enabled, dependent_composer, markers_or_none)]} + survivor_entries: Dict[ + tuple[Path, str], + List[tuple[str, bool, bool, Optional[Set[str]]]], + ] = {} + for other in all_others: + meta = self.registry.get(other) + if not isinstance(meta, dict): + continue + enabled = bool(meta.get("enabled", True)) + other_manifest = self._safe_get_manifest( + resolver, self.presets_dir / other + ) + other_cmd_templates = ( + [ + tmpl + for tmpl in other_manifest.templates + if tmpl.get("type") == "command" + and isinstance(tmpl.get("name"), str) + ] + if other_manifest is not None + else [] + ) + reg_skills = meta.get("registered_skills") + if isinstance(reg_skills, list): + reg_skills = self._infer_legacy_skill_provenance( + [n for n in reg_skills if isinstance(n, str)], + other, + active_ai or "", + ) + if isinstance(reg_skills, dict): + for other_agent, other_skills in reg_skills.items(): + if not isinstance(other_agent, str) or not isinstance( + other_skills, list + ): + continue + other_cfg = registrar.AGENT_CONFIGS.get(other_agent) + other_native = bool( + other_cfg and other_cfg.get("extension") == "/SKILL.md" + ) + other_dir = resolve_dir(other_agent, other_native) + if other_dir is None: + continue + for skill_name in other_skills: + if not isinstance(skill_name, str): + continue + matching = [ + tmpl + for tmpl in other_cmd_templates + if skill_name + in self._skill_names_for_command(tmpl["name"]) + ] + dependent = ( + bool(matching) + and all( + tmpl.get("strategy", "replace") != "replace" + for tmpl in matching + ) + and ( + removed_cmd_names is None + or all( + tmpl["name"] in removed_cmd_names + for tmpl in matching + ) + ) + ) + survivor_entries.setdefault( + (other_dir, skill_name), [] + ).append((other, enabled, dependent, {f"preset:{other}"})) + reg_cmds = meta.get("registered_commands") + if isinstance(reg_cmds, dict): + for other_agent, other_cmds in reg_cmds.items(): + if not isinstance(other_agent, str) or not isinstance( + other_cmds, list + ): + continue + other_cfg = registrar.AGENT_CONFIGS.get(other_agent) + if not other_cfg or other_cfg.get("extension") != "/SKILL.md": + continue + other_dir = resolve_dir(other_agent, True) + if other_dir is None: + continue + for other_cmd in other_cmds: + if not isinstance(other_cmd, str): + continue + other_out = registrar._compute_output_name( + other_agent, other_cmd, other_cfg + ) + other_outs = [other_out] + if other_out != other_cmd and registrar._is_safe_command_name( + other_cmd + ): + other_outs.append(other_cmd) + if other_manifest is None: + for cand in other_outs: + survivor_entries.setdefault( + (other_dir, cand), [] + ).append((other, enabled, False, None)) + continue + matching = [ + tmpl + for tmpl in other_cmd_templates + if tmpl["name"] == other_cmd + or other_cmd in (tmpl.get("aliases") or []) + ] + if not matching: + for cand in other_outs: + survivor_entries.setdefault( + (other_dir, cand), [] + ).append( + ( + other, + enabled, + False, + {f"{other}:.composed/{other_cmd}.md"}, + ) + ) + continue + for tmpl in matching: + markers = {f"{other}:.composed/{tmpl['name']}.md"} + if isinstance(tmpl.get("file"), str): + markers.add(f"{other}:{tmpl['file']}") + dependent = ( + tmpl.get("strategy", "replace") != "replace" + and ( + removed_cmd_names is None + or tmpl["name"] in removed_cmd_names + ) + ) + for cand in other_outs: + survivor_entries.setdefault( + (other_dir, cand), [] + ).append((other, enabled, dependent, markers)) def retiring_sources_for(cmd_name: str) -> Set[str]: sources = {f"preset:{pack_id}"} @@ -1125,33 +1657,54 @@ def retiring_sources_for(cmd_name: str) -> Set[str]: sources.add(f"{pack_id}:{tmpl['file']}") return sources - def read_source(skills_dir: Path, skill_dir: Path) -> Optional[str]: + def read_source_and_mode( + skills_dir: Path, skill_dir: Path + ) -> tuple[Optional[str], Optional[int]]: if not self._validate_skill_subdir( skill_dir, create=False, skills_root=skills_dir ): - return None + return None, None try: # FileHelper reads a relative path against its root, so # name the file from the skills directory, not from a # project root that may itself be relative. with FileHelper(skills_dir) as files: - content = files.read_text(Path(skill_dir.name) / "SKILL.md") + rel = Path(skill_dir.name) / "SKILL.md" + mode = files.file_mode(rel) + if mode is None: + return None, None + content = files.read_text(rel) except (OSError, ValueError): # Missing, unreadable, symlinked, not a regular file or not UTF-8. - return None + return None, None metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None - return source if isinstance(source, str) else None - - def is_survivor_owned(source: Optional[str]) -> bool: - return ( - isinstance(source, str) - and source != f"preset:{pack_id}" - and any( - source == f"preset:{other}" or source.startswith(f"{other}:") - for other in survivors - ) - ) + return (source if isinstance(source, str) else None), mode + + def classify_survivor( + skills_dir: Path, candidate: str, source: Optional[str] + ) -> tuple[bool, bool, bool]: + """Return ``(enabled_owner, disabled_independent, disabled_dependent)``.""" + if not isinstance(source, str): + return False, False, False + entries = survivor_entries.get((skills_dir, candidate), ()) + enabled_owner = False + disabled_independent = False + disabled_dependent = False + for other, enabled, dependent, markers in entries: + if markers is None: + matched = source.startswith(f"{other}:") + else: + matched = source in markers + if not matched: + continue + if enabled: + enabled_owner = True + elif dependent: + disabled_dependent = True + else: + disabled_independent = True + return enabled_owner, disabled_independent, disabled_dependent result: Dict[str, List[str]] = {} for agent, names in registered_commands.items(): @@ -1163,7 +1716,7 @@ def is_survivor_owned(source: Optional[str]) -> bool: ): result[agent] = names continue - skills_dir = self._safe_skills_dir_for_agent(agent) + skills_dir = resolve_dir(agent, True) kept: List[str] = [] for name in names: if skills_dir is None or not isinstance(name, str): @@ -1173,27 +1726,135 @@ def is_survivor_owned(source: Optional[str]) -> bool: outputs = [output] if output != name and registrar._is_safe_command_name(name): outputs.append(name) - sources = [ - read_source(skills_dir, skills_dir / candidate) - for candidate in outputs - ] - owned = [is_survivor_owned(src) for src in sources] - if not any(owned): + any_survivor_registered = any( + survivor_entries.get((skills_dir, cand)) for cand in outputs + ) + retiring_sources = retiring_sources_for(name) + inspected = [] + any_handled = False + for candidate in outputs: + src, mode = read_source_and_mode( + skills_dir, skills_dir / candidate + ) + enabled_own, disabled_indep, disabled_dep = classify_survivor( + skills_dir, candidate, src + ) + retiring_own = ( + isinstance(src, str) and src in retiring_sources + ) + if ( + enabled_own + or disabled_indep + or disabled_dep + or retiring_own + ): + any_handled = True + inspected.append( + ( + candidate, + mode, + enabled_own, + disabled_indep, + disabled_dep, + retiring_own, + ) + ) + if not any_survivor_registered and not any_handled: kept.append(name) continue - retiring_sources = retiring_sources_for(name) - for candidate, src, is_owned in zip(outputs, sources, owned): - if is_owned or not (isinstance(src, str) and src in retiring_sources): + for ( + candidate, + mode, + enabled_own, + disabled_indep, + disabled_dep, + retiring_own, + ) in inspected: + if enabled_own or disabled_indep: + continue + if not (disabled_dep or retiring_own): continue skill_file = skills_dir / candidate / "SKILL.md" + if retired_modes is not None and mode is not None: + retired_modes.setdefault(skill_file, mode) unlink_in_directory( skill_file, - root=self.project_root if skill_file.is_relative_to(self.project_root) else skills_dir, + root=( + self.project_root + if skill_file.is_relative_to(self.project_root) + else skills_dir + ), ) + if deleted_outputs is not None: + deleted_outputs.setdefault(skills_dir, set()).add( + candidate + ) if kept: result[agent] = kept return result + def _unambiguous_command_sources( + self, + pack_id: str, + manifest: Optional["PresetManifest"], + cmd_name: str, + target_names: List[str], + ) -> Dict[str, Set[str]]: + """Return unambiguous ``metadata.source`` markers for ``cmd_name`` per skill dir. + + A marker proves ``pack_id`` rendered ``cmd_name`` into ``name`` only when: + - ``:.composed/.md`` (names the command explicitly), + - ``preset:`` (when no other command of ``pack_id`` maps to ``name``), or + - ``:`` (when no other command's primary name or alias in + ``pack_id`` shares that file and maps to ``name``). + """ + owned_sources_by_name: Dict[str, Set[str]] = { + name: set() for name in target_names + } + if manifest is None: + return owned_sources_by_name + cmd_templates = [ + tmpl + for tmpl in manifest.templates + if tmpl.get("type") == "command" + and isinstance(tmpl.get("name"), str) + ] + matching = [tmpl for tmpl in cmd_templates if tmpl["name"] == cmd_name] + if not matching: + return owned_sources_by_name + other_templates = [ + tmpl for tmpl in cmd_templates if tmpl["name"] != cmd_name + ] + cmd_skill_names = set(self._skill_names_for_command(cmd_name)) + for name in target_names: + if name not in cmd_skill_names: + continue + sources = owned_sources_by_name[name] + sources.add(f"{pack_id}:.composed/{cmd_name}.md") + if not any( + name in self._skill_names_for_command(other["name"]) + for other in other_templates + ): + sources.add(f"preset:{pack_id}") + for tmpl in matching: + file_rel = tmpl.get("file") + if not isinstance(file_rel, str): + continue + if not any( + other.get("file") == file_rel + and any( + isinstance(candidate, str) + and name in self._skill_names_for_command(candidate) + for candidate in ( + other["name"], + *(other.get("aliases") or []), + ) + ) + for other in other_templates + ): + sources.add(f"{pack_id}:{file_rel}") + return owned_sources_by_name + def _surviving_owned_skills( self, command_names: List[str], @@ -1205,14 +1866,14 @@ def _surviving_owned_skills( Reads each remaining preset's ``registered_skills`` (inferring per-agent provenance for legacy flat lists) and keeps the names whose ``SKILL.md`` - still carries that preset's ``preset:`` marker, as + unambiguously carries that preset's marker for an affected command, as ``(skills_dir, agent, owner_id, command_name, skill_name)`` tuples. For native skill agents command registration writes the same file first, marked ``:``, and records it in ``registered_commands``. When the skills phase then fails, that is - all there is, so those records and that marker (for the command's own - file, raw or composed) count as well. + all there is, so those records and that marker (when unambiguous for + the command's own file, raw or composed) count as well. Several agents can record one physical directory (agy/codex/zed all use ``.agents/skills``), so each file is returned once, with the @@ -1223,11 +1884,12 @@ def _surviving_owned_skills( registrar = self._command_registrar() registrar._ensure_configs() resolver = PresetResolver(self.project_root) - affected = { - name: cmd_name - for cmd_name in command_names - for name in self._skill_names_for_command(cmd_name) - } + affected: Dict[str, List[str]] = {} + for cmd_name in command_names: + for name in self._skill_names_for_command(cmd_name): + cmds = affected.setdefault(name, []) + if cmd_name not in cmds: + cmds.append(cmd_name) found: List[tuple[Path, Optional[str], str, str, str]] = [] for pack_id, meta in presets_by_priority: if not isinstance(meta, dict): @@ -1276,21 +1938,14 @@ def _surviving_owned_skills( output = registrar._compute_output_name( agent, name, agent_config ) - if affected.get(output) != name: + if name not in affected.get(output, ()): continue name = output if name in affected and name not in group["names"]: group["names"].append(name) - manifest = resolver._get_manifest(self.presets_dir / pack_id) - # {command_name: markers command registration writes for it} - command_sources: Dict[str, Set[str]] = {} - for tmpl in manifest.templates if manifest else []: - if tmpl.get("type") == "command" and isinstance(tmpl.get("name"), str): - sources = command_sources.setdefault( - tmpl["name"], {f"{pack_id}:.composed/{tmpl['name']}.md"} - ) - if isinstance(tmpl.get("file"), str): - sources.add(f"{pack_id}:{tmpl['file']}") + manifest = self._safe_get_manifest(resolver, self.presets_dir / pack_id) + if manifest is None: + continue for skills_dir, group in groups.items(): agents = group["agents"] agent = ( @@ -1312,11 +1967,20 @@ def _surviving_owned_skills( continue metadata = registrar.parse_frontmatter(content)[0].get("metadata") source = metadata.get("source") if isinstance(metadata, dict) else None - if source == f"preset:{pack_id}" or ( - isinstance(source, str) - and source in command_sources.get(affected[name], ()) - ): - found.append((skills_dir, agent, pack_id, affected[name], name)) + if not isinstance(source, str): + continue + matched_cmds = [ + cmd_name + for cmd_name in affected[name] + if source + in self._unambiguous_command_sources( + pack_id, manifest, cmd_name, [name] + ).get(name, ()) + ] + if len(matched_cmds) == 1: + found.append( + (skills_dir, agent, pack_id, matched_cmds[0], name) + ) return found def _remove_owned_skills( @@ -1338,53 +2002,18 @@ def _remove_owned_skills( registrar = self._command_registrar() resolver = PresetResolver(self.project_root) target_names = list(dict.fromkeys(skill_names)) - cmd_skill_names = set(self._skill_names_for_command(cmd_name)) owned_sources_by_name: Dict[str, Set[str]] = { name: set() for name in target_names } for pack_id in self.registry.list(): - manifest = resolver._get_manifest(self.presets_dir / pack_id) + manifest = self._safe_get_manifest(resolver, self.presets_dir / pack_id) if not manifest: continue - cmd_templates = [ - tmpl - for tmpl in manifest.templates - if tmpl.get("type") == "command" - and isinstance(tmpl.get("name"), str) - ] - matching = [tmpl for tmpl in cmd_templates if tmpl["name"] == cmd_name] - if not matching: - continue - other_templates = [ - tmpl for tmpl in cmd_templates if tmpl["name"] != cmd_name - ] - for name in target_names: - if name not in cmd_skill_names: - continue - sources = owned_sources_by_name[name] - sources.add(f"{pack_id}:.composed/{cmd_name}.md") - if not any( - name in self._skill_names_for_command(other["name"]) - for other in other_templates - ): - sources.add(f"preset:{pack_id}") - for tmpl in matching: - file_rel = tmpl.get("file") - if not isinstance(file_rel, str): - continue - if not any( - other.get("file") == file_rel - and any( - isinstance(candidate, str) - and name in self._skill_names_for_command(candidate) - for candidate in ( - other["name"], - *(other.get("aliases") or []), - ) - ) - for other in other_templates - ): - sources.add(f"{pack_id}:{file_rel}") + pack_sources = self._unambiguous_command_sources( + pack_id, manifest, cmd_name, target_names + ) + for name, sources in pack_sources.items(): + owned_sources_by_name[name].update(sources) for name in target_names: owned_sources = owned_sources_by_name[name] if not owned_sources: @@ -2294,8 +2923,9 @@ def _delete_agent_preset_skills( registrar = self._command_registrar() marker = f"preset:{pack_id}" override_sources: Dict[str, str] = {} - manifest = PresetResolver(self.project_root)._get_manifest( - self.presets_dir / pack_id + manifest = self._safe_get_manifest( + PresetResolver(self.project_root), + self.presets_dir / pack_id, ) if manifest is not None: for template in manifest.templates: diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index e66ffcb4d3..7db7b72fa1 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -3692,11 +3692,8 @@ def test_remove_base_decides_alias_ownership_per_file( assert not removed.parent.exists() content = kept.read_text(encoding="utf-8") assert "source: append-preset:" in content - if survivor_file == "current": - assert "Base preset body" not in content - assert "Core custom body" in content and "Appended body" in content - else: - assert content == survivor_text + assert "Base preset body" not in content + assert "Core custom body" in content and "Appended body" in content @pytest.mark.parametrize("survivor_file", ["current", "dotted"]) @pytest.mark.parametrize("alternate_kind", ["user-authored", "unreadable", "symlink"]) @@ -4125,6 +4122,444 @@ def test_historical_owner_refresh_ignores_corrupt_obsolete_composed_cache( assert "Core custom body" in content and "Middle body" in content assert "Top body" not in content + def test_remove_sole_base_retires_owned_legacy_alias_preserving_user_modern( + self, project_dir, temp_dir + ): + """When a surviving composer owns only the legacy dotted alias spelling + and the modern spelling is user-owned, removing the sole base retires + the legacy alias and preserves the user-owned modern alias.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10, alias=False) + install("append-preset", "Appended body", "append", 5) + + modern = self._alias_skill(project_dir) + dotted = modern.parent.parent / self._ALIAS / "SKILL.md" + survivor_text = modern.read_text(encoding="utf-8") + assert "source: append-preset:" in survivor_text + dotted.parent.mkdir() + dotted.write_text(survivor_text, encoding="utf-8") + user_text = "---\nname: speckit-custom-short\n---\n\nUser custom alias\n" + modern.write_text(user_text, encoding="utf-8") + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + assert manager.remove("base-preset") is True + + assert not dotted.exists() + assert modern.read_text(encoding="utf-8") == user_text + + @pytest.mark.parametrize("survivor_strategy", ["append", "replace"]) + def test_remove_higher_preset_restores_survivor_alias_without_recreating_user_deleted( + self, project_dir, temp_dir, survivor_strategy + ): + """Removing a higher-priority preset that owned a shared alias restores + that exact alias for a registered surviving owner, without recreating + unrelated user-deleted aliases or aliases deleted prior to removal.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + + survivor_dir = self._create_command_preset( + temp_dir, + "survivor-preset", + "speckit.custom", + "survivor-preset", + "Survivor body", + ) + manifest_path = survivor_dir / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + data["provides"]["templates"][0]["strategy"] = survivor_strategy + data["provides"]["templates"][0]["aliases"] = [ + "speckit.custom-short", + "speckit.custom-alt", + ] + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(survivor_dir, "0.1.5", priority=10) + + high_dir = self._create_command_preset( + temp_dir, + "high-preset", + "speckit.custom", + "high-preset", + "High preset body", + ) + high_manifest = high_dir / "preset.yml" + high_data = yaml.safe_load(high_manifest.read_text(encoding="utf-8")) + high_data["provides"]["templates"][0]["strategy"] = "replace" + high_data["provides"]["templates"][0]["aliases"] = [ + "speckit.custom-short", + "speckit.custom-gone", + ] + high_manifest.write_text(yaml.safe_dump(high_data), encoding="utf-8") + manager.install_from_directory(high_dir, "0.1.5", priority=5) + + skills_dir = project_dir / ".claude" / "skills" + shared_alias = skills_dir / "speckit-custom-short" / "SKILL.md" + user_deleted_alt = skills_dir / "speckit-custom-alt" / "SKILL.md" + user_deleted_gone = skills_dir / "speckit-custom-gone" / "SKILL.md" + assert "source: high-preset:" in shared_alias.read_text(encoding="utf-8") + user_deleted_alt.unlink() + user_deleted_gone.unlink() + + assert manager.remove("high-preset") is True + + assert shared_alias.is_file() + restored = shared_alias.read_text(encoding="utf-8") + assert "High preset body" not in restored + assert "Survivor body" in restored + assert "source: survivor-preset:" in restored + if survivor_strategy == "append": + assert "Core custom body" in restored + assert not user_deleted_alt.exists() + assert not user_deleted_gone.exists() + + @pytest.mark.parametrize("disabled_strategy", ["append", "replace"]) + def test_remove_base_handles_disabled_preset_shared_alias( + self, project_dir, temp_dir, disabled_strategy + ): + """A disabled composing preset sharing an alias with the retiring base + must not shield its stale alias from retirement; an independent + disabled replace preset keeps its alias intact.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("other-preset", "Other preset body", disabled_strategy, 5) + + alias_file = self._alias_skill(project_dir) + before = alias_file.read_text(encoding="utf-8") + assert "source: other-preset:" in before + if disabled_strategy == "append": + assert "Base preset body" in before + + manager.registry.data["presets"]["other-preset"]["enabled"] = False + manager.registry._save() + + assert manager.remove("base-preset") is True + + if disabled_strategy == "append": + assert not alias_file.exists() + else: + assert alias_file.is_file() + assert alias_file.read_text(encoding="utf-8") == before + + def test_remove_preset_with_invalid_section_metadata_succeeds_with_survivor( + self, project_dir, temp_dir + ): + """A retiring preset whose manifest fails section validation must not + abort removal in ``_drop_survivor_owned_aliases`` when another preset + is installed.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("survivor-preset", "Survivor body", "append", 5) + + retiring_manifest = ( + project_dir / ".specify" / "presets" / "base-preset" / "preset.yml" + ) + data = yaml.safe_load(retiring_manifest.read_text(encoding="utf-8")) + data["provides"]["templates"][0]["strategy"] = "replace-section" + data["provides"]["templates"][0]["selector"] = "" + retiring_manifest.write_text(yaml.safe_dump(data), encoding="utf-8") + + assert manager.remove("base-preset") is True + assert manager.registry.get("base-preset") is None + alias_content = self._alias_skill(project_dir).read_text(encoding="utf-8") + assert "Base preset body" not in alias_content + assert "Core custom body" in alias_content and "Survivor body" in alias_content + + def test_remove_shared_alias_preserves_user_stripped_marker( + self, project_dir, temp_dir + ): + """When both the retiring preset and a survivor registered an alias and + the user strips ``metadata.source``, removal must preserve the unowned + file rather than forwarding it to unconditional command cleanup.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + self._write_core_custom(project_dir) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + install("base-preset", "Base preset body", "replace", 10) + install("append-preset", "Appended body", "append", 5) + + alias_file = self._alias_skill(project_dir) + user_text = "---\nname: speckit-custom-short\n---\n\nUser owned alias\n" + alias_file.write_text(user_text, encoding="utf-8") + + assert manager.remove("base-preset") is True + assert alias_file.is_file() + assert alias_file.read_text(encoding="utf-8") == user_text + + def test_remove_preset_named_preset_cleans_file_named_other_despite_unrelated_survivor( + self, project_dir, temp_dir + ): + """Retiring preset ``preset`` with file ``other`` emits ``preset:other``; + an unrelated surviving preset named ``other`` that did not register the + alias must not prevent cleanup.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + + retiring_dir = temp_dir / "preset" + retiring_dir.mkdir() + (retiring_dir / "other").write_text( + "---\ndescription: retiring\n---\n\nRetiring body\n", encoding="utf-8" + ) + (retiring_dir / "preset.yml").write_text( + yaml.safe_dump( + { + "schema_version": "1.0", + "preset": { + "id": "preset", + "name": "Preset", + "version": "1.0.0", + "description": "Retiring preset", + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": { + "templates": [ + { + "type": "command", + "name": "speckit.custom", + "file": "other", + "strategy": "replace", + "aliases": ["speckit.custom-short"], + } + ] + }, + } + ), + encoding="utf-8", + ) + manager.install_from_directory(retiring_dir, "0.1.5", priority=10) + + other_dir = self._create_command_preset( + temp_dir, "other", "speckit.unrelated", "other", "Other body" + ) + manager.install_from_directory(other_dir, "0.1.5", priority=5) + + alias_file = self._alias_skill(project_dir) + assert "source: preset:other" in alias_file.read_text(encoding="utf-8") + + assert manager.remove("preset") is True + assert not alias_file.exists() + + @pytest.mark.parametrize( + "cmd_order", + [ + ["speckit.custom-short", "speckit.custom.short"], + ["speckit.custom.short", "speckit.custom-short"], + ], + ids=["hyphen-first", "dot-first"], + ) + def test_remove_base_with_colliding_normalized_commands_refreshes_survivor( + self, project_dir, temp_dir, cmd_order + ): + """When the removed preset provides both ``speckit.custom-short`` and + ``speckit.custom.short`` (sharing ``speckit-custom-short``), a survivor + composing one of them must refresh against its own stack regardless of + command ordering.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom-short") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom-short.md").write_text( + "---\ndescription: Core custom-short\n---\n\nCore custom-short body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + base_dir = self._create_multi_command_preset( + temp_dir, "base-preset", cmd_order + ) + for cmd in cmd_order: + (base_dir / "commands" / f"{cmd}.md").write_text( + f"---\ndescription: base {cmd}\n---\n\nBase {cmd} body\n", + encoding="utf-8", + ) + manager.install_from_directory(base_dir, "0.1.5", priority=10) + + append_dir = self._create_command_preset( + temp_dir, + "append-preset", + "speckit.custom-short", + "append-preset", + "Appended custom-short body", + ) + append_manifest = append_dir / "preset.yml" + append_data = yaml.safe_load(append_manifest.read_text(encoding="utf-8")) + append_data["provides"]["templates"][0]["strategy"] = "append" + append_manifest.write_text(yaml.safe_dump(append_data), encoding="utf-8") + manager.install_from_directory(append_dir, "0.1.5", priority=5) + + skill_file = ( + project_dir / ".claude" / "skills" / "speckit-custom-short" / "SKILL.md" + ) + assert "Base speckit.custom-short body" in skill_file.read_text( + encoding="utf-8" + ) + + # Verify _surviving_owned_skills selects the exact surviving command + # deterministically for this command order (not just the last entry). + owned = manager._surviving_owned_skills( + cmd_order, + [ + (pid, meta) + for pid, meta in manager.registry.list_by_priority() + if pid != "base-preset" + ], + "claude", + project_dir / ".claude" / "skills", + ) + assert owned == [ + ( + project_dir / ".claude" / "skills", + "claude", + "append-preset", + "speckit.custom-short", + "speckit-custom-short", + ) + ] + + assert manager.remove("base-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Base speckit.custom-short body" not in content + assert "Core custom-short body" in content + assert "Appended custom-short body" in content + + def test_remove_base_preserves_ambiguous_same_preset_colliding_replace_with_core_fallback( + self, project_dir, temp_dir + ): + """When a surviving preset defines both an append command and a replace + command normalizing to the same skill directory (``preset:``), + removing the append command's base must not overwrite the independent + replace skill with the core fallback composition.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom-short") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.short.md").write_text( + "---\ndescription: Core custom.short\n---\n\nCore fallback body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + base_dir = self._create_command_preset( + temp_dir, + "base-preset", + "speckit.custom.short", + "base-preset", + "Base preset body", + ) + manager.install_from_directory(base_dir, "0.1.5", priority=10) + + combo_dir = self._create_multi_command_preset( + temp_dir, "combo-preset", ["speckit.custom.short", "speckit.custom-short"] + ) + (combo_dir / "commands" / "speckit.custom.short.md").write_text( + "---\ndescription: append\n---\n\nAppended body\n", encoding="utf-8" + ) + (combo_dir / "commands" / "speckit.custom-short.md").write_text( + "---\ndescription: replace\n---\n\nIndependent replace body\n", + encoding="utf-8", + ) + manifest_path = combo_dir / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + for tmpl in data["provides"]["templates"]: + if tmpl["name"] == "speckit.custom.short": + tmpl["strategy"] = "append" + else: + tmpl["strategy"] = "replace" + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(combo_dir, "0.1.5", priority=5) + + skill_file = ( + project_dir / ".claude" / "skills" / "speckit-custom-short" / "SKILL.md" + ) + before = skill_file.read_text(encoding="utf-8") + assert "source: preset:combo-preset" in before + assert "Independent replace body" in before + + assert manager.remove("base-preset") is True + + assert skill_file.read_text(encoding="utf-8") == before + + def test_remove_base_preserves_shared_raw_file_later_replace_alias_with_core_fallback( + self, project_dir, temp_dir, monkeypatch + ): + """When a surviving preset has an append command and a later replace + command aliasing that primary name with the same source file, a raw + ``:`` marker left by command registration is ambiguous and + must not be overwritten with the core fallback composition.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + for name in ("speckit-a", "speckit-b"): + self._create_skill(project_dir / ".claude" / "skills", name) + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "a.md").write_text( + "---\ndescription: Core a\n---\n\nCore a fallback body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + + base_dir = self._create_command_preset( + temp_dir, "base-a", "speckit.a", "base-a", "Base a body" + ) + manager.install_from_directory(base_dir, "0.1.5", priority=10) + + preset_dir = self._create_multi_command_preset( + temp_dir, "multi", ["speckit.a", "speckit.b"] + ) + (preset_dir / "commands" / "shared.md").write_text( + "---\ndescription: multi\n---\n\nShared replace body\n", + encoding="utf-8", + ) + manifest_path = preset_dir / "preset.yml" + data = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + for tmpl in data["provides"]["templates"]: + tmpl["file"] = "commands/shared.md" + if tmpl["name"] == "speckit.a": + tmpl["strategy"] = "append" + else: + tmpl["strategy"] = "replace" + tmpl["aliases"] = ["speckit.a"] + manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8") + manager.install_from_directory(preset_dir, "0.1.5", priority=5) + + self._write_init_options(project_dir, ai="codex", ai_skills=True) + skills_dir = project_dir / ".agents" / "skills" + skills_dir.mkdir(parents=True) + original_register_skills = manager._register_skills + + def fail_multi_skills(manifest, *args, **kwargs): + if manifest.id == "multi": + raise RuntimeError("simulated skills phase failure") + return original_register_skills(manifest, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_register_skills", fail_multi_skills) + with pytest.warns(UserWarning, match="simulated skills phase failure"): + manager.register_enabled_presets_for_agent("codex") + + skill_file = skills_dir / "speckit-a" / "SKILL.md" + before = skill_file.read_text(encoding="utf-8") + assert "source: multi:commands/shared.md" in before + assert "Shared replace body" in before + + assert manager.remove("base-a") is True + + assert skill_file.read_text(encoding="utf-8") == before + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) def test_remove_base_keeps_native_survivor_after_partial_skill_registration( self, project_dir, temp_dir, monkeypatch, historical From 56053e2b8b58a92cdcc855dec6710a7eb46b0326 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:29:00 +0530 Subject: [PATCH 41/41] fix(presets): isolate skill write failures, capture disabled-composer deps, and tighten native skill ownership - Isolate skill reconciliation failures per command/skill output in both apply_to_dir() and refresh_owner() so an unwritable first output does not leave remaining composed skills stale. - Pass the primary command name separately into _render_alias_skill_text() so frontmatter-only strategy: wrap restores substitute {CORE_TEMPLATE} from the primary command rather than the alias name. - Capture actual disabled-composer dependencies before preset removal (_collect_disabled_composer_dependencies) so removing a preset above a disabled composer or hidden below an intervening replace base preserves its still-valid alias in both _drop_survivor_owned_aliases() and _reconcile_preset_aliases(). - Exclude the retiring preset's explicit preset: skill marker from prefix fallback matching for broken-manifest survivors named 'preset', and handle exact marker collisions (e.g. a survivor named 'preset' with a source file named '') by unlinking the ambiguous file and restoring the registered survivor from its own command. - Probe both modern and legacy dotted spellings for registered_commands primary skills in _surviving_owned_skills(). - Resolve the active native skills directory independently of the optional ai_skills flag (_active_native_skills_dir) for renderer selection across _surviving_owned_skills(), _reconcile_preset_aliases(), _unregister_skills(), and exact-collision restoration. - Update test_partial_skill_registration_is_persisted_before_later_failure to inject invalid UTF-8 bytes into the installed plan source (matching FileHelper reads) and assert plan registration failure alongside persisted specify tracking. Assisted-by: Antigravity (model: Gemini 4 Neon (High), autonomous) --- src/specify_cli/presets/_manager.py | 16 + src/specify_cli/presets/_manager_skills.py | 787 ++++++++++++++---- .../presets/test_manager_skills.py | 514 +++++++++++- 3 files changed, 1155 insertions(+), 162 deletions(-) diff --git a/src/specify_cli/presets/_manager.py b/src/specify_cli/presets/_manager.py index 865a8c8179..cc433cf0d0 100644 --- a/src/specify_cli/presets/_manager.py +++ b/src/specify_cli/presets/_manager.py @@ -896,8 +896,20 @@ def remove(self, pack_id: str) -> bool: ) registered_commands = commands_to_unregister + # Capture which disabled composing presets actually depended on the + # departing pack before its directory and registry record are removed, + # so neither command cleanup nor post-removal alias reconciliation + # retires a disabled composer's valid alias when the removed preset was + # above it or hidden below an intervening replace base. + disabled_composer_deps = self._collect_disabled_composer_dependencies( + pack_id, removed_cmd_names + ) + # Unregister non-skill command files from AI agents. deleted_alias_outputs: Dict[Path, Set[str]] = {} + restored_primary_owners: Dict[ + tuple[Path, Optional[str], str], Dict[str, List[str]] + ] = {} if registered_commands: registered_commands = self._drop_survivor_owned_aliases( pack_id, @@ -905,6 +917,8 @@ def remove(self, pack_id: str) -> bool: deleted_outputs=deleted_alias_outputs, retired_modes=retired_skill_modes, removed_cmd_names=removed_cmd_names, + disabled_composer_deps=disabled_composer_deps, + restored_primary_owners=restored_primary_owners, ) if registered_commands: self._unregister_commands(registered_commands) @@ -926,6 +940,8 @@ def remove(self, pack_id: str) -> bool: extra_skills_dirs=affected_skill_dirs, new_file_modes=retired_skill_modes, removed_alias_outputs=deleted_alias_outputs, + disabled_composer_deps=disabled_composer_deps, + owner_restores=restored_primary_owners or None, ) except Exception as exc: import warnings diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index a8aec851e9..b026a5db8a 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -108,6 +108,10 @@ def _reconcile_skills( target_agent: Optional[str] = None, new_file_modes: Optional[Dict[Path, int]] = None, removed_alias_outputs: Optional[Dict[Path, Set[str]]] = None, + disabled_composer_deps: Optional[Set[tuple[str, Path, str]]] = None, + owner_restores: Optional[ + Dict[tuple[Path, Optional[str], str], Dict[str, List[str]]] + ] = None, ) -> Set[str]: """Re-register skills for commands whose winning layer changed. @@ -225,6 +229,18 @@ def _reconcile_skills( core_ext_skills = [s for s in non_preset_skills if s[2]["source"] != "project override"] override_skills = [s for s in non_preset_skills if s[2]["source"] == "project override"] + # A destination or skill output that cannot be written must not leave + # the others stale: isolate failures per skill output and continue + # processing the remaining commands, directories, owners, and aliases, + # then raise the first failure so the caller still warns about it. + failures: List[Exception] = [] + + def attempt(step: Callable[..., None], *args: Any, **kwargs: Any) -> None: + try: + step(*args, **kwargs) + except Exception as exc: + failures.append(exc) + def apply_to_dir( skills_dir: Path, dir_agent: Optional[str], @@ -245,9 +261,10 @@ def apply_to_dir( for candidate in self._skill_names_for_command(cmd_name) if candidate in dir_managed_names ] - if dir_core_ext_names: - self._unregister_skills_in_dir( - dir_core_ext_names, + for core_skill_name in dict.fromkeys(dir_core_ext_names): + attempt( + self._unregister_skills_in_dir, + [core_skill_name], skills_dir, dir_agent, restore_from_bundled_core=True, @@ -354,15 +371,16 @@ def apply_to_dir( stale_cmds = [cmd for cmd in dir_cmds if cmd in unresolvable_cmds] if stale_cmds: for cmd in stale_cmds: - self._remove_owned_skills( - skills_dir, - cmd, - [ - name - for name in self._skill_names_for_command(cmd) - if name in dir_managed_names - ], - ) + for name in dict.fromkeys( + self._skill_names_for_command(cmd) + ): + if name in dir_managed_names: + attempt( + self._remove_owned_skills, + skills_dir, + cmd, + [name], + ) dir_cmds = [cmd for cmd in dir_cmds if cmd not in unresolvable_cmds] if not dir_cmds: continue @@ -374,64 +392,83 @@ def apply_to_dir( manifest = PresetManifest(manifest_path) except PresetValidationError: continue - cmds_set = set(dir_cmds) - filtered_manifest = self._FilteredManifest(manifest, cmds_set) - # Not dead code: _register_skills only *overwrites* skill - # subdirectories that already exist (plus brand-new ones for - # the active ai_skills agent). For a restore into a - # historical directory, _unregister_skills has just deleted - # the retiring preset's subdirectory, so pre-create the - # tracked (dir_managed_names) subdirectories here — under - # the same symlink guard — or the surviving preset's - # override would be silently skipped (#2948). - for cmd_name in dir_cmds: - for skill_name in self._skill_names_for_command(cmd_name): - if skill_name not in dir_managed_names: - continue + + def reconcile_one_skill( + cmd_name: str, + skill_name: str, + *, + _manifest: PresetManifest = manifest, + _pack_dir: Path = pack_dir, + _pack_id: str = pack_id, + ) -> None: + # Not dead code: _register_skills only *overwrites* skill + # subdirectories that already exist (plus brand-new ones + # for the active ai_skills agent). For a restore into a + # historical directory, _unregister_skills has just deleted + # the retiring preset's subdirectory, so pre-create the + # tracked (dir_managed_names) subdirectories here — under + # the same symlink guard — or the surviving preset's + # override would be silently skipped (#2948). + if skill_name in dir_managed_names: skill_subdir = skills_dir / skill_name if not self._validate_skill_subdir( skill_subdir, create=True, skills_root=skills_dir, ): - continue - if is_active: - # 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, only_skill_names=managed_names, - new_file_modes=new_file_modes, - ) - else: - written = self._register_skills( - filtered_manifest, pack_dir, - target_dir=skills_dir, target_agent=dir_agent or "", - only_skill_names=managed_names, - new_file_modes=new_file_modes, + return + filtered_manifest = self._FilteredManifest( + _manifest, {cmd_name} ) - if target_agent is None: - written_names = { - name - for names in written.values() - for name in names - } - else: - written_names = set(written.get(target_agent, [])) + if is_active: + # 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, + only_skill_names={skill_name}, + new_file_modes=new_file_modes, + ) + else: + written = self._register_skills( + filtered_manifest, + _pack_dir, + target_dir=skills_dir, + target_agent=dir_agent or "", + only_skill_names={skill_name}, + new_file_modes=new_file_modes, + ) + if target_agent is None: + written_names = { + name + for names in written.values() + for name in names + } + else: + written_names = set(written.get(target_agent, [])) + if skill_name in written_names: + reconciled_skill_commands.add(cmd_name) + # The winning preset may not have previously written to + # this directory's agent (most notably a historical agent + # reconciliation just restored content into via + # extra_skills_dirs). If that write isn't merged back into + # the preset's own registered_skills, its registry entry + # silently lies about which directories it owns and a + # later removal of this same preset orphans the directory + # reconciliation just wrote to on its behalf (#2948). + self._merge_pack_registered_skills(_pack_id, written) + for cmd_name in dir_cmds: - if written_names.intersection( + for skill_name in dict.fromkeys( self._skill_names_for_command(cmd_name) ): - reconciled_skill_commands.add(cmd_name) - # The winning preset may not have previously written to - # this directory's agent (most notably a historical agent - # reconciliation just restored content into via - # extra_skills_dirs). If that write isn't merged back into - # the preset's own registered_skills, its registry entry - # silently lies about which directories it owns and a - # later removal of this same preset orphans the directory - # reconciliation just wrote to on its behalf (#2948). - self._merge_pack_registered_skills(pack_id, written) + if ( + managed_names is not None + and skill_name not in managed_names + ): + continue + attempt(reconcile_one_skill, cmd_name, skill_name) extra_dirs = dict(extra_skills_dirs or {}) # {(skills_dir, agent, owner_id): {cmd_name: [skill_name, ...]}} @@ -491,23 +528,14 @@ def apply_to_dir( and not collides_with_other_cmd ): prior_agent, prior_names = extra_dirs.get(skills_dir, (agent, [])) + chosen_agent = agent if agent == active_ai else prior_agent extra_dirs[skills_dir] = ( - prior_agent, list(dict.fromkeys([*prior_names, name])) + chosen_agent, list(dict.fromkeys([*prior_names, name])) ) continue owner_refreshes.setdefault( (skills_dir, agent, owner_id), {} ).setdefault(cmd_name, []).append(name) - # A destination that cannot be written must not leave the others - # stale: finish the remaining directories and the alias pass, then - # raise the first failure so the caller still warns about it. - failures: List[Exception] = [] - - def attempt(step: Callable[..., None], *args: Any, **kwargs: Any) -> None: - try: - step(*args, **kwargs) - except Exception as exc: - failures.append(exc) if active_skills_dir: active_provenance = extra_dirs.get(active_skills_dir) @@ -540,20 +568,55 @@ def refresh_owner( agent: Optional[str], owner_id: str, owned: Dict[str, List[str]], + *, + create_missing_dirs: bool = False, ) -> None: owner_dir = self.presets_dir / owner_id try: manifest = PresetManifest(owner_dir / "preset.yml") except PresetValidationError: return - overrides: Dict[str, str] = {} + + def write_owner_skill( + cmd_name: str, skill_name: str, composed_content: str + ) -> None: + if create_missing_dirs: + if not self._validate_skill_subdir( + skills_dir / skill_name, + create=True, + skills_root=skills_dir, + ): + return + written = self._register_skills( + self._FilteredManifest(manifest, {cmd_name}), + owner_dir, + target_dir=skills_dir, + target_agent=agent or "", + only_skill_names={skill_name}, + content_overrides={cmd_name: composed_content}, + new_file_modes=new_file_modes, + ) + if target_agent is None or agent == target_agent: + written_names = { + n for names in written.values() for n in names + } + if skill_name in written_names: + reconciled_skill_commands.add(cmd_name) + for cmd_name, names in owned.items(): - layers = cmd_layers[cmd_name] + layers = cmd_layers.get(cmd_name) + if layers is None: + layers = resolver.collect_all_layers(cmd_name, "command") owner_idx = next( - idx - for idx, layer in enumerate(layers) - if layer["path"].is_relative_to(owner_dir) + ( + idx + for idx, layer in enumerate(layers) + if layer["path"].is_relative_to(owner_dir) + ), + None, ) + if owner_idx is None: + continue owner_layers = self._layers_registered_in( layers[owner_idx:], skills_dir, active_ai, active_skills_dir, cmd_name, @@ -562,37 +625,33 @@ def refresh_owner( cmd_name, "command", layers=owner_layers ) if composed is not None: - overrides[cmd_name] = composed + for skill_name in dict.fromkeys(names): + attempt(write_owner_skill, cmd_name, skill_name, composed) elif all(layer["strategy"] != "replace" for layer in owner_layers): # Nothing left under the owner to compose onto. - self._remove_owned_skills(skills_dir, cmd_name, names) + for skill_name in dict.fromkeys(names): + attempt( + self._remove_owned_skills, + skills_dir, + cmd_name, + [skill_name], + ) # Otherwise a surviving layer is unreadable: keep the # existing output rather than deleting it. - if not overrides: - return - written = self._register_skills( - self._FilteredManifest(manifest, set(overrides)), - owner_dir, - target_dir=skills_dir, - target_agent=agent or "", - only_skill_names={ - name - for cmd_name in overrides - for name in owned[cmd_name] - }, - content_overrides=overrides, - ) - if target_agent is None or agent == target_agent: - written_names = {n for names in written.values() for n in names} - reconciled_skill_commands.update( - cmd_name - for cmd_name, names in owned.items() - if written_names.intersection(names) - ) for (skills_dir, agent, owner_id), owned in owner_refreshes.items(): attempt(refresh_owner, skills_dir, agent, owner_id, owned) + for (skills_dir, agent, owner_id), owned in (owner_restores or {}).items(): + attempt( + refresh_owner, + skills_dir, + agent, + owner_id, + owned, + create_missing_dirs=True, + ) + combined_removed_outputs: Dict[Path, Set[str]] = { skills_dir: set(names) for skills_dir, names in (removed_alias_outputs or {}).items() @@ -613,6 +672,7 @@ def refresh_owner( removal_pass=extra_skills_dirs is not None, removed_alias_outputs=combined_removed_outputs or None, new_file_modes=new_file_modes, + disabled_composer_deps=disabled_composer_deps, ) if failures: @@ -630,6 +690,8 @@ def _render_alias_skill_text( pack_id: str, source_rel: str, version: Optional[str], + *, + primary_command: Optional[str] = None, ) -> str: """Render a native-skill alias ``SKILL.md`` for an explicit output dir.""" from ..integrations import get_integration @@ -637,7 +699,7 @@ def _render_alias_skill_text( frontmatter, body = registrar.parse_frontmatter(raw_content) if frontmatter.get("strategy") == "wrap": body, core_frontmatter = _substitute_core_template( - body, alias, self.project_root, registrar + body, primary_command or alias, self.project_root, registrar ) frontmatter = dict(frontmatter) for key in ("scripts", "agent_scripts"): @@ -687,6 +749,7 @@ def _reconcile_preset_aliases( removal_pass: bool = False, removed_alias_outputs: Optional[Dict[Path, Set[str]]] = None, new_file_modes: Optional[Dict[Path, int]] = None, + disabled_composer_deps: Optional[Set[tuple[str, Path, str]]] = None, ) -> None: """Re-render, retire or restore native-skill aliases of composed commands. @@ -829,19 +892,20 @@ def group_recorded_agents( group["aliases"].append(name) return groups + active_native_dir = self._active_native_skills_dir( + active_ai, active_skills_dir, registrar.AGENT_CONFIGS + ) + def pick_renderer_agent(skills_dir: Path, agents: List[str]) -> str: - active_config = ( - registrar.AGENT_CONFIGS.get(active_ai) - if isinstance(active_ai, str) - else None - ) return ( active_ai - if active_ai in agents - or ( - skills_dir == active_skills_dir - and active_config is not None - and active_config.get("extension") == "/SKILL.md" + if active_ai + and ( + active_ai in agents + or ( + active_native_dir is not None + and skills_dir == active_native_dir + ) ) else sorted(agents)[0] ) @@ -1022,6 +1086,7 @@ def pick_renderer_agent(skills_dir: Path, agents: List[str]) -> str: pack_id, raw_rel, manifest.version, + primary_command=primary, ) _write_shared_text( skills_dir, @@ -1154,6 +1219,7 @@ def pick_renderer_agent(skills_dir: Path, agents: List[str]) -> str: pack_id, f".composed/{primary}.md", manifest.version, + primary_command=primary, ) _write_shared_text( skills_dir, @@ -1208,6 +1274,12 @@ def pick_renderer_agent(skills_dir: Path, agents: List[str]) -> str: tmpl = alias_to_tmpl.get(alias) if tmpl is None: continue + if ( + disabled_composer_deps is not None + and (pack_id, skills_dir, tmpl["name"]) + not in disabled_composer_deps + ): + continue modern_skill_name = registrar._compute_output_name( agent, alias, agent_config ) @@ -1439,6 +1511,249 @@ def _layer_declares_alias( for tmpl in manifest.templates ) + def _active_native_skills_dir( + self, + active_ai: Optional[str], + active_skills_dir: Optional[Path], + agent_configs: Dict[str, Any], + ) -> Optional[Path]: + """Return the active agent's skills directory when it is a native skill agent. + + Native skill agents (``extension == "/SKILL.md"``) always render into + their skills directory even when ``ai_skills`` is false or absent, so + renderer tie-breaks must resolve their directory independently of the + optional ``ai_skills`` flag. + """ + if not isinstance(active_ai, str) or not active_ai: + return None + config = agent_configs.get(active_ai) + if not config or config.get("extension") != "/SKILL.md": + return None + if active_skills_dir is not None: + return active_skills_dir + return self._safe_skills_dir_for_agent(active_ai) + + def _collect_disabled_composer_dependencies( + self, + pack_id: str, + removed_cmd_names: Optional[Set[str]] = None, + ) -> Set[tuple[str, Path, str]]: + """Capture ``(disabled_pack_id, skills_dir, cmd_name)`` pairs that depend on ``pack_id``. + + Must run while ``pack_id`` is still in the registry and on disk. A + disabled composing preset depends on ``pack_id`` for ``cmd_name`` in + ``skills_dir`` only when: + - ``pack_id`` has lower priority (sits below the composer), + - ``pack_id`` actually supplies a command layer for ``cmd_name`` in + ``skills_dir``, and + - no enabled ``replace`` layer registered in ``skills_dir`` sits + strictly between the disabled composer and ``pack_id``. + """ + from .. import load_init_options + + all_presets = list(self.registry.list_by_priority(include_disabled=True)) + priority_rank = {pid: idx for idx, (pid, _meta) in enumerate(all_presets)} + pack_rank = priority_rank.get(pack_id) + if pack_rank is None: + return set() + disabled_presets = [ + (pid, meta) + for pid, meta in all_presets + if pid != pack_id + and isinstance(meta, dict) + and not meta.get("enabled", True) + ] + if not disabled_presets: + return set() + + try: + registrar = self._command_registrar() + except ImportError: + return set() + registrar._ensure_configs() + + resolver = PresetResolver(self.project_root) + pack_dir = self.presets_dir / pack_id + pack_manifest = self._safe_get_manifest(resolver, pack_dir) + pack_meta = self.registry.get(pack_id) + pack_enabled = ( + bool(pack_meta.get("enabled", True)) + if isinstance(pack_meta, dict) + else False + ) + if pack_manifest is not None: + pack_primary_cmds = { + tmpl["name"] + for tmpl in pack_manifest.templates + if tmpl.get("type") == "command" + and isinstance(tmpl.get("name"), str) + } + elif removed_cmd_names is not None: + pack_primary_cmds = set(removed_cmd_names) + else: + pack_primary_cmds = set() + if isinstance(pack_meta, dict): + reg_cmds = pack_meta.get("registered_commands") + if isinstance(reg_cmds, dict): + for names in reg_cmds.values(): + if isinstance(names, list): + pack_primary_cmds.update( + n for n in names if isinstance(n, str) + ) + if removed_cmd_names is not None: + pack_primary_cmds &= removed_cmd_names + if not pack_primary_cmds: + return set() + + init_opts = load_init_options(self.project_root) + active_ai = init_opts.get("ai") if isinstance(init_opts, dict) else None + if not isinstance(active_ai, str) or not active_ai: + active_ai = None + active_skills_dir = self._get_skills_dir() + + def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: + if agent_name == active_ai: + return ( + active_skills_dir + if active_skills_dir is not None or not native_skill_agent + else self._safe_skills_dir_for_agent(agent_name) + ) + return self._safe_skills_dir_for_agent(agent_name) + + enabled_layers_cache: Dict[str, Optional[List[Dict[str, Any]]]] = {} + + def get_enabled_layers(cmd_name: str) -> Optional[List[Dict[str, Any]]]: + if cmd_name not in enabled_layers_cache: + try: + enabled_layers_cache[cmd_name] = resolver.collect_all_layers( + cmd_name, "command" + ) + except PresetValidationError: + enabled_layers_cache[cmd_name] = None + return enabled_layers_cache[cmd_name] + + def pack_contributes_to( + other_id: str, cmd_name: str, skills_dir: Path + ) -> bool: + if cmd_name not in pack_primary_cmds: + return False + other_rank = priority_rank.get(other_id) + if other_rank is None or pack_rank <= other_rank: + return False + enabled_layers = get_enabled_layers(cmd_name) + if enabled_layers is None: + return True + dir_layers = self._layers_registered_in( + enabled_layers, skills_dir, active_ai, active_skills_dir, cmd_name + ) + if pack_enabled: + if not any( + layer["path"].is_relative_to(pack_dir) + for layer in dir_layers + ): + return False + else: + synthetic_layer = [ + { + "path": pack_dir / "commands" / f"{cmd_name}.md", + "source": pack_id, + "strategy": "replace", + } + ] + if not self._layers_registered_in( + synthetic_layer, + skills_dir, + active_ai, + active_skills_dir, + cmd_name, + ): + return False + for layer in dir_layers: + if layer["strategy"] != "replace": + continue + try: + rel = layer["path"].relative_to(self.presets_dir) + except (KeyError, TypeError, ValueError): + continue + if not rel.parts: + continue + mid_rank = priority_rank.get(rel.parts[0]) + if mid_rank is not None and other_rank < mid_rank < pack_rank: + return False + return True + + deps: Set[tuple[str, Path, str]] = set() + for other_id, meta in disabled_presets: + other_manifest = self._safe_get_manifest( + resolver, self.presets_dir / other_id + ) + if other_manifest is None: + continue + composing_templates = [ + tmpl + for tmpl in other_manifest.templates + if tmpl.get("type") == "command" + and isinstance(tmpl.get("name"), str) + and tmpl.get("strategy", "replace") != "replace" + ] + if not composing_templates: + continue + candidates: Set[tuple[Path, str]] = set() + reg_skills = meta.get("registered_skills") + if isinstance(reg_skills, list): + reg_skills = self._infer_legacy_skill_provenance( + [n for n in reg_skills if isinstance(n, str)], + other_id, + active_ai or "", + ) + if isinstance(reg_skills, dict): + for other_agent, other_skills in reg_skills.items(): + if not isinstance(other_agent, str) or not isinstance( + other_skills, list + ): + continue + other_cfg = registrar.AGENT_CONFIGS.get(other_agent) + other_native = bool( + other_cfg and other_cfg.get("extension") == "/SKILL.md" + ) + other_dir = resolve_dir(other_agent, other_native) + if other_dir is None: + continue + for skill_name in other_skills: + if not isinstance(skill_name, str): + continue + for tmpl in composing_templates: + if skill_name in self._skill_names_for_command( + tmpl["name"] + ): + candidates.add((other_dir, tmpl["name"])) + reg_cmds = meta.get("registered_commands") + if isinstance(reg_cmds, dict): + for other_agent, other_cmds in reg_cmds.items(): + if not isinstance(other_agent, str) or not isinstance( + other_cmds, list + ): + continue + other_cfg = registrar.AGENT_CONFIGS.get(other_agent) + if not other_cfg or other_cfg.get("extension") != "/SKILL.md": + continue + other_dir = resolve_dir(other_agent, True) + if other_dir is None: + continue + for other_cmd in other_cmds: + if not isinstance(other_cmd, str): + continue + for tmpl in composing_templates: + if ( + tmpl["name"] == other_cmd + or other_cmd in (tmpl.get("aliases") or []) + ): + candidates.add((other_dir, tmpl["name"])) + for other_dir, cmd_name in candidates: + if pack_contributes_to(other_id, cmd_name, other_dir): + deps.add((other_id, other_dir, cmd_name)) + return deps + def _drop_survivor_owned_aliases( self, pack_id: str, @@ -1447,6 +1762,10 @@ def _drop_survivor_owned_aliases( deleted_outputs: Optional[Dict[Path, Set[str]]] = None, retired_modes: Optional[Dict[Path, int]] = None, removed_cmd_names: Optional[Set[str]] = None, + disabled_composer_deps: Optional[Set[tuple[str, Path, str]]] = None, + restored_primary_owners: Optional[ + Dict[tuple[Path, Optional[str], str], Dict[str, List[str]]] + ] = None, ) -> Dict[str, List[str]]: """Clean retiring native-skill outputs per spelling without harming survivors. @@ -1482,10 +1801,19 @@ def _drop_survivor_owned_aliases( except ImportError: return registered_commands registrar._ensure_configs() - all_others = [pid for pid in self.registry.list() if pid != pack_id] + all_others = [ + pid + for pid, _meta in self.registry.list_by_priority(include_disabled=True) + if pid != pack_id + ] if not all_others: return registered_commands + if disabled_composer_deps is None: + disabled_composer_deps = self._collect_disabled_composer_dependencies( + pack_id, removed_cmd_names + ) + resolver = PresetResolver(self.project_root) retiring_manifest = self._safe_get_manifest( resolver, self.presets_dir / pack_id @@ -1495,6 +1823,14 @@ def _drop_survivor_owned_aliases( if not isinstance(active_ai, str) or not active_ai: active_ai = None active_skills_dir = self._get_skills_dir() + active_native_dir = self._active_native_skills_dir( + active_ai, active_skills_dir, registrar.AGENT_CONFIGS + ) + effective_active_dir = ( + active_skills_dir + if active_skills_dir is not None + else active_native_dir + ) def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: if agent_name == active_ai: @@ -1505,11 +1841,22 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: ) return self._safe_skills_dir_for_agent(agent_name) - # {(skills_dir, candidate_name): [(other_id, enabled, dependent_composer, markers_or_none)]} + # {(skills_dir, candidate_name): [(other_id, enabled, dependent_composer, markers_or_none, other_agent, primary_cmd_or_none)]} survivor_entries: Dict[ tuple[Path, str], - List[tuple[str, bool, bool, Optional[Set[str]]]], + List[ + tuple[ + str, + bool, + bool, + Optional[Set[str]], + str, + Optional[str], + ] + ], ] = {} + # {(other_id, skills_dir): [agent_name, ...]} for renderer tie-breaking + survivor_dir_agents: Dict[tuple[str, Path], List[str]] = {} for other in all_others: meta = self.registry.get(other) if not isinstance(meta, dict): @@ -1548,6 +1895,11 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: other_dir = resolve_dir(other_agent, other_native) if other_dir is None: continue + agents_in_dir = survivor_dir_agents.setdefault( + (other, other_dir), [] + ) + if other_agent not in agents_in_dir: + agents_in_dir.append(other_agent) for skill_name in other_skills: if not isinstance(skill_name, str): continue @@ -1558,22 +1910,30 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: in self._skill_names_for_command(tmpl["name"]) ] dependent = ( - bool(matching) + not enabled + and bool(matching) and all( tmpl.get("strategy", "replace") != "replace" + and (other, other_dir, tmpl["name"]) + in disabled_composer_deps for tmpl in matching ) - and ( - removed_cmd_names is None - or all( - tmpl["name"] in removed_cmd_names - for tmpl in matching - ) - ) + ) + primary_cmd = ( + matching[0]["name"] if len(matching) == 1 else None ) survivor_entries.setdefault( (other_dir, skill_name), [] - ).append((other, enabled, dependent, {f"preset:{other}"})) + ).append( + ( + other, + enabled, + dependent, + {f"preset:{other}"}, + other_agent, + primary_cmd, + ) + ) reg_cmds = meta.get("registered_commands") if isinstance(reg_cmds, dict): for other_agent, other_cmds in reg_cmds.items(): @@ -1587,6 +1947,11 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: other_dir = resolve_dir(other_agent, True) if other_dir is None: continue + agents_in_dir = survivor_dir_agents.setdefault( + (other, other_dir), [] + ) + if other_agent not in agents_in_dir: + agents_in_dir.append(other_agent) for other_cmd in other_cmds: if not isinstance(other_cmd, str): continue @@ -1602,7 +1967,9 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: for cand in other_outs: survivor_entries.setdefault( (other_dir, cand), [] - ).append((other, enabled, False, None)) + ).append( + (other, enabled, False, None, other_agent, None) + ) continue matching = [ tmpl @@ -1620,6 +1987,8 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: enabled, False, {f"{other}:.composed/{other_cmd}.md"}, + other_agent, + None, ) ) continue @@ -1628,19 +1997,32 @@ def resolve_dir(agent_name: str, native_skill_agent: bool) -> Optional[Path]: if isinstance(tmpl.get("file"), str): markers.add(f"{other}:{tmpl['file']}") dependent = ( - tmpl.get("strategy", "replace") != "replace" - and ( - removed_cmd_names is None - or tmpl["name"] in removed_cmd_names - ) + not enabled + and tmpl.get("strategy", "replace") != "replace" + and (other, other_dir, tmpl["name"]) + in disabled_composer_deps + ) + primary_cmd = ( + tmpl["name"] if other_cmd == tmpl["name"] else None ) for cand in other_outs: survivor_entries.setdefault( (other_dir, cand), [] - ).append((other, enabled, dependent, markers)) + ).append( + ( + other, + enabled, + dependent, + markers, + other_agent, + primary_cmd, + ) + ) + + retiring_skill_marker = f"preset:{pack_id}" def retiring_sources_for(cmd_name: str) -> Set[str]: - sources = {f"preset:{pack_id}"} + sources = {retiring_skill_marker} if retiring_manifest is None: sources.add(f"{pack_id}:.composed/{cmd_name}.md") return sources @@ -1683,28 +2065,64 @@ def read_source_and_mode( def classify_survivor( skills_dir: Path, candidate: str, source: Optional[str] - ) -> tuple[bool, bool, bool]: - """Return ``(enabled_owner, disabled_independent, disabled_dependent)``.""" + ) -> tuple[bool, bool, bool, List[tuple[str, str]]]: + """Return ``(enabled_owner, disabled_independent, disabled_dependent, colliding_primaries)``.""" if not isinstance(source, str): - return False, False, False + return False, False, False, [] entries = survivor_entries.get((skills_dir, candidate), ()) enabled_owner = False disabled_independent = False disabled_dependent = False - for other, enabled, dependent, markers in entries: + colliding_primaries: List[tuple[str, str]] = [] + for ( + other, + enabled, + dependent, + markers, + _other_agent, + primary_cmd, + ) in entries: if markers is None: - matched = source.startswith(f"{other}:") + # Exclude the retiring pack's explicit skill marker so a + # survivor named ``preset`` with a missing/invalid manifest + # cannot claim ``preset:`` via prefix match. + matched = ( + source.startswith(f"{other}:") + and source != retiring_skill_marker + ) else: matched = source in markers if not matched: continue if enabled: enabled_owner = True + if ( + primary_cmd is not None + and (other, primary_cmd) not in colliding_primaries + ): + colliding_primaries.append((other, primary_cmd)) elif dependent: disabled_dependent = True else: disabled_independent = True - return enabled_owner, disabled_independent, disabled_dependent + return ( + enabled_owner, + disabled_independent, + disabled_dependent, + colliding_primaries, + ) + + def pick_survivor_renderer(other_id: str, skills_dir: Path) -> Optional[str]: + agents = survivor_dir_agents.get((other_id, skills_dir), []) + if active_ai and ( + active_ai in agents + or ( + effective_active_dir is not None + and skills_dir == effective_active_dir + ) + ): + return active_ai + return sorted(agents)[0] if agents else None result: Dict[str, List[str]] = {} for agent, names in registered_commands.items(): @@ -1736,9 +2154,12 @@ def classify_survivor( src, mode = read_source_and_mode( skills_dir, skills_dir / candidate ) - enabled_own, disabled_indep, disabled_dep = classify_survivor( - skills_dir, candidate, src - ) + ( + enabled_own, + disabled_indep, + disabled_dep, + colliding_primaries, + ) = classify_survivor(skills_dir, candidate, src) retiring_own = ( isinstance(src, str) and src in retiring_sources ) @@ -1757,6 +2178,7 @@ def classify_survivor( disabled_indep, disabled_dep, retiring_own, + colliding_primaries, ) ) if not any_survivor_registered and not any_handled: @@ -1769,8 +2191,15 @@ def classify_survivor( disabled_indep, disabled_dep, retiring_own, + colliding_primaries, ) in inspected: - if enabled_own or disabled_indep: + # An exact marker collision (e.g. a survivor named ``preset`` + # whose source file is literally ```` matching + # ``preset:``) is ambiguous: unlink the file + # and let reconciliation restore the registered survivor + # from its own command instead of keeping possibly removed + # instructions on disk. + if (enabled_own or disabled_indep) and not retiring_own: continue if not (disabled_dep or retiring_own): continue @@ -1789,6 +2218,19 @@ def classify_survivor( deleted_outputs.setdefault(skills_dir, set()).add( candidate ) + if ( + enabled_own + and retiring_own + and colliding_primaries + and restored_primary_owners is not None + ): + other_id, primary_cmd = colliding_primaries[0] + renderer = pick_survivor_renderer(other_id, skills_dir) + restored_names = restored_primary_owners.setdefault( + (skills_dir, renderer, other_id), {} + ).setdefault(primary_cmd, []) + if candidate not in restored_names: + restored_names.append(candidate) if kept: result[agent] = kept return result @@ -1883,6 +2325,14 @@ def _surviving_owned_skills( """ registrar = self._command_registrar() registrar._ensure_configs() + active_native_dir = self._active_native_skills_dir( + active_ai, active_skills_dir, registrar.AGENT_CONFIGS + ) + effective_active_dir = ( + active_skills_dir + if active_skills_dir is not None + else active_native_dir + ) resolver = PresetResolver(self.project_root) affected: Dict[str, List[str]] = {} for cmd_name in command_names: @@ -1934,15 +2384,29 @@ def _surviving_owned_skills( continue if from_commands: # Only a primary command: aliases are reconciled - # by ``_reconcile_preset_aliases``. + # by ``_reconcile_preset_aliases``. Probe both the + # modern output name and the supported legacy dotted + # spelling so a legacy primary skill left behind + # after a failed skills phase is still reconciled. output = registrar._compute_output_name( agent, name, agent_config ) if name not in affected.get(output, ()): continue - name = output - if name in affected and name not in group["names"]: - group["names"].append(name) + candidates = [output] + if ( + output != name + and registrar._is_safe_command_name(name) + ): + candidates.append(name) + else: + candidates = [name] + for candidate in candidates: + if ( + candidate in affected + and candidate not in group["names"] + ): + group["names"].append(candidate) manifest = self._safe_get_manifest(resolver, self.presets_dir / pack_id) if manifest is None: continue @@ -1951,7 +2415,13 @@ def _surviving_owned_skills( agent = ( active_ai if active_ai - and (active_ai in agents or skills_dir == active_skills_dir) + and ( + active_ai in agents + or ( + effective_active_dir is not None + and skills_dir == effective_active_dir + ) + ) else sorted(agents)[0] ) for name in group["names"]: @@ -2858,11 +3328,36 @@ def _unregister_skills( ): group["names"].append(name) + active_skills_dir = self._get_skills_dir() + try: + registrar = self._command_registrar() + registrar._ensure_configs() + agent_configs = registrar.AGENT_CONFIGS + except ImportError: + agent_configs = {} + active_native_dir = self._active_native_skills_dir( + active_agent, active_skills_dir, agent_configs + ) + effective_active_dir = ( + active_skills_dir + if active_skills_dir is not None + else active_native_dir + ) + restored: Dict[Path, tuple[Optional[str], List[str]]] = {} for skills_dir, group in groups.items(): agents = group["agents"] renderer_agent = ( - active_agent if active_agent in agents else sorted(agents)[0] + active_agent + if active_agent + and ( + active_agent in agents + or ( + effective_active_dir is not None + and skills_dir == effective_active_dir + ) + ) + else sorted(agents)[0] ) mutated_names = self._unregister_skills_in_dir( group["names"], diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 7db7b72fa1..211760dcd2 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1405,7 +1405,7 @@ def test_preset_skill_registration_handles_non_dict_init_options(self, project_d assert "untouched" in skill_content def test_partial_skill_registration_is_persisted_before_later_failure( - self, project_dir, temp_dir, monkeypatch + self, project_dir, temp_dir ): """A successful earlier skill write remains tracked if a later read fails.""" self._write_init_options(project_dir, ai="copilot", ai_skills=False) @@ -1421,28 +1421,31 @@ def test_partial_skill_registration_is_persisted_before_later_failure( manager.install_from_directory(preset_dir, "0.1.5") self._write_init_options(project_dir, ai="copilot", ai_skills=True) - original_read_text = Path.read_text - - def fail_plan_source(path, *args, **kwargs): - if ( - path.name == "speckit.plan.md" - and path.parent.name == "commands" - and "partial-skill-failure-preset" in path.parts - ): - raise UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid") - return original_read_text(path, *args, **kwargs) + installed_plan = ( + project_dir + / ".specify" + / "presets" + / "partial-skill-failure-preset" + / "commands" + / "speckit.plan.md" + ) + installed_plan.write_bytes(b"\xff\xfeinvalid utf-8") - monkeypatch.setattr(Path, "read_text", fail_plan_source) manager.register_enabled_presets_for_agent("copilot") metadata = manager.registry.get("partial-skill-failure-preset") - assert "speckit-specify" in metadata["registered_skills"].get( - "copilot", [] - ), ( + copilot_skills = metadata["registered_skills"].get("copilot", []) + assert "speckit-specify" in copilot_skills, ( "the first successful write must be persisted before the later " "template failure aborts the registration call" ) - monkeypatch.setattr(Path, "read_text", original_read_text) + assert "speckit-plan" not in copilot_skills, ( + "the unreadable plan source must fail registration instead of " + "being silently recorded" + ) + assert not ( + project_dir / ".github" / "skills" / "speckit-plan" / "SKILL.md" + ).exists() assert manager.remove("partial-skill-failure-preset") is True remaining_skill = ( project_dir @@ -4634,6 +4637,485 @@ def fail_base_record(pack_id, written): assert not skill.exists() assert manager.registry.is_installed(survivor_id) + @pytest.mark.parametrize("manifest_state", ["missing", "invalid"]) + def test_remove_native_skill_with_broken_manifest_survivor_named_preset( + self, project_dir, temp_dir, manifest_state + ): + """A survivor named ``preset`` with a missing or invalid manifest must + not claim the retiring pack's ``preset:`` marker via + prefix fallback.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager = PresetManager(project_dir) + for preset_id, priority in [("preset", 10), ("base-preset", 5)]: + preset = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, f"{preset_id} body" + ) + manager.install_from_directory(preset, "0.1.5", priority=priority) + + # Simulate a partial skill-registry persistence failure on base-preset: + # SKILL.md carries preset:base-preset, while registered_skills lacks codex. + base_meta = manager.registry.get("base-preset") + assert "speckit.custom" in base_meta["registered_commands"]["codex"] + manager.registry.update("base-preset", {"registered_skills": {}}) + + survivor_manifest = project_dir / ".specify" / "presets" / "preset" / "preset.yml" + if manifest_state == "missing": + survivor_manifest.unlink() + else: + survivor_manifest.write_text("schema_version: [\n", encoding="utf-8") + + skill = project_dir / ".agents" / "skills" / "speckit-custom" / "SKILL.md" + assert "preset:base-preset" in skill.read_text(encoding="utf-8") + + assert manager.remove("base-preset") is True + + assert not skill.exists(), ( + "broken survivor named 'preset' must not preserve retiring " + "'preset:base-preset' skill via prefix match" + ) + + @pytest.mark.parametrize("historical", [False, True], ids=["active", "historical"]) + def test_remove_native_skill_exact_marker_collision_restores_survivor_named_preset( + self, project_dir, temp_dir, historical + ): + """When a survivor named ``preset`` has a source file literally named + ``base-preset`` (matching ``preset:base-preset``), removing + ``base-preset`` after a partial skills-registry failure must not leave + its removed instructions active; it restores the survivor from its own + command.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager = PresetManager(project_dir) + + survivor_dir = temp_dir / "preset-survivor" + survivor_dir.mkdir(parents=True) + (survivor_dir / "base-preset").write_text( + "---\ndescription: Survivor preset\n---\n\nSurvivor preset body\n", + encoding="utf-8", + ) + (survivor_dir / "preset.yml").write_text( + yaml.safe_dump( + { + "schema_version": "1.0", + "preset": { + "id": "preset", + "name": "Preset Survivor", + "version": "1.0.0", + "description": "Survivor with colliding file name", + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": { + "templates": [ + { + "type": "command", + "name": "speckit.custom", + "file": "base-preset", + "description": "Survivor custom", + "strategy": "replace", + } + ] + }, + } + ), + encoding="utf-8", + ) + manager.install_from_directory(survivor_dir, "0.1.5", priority=10) + + base_dir = self._create_command_preset( + temp_dir, "base-preset", "speckit.custom", "Base", "Retiring base body" + ) + manager.install_from_directory(base_dir, "0.1.5", priority=5) + # Simulate partial skill-registry failure: file carries preset:base-preset, + # while base-preset is tracked only in registered_commands. + manager.registry.update("base-preset", {"registered_skills": {}}) + + skill = project_dir / ".agents" / "skills" / "speckit-custom" / "SKILL.md" + assert "preset:base-preset" in skill.read_text(encoding="utf-8") + assert "Retiring base body" in skill.read_text(encoding="utf-8") + + if historical: + self._write_init_options(project_dir, ai="claude", ai_skills=True) + (project_dir / ".claude" / "skills").mkdir(parents=True, exist_ok=True) + + assert manager.remove("base-preset") is True + + assert skill.exists() + content = skill.read_text(encoding="utf-8") + assert "Survivor preset body" in content + assert "Retiring base body" not in content + + @pytest.mark.parametrize( + "pass_kind", ["active-dir", "historical-owner"] + ) + def test_remove_base_continues_remaining_composed_skills_after_write_failure( + self, project_dir, temp_dir, monkeypatch, pass_kind + ): + """A failure writing the first of two composed skills must not prevent + the second writable skill from being refreshed in either the directory + pass or the historical-owner pass.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + for suffix in ("a", "b"): + (core_cmds / f"custom-{suffix}.md").write_text( + f"---\ndescription: Core {suffix}\n---\n\nCore {suffix} body\n", + encoding="utf-8", + ) + self._create_skill( + project_dir / ".claude" / "skills", f"speckit-custom-{suffix}" + ) + + def make_two_cmd_preset(pack_id: str, strategy: str, body_prefix: str) -> Path: + pdir = temp_dir / pack_id + (pdir / "commands").mkdir(parents=True, exist_ok=True) + templates = [] + for suffix in ("a", "b"): + cmd_name = f"speckit.custom-{suffix}" + (pdir / "commands" / f"{cmd_name}.md").write_text( + f"---\ndescription: {pack_id} {suffix}\n---\n\n" + f"{body_prefix} {suffix}\n", + encoding="utf-8", + ) + templates.append( + { + "type": "command", + "name": cmd_name, + "file": f"commands/{cmd_name}.md", + "description": f"{pack_id} {suffix}", + "strategy": strategy, + } + ) + (pdir / "preset.yml").write_text( + yaml.safe_dump( + { + "schema_version": "1.0", + "preset": { + "id": pack_id, + "name": pack_id, + "version": "1.0.0", + "description": pack_id, + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": {"templates": templates}, + } + ), + encoding="utf-8", + ) + return pdir + + manager = PresetManager(project_dir) + manager.install_from_directory( + make_two_cmd_preset("base-preset", "replace", "Base body"), + "0.1.5", + priority=10, + ) + manager.install_from_directory( + make_two_cmd_preset("append-preset", "append", "Appended body"), + "0.1.5", + priority=7, + ) + + if pass_kind == "historical-owner": + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager.register_enabled_presets_for_agent("codex") + # Only Codex gets top-preset, so Claude's append-preset skills take + # the historical refresh_owner pass. + manager.install_from_directory( + make_two_cmd_preset("top-preset", "append", "Top body"), + "0.1.5", + priority=5, + ) + + import specify_cli.shared_infra as shared_infra + + original_write = shared_infra._write_shared_text + + def fail_first_skill(root, target, content, *args, **kwargs): + if ( + target.parent.name == "speckit-custom-a" + and ".claude" in target.parts + ): + raise PermissionError("simulated write failure on custom-a") + return original_write(root, target, content, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(shared_infra, "_write_shared_text", fail_first_skill) + with pytest.warns(UserWarning, match="simulated write failure on custom-a"): + assert manager.remove("base-preset") is True + + skill_b = ( + project_dir / ".claude" / "skills" / "speckit-custom-b" / "SKILL.md" + ) + content_b = skill_b.read_text(encoding="utf-8") + assert "Core b body" in content_b + assert "Appended body b" in content_b + assert "Base body b" not in content_b + + def test_restore_shared_alias_expands_frontmatter_wrap_using_primary_command( + self, project_dir, temp_dir + ): + """Restoring a shared alias for a frontmatter-only ``strategy: wrap`` + template must substitute ``{CORE_TEMPLATE}`` using the primary command + name rather than the alias name.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + + wrap_dir = temp_dir / "wrap-preset" + (wrap_dir / "commands").mkdir(parents=True) + (wrap_dir / "commands" / "speckit.custom.md").write_text( + "---\ndescription: Wrapped custom\nstrategy: wrap\n---\n\n" + "Wrap header\n\n{CORE_TEMPLATE}\n\nWrap footer\n", + encoding="utf-8", + ) + (wrap_dir / "preset.yml").write_text( + yaml.safe_dump( + { + "schema_version": "1.0", + "preset": { + "id": "wrap-preset", + "name": "Wrap Preset", + "version": "1.0.0", + "description": "Frontmatter wrap", + }, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": { + "templates": [ + { + "type": "command", + "name": "speckit.custom", + "file": "commands/speckit.custom.md", + "description": "Wrapped custom", + "aliases": ["speckit.short"], + } + ] + }, + } + ), + encoding="utf-8", + ) + + manager = PresetManager(project_dir) + manager.install_from_directory(wrap_dir, "0.1.5", priority=10) + top_dir = self._create_command_preset( + temp_dir, "top-preset", "speckit.custom", "Top", "Top override body" + ) + top_manifest_path = top_dir / "preset.yml" + top_manifest = yaml.safe_load(top_manifest_path.read_text(encoding="utf-8")) + top_manifest["provides"]["templates"][0]["strategy"] = "replace" + top_manifest["provides"]["templates"][0]["aliases"] = ["speckit.short"] + top_manifest_path.write_text(yaml.safe_dump(top_manifest), encoding="utf-8") + manager.install_from_directory(top_dir, "0.1.5", priority=5) + + alias_skill = project_dir / ".agents" / "skills" / "speckit-short" / "SKILL.md" + assert "Top override body" in alias_skill.read_text(encoding="utf-8") + + assert manager.remove("top-preset") is True + + assert alias_skill.exists() + restored = alias_skill.read_text(encoding="utf-8") + assert "Wrap header" in restored + assert "Core custom body" in restored + assert "Wrap footer" in restored + assert "{CORE_TEMPLATE}" not in restored + + @pytest.mark.parametrize( + "relation,share_alias", + [ + ("above-composer", False), + ("above-composer", True), + ("hidden-below-replace", False), + ("hidden-below-replace", True), + ], + ids=[ + "above-unshared", + "above-shared", + "below-replace-unshared", + "below-replace-shared", + ], + ) + def test_remove_unrelated_layer_preserves_disabled_composer_valid_alias( + self, project_dir, temp_dir, relation, share_alias + ): + """Removing a preset that was above a disabled composer or hidden below + its nearest ``replace`` base must not delete the disabled composer's + still-valid alias.""" + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + manager = PresetManager(project_dir) + install = functools.partial(self._install_alias_layer, manager, temp_dir) + + if relation == "above-composer": + install("base-preset", "Base body", "replace", 20, alias=False) + install("disabled-composer", "Composer body", "append", 10, alias=True) + manager.registry.update("disabled-composer", {"enabled": False}) + install("departing-top", "Top body", "replace", 5, alias=share_alias) + if share_alias: + # Re-point the shared alias file back to disabled-composer so + # _drop_survivor_owned_aliases sees disabled-composer owning it. + alias_file = ( + project_dir / ".agents" / "skills" / "speckit-custom-short" / "SKILL.md" + ) + alias_file.write_text( + "---\nname: speckit-custom-short\ndescription: Composer\nmetadata:\n" + " source: disabled-composer:.composed/speckit.custom.md\n" + "---\n\nBase body\n\nComposer body\n", + encoding="utf-8", + ) + departing_id = "departing-top" + expected_base = "Base body" + else: + install( + "departing-bottom", "Hidden bottom body", "replace", 30, alias=share_alias + ) + install("mid-base", "Mid base body", "replace", 20, alias=False) + install("disabled-composer", "Composer body", "append", 10, alias=True) + manager.registry.update("disabled-composer", {"enabled": False}) + departing_id = "departing-bottom" + expected_base = "Mid base body" + + alias_skill = ( + project_dir / ".agents" / "skills" / "speckit-custom-short" / "SKILL.md" + ) + before = alias_skill.read_text(encoding="utf-8") + assert expected_base in before and "Composer body" in before + + assert manager.remove(departing_id) is True + + assert alias_skill.exists(), ( + f"disabled composer's valid alias must survive removal of {relation} preset" + ) + after = alias_skill.read_text(encoding="utf-8") + assert expected_base in after and "Composer body" in after + + def test_remove_base_reconciles_historical_legacy_primary_skill_after_failed_skills_phase( + self, project_dir, temp_dir, monkeypatch + ): + """A historical survivor recorded only in ``registered_commands`` after + a failed skills phase must still have its legacy dotted primary skill + (``speckit.custom/SKILL.md``) refreshed when its base is removed.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + self._install_alias_layer( + manager, temp_dir, "base-preset", "Base preset body", "replace", 10, alias=False + ) + self._install_alias_layer( + manager, temp_dir, "append-preset", "Appended body", "append", 5, alias=False + ) + + # Register into codex with a failed skills phase on append-preset so + # codex is recorded only in append-preset's registered_commands. + self._write_init_options(project_dir, ai="codex", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + original = manager._register_skills + + def fail_append_skills(manifest, *args, **kwargs): + if manifest.id == "append-preset": + raise RuntimeError("simulated append skills phase failure") + return original(manifest, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(manager, "_register_skills", fail_append_skills) + with pytest.warns(UserWarning, match="simulated append skills phase failure"): + manager.register_enabled_presets_for_agent("codex") + + # Move append-preset's owned primary skill to the supported legacy dotted path. + modern_dir = project_dir / ".agents" / "skills" / "speckit-custom" + legacy_dir = project_dir / ".agents" / "skills" / "speckit.custom" + modern_dir.rename(legacy_dir) + legacy_skill = legacy_dir / "SKILL.md" + assert "Base preset body" in legacy_skill.read_text(encoding="utf-8") + assert "append-preset:.composed/speckit.custom.md" in legacy_skill.read_text( + encoding="utf-8" + ) + append_meta = manager.registry.get("append-preset") + assert "speckit.custom" in append_meta["registered_commands"]["codex"] + assert not append_meta.get("registered_skills", {}).get("codex") + + # Switch back to claude so Codex is historical. + self._write_init_options(project_dir, ai="claude", ai_skills=True) + + assert manager.remove("base-preset") is True + + refreshed = legacy_skill.read_text(encoding="utf-8") + assert "Core custom body" in refreshed + assert "Appended body" in refreshed + assert "Base preset body" not in refreshed + + @pytest.mark.parametrize("ai_skills_setting", [False, None], ids=["false", "absent"]) + def test_remove_base_uses_active_codex_renderer_when_ai_skills_false_or_absent( + self, project_dir, temp_dir, ai_skills_setting + ): + """With ``ai_skills`` false or absent, active Codex still owns + ``.agents/skills``, so removal must refresh primary and alias outputs + recorded only under ``agy`` with Codex's ``$speckit-*`` references + instead of ``agy``'s ``/speckit-*`` references.""" + self._write_init_options(project_dir, ai="agy", ai_skills=True) + (project_dir / ".agents" / "skills").mkdir(parents=True) + core_cmds = project_dir / ".specify" / "templates" / "commands" + core_cmds.mkdir(parents=True, exist_ok=True) + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\n" + "Core custom body calling __SPECKIT_COMMAND_SPECIFY__\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + self._install_alias_layer( + manager, temp_dir, "base-preset", "Base preset body", "replace", 10, alias=False + ) + self._install_alias_layer( + manager, + temp_dir, + "append-preset", + "Appended body calling __SPECKIT_COMMAND_PLAN__", + "append", + 5, + alias=True, + ) + + # Only agy recorded the outputs in .agents/skills. + append_meta = manager.registry.get("append-preset") + assert list(append_meta["registered_commands"]) == ["agy"] + + # Switch init-options to codex with ai_skills false or omitted. + import json as _json + + init_opts_path = project_dir / ".specify" / "init-options.json" + opts = {"ai": "codex"} + if ai_skills_setting is not None: + opts["ai_skills"] = ai_skills_setting + init_opts_path.write_text(_json.dumps(opts), encoding="utf-8") + + assert manager.remove("base-preset") is True + + for skill_name in ("speckit-custom", "speckit-custom-short"): + content = ( + project_dir / ".agents" / "skills" / skill_name / "SKILL.md" + ).read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "$speckit-specify" in content, ( + f"{skill_name} should use Codex's $speckit-* prefix: {content}" + ) + assert "$speckit-plan" in content, ( + f"{skill_name} should use Codex's $speckit-* prefix: {content}" + ) + assert "/speckit-specify" not in content + assert "/speckit-plan" not in content + def test_baseless_lower_composer_alias_stays_retired_after_rescaffold( self, project_dir, temp_dir ):