diff --git a/src/specify_cli/presets/_manager.py b/src/specify_cli/presets/_manager.py index cf6c61f434..08e7662965 100644 --- a/src/specify_cli/presets/_manager.py +++ b/src/specify_cli/presets/_manager.py @@ -21,7 +21,7 @@ _write_shared_bytes, _write_shared_text, ) -from ._manager_commands import _PresetCommandMethods +from ._manager_commands import _PresetCommandMethods, _preset_command_names from ._manager_skills import _PresetSkillMethods from ._manifest import ( PresetCompatibilityError, @@ -478,11 +478,7 @@ def install_from_directory( # Reconcile all affected commands from the full priority stack so that # install order doesn't determine the winning command file. - cmd_names = [ - t["name"] - for t in manifest.templates - if t.get("type") == "command" - ] + cmd_names = _preset_command_names(dest_dir, manifest) if cmd_names: try: self._reconcile_composed_commands(cmd_names) @@ -767,6 +763,7 @@ def remove(self, pack_id: str) -> bool: manifest_path = pack_dir / "preset.yml" if manifest_path.exists(): try: + removed_cmd_names.update(_preset_command_names(pack_dir)) manifest = PresetManifest(manifest_path) for tmpl in manifest.templates: if ( diff --git a/src/specify_cli/presets/_manager_commands.py b/src/specify_cli/presets/_manager_commands.py index d171eb28dd..25f23fe655 100644 --- a/src/specify_cli/presets/_manager_commands.py +++ b/src/specify_cli/presets/_manager_commands.py @@ -1,6 +1,7 @@ """Agent command registration and reconciliation for installed presets.""" import copy +import re from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set @@ -15,7 +16,10 @@ resolve_active_agent_for_registration, ) from ..extensions import ExtensionRegistry -from ..integrations._file_changes import write_text as _write_text +from ..shared_infra import ( + _ensure_safe_shared_directory, + _write_shared_text, +) from ._manifest import PresetManifest from ._resolver import PresetResolver @@ -89,6 +93,32 @@ def _substitute_core_template( return body.replace("{CORE_TEMPLATE}", core_body), core_frontmatter +def _preset_command_names( + preset_dir: Path, manifest: PresetManifest | None = None +) -> list[str]: + """Return declared and convention-based command names for an installed preset.""" + manifest = manifest or PresetManifest(preset_dir / "preset.yml") + command_templates = [ + template + for template in manifest.templates + if template.get("type") == "command" + ] + names = [template["name"] for template in command_templates] + declared_files = { + (preset_dir / template["file"]).resolve() + for template in command_templates + if isinstance(template.get("file"), str) + } + convention_dir = preset_dir / "commands" + if convention_dir.is_dir(): + for path in convention_dir.glob("*.md"): + if path.resolve() in declared_files: + continue + if re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", path.stem): + names.append(path.stem) + return list(dict.fromkeys(names)) + + class _PresetCommandMethods: """Command artifact methods shared through PresetManager's lifecycle state.""" @@ -148,9 +178,11 @@ def _register_commands( if composed is not None: if composed_dir is None: composed_dir = preset_dir / ".composed" - composed_dir.mkdir(parents=True, exist_ok=True) + _ensure_safe_shared_directory( + self.project_root, composed_dir + ) composed_file = composed_dir / f"{cmd['name']}.md" - _write_text(composed_file, composed, encoding="utf-8") + _write_shared_text(self.project_root, composed_file, composed) commands_to_register.append({ **cmd, "file": f".composed/{cmd['name']}.md", @@ -994,6 +1026,30 @@ def record_written(written: Dict[str, List[str]]) -> None: # repeated filesystem reads for each command name. presets_by_priority = list(self.registry.list_by_priority()) + def preset_template_for_path( + pack_id: str, pack_dir: Path, path: Path, cmd_name: str + ) -> tuple[str, Dict[str, Any]] | None: + manifest = resolver._get_manifest(pack_dir) + if manifest: + for template in manifest.templates: + if ( + template.get("name") == cmd_name + and template.get("type") == "command" + ): + return manifest.id, template + + if ( + path.parent == pack_dir / "commands" + and path.stem == cmd_name + and re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", cmd_name) + ): + return pack_id, { + "name": cmd_name, + "type": "command", + "file": path.relative_to(pack_dir).as_posix(), + } + return None + for cmd_name in command_names: layers = resolver.collect_all_layers(cmd_name, "command") if not layers: @@ -1014,18 +1070,18 @@ def record_written(written: Dict[str, List[str]]) -> None: for pack_id, _meta in presets_by_priority: pack_dir = self.presets_dir / pack_id if top_path.is_relative_to(pack_dir): - manifest = resolver._get_manifest(pack_dir) - if manifest: - for tmpl in manifest.templates: - if tmpl.get("name") == cmd_name and tmpl.get("type") == "command": - written = self._register_for_non_skill_agents( - registrar, [tmpl], manifest.id, pack_dir, - only_agent=only_agent, extra_agents=extra_agents, - ) - record_written(written) - self._merge_pack_registered_commands(manifest.id, written) - registered = True - break + owned_template = preset_template_for_path( + pack_id, pack_dir, top_path, cmd_name + ) + if owned_template: + owner_id, tmpl = owned_template + written = self._register_for_non_skill_agents( + registrar, [tmpl], owner_id, pack_dir, + only_agent=only_agent, extra_agents=extra_agents, + ) + record_written(written) + self._merge_pack_registered_commands(owner_id, written) + registered = True break if not registered: # Top layer is a non-preset source (extension, core, or @@ -1121,39 +1177,41 @@ def record_written(written: Dict[str, List[str]]) -> None: ) continue - # Write to the highest-priority preset's .composed dir + # Write to the winning preset's .composed dir when the + # convention-only command has no manifest entry. Tracking the + # registration there lets preset removal clean it up later. registered = False for pack_id, _meta in presets_by_priority: pack_dir = self.presets_dir / pack_id - manifest = resolver._get_manifest(pack_dir) - if not manifest: + if not layers[0]["path"].is_relative_to(pack_dir): continue - for tmpl in manifest.templates: - if tmpl.get("name") == cmd_name and tmpl.get("type") == "command": - composed_dir = pack_dir / ".composed" - composed_dir.mkdir(parents=True, exist_ok=True) - composed_file = composed_dir / f"{cmd_name}.md" - _write_text(composed_file, composed, encoding="utf-8") - written = self._register_for_non_skill_agents( - registrar, - [{**tmpl, "file": f".composed/{cmd_name}.md"}], - manifest.id, pack_dir, - only_agent=only_agent, extra_agents=extra_agents, - ) - record_written(written) - self._merge_pack_registered_commands(manifest.id, written) - registered = True - break - else: + owned_template = preset_template_for_path( + pack_id, pack_dir, layers[0]["path"], cmd_name + ) + if not owned_template: continue + owner_id, tmpl = owned_template + composed_dir = pack_dir / ".composed" + _ensure_safe_shared_directory(self.project_root, composed_dir) + composed_file = composed_dir / f"{cmd_name}.md" + _write_shared_text(self.project_root, composed_file, composed) + written = self._register_for_non_skill_agents( + registrar, + [{**tmpl, "file": f".composed/{cmd_name}.md"}], + owner_id, pack_dir, + only_agent=only_agent, extra_agents=extra_agents, + ) + record_written(written) + self._merge_pack_registered_commands(owner_id, written) + registered = True break if not registered: # No preset owns this composed command — write to a # shared .composed dir and register from the top layer. shared_composed = self.presets_dir / ".composed" - shared_composed.mkdir(parents=True, exist_ok=True) + _ensure_safe_shared_directory(self.project_root, shared_composed) composed_file = shared_composed / f"{cmd_name}.md" - _write_text(composed_file, composed, encoding="utf-8") + _write_shared_text(self.project_root, composed_file, composed) source = layers[0]["source"] if source.startswith("extension:"): source_id = source.split(":", 1)[1].split(" ", 1)[0] diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 169f6d9215..16fd8f93b8 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -2,6 +2,7 @@ import copy import os +import re from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Union @@ -29,9 +30,15 @@ class _FilteredManifest: that aren't being reconciled. """ - def __init__(self, manifest: "PresetManifest", cmd_names: set): + def __init__( + self, + manifest: "PresetManifest", + cmd_names: set, + convention_templates: Optional[List[Dict[str, Any]]] = None, + ): self._manifest = manifest self._cmd_names = cmd_names + self._convention_templates = convention_templates or [] def __getattr__(self, name: str): return getattr(self._manifest, name) @@ -41,7 +48,7 @@ def templates(self) -> List[Dict[str, Any]]: return [ t for t in self._manifest.templates if t.get("name") in self._cmd_names - ] + ] + self._convention_templates def _merge_pack_registered_skills( self, pack_id: str, written: Optional[Dict[str, List[str]]] @@ -140,7 +147,6 @@ def _reconcile_skills( 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 - # Cache registry once to avoid repeated filesystem reads presets_by_priority = list(self.registry.list_by_priority()) @@ -153,6 +159,17 @@ def _reconcile_skills( non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() + if active_skills_dir and active_ai and is_ai_skills_enabled(init_opts): + # The active skills-mode directory may already contain a core + # skill that a convention-only preset overrides. Admit only + # existing active skill directories that no preset has recorded + # yet; historical directories remain limited to tracked names. + for cmd_name in command_names: + managed_skill_names.update( + skill_name + for skill_name in self._skill_names_for_command(cmd_name) + if (active_skills_dir / skill_name).is_dir() + ) for cmd_name in command_names: layers = resolver.collect_all_layers(cmd_name, "command") @@ -337,7 +354,36 @@ def apply_to_dir( except PresetValidationError: continue cmds_set = set(dir_cmds) - filtered_manifest = self._FilteredManifest(manifest, cmds_set) + convention_templates = [] + for cmd_name in dir_cmds: + if any( + template.get("name") == cmd_name + and template.get("type") == "command" + for template in manifest.templates + ): + continue + layers = resolver.collect_all_layers(cmd_name, "command") + if not layers: + continue + source_path = layers[0]["path"] + if ( + source_path.is_relative_to(pack_dir) + and source_path.parent == pack_dir / "commands" + and source_path.stem == cmd_name + and re.fullmatch( + r"[a-z0-9-]+(?:\.[a-z0-9-]+)*", cmd_name + ) + ): + convention_templates.append( + { + "name": cmd_name, + "type": "command", + "file": source_path.relative_to(pack_dir).as_posix(), + } + ) + filtered_manifest = self._FilteredManifest( + manifest, cmds_set, convention_templates + ) # 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 diff --git a/src/specify_cli/presets/command_set_priority.py b/src/specify_cli/presets/command_set_priority.py index 8337c251fa..3c0ca4bf99 100644 --- a/src/specify_cli/presets/command_set_priority.py +++ b/src/specify_cli/presets/command_set_priority.py @@ -58,6 +58,30 @@ def preset_set_priority( # Update priority manager.registry.update(preset_id, {"priority": priority}) + + # Disabled presets are deliberately excluded from resolution. Updating + # their priority must not rewrite files still owned by the active stack. + # A priority change can change the winning command or skill layer just as + # install and removal do, so rematerialize artifacts provided by this + # preset from the full priority stack. + if metadata.get("enabled", True) is not False: + try: + from ._manager_commands import _preset_command_names + + preset_dir = manager.presets_dir / preset_id + command_names = _preset_command_names(preset_dir) + if command_names: + manager._reconcile_composed_commands(command_names) + manager._reconcile_skills(command_names) + except Exception as exc: # noqa: BLE001 - lifecycle reconciliation is best-effort + import warnings + + warnings.warn( + f"Post-priority reconciliation failed for {preset_id}: {exc}. " + "Agent command files may not reflect the current priority stack.", + stacklevel=2, + ) + manager.reconcile_constitution( f"Failed to reconcile constitution after changing priority for preset {preset_id}" ) diff --git a/tests/specify_cli/presets/test_command_set_priority.py b/tests/specify_cli/presets/test_command_set_priority.py index 14afba58a0..223aef17b8 100644 --- a/tests/specify_cli/presets/test_command_set_priority.py +++ b/tests/specify_cli/presets/test_command_set_priority.py @@ -7,13 +7,16 @@ ) from tests.conftest import strip_ansi from tests.specify_cli.presets._helpers import ( + PresetArtifactTestHelpers, install_constitution_sync_preset, install_self_test_preset, +) +from tests.specify_cli.presets._helpers import ( make_convention_constitution_preset as _make_convention_constitution_preset, ) -class TestPresetSetPriority: +class TestPresetSetPriority(PresetArtifactTestHelpers): """Test preset set-priority CLI command.""" def test_set_priority_changes_priority(self, project_dir, pack_dir): @@ -72,6 +75,384 @@ def test_set_priority_reconciles_generated_constitution( assert result.exit_code == 0, result.output assert memory.read_text() == "# Convention Constitution\n" + def test_set_priority_reconciles_generated_commands(self, project_dir, temp_dir): + """Changing priority rematerializes the winning preset command.""" + from unittest.mock import patch + + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + commands_dir = project_dir / ".gemini" / "commands" + commands_dir.mkdir(parents=True) + + manager = PresetManager(project_dir) + first = self._create_command_preset( + temp_dir, "priority-first", "speckit.demo", "First", "BODY-A" + ) + second = self._create_command_preset( + temp_dir, "priority-second", "speckit.demo", "Second", "BODY-B" + ) + manager.install_from_directory(first, "0.1.5", priority=10) + manager.install_from_directory(second, "0.1.5", priority=20) + + command_file = commands_dir / "speckit.demo.toml" + assert "BODY-A" in command_file.read_text() + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, ["preset", "set-priority", "priority-second", "1"] + ) + + assert result.exit_code == 0, result.output + assert "BODY-B" in command_file.read_text() + assert "BODY-A" not in command_file.read_text() + + def test_set_priority_includes_convention_only_commands(self, project_dir, temp_dir): + """A convention command omitted from the manifest still participates.""" + from unittest.mock import patch + import warnings + + import yaml + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + commands_dir = project_dir / ".gemini" / "commands" + commands_dir.mkdir(parents=True) + manager = PresetManager(project_dir) + first = self._create_command_preset( + temp_dir, "priority-convention", "speckit.demo", "First", "BODY-A" + ) + second = self._create_command_preset( + temp_dir, "priority-declared", "speckit.demo", "Second", "BODY-B" + ) + manifest_path = first / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + (first / "templates").mkdir() + (first / "templates" / "spec-template.md").write_text("# Spec\n") + manifest["provides"]["templates"] = [ + { + "type": "template", + "name": "spec-template", + "file": "templates/spec-template.md", + }, + { + "type": "command", + "name": "speckit.specify", + "file": "commands/specify-wrapper.md", + }, + ] + (first / "commands" / "specify-wrapper.md").write_text( + "---\nstrategy: wrap\n---\n\n{CORE_TEMPLATE}\n" + ) + manifest_path.write_text(yaml.safe_dump(manifest)) + manager.install_from_directory(first, "0.1.5", priority=10) + manager.install_from_directory(second, "0.1.5", priority=20) + + command_file = commands_dir / "speckit.demo.toml" + assert "BODY-A" in command_file.read_text() + with patch.object(Path, "cwd", return_value=project_dir), warnings.catch_warnings( + record=True + ) as caught: + warnings.simplefilter("always") + result = CliRunner().invoke( + app, ["preset", "set-priority", "priority-convention", "30"] + ) + + assert result.exit_code == 0, result.output + assert "BODY-B" in command_file.read_text() + assert "BODY-A" not in command_file.read_text() + assert not (commands_dir / "specify-wrapper.toml").exists() + assert not any("specify-wrapper" in str(warning.message) for warning in caught) + + def test_set_priority_tracks_convention_command_for_preset_removal( + self, project_dir, temp_dir + ): + """Removing a convention-only winner restores the next command layer.""" + from unittest.mock import patch + + import yaml + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + commands_dir = project_dir / ".gemini" / "commands" + commands_dir.mkdir(parents=True) + manager = PresetManager(project_dir) + convention = self._create_command_preset( + temp_dir, "priority-convention-owner", "speckit.demo", "Convention", "BODY-A" + ) + manifest_path = convention / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + (convention / "templates").mkdir() + (convention / "templates" / "spec-template.md").write_text("# Spec\n") + manifest["provides"]["templates"] = [ + { + "type": "template", + "name": "spec-template", + "file": "templates/spec-template.md", + } + ] + manifest_path.write_text(yaml.safe_dump(manifest)) + declared = self._create_command_preset( + temp_dir, "priority-declared-owner", "speckit.demo", "Declared", "BODY-B" + ) + manager.install_from_directory(convention, "0.1.5", priority=40) + manager.install_from_directory(declared, "0.1.5", priority=20) + command_file = commands_dir / "speckit.demo.toml" + assert "BODY-B" in command_file.read_text() + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, + ["preset", "set-priority", "priority-convention-owner", "1"], + ) + assert result.exit_code == 0, result.output + assert "BODY-A" in command_file.read_text() + manager = PresetManager(project_dir) + registered = manager.registry.get("priority-convention-owner")[ + "registered_commands" + ] + assert "speckit.demo" in registered.get("gemini", []) + + manager.remove("priority-convention-owner") + assert "BODY-B" in command_file.read_text() + + def test_set_priority_renders_convention_only_skill_winner( + self, project_dir, temp_dir + ): + """Convention-only command winners are materialized in skills mode.""" + from unittest.mock import patch + + import yaml + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + manager = PresetManager(project_dir) + convention = self._create_command_preset( + temp_dir, "skill-convention-owner", "speckit.demo", "Convention", "BODY-A" + ) + manifest_path = convention / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + (convention / "templates").mkdir() + (convention / "templates" / "spec-template.md").write_text("# Spec\n") + manifest["provides"]["templates"] = [ + { + "type": "template", + "name": "spec-template", + "file": "templates/spec-template.md", + } + ] + manifest_path.write_text(yaml.safe_dump(manifest)) + declared = self._create_command_preset( + temp_dir, "skill-declared-owner", "speckit.demo", "Declared", "BODY-B" + ) + manager.install_from_directory(convention, "0.1.5", priority=40) + manager.install_from_directory(declared, "0.1.5", priority=20) + skill_file = project_dir / ".claude" / "skills" / "speckit-demo" / "SKILL.md" + assert "BODY-B" in skill_file.read_text() + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, ["preset", "set-priority", "skill-convention-owner", "1"] + ) + assert result.exit_code == 0, result.output + assert "BODY-A" in skill_file.read_text() + assert "BODY-B" not in skill_file.read_text() + manager = PresetManager(project_dir) + assert manager.remove("skill-convention-owner") + assert "BODY-B" in skill_file.read_text() + + def test_reinstall_rematerializes_convention_only_command( + self, project_dir, temp_dir + ): + """Reinstall reconciles convention-only commands from the current stack.""" + import yaml + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + commands_dir = project_dir / ".gemini" / "commands" + commands_dir.mkdir(parents=True) + manager = PresetManager(project_dir) + source = self._create_command_preset( + temp_dir, "convention-reinstall", "speckit.demo", "Demo", "BODY-A" + ) + manifest_path = source / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + (source / "templates").mkdir() + (source / "templates" / "spec-template.md").write_text("# Spec\n") + manifest["provides"]["templates"] = [ + { + "type": "template", + "name": "spec-template", + "file": "templates/spec-template.md", + } + ] + manifest_path.write_text(yaml.safe_dump(manifest)) + + manager.install_from_directory(source, "0.1.5") + command_file = commands_dir / "speckit.demo.toml" + assert "BODY-A" in command_file.read_text() + assert manager.remove("convention-reinstall") + assert not command_file.exists() or "BODY-A" not in command_file.read_text() + + manager.install_from_directory(source, "0.1.5") + assert "BODY-A" in command_file.read_text() + + def test_set_priority_refreshes_core_skill_for_convention_override( + self, project_dir, temp_dir + ): + """An active core skill is included when a convention command overrides it.""" + from unittest.mock import patch + + import yaml + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + core_commands = project_dir / ".specify" / "templates" / "commands" + core_commands.mkdir(parents=True, exist_ok=True) + (core_commands / "demo.md").write_text("CORE-COMMAND\n") + skill_file = project_dir / ".claude" / "skills" / "speckit-demo" / "SKILL.md" + skill_file.parent.mkdir(parents=True) + skill_file.write_text("CORE-SKILL\n") + + manager = PresetManager(project_dir) + source = self._create_command_preset( + temp_dir, "core-skill-override", "speckit.demo", "Demo", "BODY-A" + ) + manifest_path = source / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + (source / "templates").mkdir() + (source / "templates" / "spec-template.md").write_text("# Spec\n") + manifest["provides"]["templates"] = [ + { + "type": "template", + "name": "spec-template", + "file": "templates/spec-template.md", + } + ] + manifest_path.write_text(yaml.safe_dump(manifest)) + manager.install_from_directory(source, "0.1.5") + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, ["preset", "set-priority", "core-skill-override", "1"] + ) + + assert result.exit_code == 0, result.output + assert "BODY-A" in skill_file.read_text() + + def test_set_priority_disabled_preset_keeps_materialized_command( + self, project_dir, temp_dir + ): + """Changing a disabled preset's priority leaves active artifacts alone.""" + from unittest.mock import patch + + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + commands_dir = project_dir / ".gemini" / "commands" + commands_dir.mkdir(parents=True) + manager = PresetManager(project_dir) + preset_dir = self._create_command_preset( + temp_dir, "disabled-priority", "speckit.demo", "Disabled", "FROZEN" + ) + manager.install_from_directory(preset_dir, "0.1.5") + manager.registry.update("disabled-priority", {"enabled": False}) + fallback_dir = self._create_command_preset( + temp_dir, "enabled-fallback", "speckit.demo", "Fallback", "ACTIVE" + ) + manager.install_from_directory(fallback_dir, "0.1.5", priority=20) + command_file = commands_dir / "speckit.demo.toml" + command_file.write_text("# Preserve this artifact while changing disabled priority\nFROZEN\n") + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, ["preset", "set-priority", "disabled-priority", "25"] + ) + + assert result.exit_code == 0, result.output + assert PresetManager(project_dir).registry.get("disabled-priority")["priority"] == 25 + assert command_file.read_text().endswith("FROZEN\n") + + def test_set_priority_reconciles_skill_rendering(self, project_dir, temp_dir): + """Priority changes select the winning command when rendered as skills.""" + from unittest.mock import patch + + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="claude", ai_skills=True) + manager = PresetManager(project_dir) + first = self._create_command_preset( + temp_dir, "skill-priority-first", "speckit.demo", "First", "BODY-A" + ) + second = self._create_command_preset( + temp_dir, "skill-priority-second", "speckit.demo", "Second", "BODY-B" + ) + manager.install_from_directory(first, "0.1.5", priority=10) + manager.install_from_directory(second, "0.1.5", priority=20) + skill_file = project_dir / ".claude" / "skills" / "speckit-demo" / "SKILL.md" + assert "BODY-A" in skill_file.read_text() + + with patch.object(Path, "cwd", return_value=project_dir): + result = CliRunner().invoke( + app, ["preset", "set-priority", "skill-priority-second", "1"] + ) + + assert result.exit_code == 0, result.output + assert "BODY-B" in skill_file.read_text() + assert "BODY-A" not in skill_file.read_text() + + def test_set_priority_reconciliation_failure_keeps_priority_and_constitution( + self, project_dir, temp_dir, monkeypatch + ): + """Command refresh errors warn without rolling back priority or constitution.""" + from unittest.mock import patch + + import pytest + from typer.testing import CliRunner + + from specify_cli import app + + self._write_init_options(project_dir, ai="gemini", ai_skills=False) + (project_dir / ".gemini" / "commands").mkdir(parents=True) + manager = PresetManager(project_dir) + preset_dir = self._create_command_preset( + temp_dir, "priority-failure", "speckit.demo", "Failure", "BODY" + ) + manager.install_from_directory(preset_dir, "0.1.5") + called = [] + + def fail_reconcile(self, command_names): + raise OSError("forced command write failure") + + def reconcile_constitution(self, message): + called.append(message) + + monkeypatch.setattr(PresetManager, "_reconcile_composed_commands", fail_reconcile) + monkeypatch.setattr(PresetManager, "reconcile_constitution", reconcile_constitution) + with patch.object(Path, "cwd", return_value=project_dir), pytest.warns( + UserWarning, match="forced command write failure" + ): + result = CliRunner().invoke( + app, ["preset", "set-priority", "priority-failure", "2"] + ) + + assert result.exit_code == 0, result.output + assert PresetManager(project_dir).registry.get("priority-failure")["priority"] == 2 + assert called + def test_set_priority_same_value_no_change(self, project_dir, pack_dir): """Test set-priority with same value shows already set message.""" from unittest.mock import patch diff --git a/tests/specify_cli/presets/test_manager_commands.py b/tests/specify_cli/presets/test_manager_commands.py index d83ef12d17..3fd5e34355 100644 --- a/tests/specify_cli/presets/test_manager_commands.py +++ b/tests/specify_cli/presets/test_manager_commands.py @@ -1,5 +1,6 @@ """Tests for preset command artifacts in specify_cli.presets._manager_commands.""" +import shutil from pathlib import Path import pytest @@ -3075,7 +3076,7 @@ def _make_wrap_preset_dir( return preset_dir -class TestRemoveReconciliation: +class TestRemoveReconciliation(PresetArtifactTestHelpers): """Test that removing a preset re-registers the next layer's command.""" def test_install_composes_extension_command_and_rewrites_subdir_paths_for_non_skill_agent( @@ -3158,3 +3159,37 @@ def test_install_composes_extension_command_and_rewrites_subdir_paths_for_non_sk assert ".specify/extensions/fakeext/agents/control/commander.md" in content assert "Read agents/control" not in content assert "## Extra" in content + + def test_reconcile_composed_command_refuses_symlinked_cache( + self, project_dir, temp_dir + ): + """A composed command cache cannot write outside the project via symlink.""" + from specify_cli.shared_infra import SymlinkedSharedPathError + + gemini_dir = project_dir / ".gemini" / "commands" + gemini_dir.mkdir(parents=True) + core = project_dir / ".specify" / "templates" / "commands" + core.mkdir(parents=True, exist_ok=True) + (core / "demo.md").write_text("# Base\n") + + preset = self._create_command_preset( + temp_dir, "safe-compose", "speckit.demo", "Composed", "# Overlay\n" + ) + manifest_path = preset / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = "append" + manifest_path.write_text(yaml.safe_dump(manifest)) + manager = PresetManager(project_dir) + manager.install_from_directory(preset, "0.1.5") + + outside = temp_dir / "outside" + outside.mkdir() + target = outside / "demo.md" + target.write_text("preserve\n") + composed = project_dir / ".specify" / "presets" / "safe-compose" / ".composed" + shutil.rmtree(composed) + composed.symlink_to(outside, target_is_directory=True) + + with pytest.raises(SymlinkedSharedPathError): + manager._reconcile_composed_commands(["speckit.demo"]) + assert target.read_text() == "preserve\n"