diff --git a/design/file-helper.md b/design/file-helper.md index b80823fb05..dcd145ea22 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -252,6 +252,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 d83c55d86d..4980bd4d7e 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -523,6 +523,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.py b/src/specify_cli/presets/_manager.py index cf6c61f434..cc433cf0d0 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 @@ -894,7 +896,30 @@ 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, + registered_commands, + 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) @@ -911,7 +936,12 @@ 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, + 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 03aef5ff11..b026a5db8a 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 @@ -12,6 +12,8 @@ from .._init_options import is_ai_skills_enabled from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter +from ..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 @@ -104,6 +106,12 @@ def _reconcile_skills( Dict[Path, tuple[Optional[str], List[str]]] ] = None, 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. @@ -119,6 +127,13 @@ 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. + 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. @@ -150,14 +165,19 @@ def _reconcile_skills( # directory-independent, so it's computed once and then applied to # every affected directory below. preset_cmds: Dict[str, List[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() + 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 @@ -194,6 +214,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 ( + 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: @@ -204,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], @@ -224,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, @@ -301,6 +339,10 @@ def apply_to_dir( skills_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 ( @@ -326,6 +368,20 @@ def apply_to_dir( 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: + for cmd in stale_cmds: + 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 pack_dir = self.presets_dir / pack_id @@ -336,65 +392,156 @@ 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) - else: - written = self._register_skills( - filtered_manifest, pack_dir, - target_dir=skills_dir, target_agent=dir_agent or "", + 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) - - extra_dirs = extra_skills_dirs or {} + 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, ...]}} + 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 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 + ): + 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 + # 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, + cmd_name, + ) + # 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) + 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] = ( + chosen_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: - apply_to_dir( + attempt( + apply_to_dir, active_skills_dir, active_ai, is_active=True, @@ -408,15 +555,1960 @@ 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), ) + def refresh_owner( + skills_dir: Path, + 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 + + 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.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) + ), + 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, + ) + composed = resolver.resolve_content( + cmd_name, "command", layers=owner_layers + ) + if composed is not None: + 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. + 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. + + 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() + 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, + presets_by_priority, + active_ai, + 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, + disabled_composer_deps=disabled_composer_deps, + ) + + 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], + *, + primary_command: Optional[str] = None, + ) -> 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, primary_command or 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], + presets_by_priority: List[Any], + active_ai: Optional[str], + active_skills_dir: Optional[Path], + *, + 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, + disabled_composer_deps: Optional[Set[tuple[str, Path, str]]] = None, + ) -> 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 for that command 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. + 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. + 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() + except ImportError: + return + 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] = [] + + 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 + + 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) + 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 and active_skills_dir is not None + else self._safe_skills_dir_for_agent(agent) + ) + if skills_dir is None: + continue + 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) + 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: + return ( + active_ai + 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] + ) + + 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"]: + entry = alias_to_tmpl.get(alias) if isinstance(alias, str) else None + if entry is None: + continue + 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 + 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 + # 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 + + 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, + primary_command=primary, + ) + _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, + ) + 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 + ) + else skills_dir + ), + ) + 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 + 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 + 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" + try: + self._write_alias_composed_cache( + composed_file, composed + ) + except (ValueError, OSError) as exc: + failures.append(exc) + continue + saved_mode = ( + (new_file_modes or {}).get(skill_file) + if missing + else None + ) + 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, + primary_command=primary, + ) + _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 + 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 + 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 + ) + 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] + + 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. 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 ..shared_infra import _ensure_safe_shared_directory, _write_shared_text + + _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 + ) + + def _layers_registered_in( + self, + layers: List[Dict[str, Any]], + skills_dir: Path, + active_ai: Optional[str], + active_skills_dir: Optional[Path], + cmd_name: str, + ) -> List[Dict[str, Any]]: + """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`` 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, + 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() + agent_configs = registrar.AGENT_CONFIGS + 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" + + def resolves_here(agent: Any) -> bool: + if not isinstance(agent, str): + return False + 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: + meta = self.registry.get(pack_id) + if not isinstance(meta, dict): + return True + if isinstance(meta.get("registered_skills"), list): + 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( + lists_command(key, names) + and (key == "registered_skills" or writes_skills(agent)) + and resolves_here(agent) + for agent, names in recorded.items() + ): + return True + return False + + 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( + lists_command("registered_commands", 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): + 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 + + @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: + """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 = self._safe_get_manifest(resolver, 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 _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, + 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, + 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. + + 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. + + 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: + registrar = self._command_registrar() + except ImportError: + return registered_commands + registrar._ensure_configs() + 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 + ) + 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() + 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: + 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, other_agent, primary_cmd_or_none)]} + survivor_entries: Dict[ + tuple[Path, 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): + 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 + 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 + matching = [ + tmpl + for tmpl in other_cmd_templates + if skill_name + in self._skill_names_for_command(tmpl["name"]) + ] + dependent = ( + 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 + ) + ) + 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}"}, + other_agent, + primary_cmd, + ) + ) + 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 + 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 + 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, other_agent, 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"}, + other_agent, + None, + ) + ) + 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 = ( + 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, + other_agent, + primary_cmd, + ) + ) + + retiring_skill_marker = f"preset:{pack_id}" + + def retiring_sources_for(cmd_name: str) -> Set[str]: + sources = {retiring_skill_marker} + 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_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, 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: + 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, 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), mode + + def classify_survivor( + skills_dir: Path, candidate: str, source: Optional[str] + ) -> 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, [] + entries = survivor_entries.get((skills_dir, candidate), ()) + enabled_owner = False + disabled_independent = False + disabled_dependent = False + colliding_primaries: List[tuple[str, str]] = [] + for ( + other, + enabled, + dependent, + markers, + _other_agent, + primary_cmd, + ) in entries: + if markers is None: + # 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, + 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(): + 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 = resolve_dir(agent, True) + kept: List[str] = [] + for name in names: + 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) + 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, + colliding_primaries, + ) = 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, + colliding_primaries, + ) + ) + if not any_survivor_registered and not any_handled: + kept.append(name) + continue + for ( + candidate, + mode, + enabled_own, + disabled_indep, + disabled_dep, + retiring_own, + colliding_primaries, + ) in inspected: + # 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 + 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 + ), + ) + if deleted_outputs is not None: + 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 + + 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], + presets_by_priority: List[Any], + active_ai: Optional[str], + active_skills_dir: Optional[Path], + ) -> 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`` + 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 (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 + 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() + 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: + 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): + continue + recorded = meta.get("registered_skills") + if isinstance(recorded, list): + recorded = self._infer_legacy_skill_provenance( + [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]]] = {} + 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) + native_skill_agent = bool( + agent_config and agent_config.get("extension") == "/SKILL.md" + ) + 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": []}) + 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``. 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 + 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 + for skills_dir, group in groups.items(): + agents = group["agents"] + agent = ( + active_ai + if active_ai + 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"]: + skill_dir = skills_dir / name + if not self._validate_skill_subdir( + skill_dir, create=False, skills_root=skills_dir + ): + continue + try: + 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 + 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( + 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 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) + target_names = list(dict.fromkeys(skill_names)) + owned_sources_by_name: Dict[str, Set[str]] = { + name: set() for name in target_names + } + for pack_id in self.registry.list(): + manifest = self._safe_get_manifest(resolver, self.presets_dir / pack_id) + if not manifest: + continue + 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: + continue + 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 + ): + continue + try: + # Named from the helper's root: see _drop_survivor_owned_aliases. + with FileHelper(skills_dir) as files: + content = files.read_text(Path(name) / "SKILL.md") + except (OSError, ValueError): + # Missing, unreadable, not a regular file or not UTF-8. + continue + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + source = metadata.get("source") if isinstance(metadata, dict) else None + 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, + ) + def _resolve_agent_skills_dir(self, agent_name: str) -> Path: """Resolve the real skill output directory for an integration.""" from .. import _get_skills_dir as _project_skills_dir @@ -627,6 +2719,9 @@ 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, + new_file_modes: Optional[Dict[Path, int]] = None, ) -> Dict[str, List[str]]: """Generate SKILL.md files for preset command overrides. @@ -652,6 +2747,14 @@ 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. + 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 @@ -707,15 +2810,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 @@ -737,11 +2846,20 @@ 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 - # Parse the command file - content = source_file.read_text(encoding="utf-8") + # 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 @@ -760,9 +2878,12 @@ def _register_skills( or frontmatter.get("strategy") or "replace" ) + # 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 not composed_file.exists() + override is None + and effective_strategy != "replace" and resolver.resolve_content(cmd_name, "command") is None ): continue @@ -822,7 +2943,11 @@ 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, + new_file_mode=(new_file_modes or {}).get(skill_file), ) written.append(target_skill_name) self._merge_pack_registered_skills( @@ -921,12 +3046,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") @@ -979,6 +3102,42 @@ 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: + with FileHelper(skills_dir) as files: + mode = files.file_mode(Path(name) / "SKILL.md") + except (OSError, ValueError): + # Unreadable, or not a regular file reached without links. + continue + if mode is not None: + modes[skill_file] = mode + return modes + def _safe_skills_dir_for_agent(self, agent_name: str) -> Optional[Path]: """Resolve ``agent_name``'s skills directory, validated for safety. @@ -1169,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"], @@ -1234,8 +3418,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: @@ -1507,7 +3692,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 @@ -1576,7 +3763,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 + ) if resources: import copy from ..extensions import ExtensionRegistry diff --git a/src/specify_cli/presets/_resolver.py b/src/specify_cli/presets/_resolver.py index f6c94700e6..ed968953e3 100644 --- a/src/specify_cli/presets/_resolver.py +++ b/src/specify_cli/presets/_resolver.py @@ -762,6 +762,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. @@ -777,11 +779,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/src/specify_cli/shared_infra.py b/src/specify_cli/shared_infra.py index a74e5fa5b2..3458229eed 100644 --- a/src/specify_cli/shared_infra.py +++ b/src/specify_cli/shared_infra.py @@ -340,8 +340,35 @@ def _shared_script_mode(src_path: Path, content: bytes) -> int: return mode -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, + 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. 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. + Either way the content is never readable under a wider mode than the + one it ends up with. + """ + mode: int | None = 0o644 + if preserve_mode: + 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(_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) def _write_shared_bytes( @@ -349,11 +376,23 @@ def _write_shared_bytes( dest: Path, content: bytes, *, - mode: int = 0o644, + mode: int | None = 0o644, ) -> None: + """Atomically replace ``dest`` with ``content`` (see ``FileHelper.write_bytes``). + + ``mode`` is the exact permission bits of the result. ``None`` gives the + bits an ordinary create would: 0666 narrowed by the process umask. + """ _ensure_safe_shared_destination(project_path, dest) from .integrations._file_changes import changing_file + if mode is None: + # FileHelper sets exact bits, so apply the umask here. Python has no + # read-only umask query; set it and put it straight back. + umask = os.umask(0o022) + os.umask(umask) + mode = 0o666 & ~umask + # Shared infrastructure refuses links even in projects that opt in elsewhere. with FileHelper(project_path) as files, changing_file(dest): try: 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 a836286952..211760dcd2 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1,12 +1,16 @@ """Tests for preset skill artifacts in specify_cli.presets._manager_skills.""" +import functools import os import shutil +import stat +import warnings from pathlib import Path import pytest import yaml +from specify_cli.extensions import ExtensionManager from specify_cli.presets import PresetManager from tests.specify_cli.presets._helpers import ( PresetArtifactTestHelpers, @@ -1401,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) @@ -1417,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 @@ -1917,205 +1924,3656 @@ def test_remove_preserves_non_owned_skill_during_reconciliation( "---\nname: speckit-specify\n---\n\nUser-owned body\n" ) - def test_shared_skills_dir_restored_once_using_active_agent( + def _install_composed_specify_stack(self, project_dir, temp_dir, layers): + """Install ``(preset_id, body, strategy, priority)`` layers for speckit.specify.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-specify") + (project_dir / ".specify" / "templates" / "commands" / "specify.md").write_text( + "---\ndescription: Core specify\n---\n\nCore specify body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + for preset_id, body, strategy, priority in layers: + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.specify", preset_id, body + ) + if strategy != "replace": + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + return manager, project_dir / ".claude" / "skills" / "speckit-specify" / "SKILL.md" + + def _install_unbacked_custom_stack(self, project_dir, temp_dir, 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 layers or [ + ("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" + 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( self, project_dir, temp_dir ): - """Removal must restore a physical skills directory shared by - multiple agents exactly once, using the active agent's renderer. + """With no core or extension fallback, removing the only base leaves + 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) - Codex and Antigravity (agy) both resolve their skills directory to - ``.agents/skills``. Registering a preset under codex, switching to - agy, then switching back to codex records provenance for *both* - agent keys even though they share one physical directory. Before - the fix, ``_unregister_skills`` restored once per recorded agent - key rather than once per unique directory, so the directory was - written twice on removal with whichever agent was iterated *last* - silently winning — regardless of which agent is actually active - (#2948). - """ + 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() + + 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_sole_base_under_two_composers_survives_rescaffold( + self, project_dir, temp_dir + ): + """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, + [ + ("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") + + assert not skill_file.exists() + + 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) + 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) + + skill_dir = project_dir / ".claude" / "skills" / "speckit-custom" + assert (skill_dir, True, True) in events + assert not skill_dir.exists() + + 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 + + _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) + # 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 + + 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 + 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 + + # 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_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) - shared_skills_dir = project_dir / ".agents" / "skills" - self._create_skill(shared_skills_dir, "speckit-specify") + 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 / "specify.md").write_text( - "---\ndescription: Core specify command\n---\n\nCore specify body\n", + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", encoding="utf-8", ) - - preset_dir = self._create_command_preset( - temp_dir, "shared-dir-preset", "speckit.specify", - "Shared dir test", "preset body", - ) manager = PresetManager(project_dir) - manager.install_from_directory(preset_dir, "0.1.5") - - # Switch to agy (shares .agents/skills with codex) and back to - # codex, mirroring `integration use agy` then `integration use - # codex`. Both agent keys end up recorded in registered_skills even - # though they refer to the same physical directory. + 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) - metadata = manager.registry.get("shared-dir-preset") - registered_skills = metadata.get("registered_skills", {}) - assert set(registered_skills) == {"codex", "agy"}, ( - "both agent keys must be recorded even though they share one " - "physical directory (#2948)" + 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 - from unittest.mock import patch + @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*")) - # Exercise `_unregister_skills` directly (the method this fix - # changed) rather than the full `remove()` flow, which separately - # triggers post-removal reconciliation that may also touch the - # active agent's directory — an unrelated call this test isn't - # targeting. - with patch.object( - manager, - "_unregister_skills_in_dir", - wraps=manager._unregister_skills_in_dir, - ) as spy: - manager._unregister_skills(registered_skills, preset_dir) + 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") - assert spy.call_count == 1, ( - "a physical directory shared by multiple recorded agents must " - "be restored exactly once, not once per agent key (#2948)" - ) - (_names, called_dir, called_agent), _kwargs = spy.call_args - assert called_dir == shared_skills_dir - assert called_agent == "codex", ( - "the currently active agent must be used as the renderer when " - "it shares the restored directory, not whichever agent was " - "recorded last (#2948)" - ) + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True - skill_file = shared_skills_dir / "speckit-specify" / "SKILL.md" - content = skill_file.read_text() - assert "preset:shared-dir-preset" not in content - assert "Core specify body" in content + assert alias_file.read_text(encoding="utf-8") == edited - def test_remove_higher_priority_skills_only_preset_restores_lower_preset( - self, project_dir, temp_dir - ): - """Removing a skills-mode preset must reconcile against the surviving - stack, not fall back to core/extension content. - Copilot in skills mode never populates ``registered_commands`` for - its overrides (``_register_commands``'s ``ai_skills`` guard skips - command-file registration entirely), so with two presets overriding - the same command, the removed preset's command name was never added - to ``removed_cmd_names`` and reconciliation was skipped outright. - ``_unregister_skills`` then restored straight to core/extension - content instead of resolving the lower-priority preset that should - now win (#2948). - """ - self._write_init_options(project_dir, ai="copilot", ai_skills=True) + @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) - preset_a_dir = self._create_command_preset( - temp_dir, "skills-preset-a", "speckit.specify", - "Preset A", "preset A body", - ) - preset_b_dir = self._create_command_preset( - temp_dir, "skills-preset-b", "speckit.specify", - "Preset B", "preset B body", - ) - manifest_path = preset_b_dir / "preset.yml" - manifest = yaml.safe_load(manifest_path.read_text()) - manifest["preset"]["version"] = "3.2.1" - manifest_path.write_text(yaml.safe_dump(manifest)) + 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 + # 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) - # Lower priority number = higher precedence. - manager.install_from_directory(preset_a_dir, "0.1.5", priority=5) - manager.install_from_directory(preset_b_dir, "0.1.5", priority=10) - skills_dir = project_dir / ".github" / "skills" - skill_file = skills_dir / "speckit-specify" / "SKILL.md" - assert "preset:skills-preset-a" in skill_file.read_text(), ( - "sanity: the higher-precedence preset should win initially" - ) + 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) - assert manager.remove("skills-preset-a") is True + 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) - content = skill_file.read_text() - assert "preset:skills-preset-b" in content, ( - "removing the higher-precedence skills-mode preset must " - "restore the surviving lower-precedence preset's override, " - "not fall back to core/extension content (#2948)" - ) - assert "preset:skills-preset-a" not in content - assert yaml.safe_load(content.split("---", 2)[1])["metadata"]["version"] == "3.2.1" + assert manager.remove("base-preset") is True - def test_remove_reconciles_skill_for_every_historical_agent( - self, project_dir, temp_dir - ): - """Removing a preset must reconcile every historical skills - directory its ``registered_skills`` actually targeted, not only - the currently active one. + assert claude_skill.read_text(encoding="utf-8") == before - Preset B (survives) is installed while claude is active, then - preset A (higher precedence) overrides the same command while - claude is still active. Switching to codex and rescaffolding - records codex too, so preset A's ``registered_skills`` spans both - claude (now inactive) and codex (active) directories. Removing A - restores both directories to core/extension via - ``_unregister_skills``, but ``_reconcile_skills`` used to only - resolve/apply the surviving winner for the currently active - skills directory, leaving claude's directory reverted to - core/extension content instead of preset B's override (#2948). - """ + @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) - claude_skills_dir = project_dir / ".claude" / "skills" + 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) - # A core template fallback is required so unregistering the - # top-priority preset's SKILL.md restores core content rather than - # deleting the skill directory outright when no preset remains to - # apply on top of it (mirrors the pre-existing skills-reconciliation - # fixtures elsewhere in this file). + 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() + + @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 / "specify.md").write_text( - "---\ndescription: Core specify command\n---\n\nCore specify body\n", + (core_cmds / "custom.md").write_text( + "---\ndescription: Core custom\n---\n\nCore custom body\n", encoding="utf-8", ) + manager = PresetManager(project_dir) - preset_b_dir = self._create_command_preset( - temp_dir, "hist-skill-preset-b", "speckit.specify", - "Preset B", "preset B body", - ) - preset_a_dir = self._create_command_preset( - temp_dir, "hist-skill-preset-a", "speckit.specify", - "Preset A", "preset A body", - ) + 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) - 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) + assert manager.remove("base-preset") is True - claude_skill_file = claude_skills_dir / "speckit-specify" / "SKILL.md" - assert "preset:hist-skill-preset-a" in claude_skill_file.read_text(), ( - "sanity: preset A (higher precedence) should win initially" + 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) - # Switch the active integration to codex (a distinct skills - # directory) and rescaffold, mirroring `integration use codex`. + 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) - codex_skills_dir = project_dir / ".agents" / "skills" 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" + ) + + @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) - metadata_a = manager.registry.get("hist-skill-preset-a") - assert set(metadata_a.get("registered_skills", {})) == {"claude", "codex"}, ( - "sanity: preset A's registered_skills must span both the " - "historical (claude) and currently active (codex) agents" - ) + assert manager.remove("base-preset") is True - assert manager.remove("hist-skill-preset-a") is True + assert "Core custom body" in alias_file.read_text(encoding="utf-8") + assert stat.S_IMODE(alias_file.stat().st_mode) == 0o600 - codex_skill_file = codex_skills_dir / "speckit-specify" / "SKILL.md" + @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 + + @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 + + @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 + ): + """``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 + + @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_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"]) + @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, legacy + ): + """``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) + if legacy: + manager.registry.update("low-preset", {"registered_skills": ["speckit-custom"]}) + + 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 + + @pytest.mark.parametrize( + "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, 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. 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) + 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"] == [] + if mode == "unrelated-claude-command": + extensions.registry.update( + "foreign", + { + "registered_commands": { + extension_agent: ["speckit.foreign.run"], + "claude": ["speckit.foreign.other"], + } + }, + ) + 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") + 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 not expect_kept: + 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 + ): + """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 + + @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 + + @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 + ): + """``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 + + @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 + + @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 + + @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("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) + + _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.""" + 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 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) + 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}") + + # 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 + ): + """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 + + @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 + 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"]) + 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 + + 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 + ): + """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 + + @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) + + @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 + ): + """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 + ): + """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 + ): + """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 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}) + 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() + + @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() + + def test_remove_sole_base_with_disabled_composer_survives_rescaffold( + self, project_dir, temp_dir + ): + """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, + [ + ("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 skill_file.exists() + + 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 + ): + """Removing a composition's base layer must recompose the surviving skill. + + The appending preset owns the composed SKILL.md, so removing the + replace preset beneath it restored nothing in the active skills + directory and reconciliation skipped it: the skill kept the removed + preset's body while command-file agents were recomposed onto core. + """ + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" in content and "Appended body" in content + + assert manager.remove("base-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core specify body" in content + assert "Appended body" in content + assert "preset:append-preset" in content + + def test_remove_middle_preset_drops_its_layer_from_composed_skill( + self, project_dir, temp_dir + ): + """Removing a middle composing layer must drop its fragment from the skill.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("middle-preset", "Middle body", "append", 7), + ("top-preset", "Top body", "append", 5), + ], + ) + assert "Middle body" in skill_file.read_text(encoding="utf-8") + + assert manager.remove("middle-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Middle body" not in content + assert "Base preset body" in content + assert "Top body" in content + + def test_remove_base_preset_preserves_hand_edited_composed_skill( + self, project_dir, temp_dir + ): + """Recomposition after removal must not overwrite a hand-edited skill.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + edited = "---\nname: speckit-specify\n---\n\nUser-owned body\n" + skill_file.write_text(edited, encoding="utf-8") + + assert manager.remove("base-preset") is True + + assert skill_file.read_text(encoding="utf-8") == edited + + def test_remove_base_preset_preserves_user_owned_legacy_skill( + self, project_dir, temp_dir + ): + """Recomposition writes only the skill name that still carries the + winning preset's marker, not a user-owned legacy sibling.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + legacy_file = skill_file.parent.parent / "speckit.specify" / "SKILL.md" + legacy_file.parent.mkdir(parents=True, exist_ok=True) + legacy = "---\nname: speckit.specify\n---\n\nUser-owned legacy body\n" + legacy_file.write_text(legacy, encoding="utf-8") + + assert manager.remove("base-preset") is True + + assert legacy_file.read_text(encoding="utf-8") == legacy + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Appended body" in content + + def test_shared_skills_dir_restored_once_using_active_agent( + self, project_dir, temp_dir + ): + """Removal must restore a physical skills directory shared by + multiple agents exactly once, using the active agent's renderer. + + Codex and Antigravity (agy) both resolve their skills directory to + ``.agents/skills``. Registering a preset under codex, switching to + agy, then switching back to codex records provenance for *both* + agent keys even though they share one physical directory. Before + the fix, ``_unregister_skills`` restored once per recorded agent + key rather than once per unique directory, so the directory was + written twice on removal with whichever agent was iterated *last* + silently winning — regardless of which agent is actually active + (#2948). + """ + self._write_init_options(project_dir, ai="codex", ai_skills=True) + shared_skills_dir = project_dir / ".agents" / "skills" + self._create_skill(shared_skills_dir, "speckit-specify") + + 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_dir = self._create_command_preset( + temp_dir, "shared-dir-preset", "speckit.specify", + "Shared dir test", "preset body", + ) + manager = PresetManager(project_dir) + manager.install_from_directory(preset_dir, "0.1.5") + + # Switch to agy (shares .agents/skills with codex) and back to + # codex, mirroring `integration use agy` then `integration use + # codex`. Both agent keys end up recorded in registered_skills even + # though they refer to the same physical 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") + + metadata = manager.registry.get("shared-dir-preset") + registered_skills = metadata.get("registered_skills", {}) + assert set(registered_skills) == {"codex", "agy"}, ( + "both agent keys must be recorded even though they share one " + "physical directory (#2948)" + ) + + from unittest.mock import patch + + # Exercise `_unregister_skills` directly (the method this fix + # changed) rather than the full `remove()` flow, which separately + # triggers post-removal reconciliation that may also touch the + # active agent's directory — an unrelated call this test isn't + # targeting. + with patch.object( + manager, + "_unregister_skills_in_dir", + wraps=manager._unregister_skills_in_dir, + ) as spy: + manager._unregister_skills(registered_skills, preset_dir) + + assert spy.call_count == 1, ( + "a physical directory shared by multiple recorded agents must " + "be restored exactly once, not once per agent key (#2948)" + ) + (_names, called_dir, called_agent), _kwargs = spy.call_args + assert called_dir == shared_skills_dir + assert called_agent == "codex", ( + "the currently active agent must be used as the renderer when " + "it shares the restored directory, not whichever agent was " + "recorded last (#2948)" + ) + + skill_file = shared_skills_dir / "speckit-specify" / "SKILL.md" + content = skill_file.read_text() + assert "preset:shared-dir-preset" not in content + assert "Core specify body" in content + + def test_remove_higher_priority_skills_only_preset_restores_lower_preset( + self, project_dir, temp_dir + ): + """Removing a skills-mode preset must reconcile against the surviving + stack, not fall back to core/extension content. + + Copilot in skills mode never populates ``registered_commands`` for + its overrides (``_register_commands``'s ``ai_skills`` guard skips + command-file registration entirely), so with two presets overriding + the same command, the removed preset's command name was never added + to ``removed_cmd_names`` and reconciliation was skipped outright. + ``_unregister_skills`` then restored straight to core/extension + content instead of resolving the lower-priority preset that should + now win (#2948). + """ + self._write_init_options(project_dir, ai="copilot", ai_skills=True) + + preset_a_dir = self._create_command_preset( + temp_dir, "skills-preset-a", "speckit.specify", + "Preset A", "preset A body", + ) + preset_b_dir = self._create_command_preset( + temp_dir, "skills-preset-b", "speckit.specify", + "Preset B", "preset B body", + ) + manifest_path = preset_b_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["preset"]["version"] = "3.2.1" + manifest_path.write_text(yaml.safe_dump(manifest)) + + manager = PresetManager(project_dir) + # Lower priority number = higher precedence. + manager.install_from_directory(preset_a_dir, "0.1.5", priority=5) + manager.install_from_directory(preset_b_dir, "0.1.5", priority=10) + + skills_dir = project_dir / ".github" / "skills" + skill_file = skills_dir / "speckit-specify" / "SKILL.md" + assert "preset:skills-preset-a" in skill_file.read_text(), ( + "sanity: the higher-precedence preset should win initially" + ) + + assert manager.remove("skills-preset-a") is True + + content = skill_file.read_text() + assert "preset:skills-preset-b" in content, ( + "removing the higher-precedence skills-mode preset must " + "restore the surviving lower-precedence preset's override, " + "not fall back to core/extension content (#2948)" + ) + assert "preset:skills-preset-a" not in content + assert yaml.safe_load(content.split("---", 2)[1])["metadata"]["version"] == "3.2.1" + + def test_remove_reconciles_skill_for_every_historical_agent( + self, project_dir, temp_dir + ): + """Removing a preset must reconcile every historical skills + directory its ``registered_skills`` actually targeted, not only + the currently active one. + + Preset B (survives) is installed while claude is active, then + preset A (higher precedence) overrides the same command while + claude is still active. Switching to codex and rescaffolding + records codex too, so preset A's ``registered_skills`` spans both + claude (now inactive) and codex (active) directories. Removing A + restores both directories to core/extension via + ``_unregister_skills``, but ``_reconcile_skills`` used to only + resolve/apply the surviving winner for the currently active + skills directory, leaving claude's directory reverted to + core/extension content instead of preset B's override (#2948). + """ + self._write_init_options(project_dir, ai="claude", ai_skills=True) + claude_skills_dir = project_dir / ".claude" / "skills" + + # A core template fallback is required so unregistering the + # top-priority preset's SKILL.md restores core content rather than + # deleting the skill directory outright when no preset remains to + # apply on top of it (mirrors the pre-existing skills-reconciliation + # fixtures elsewhere in this file). + 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-skill-preset-b", "speckit.specify", + "Preset B", "preset B body", + ) + preset_a_dir = self._create_command_preset( + temp_dir, "hist-skill-preset-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) + + claude_skill_file = claude_skills_dir / "speckit-specify" / "SKILL.md" + assert "preset:hist-skill-preset-a" in claude_skill_file.read_text(), ( + "sanity: preset A (higher precedence) should win initially" + ) + + # Switch the active integration to codex (a distinct skills + # directory) and rescaffold, mirroring `integration use codex`. + self._write_init_options(project_dir, ai="codex", ai_skills=True) + codex_skills_dir = project_dir / ".agents" / "skills" + manager.register_enabled_presets_for_agent("codex") + + metadata_a = manager.registry.get("hist-skill-preset-a") + assert set(metadata_a.get("registered_skills", {})) == {"claude", "codex"}, ( + "sanity: preset A's registered_skills must span both the " + "historical (claude) and currently active (codex) agents" + ) + + assert manager.remove("hist-skill-preset-a") is True + + codex_skill_file = codex_skills_dir / "speckit-specify" / "SKILL.md" assert claude_skill_file.exists(), "claude's skill file must still exist after removal" assert codex_skill_file.exists(), "codex's skill file must still exist after removal" assert "preset:hist-skill-preset-b" in claude_skill_file.read_text(), ( @@ -2128,6 +5586,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 ): diff --git a/tests/specify_cli/presets/test_resolver.py b/tests/specify_cli/presets/test_resolver.py index 56463a38b3..f2041c44d1 100644 --- a/tests/specify_cli/presets/test_resolver.py +++ b/tests/specify_cli/presets/test_resolver.py @@ -2089,3 +2089,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 06ade38b61..0338db0eff 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..bcd7c21ea3 --- /dev/null +++ b/tests/test_shared_infra_write_mode.py @@ -0,0 +1,110 @@ +"""Unit tests for the mode the shared text writer leaves on a file.""" + +from __future__ import annotations + +import os +import stat +from pathlib import Path + +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_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") + 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