π« Toolkit to help you get started with SDD or any other process!
feat: implement preset wrap strategy (#2189)
Kennedy22e76995c752
diff --git a/presets/README.md b/presets/README.mdindex dd3997b23..72751b4bf 100644--- a/presets/README.md+++ b/presets/README.md@@ -116,5 +116,5 @@ The following enhancements are under consideration for future releases:| **command** | β (default) | β | β | β || **script** | β (default) | β | β | β |- For artifacts and commands (which are LLM directives), `wrap` would inject preset content before and after the core template using a `{CORE_TEMPLATE}` placeholder. For scripts, `wrap` would run custom logic before/after the core script via a `$CORE_SCRIPT` variable.+ For artifacts and commands (which are LLM directives), `wrap` injects preset content before and after the core template using a `{CORE_TEMPLATE}` placeholder (implemented). For scripts, `wrap` would run custom logic before/after the core script via a `$CORE_SCRIPT` variable (not yet implemented).- **Script overrides** β Enable presets to provide alternative versions of core scripts (e.g. `create-new-feature.sh`) for workflow customization. A `strategy: "wrap"` option could allow presets to run custom logic before/after the core script without fully replacing it.diff --git a/presets/self-test/commands/speckit.wrap-test.md b/presets/self-test/commands/speckit.wrap-test.mdnew file mode 100644index 000000000..78ace30ea--- /dev/null+++ b/presets/self-test/commands/speckit.wrap-test.md@@ -0,0 +1,14 @@+---+description: "Self-test wrap command β pre/post around core"+strategy: wrap+---++## Preset Pre-Logic++preset:self-test wrap-pre++{CORE_TEMPLATE}++## Preset Post-Logic++preset:self-test wrap-postdiff --git a/presets/self-test/preset.yml b/presets/self-test/preset.ymlindex 82c7b068a..8e718430a 100644--- a/presets/self-test/preset.yml+++ b/presets/self-test/preset.yml@@ -56,6 +56,11 @@ provides:description: "Self-test override of the specify command"replaces: "speckit.specify"+ - type: "command"+ name: "speckit.wrap-test"+ file: "commands/speckit.wrap-test.md"+ description: "Self-test wrap strategy command"+tags:- "testing"- "self-test"diff --git a/src/specify_cli/__init__.py b/src/specify_cli/__init__.pyindex 8c6fd02b9..97cb993a9 100644--- a/src/specify_cli/__init__.py+++ b/src/specify_cli/__init__.py@@ -1115,7 +1115,7 @@ def init(console.print(f"[cyan]--force supplied: merging into existing directory '[cyan]{project_name}[/cyan]'[/cyan]")else:error_panel = Panel(- f"Directory '[cyan]{project_name}[/cyan]' already exists\n"+ f"Directory already exists: '[cyan]{project_name}[/cyan]'\n""Please choose a different project name or remove the existing directory.\n""Use [bold]--force[/bold] to merge into the existing directory.",title="[red]Directory Conflict[/red]",@@ -1371,7 +1371,6 @@ def init("branch_numbering": branch_numbering or "sequential","context_file": resolved_integration.context_file,"here": here,- "preset": preset,"script": selected_script,"speckit_version": get_speckit_version(),}diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.pyindex ef4e879c0..c5e25a708 100644--- a/src/specify_cli/agents.py+++ b/src/specify_cli/agents.py@@ -468,6 +468,15 @@ class CommandRegistrar:content = source_file.read_text(encoding="utf-8")frontmatter, body = self.parse_frontmatter(content)+ if frontmatter.get("strategy") == "wrap":+ from .presets import _substitute_core_template+ body, core_frontmatter = _substitute_core_template(body, cmd_name, project_root, self)+ 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 = self._adjust_script_paths(frontmatter)for key in agent_config.get("strip_frontmatter_keys", []):@@ -495,10 +504,12 @@ class CommandRegistrar:project_root,)elif agent_config["format"] == "markdown":- output = self.render_markdown_command(- frontmatter, body, source_id, context_note- )+ body = self.resolve_skill_placeholders(agent_name, frontmatter, body, project_root)+ body = self._convert_argument_placeholder(body, "$ARGUMENTS", agent_config["args"])+ output = self.render_markdown_command(frontmatter, body, source_id, context_note)elif agent_config["format"] == "toml":+ body = self.resolve_skill_placeholders(agent_name, frontmatter, body, project_root)+ body = self._convert_argument_placeholder(body, "$ARGUMENTS", agent_config["args"])output = self.render_toml_command(frontmatter, body, source_id)elif agent_config["format"] == "yaml":output = self.render_yaml_command(diff --git a/src/specify_cli/extensions.py b/src/specify_cli/extensions.pyindex d5543cd0b..26ceab403 100644--- a/src/specify_cli/extensions.py+++ b/src/specify_cli/extensions.py@@ -140,11 +140,16 @@ class ExtensionManifest:"""Load YAML file safely."""try:with open(path, 'r') as f:- return yaml.safe_load(f) or {}+ data = yaml.safe_load(f)except yaml.YAMLError as e:raise ValidationError(f"Invalid YAML in {path}: {e}")except FileNotFoundError:raise ValidationError(f"Manifest not found: {path}")+ if not isinstance(data, dict):+ raise ValidationError(+ f"Manifest must be a YAML mapping, got {type(data).__name__}: {path}"+ )+ return datadef _validate(self):"""Validate manifest structure and required fields."""diff --git a/src/specify_cli/presets.py b/src/specify_cli/presets.pyindex d5513c832..5f28be720 100644--- a/src/specify_cli/presets.py+++ b/src/specify_cli/presets.py@@ -16,7 +16,10 @@ import zipfileimport shutilfrom dataclasses import dataclassfrom pathlib import Path-from typing import Optional, Dict, List, Any+from typing import TYPE_CHECKING, Optional, Dict, List, Any++if TYPE_CHECKING:+ from .agents import CommandRegistrarfrom datetime import datetime, timezoneimport re@@ -27,6 +30,59 @@ from packaging.specifiers import SpecifierSet, InvalidSpecifierfrom .extensions import ExtensionRegistry, normalize_priority+def _substitute_core_template(+ body: str,+ cmd_name: str,+ project_root: "Path",+ registrar: "CommandRegistrar",+) -> "tuple[str, dict]":+ """Substitute {CORE_TEMPLATE} with the body of the installed core command template.++ Args:+ body: Preset command body (may contain {CORE_TEMPLATE} placeholder).+ cmd_name: Full command name (e.g. "speckit.git.feature" or "speckit.specify").+ project_root: Project root path.+ registrar: CommandRegistrar instance for parse_frontmatter.++ Returns:+ A tuple of (body, core_frontmatter) where body has {CORE_TEMPLATE} replaced+ by the core template body and core_frontmatter holds the core template's parsed+ frontmatter (so callers can inherit scripts/agent_scripts from it). Both are+ unchanged / empty when the placeholder is absent or the core template file does+ not exist.+ """+ if "{CORE_TEMPLATE}" not in body:+ return body, {}++ # Derive the short name (strip "speckit." prefix) used by core command templates.+ short_name = cmd_name+ if short_name.startswith("speckit."):+ short_name = short_name[len("speckit."):]++ resolver = PresetResolver(project_root)+ # Resolution order for the core template:+ # 1. resolve_core(cmd_name) β covers tier-1 project overrides and tier-3/4+ # name-based lookup (file named <cmd_name>.md). Checked first so that a+ # local override always wins, even for extension commands.+ # 2. resolve_extension_command_via_manifest(cmd_name) β manifest-based tier-3+ # fallback for extension commands whose file is named differently from the+ # command name (e.g. speckit.selftest.extension β commands/selftest.md).+ # 3. resolve_core(short_name) β core template fallback using the unprefixed+ # name (e.g. specify β templates/commands/specify.md).+ # resolve_core() skips installed presets (tier 2) to prevent accidental nesting+ # where another preset's wrap output is mistaken for the real core.+ core_file = (+ resolver.resolve_core(cmd_name, "command")+ or resolver.resolve_extension_command_via_manifest(cmd_name)+ or resolver.resolve_core(short_name, "command")+ )+ if core_file is None:+ return body, {}++ core_frontmatter, core_body = registrar.parse_frontmatter(core_file.read_text(encoding="utf-8"))+ return body.replace("{CORE_TEMPLATE}", core_body), core_frontmatter++@dataclassclass PresetCatalogEntry:"""Represents a single entry in the preset catalog stack."""@@ -555,6 +611,232 @@ class PresetManager:registrar = CommandRegistrar()registrar.unregister_commands(registered_commands, self.project_root)+ def _replay_wraps_for_command(self, cmd_name: str) -> None:+ """Recompose and rewrite agent files for a wrap-strategy command.++ Collects all installed presets that declare cmd_name in their+ wrap_commands registry field, sorts them so the highest-precedence+ preset (lowest priority number) wraps outermost, then writes the+ fully composed output to every agent directory.++ Called after every install and remove to keep agent files correct+ regardless of installation order.++ Args:+ cmd_name: Full command name (e.g. "speckit.specify")+ """+ try:+ from .agents import CommandRegistrar+ except ImportError:+ return++ # Collect enabled presets that wrap this command, sorted ascending+ # (lowest priority number = highest precedence = outermost).+ wrap_presets = []+ for pack_id, metadata in self.registry.list_by_priority(include_disabled=False):+ if cmd_name not in metadata.get("wrap_commands", []):+ continue+ pack_dir = self.presets_dir / pack_id+ if not pack_dir.is_dir():+ continue # corrupted state β skip+ wrap_presets.append((pack_id, pack_dir))++ if not wrap_presets:+ return++ # Derive short name for core resolution fallback.+ short_name = cmd_name+ if short_name.startswith("speckit."):+ short_name = short_name[len("speckit."):]++ resolver = PresetResolver(self.project_root)+ core_file = (+ resolver.resolve_core(cmd_name, "command")+ or resolver.resolve_extension_command_via_manifest(cmd_name)+ or (+ resolver.resolve_extension_command_via_manifest(short_name)+ if short_name != cmd_name+ else None+ )+ or resolver.resolve_core(short_name, "command")+ )+ if core_file is None:+ return++ registrar = CommandRegistrar()+ core_frontmatter, core_body = registrar.parse_frontmatter(+ core_file.read_text(encoding="utf-8")+ )+ replay_aliases: List[str] = []+ seen_aliases: set[str] = set()++ # Apply wraps innermost-first (reverse of ascending list).+ accumulated_body = core_body+ outermost_frontmatter = {}+ outermost_pack_id = wrap_presets[0][0] # fallback; updated per contributing preset+ for pack_id, pack_dir in reversed(wrap_presets):+ manifest_path = pack_dir / "preset.yml"+ cmd_file: Optional[Path] = None+ if manifest_path.exists():+ try:+ manifest = PresetManifest(manifest_path)+ except (PresetValidationError, KeyError, TypeError, ValueError):+ manifest = None+ if manifest is not None:+ for template in manifest.templates:+ if template.get("type") != "command" or template.get("name") != cmd_name:+ continue+ file_rel = template.get("file")+ if isinstance(file_rel, str):+ rel_path = Path(file_rel)+ if not rel_path.is_absolute():+ try:+ preset_root = pack_dir.resolve()+ candidate = (preset_root / rel_path).resolve()+ candidate.relative_to(preset_root)+ except (OSError, ValueError):+ candidate = None+ if candidate is not None:+ cmd_file = candidate+ aliases = template.get("aliases", [])+ if not isinstance(aliases, list):+ aliases = []+ for alias in aliases:+ if isinstance(alias, str) and alias not in seen_aliases:+ replay_aliases.append(alias)+ seen_aliases.add(alias)+ break+ if cmd_file is None:+ cmd_file = pack_dir / "commands" / f"{cmd_name}.md"+ if not cmd_file.exists():+ continue+ wrap_fm, wrap_body = registrar.parse_frontmatter(+ cmd_file.read_text(encoding="utf-8")+ )+ accumulated_body = wrap_body.replace("{CORE_TEMPLATE}", accumulated_body)+ outermost_frontmatter = wrap_fm # last iteration = outermost preset+ outermost_pack_id = pack_id++ # Build final frontmatter: outermost preset wins; fall back to core for+ # scripts/agent_scripts if the outermost preset does not define them.+ final_frontmatter = dict(outermost_frontmatter)+ final_frontmatter.pop("strategy", None)+ for key in ("scripts", "agent_scripts"):+ if key not in final_frontmatter and key in core_frontmatter:+ final_frontmatter[key] = core_frontmatter[key]++ composed_content = (+ registrar.render_frontmatter(final_frontmatter) + "\n" + accumulated_body+ )++ self._replay_skill_override(cmd_name, composed_content, outermost_pack_id)++ with tempfile.TemporaryDirectory() as tmpdir:+ tmp_path = Path(tmpdir)+ cmd_dir = tmp_path / "commands"+ cmd_dir.mkdir()+ (cmd_dir / f"{cmd_name}.md").write_text(composed_content, encoding="utf-8")+ registrar._ensure_configs()+ for agent_name, agent_config in registrar.AGENT_CONFIGS.items():+ if agent_config.get("extension") == "/SKILL.md":+ continue+ agent_dir = self.project_root / agent_config["dir"]+ if not agent_dir.exists():+ continue+ try:+ registrar.register_commands(+ agent_name,+ [{+ "name": cmd_name,+ "file": f"commands/{cmd_name}.md",+ "aliases": replay_aliases,+ }],+ f"preset:{outermost_pack_id}",+ tmp_path,+ self.project_root,+ )+ except ValueError:+ continue++ def _replay_skill_override(+ self,+ cmd_name: str,+ composed_content: str,+ outermost_pack_id: str,+ ) -> None:+ """Rewrite any active SKILL.md override for a replayed wrap command."""+ skills_dir = self._get_skills_dir()+ if not skills_dir:+ return++ from . import SKILL_DESCRIPTIONS, load_init_options+ from .agents import CommandRegistrar+ from .integrations import get_integration++ init_opts = load_init_options(self.project_root)+ if not isinstance(init_opts, dict):+ init_opts = {}+ selected_ai = init_opts.get("ai")+ if not isinstance(selected_ai, str):+ return++ registrar = CommandRegistrar()+ integration = get_integration(selected_ai)+ agent_config = registrar.AGENT_CONFIGS.get(selected_ai, {})+ create_missing_skills = bool(init_opts.get("ai_skills")) and agent_config.get("extension") != "/SKILL.md"++ skill_name, legacy_skill_name = self._skill_names_for_command(cmd_name)+ target_skill_names: List[str] = []+ if (skills_dir / skill_name).is_dir():+ target_skill_names.append(skill_name)+ if legacy_skill_name != skill_name and (skills_dir / legacy_skill_name).is_dir():+ target_skill_names.append(legacy_skill_name)+ if not target_skill_names and create_missing_skills:+ missing_skill_dir = skills_dir / skill_name+ if not missing_skill_dir.exists():+ target_skill_names.append(skill_name)+ if not target_skill_names:+ return++ raw_short_name = cmd_name+ if raw_short_name.startswith("speckit."):+ raw_short_name = raw_short_name[len("speckit."):]+ short_name = raw_short_name.replace(".", "-")+ skill_title = self._skill_title_from_command(cmd_name)++ frontmatter, body = registrar.parse_frontmatter(composed_content)+ original_desc = frontmatter.get("description", "")+ enhanced_desc = SKILL_DESCRIPTIONS.get(+ short_name,+ original_desc or f"Spec-kit workflow command: {short_name}",+ )+ body = registrar.resolve_skill_placeholders(+ selected_ai, dict(frontmatter), body, self.project_root+ )++ for target_skill_name in target_skill_names:+ skill_subdir = skills_dir / target_skill_name+ if skill_subdir.exists() and not skill_subdir.is_dir():+ continue+ skill_subdir.mkdir(parents=True, exist_ok=True)+ frontmatter_data = registrar.build_skill_frontmatter(+ selected_ai,+ target_skill_name,+ enhanced_desc,+ f"preset:{outermost_pack_id}",+ )+ frontmatter_text = yaml.safe_dump(frontmatter_data, sort_keys=False).strip()+ skill_content = (+ f"---\n"+ f"{frontmatter_text}\n"+ f"---\n\n"+ f"# Speckit {skill_title} Skill\n\n"+ f"{body}\n"+ )+ if integration is not None and hasattr(integration, "post_process_skill_content"):+ skill_content = integration.post_process_skill_content(skill_content)+ (skill_subdir / "SKILL.md").write_text(skill_content, encoding="utf-8")+def _get_skills_dir(self) -> Optional[Path]:"""Return the active skills directory for preset skill overrides.@@ -624,7 +906,7 @@ class PresetManager:try:manifest = ExtensionManifest(manifest_path)- except ValidationError:+ except (ValidationError, TypeError, AttributeError):continueext_root = ext_dir.resolve()@@ -761,6 +1043,13 @@ class PresetManager:content = source_file.read_text(encoding="utf-8")frontmatter, body = registrar.parse_frontmatter(content)+ if frontmatter.get("strategy") == "wrap":+ body, core_frontmatter = _substitute_core_template(body, cmd_name, 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]+original_desc = frontmatter.get("description", "")enhanced_desc = SKILL_DESCRIPTIONS.get(short_name,@@ -974,6 +1263,24 @@ class PresetManager:# Update corresponding skills when --ai-skills was previously usedregistered_skills = self._register_skills(manifest, dest_dir)+ # Detect wrap commands before registry.add() so a read failure doesn't+ # leave a partially-committed registry entry.+ wrap_commands = []+ try:+ from .agents import CommandRegistrar as _CR+ _registrar = _CR()+ for cmd_tmpl in manifest.templates:+ if cmd_tmpl.get("type") != "command":+ continue+ cmd_file = dest_dir / cmd_tmpl["file"]+ if not cmd_file.exists():+ continue+ cmd_fm, _ = _registrar.parse_frontmatter(cmd_file.read_text(encoding="utf-8"))+ if cmd_fm.get("strategy") == "wrap":+ wrap_commands.append(cmd_tmpl["name"])+ except ImportError:+ pass+self.registry.add(manifest.id, {"version": manifest.version,"source": "local",@@ -982,8 +1289,12 @@ class PresetManager:"priority": priority,"registered_commands": registered_commands,"registered_skills": registered_skills,+ "wrap_commands": wrap_commands,})+ for cmd_name in wrap_commands:+ self._replay_wraps_for_command(cmd_name)+return manifestdef install_from_zip(@@ -1058,9 +1369,16 @@ class PresetManager:# Restore original skills when preset is removedregistered_skills = metadata.get("registered_skills", []) if metadata else []registered_commands = metadata.get("registered_commands", {}) if metadata else {}+ wrap_commands = metadata.get("wrap_commands", []) if metadata else []pack_dir = self.presets_dir / pack_id++ # _unregister_skills must run before directory deletion (reads preset files)if registered_skills:self._unregister_skills(registered_skills, pack_dir)+ # When _unregister_skills has already handled skill-agent files, strip+ # those entries from registered_commands to avoid double-deletion.+ # (When registered_skills is empty, skill-agent entries in+ # registered_commands are the only deletion path for those files.)try:from .agents import CommandRegistrarexcept ImportError:@@ -1072,14 +1390,44 @@ class PresetManager:if CommandRegistrar.AGENT_CONFIGS.get(agent_name, {}).get("extension") != "/SKILL.md"}- # Unregister non-skill command files from AI agents.- if registered_commands:- self._unregister_commands(registered_commands)-+ # Delete the preset directory before mutating the registry so a+ # filesystem failure cannot leave files on disk without a registry entry.if pack_dir.exists():shutil.rmtree(pack_dir)+ # Remove from registry before replaying so _replay_wraps_for_command sees+ # the post-removal registry state.self.registry.remove(pack_id)++ # Separate wrap commands from non-wrap commands in registered_commands.+ non_wrap_commands = {+ agent_name: [c for c in cmd_names if c not in wrap_commands]+ for agent_name, cmd_names in registered_commands.items()+ }+ non_wrap_commands = {k: v for k, v in non_wrap_commands.items() if v}++ # Unregister non-wrap command files from AI agents.+ if non_wrap_commands:+ self._unregister_commands(non_wrap_commands)++ # For each wrapped command, either re-compose remaining wraps or delete.+ for cmd_name in wrap_commands:+ remaining = [+ pid for pid, meta in self.registry.list().items()+ if cmd_name in meta.get("wrap_commands", [])+ ]+ if remaining:+ self._replay_wraps_for_command(cmd_name)+ else:+ # No wrap presets remain β delete the agent file entirely.+ wrap_agent_commands = {+ agent_name: [c for c in cmd_names if c == cmd_name]+ for agent_name, cmd_names in registered_commands.items()+ }+ wrap_agent_commands = {k: v for k, v in wrap_agent_commands.items() if v}+ if wrap_agent_commands:+ self._unregister_commands(wrap_agent_commands)+return Truedef list_installed(self) -> List[Dict[str, Any]]:@@ -1735,6 +2083,7 @@ class PresetResolver:self,template_name: str,template_type: str = "template",+ skip_presets: bool = False,) -> Optional[Path]:"""Resolve a template name to its file path.@@ -1743,6 +2092,8 @@ class PresetResolver:Args:template_name: Template name (e.g., "spec-template")template_type: Template type ("template", "command", or "script")+ skip_presets: When True, skip tier 2 (installed presets). Use+ resolve_core() as the preferred caller-facing API for this.Returns:Path to the resolved template file, or None if not found@@ -1771,7 +2122,7 @@ class PresetResolver:return override# Priority 2: Installed presets (sorted by priority β lower number wins)- if self.presets_dir.exists():+ if not skip_presets and self.presets_dir.exists():registry = PresetRegistry(self.presets_dir)for pack_id, _metadata in registry.list_by_priority():pack_dir = self.presets_dir / pack_id@@ -1810,6 +2161,99 @@ class PresetResolver:if core.exists():return core+ # Priority 5: Bundled core_pack (wheel install) or repo-root templates+ # (source-checkout / editable install). This is the canonical home for+ # speckit's built-in command/template files and must always be checked+ # so that strategy:wrap presets can locate {CORE_TEMPLATE}.+ from specify_cli import _locate_core_pack # local import to avoid cycles+ _core_pack = _locate_core_pack()+ if _core_pack is not None:+ # Wheel install path+ if template_type == "template":+ candidate = _core_pack / "templates" / f"{template_name}.md"+ elif template_type == "command":+ candidate = _core_pack / "commands" / f"{template_name}.md"+ elif template_type == "script":+ candidate = _core_pack / "scripts" / f"{template_name}{ext}"+ else:+ candidate = _core_pack / f"{template_name}.md"+ if candidate.exists():+ return candidate+ else:+ # Source-checkout / editable install: templates live at repo root+ repo_root = Path(__file__).parent.parent.parent+ if template_type == "template":+ candidate = repo_root / "templates" / f"{template_name}.md"+ elif template_type == "command":+ candidate = repo_root / "templates" / "commands" / f"{template_name}.md"+ elif template_type == "script":+ candidate = repo_root / "scripts" / f"{template_name}{ext}"+ else:+ candidate = repo_root / f"{template_name}.md"+ if candidate.exists():+ return candidate++ return None++ def resolve_core(+ self,+ template_name: str,+ template_type: str = "template",+ ) -> Optional[Path]:+ """Resolve while skipping installed presets (tier 2).++ Searches tiers 1, 3, 4, and 5 (bundled core_pack / repo-root fallback).+ Use when resolving {CORE_TEMPLATE} to guarantee the result is actual+ base content, never another preset's wrap output.+ """+ return self.resolve(template_name, template_type, skip_presets=True)++ def resolve_extension_command_via_manifest(self, cmd_name: str) -> Optional[Path]:+ """Resolve an extension command by consulting installed extension manifests.++ Walks installed extension directories in priority order, loads each+ extension.yml via ExtensionManifest, and looks up the command by its+ declared name to find the actual file path. This is necessary because+ the manifest's ``provides.commands[].file`` field is authoritative and+ may differ from the command name+ (e.g. ``speckit.selftest.extension`` β ``commands/selftest.md``).++ Returns None if no manifest maps the given command name, so the caller+ can fall back to the name-based lookup.+ """+ if not self.extensions_dir.exists():+ return None++ from .extensions import ExtensionManifest, ValidationError++ for _priority, ext_id, _metadata in self._get_all_extensions_by_priority():+ ext_dir = self.extensions_dir / ext_id+ manifest_path = ext_dir / "extension.yml"+ if not manifest_path.is_file():+ continue+ try:+ manifest = ExtensionManifest(manifest_path)+ except (ValidationError, OSError, TypeError, AttributeError):+ continue+ for cmd_info in manifest.commands:+ if cmd_info.get("name") != cmd_name:+ continue+ file_rel = cmd_info.get("file")+ if not file_rel:+ continue+ # Mirror the containment check in ExtensionManager to guard against+ # path traversal via a malformed manifest (e.g. file: ../../AGENTS.md).+ cmd_path = Path(file_rel)+ if cmd_path.is_absolute():+ continue+ try:+ ext_root = ext_dir.resolve()+ candidate = (ext_root / cmd_path).resolve()+ candidate.relative_to(ext_root) # raises ValueError if outside+ except (OSError, ValueError):+ continue+ if candidate.is_file():+ return candidatereturn Nonedef resolve_with_source(diff --git a/tests/integrations/test_cli.py b/tests/integrations/test_cli.pyindex 04a91682e..ff9386d62 100644--- a/tests/integrations/test_cli.py+++ b/tests/integrations/test_cli.py@@ -261,7 +261,7 @@ class TestForceExistingDirectory:], catch_exceptions=False)assert result.exit_code == 1- assert "already exists" in result.output+ assert "already exists" in _normalize_cli_output(result.output)class TestGitExtensionAutoInstall:diff --git a/tests/test_extensions.py b/tests/test_extensions.pyindex 5379178af..e1acb8486 100644--- a/tests/test_extensions.py+++ b/tests/test_extensions.py@@ -217,6 +217,14 @@ class TestExtensionManifest:with pytest.raises(ValidationError, match="Missing required field"):ExtensionManifest(manifest_path)+ def test_non_mapping_yaml_raises_validation_error(self, temp_dir):+ """Manifest whose YAML root is a scalar or list raises ValidationError, not TypeError."""+ manifest_path = temp_dir / "extension.yml"+ for bad_content in ("42\n", "[]\n", "null\n"):+ manifest_path.write_text(bad_content)+ with pytest.raises(ValidationError, match="YAML mapping"):+ ExtensionManifest(manifest_path)+def test_invalid_extension_id(self, temp_dir, valid_manifest_data):"""Test manifest with invalid extension ID format."""import yamldiff --git a/tests/test_presets.py b/tests/test_presets.pyindex 60322b99a..d913c3b19 100644--- a/tests/test_presets.py+++ b/tests/test_presets.py@@ -999,6 +999,94 @@ class TestPresetResolver:assert result is None+class TestResolveCore:+ """Test PresetResolver.resolve_core() skips the installed-presets tier."""++ def test_resolve_core_does_not_return_preset_files(self, project_dir):+ """resolve_core must not return files from .specify/presets/."""+ preset_cmd_dir = project_dir / ".specify" / "presets" / "my-preset" / "commands"+ preset_cmd_dir.mkdir(parents=True)+ (preset_cmd_dir / "specify.md").write_text("---\ndescription: preset wrap\n---\n\nwrap body\n")++ resolver = PresetResolver(project_dir)+ result = resolver.resolve_core("specify", "command")+ # The preset file must never be returned β but the bundled core may be.+ if result is not None:+ assert "presets" not in result.parts++ def test_resolve_core_returns_core_template(self, project_dir):+ """resolve_core falls through to core templates (tier 4)."""+ core_cmd_dir = project_dir / ".specify" / "templates" / "commands"+ core_cmd_dir.mkdir(parents=True, exist_ok=True)+ (core_cmd_dir / "specify.md").write_text("---\ndescription: core\n---\n\ncore body\n")++ # Also place a preset file β resolve_core must still return the core+ preset_cmd_dir = project_dir / ".specify" / "presets" / "my-preset" / "commands"+ preset_cmd_dir.mkdir(parents=True)+ (preset_cmd_dir / "specify.md").write_text("---\ndescription: preset wrap\n---\n\nwrap body\n")++ resolver = PresetResolver(project_dir)+ result = resolver.resolve_core("specify", "command")+ assert result is not None+ assert "presets" not in result.parts+ assert result.parts[-3:] == ("templates", "commands", "specify.md")++ def test_resolve_core_returns_override(self, project_dir):+ """resolve_core returns tier-1 override if present."""+ override_dir = project_dir / ".specify" / "templates" / "overrides"+ override_dir.mkdir(parents=True)+ (override_dir / "specify.md").write_text("---\ndescription: override\n---\n\noverride body\n")++ resolver = PresetResolver(project_dir)+ result = resolver.resolve_core("specify", "command")+ assert result is not None+ assert result.parts[-2:] == ("overrides", "specify.md")++ def test_resolve_core_returns_extension_template(self, project_dir):+ """resolve_core returns extension templates (tier 3)."""+ ext_cmd_dir = project_dir / ".specify" / "extensions" / "myext" / "commands"+ ext_cmd_dir.mkdir(parents=True)+ (ext_cmd_dir / "myext-cmd.md").write_text("---\ndescription: ext\n---\n\next body\n")++ resolver = PresetResolver(project_dir)+ result = resolver.resolve_core("myext-cmd", "command")+ assert result is not None+ assert result.parts[-4:-1] == ("extensions", "myext", "commands")++ def test_resolve_core_returns_none_when_nothing_found(self, project_dir):+ """resolve_core returns None when no file found in tiers 1/3/4."""+ resolver = PresetResolver(project_dir)+ result = resolver.resolve_core("nonexistent", "command")+ assert result is None++ def test_resolve_extension_command_via_manifest_skips_oserror_manifests(self, project_dir):+ """resolve_extension_command_via_manifest skips extensions whose manifest raises OSError."""+ import unittest.mock as mock++ ext_dir = project_dir / ".specify" / "extensions" / "bad-ext"+ cmd_dir = ext_dir / "commands"+ cmd_dir.mkdir(parents=True)+ (cmd_dir / "mycmd.md").write_text("---\ndescription: d\n---\n\nbody\n")+ (ext_dir / "extension.yml").write_text(+ "schema_version: '1.0'\n"+ "extension:\n id: bad-ext\n name: Bad\n version: 1.0.0\n"+ " description: d\n author: a\n repository: https://example.com\n"+ " license: MIT\n"+ "requires:\n speckit_version: '>=0.2.0'\n"+ "provides:\n commands:\n"+ " - name: speckit.bad-ext.mycmd\n"+ " file: commands/mycmd.md\n"+ " description: My command\n"+ )++ resolver = PresetResolver(project_dir)+ # Simulate a permission error when opening the manifest file.+ with mock.patch("builtins.open", side_effect=PermissionError("denied")):+ result = resolver.resolve_extension_command_via_manifest("speckit.bad-ext.mycmd")++ assert result is None, "OSError during manifest load must be silently skipped"++class TestExtensionPriorityResolution:"""Test extension priority resolution with registered and unregistered extensions."""@@ -1665,7 +1753,7 @@ class TestSelfTestPreset:assert manifest.id == "self-test"assert manifest.name == "Self-Test Preset"assert manifest.version == "1.0.0"- assert len(manifest.templates) == 7 # 6 templates + 1 command+ assert len(manifest.templates) == 8 # 6 templates + 2 commandsdef test_self_test_provides_all_core_templates(self):"""Verify the self-test preset provides an override for every core template."""@@ -3041,3 +3129,1184 @@ class TestBundledPresetLocator:output = strip_ansi(result.output).lower()assert "bundled" in output, result.outputassert "reinstall" in output, result.output+++class TestWrapStrategy:+ """Tests for strategy: wrap preset command substitution."""++ def test_substitute_core_template_replaces_placeholder(self, project_dir):+ """Core template body replaces {CORE_TEMPLATE} in preset command body."""+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ # Set up a core command template+ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\n---\n\n# Core Specify\n\nDo the thing.\n"+ )++ registrar = CommandRegistrar()+ body = "## Pre-Logic\n\nBefore stuff.\n\n{CORE_TEMPLATE}\n\n## Post-Logic\n\nAfter stuff.\n"+ result, core_fm = _substitute_core_template(body, "specify", project_dir, registrar)++ assert "{CORE_TEMPLATE}" not in result+ assert "# Core Specify" in result+ assert "## Pre-Logic" in result+ assert "## Post-Logic" in result+ assert core_fm.get("description") == "core"++ def test_substitute_core_template_no_op_when_placeholder_absent(self, project_dir):+ """Returns body unchanged when {CORE_TEMPLATE} is not present."""+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCore body.\n")++ registrar = CommandRegistrar()+ body = "## No placeholder here.\n"+ result, core_fm = _substitute_core_template(body, "specify", project_dir, registrar)+ assert result == body+ assert core_fm == {}++ def test_substitute_core_template_no_op_when_core_missing(self, project_dir):+ """Returns body unchanged when core template file does not exist."""+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ registrar = CommandRegistrar()+ body = "Pre.\n\n{CORE_TEMPLATE}\n\nPost.\n"+ result, core_fm = _substitute_core_template(body, "nonexistent", project_dir, registrar)+ assert result == body+ assert "{CORE_TEMPLATE}" in result+ assert core_fm == {}++ def test_register_commands_substitutes_core_template_for_wrap_strategy(self, project_dir):+ """register_commands substitutes {CORE_TEMPLATE} when strategy: wrap."""+ from specify_cli.agents import CommandRegistrar++ # Set up core command template+ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\n---\n\n# Core Specify\n\nCore body here.\n"+ )++ # Create a preset command dir with a wrap-strategy command+ cmd_dir = project_dir / "preset" / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: wrap test\nstrategy: wrap\n---\n\n"+ "## Pre\n\n{CORE_TEMPLATE}\n\n## Post\n"+ )++ commands = [{"name": "speckit.specify", "file": "commands/speckit.specify.md"}]+ registrar = CommandRegistrar()++ # Use a generic agent that writes markdown to commands/+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)++ # Patch AGENT_CONFIGS to use a simple markdown agent pointing at our dir+ import copy+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown",+ "args": "$ARGUMENTS",+ "extension": ".md",+ "strip_frontmatter_keys": [],+ }+ try:+ registrar.register_commands(+ "test-agent", commands, "test-preset",+ project_dir / "preset", project_dir+ )+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "{CORE_TEMPLATE}" not in written+ assert "# Core Specify" in written+ assert "## Pre" in written+ assert "## Post" in written++ def test_end_to_end_wrap_via_self_test_preset(self, project_dir):+ """Installing self-test preset with a wrap command substitutes {CORE_TEMPLATE}."""+ from specify_cli.presets import PresetManager++ # Install a core template that wrap-test will wrap around+ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "wrap-test.md").write_text(+ "---\ndescription: core wrap-test\n---\n\n# Core Wrap-Test Body\n"+ )++ # Set up skills dir (simulating --ai claude)+ skills_dir = project_dir / ".claude" / "skills"+ skills_dir.mkdir(parents=True, exist_ok=True)+ skill_subdir = skills_dir / "speckit-wrap-test"+ skill_subdir.mkdir()+ (skill_subdir / "SKILL.md").write_text("---\nname: speckit-wrap-test\n---\n\nold content\n")++ # Write init-options so _register_skills finds the claude skills dir+ import json+ (project_dir / ".specify" / "init-options.json").write_text(+ json.dumps({"ai": "claude", "ai_skills": True})+ )++ manager = PresetManager(project_dir)+ manager.install_from_directory(SELF_TEST_PRESET_DIR, "0.1.5")++ written = (skill_subdir / "SKILL.md").read_text()+ assert "{CORE_TEMPLATE}" not in written+ assert "# Core Wrap-Test Body" in written+ assert "preset:self-test wrap-pre" in written+ assert "preset:self-test wrap-post" in written++ def test_substitute_core_template_returns_core_scripts(self, project_dir):+ """core_frontmatter in the returned tuple includes scripts/agent_scripts."""+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: run.sh\nagent_scripts:\n sh: agent-run.sh\n---\n\n# Body\n"+ )++ registrar = CommandRegistrar()+ body = "## Wrapper\n\n{CORE_TEMPLATE}\n"+ result, core_fm = _substitute_core_template(body, "specify", project_dir, registrar)++ assert "# Body" in result+ assert core_fm.get("scripts") == {"sh": "run.sh"}+ assert core_fm.get("agent_scripts") == {"sh": "agent-run.sh"}++ def test_register_skills_inherits_scripts_from_core_when_preset_omits_them(self, project_dir):+ """_register_skills merges scripts/agent_scripts from core when preset lacks them."""+ from specify_cli.presets import PresetManager+ import json++ # Core template with scripts+ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "wrap-test.md").write_text(+ "---\ndescription: core\nscripts:\n sh: .specify/scripts/run.sh\n---\n\n"+ "Run: {SCRIPT}\n"+ )++ # Skills dir for claude+ skills_dir = project_dir / ".claude" / "skills"+ skills_dir.mkdir(parents=True, exist_ok=True)+ skill_subdir = skills_dir / "speckit-wrap-test"+ skill_subdir.mkdir()+ (skill_subdir / "SKILL.md").write_text("---\nname: speckit-wrap-test\n---\n\nold\n")++ (project_dir / ".specify" / "init-options.json").write_text(+ json.dumps({"ai": "claude", "ai_skills": True})+ )++ manager = PresetManager(project_dir)+ manager.install_from_directory(SELF_TEST_PRESET_DIR, "0.1.5")++ written = (skill_subdir / "SKILL.md").read_text()+ # {SCRIPT} should have been resolved (not left as a literal placeholder)+ assert "{SCRIPT}" not in written++ def test_register_skills_preset_scripts_take_precedence_over_core(self, project_dir):+ """preset-defined scripts/agent_scripts are not overwritten by core frontmatter."""+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: core-run.sh\n---\n\nCore body.\n"+ )++ registrar = CommandRegistrar()+ body = "{CORE_TEMPLATE}"+ _, core_fm = _substitute_core_template(body, "specify", project_dir, registrar)++ # Simulate preset frontmatter that already defines scripts+ preset_fm = {"description": "preset", "strategy": "wrap", "scripts": {"sh": "preset-run.sh"}}+ for key in ("scripts", "agent_scripts"):+ if key not in preset_fm and key in core_fm:+ preset_fm[key] = core_fm[key]++ # Preset's scripts must not be overwritten by core+ assert preset_fm["scripts"] == {"sh": "preset-run.sh"}++ def test_register_commands_inherits_scripts_from_core(self, project_dir):+ """register_commands merges scripts/agent_scripts from core and normalizes paths."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: .specify/scripts/run.sh {ARGS}\n---\n\n"+ "Run: {SCRIPT}\n"+ )++ cmd_dir = project_dir / "preset" / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ # Preset has strategy: wrap but no scripts of its own+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: wrap no scripts\nstrategy: wrap\n---\n\n"+ "## Pre\n\n{CORE_TEMPLATE}\n\n## Post\n"+ )++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown",+ "args": "$ARGUMENTS",+ "extension": ".md",+ "strip_frontmatter_keys": [],+ }+ try:+ registrar.register_commands(+ "test-agent",+ [{"name": "speckit.specify", "file": "commands/speckit.specify.md"}],+ "test-preset",+ project_dir / "preset",+ project_dir,+ )+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "{CORE_TEMPLATE}" not in written+ assert "Run:" in written+ assert "scripts:" in written+ assert "run.sh" in written++ def test_register_commands_toml_resolves_inherited_scripts(self, project_dir):+ """TOML agents resolve {SCRIPT} from inherited core scripts when preset omits them."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: .specify/scripts/run.sh {ARGS}\n---\n\n"+ "Run: {SCRIPT}\n"+ )++ cmd_dir = project_dir / "preset" / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: toml wrap\nstrategy: wrap\n---\n\n"+ "## Pre\n\n{CORE_TEMPLATE}\n\n## Post\n"+ )++ toml_dir = project_dir / ".gemini" / "commands"+ toml_dir.mkdir(parents=True, exist_ok=True)++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-toml-agent"] = {+ "dir": str(toml_dir.relative_to(project_dir)),+ "format": "toml",+ "args": "{{args}}",+ "extension": ".toml",+ "strip_frontmatter_keys": [],+ }+ try:+ registrar.register_commands(+ "test-toml-agent",+ [{"name": "speckit.specify", "file": "commands/speckit.specify.md"}],+ "test-preset",+ project_dir / "preset",+ project_dir,+ )+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (toml_dir / "speckit.specify.toml").read_text()+ assert "{CORE_TEMPLATE}" not in written+ assert "{SCRIPT}" not in written+ assert "run.sh" in written+ # args token must use TOML format, not the intermediate $ARGUMENTS+ assert "$ARGUMENTS" not in written+ assert "{{args}}" in written++ def test_register_commands_markdown_resolves_inherited_scripts(self, project_dir):+ """Markdown agents resolve {SCRIPT} from inherited core scripts when preset omits them."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: .specify/scripts/run.sh {ARGS}\n---\n\n"+ "Run: {SCRIPT}\n"+ )++ cmd_dir = project_dir / "preset" / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: markdown wrap\nstrategy: wrap\n---\n\n"+ "## Pre\n\n{CORE_TEMPLATE}\n\n## Post\n"+ )++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-md-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown",+ "args": "$ARGUMENTS",+ "extension": ".md",+ "strip_frontmatter_keys": [],+ }+ try:+ registrar.register_commands(+ "test-md-agent",+ [{"name": "speckit.specify", "file": "commands/speckit.specify.md"}],+ "test-preset",+ project_dir / "preset",+ project_dir,+ )+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "{CORE_TEMPLATE}" not in written+ assert "{SCRIPT}" not in written+ assert "run.sh" in written+ assert "strategy" not in written++ def test_register_commands_markdown_converts_args_after_script_resolution(self, project_dir):+ """Markdown agents re-run arg placeholder conversion after resolve_skill_placeholders.++ resolve_skill_placeholders injects $ARGUMENTS (via {ARGS} expansion). A second+ _convert_argument_placeholder call must convert those to the agent's native format.+ """+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text(+ "---\ndescription: core\nscripts:\n sh: .specify/scripts/run.sh {ARGS}\n---\n\n"+ "Run: {SCRIPT}\n"+ )++ cmd_dir = project_dir / "preset" / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: forge wrap\nstrategy: wrap\n---\n\n"+ "## Pre\n\n{CORE_TEMPLATE}\n\n## Post\n"+ )++ agent_dir = project_dir / ".forge" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-forge-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown",+ "args": "{{parameters}}",+ "extension": ".md",+ "strip_frontmatter_keys": [],+ }+ try:+ registrar.register_commands(+ "test-forge-agent",+ [{"name": "speckit.specify", "file": "commands/speckit.specify.md"}],+ "test-preset",+ project_dir / "preset",+ project_dir,+ )+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "{SCRIPT}" not in written+ assert "run.sh" in written+ # $ARGUMENTS injected by resolve_skill_placeholders must be re-converted+ assert "$ARGUMENTS" not in written+ assert "{{parameters}}" in written++ def test_extension_command_resolves_via_extension_directory(self, project_dir):+ """Extension commands (e.g. speckit.git.feature) resolve from the extension directory.++ Both _register_skills and register_commands pass the full cmd_name to+ _substitute_core_template, which tries the full name first via PresetResolver+ and finds speckit.git.feature.md in the extension commands directory.+ """+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ # Place the template where a real extension would install it+ ext_cmd_dir = project_dir / ".specify" / "extensions" / "git" / "commands"+ ext_cmd_dir.mkdir(parents=True, exist_ok=True)+ (ext_cmd_dir / "speckit.git.feature.md").write_text(+ "---\ndescription: git feature core\n---\n\n# Git Feature Core\n"+ )+ # Ensure a hyphenated or dot-separated fallback does NOT exist+ assert not (project_dir / ".specify" / "templates" / "commands" / "git.feature.md").exists()+ assert not (project_dir / ".specify" / "templates" / "commands" / "git-feature.md").exists()++ registrar = CommandRegistrar()+ body = "## Wrapper\n\n{CORE_TEMPLATE}\n"++ # Both call sites now pass the full cmd_name+ result, _ = _substitute_core_template(body, "speckit.git.feature", project_dir, registrar)++ assert "# Git Feature Core" in result+ assert "{CORE_TEMPLATE}" not in result++ def test_extension_command_resolves_via_manifest_when_filename_differs(self, project_dir):+ """Extension commands whose filename differs from the command name resolve via extension.yml.++ The selftest extension maps speckit.selftest.extension β commands/selftest.md.+ Name-based lookup would look for commands/speckit.selftest.extension.md and fail;+ manifest-based lookup must find the actual file declared in the manifest.+ """+ from specify_cli.presets import _substitute_core_template+ from specify_cli.agents import CommandRegistrar++ ext_dir = project_dir / ".specify" / "extensions" / "selftest"+ cmd_dir = ext_dir / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)++ # File is named selftest.md, NOT speckit.selftest.extension.md+ (cmd_dir / "selftest.md").write_text(+ "---\ndescription: selftest core\n---\n\n# Selftest Core\n"+ )+ # Manifest maps the command name to the actual file+ (ext_dir / "extension.yml").write_text(+ "schema_version: '1.0'\n"+ "extension:\n id: selftest\n name: Self-Test\n version: 1.0.0\n"+ " description: test\n author: test\n repository: https://example.com\n"+ " license: MIT\n"+ "requires:\n speckit_version: '>=0.2.0'\n"+ "provides:\n"+ " commands:\n"+ " - name: speckit.selftest.extension\n"+ " file: commands/selftest.md\n"+ " description: Selftest command\n"+ )++ registrar = CommandRegistrar()+ body = "## Wrapper\n\n{CORE_TEMPLATE}\n"+ result, _ = _substitute_core_template(body, "speckit.selftest.extension", project_dir, registrar)++ assert "# Selftest Core" in result+ assert "{CORE_TEMPLATE}" not in result+++# ===== _replay_wraps_for_command Tests =====++def _make_wrap_preset_dir(+ base: Path,+ preset_id: str,+ cmd_name: str,+ pre: str,+ post: str,+ aliases: list[str] | None = None,+ file_rel: str | None = None,+) -> Path:+ """Create a minimal wrap-strategy preset directory for testing."""+ preset_dir = base / preset_id+ cmd_dir = preset_dir / "commands"+ cmd_dir.mkdir(parents=True)+ file_rel = file_rel or f"commands/{cmd_name}.md"+ template = {+ "type": "command",+ "name": cmd_name,+ "file": file_rel,+ "description": f"{preset_id} wrap",+ }+ if aliases is not None:+ template["aliases"] = aliases+ manifest = {+ "schema_version": "1.0",+ "preset": {+ "id": preset_id,+ "name": preset_id,+ "version": "1.0.0",+ "description": f"Preset {preset_id}",+ "author": "test",+ "repository": "https://example.com",+ "license": "MIT",+ },+ "requires": {"speckit_version": ">=0.1.0"},+ "provides": {+ "templates": [template]+ },+ "tags": [],+ }+ import yaml as _yaml+ (preset_dir / "preset.yml").write_text(_yaml.dump(manifest))+ command_path = preset_dir / file_rel+ command_path.parent.mkdir(parents=True, exist_ok=True)+ command_path.write_text(+ f"---\ndescription: {preset_id} wrap\nstrategy: wrap\n---\n\n"+ f"[{pre}]\n\n{{CORE_TEMPLATE}}\n\n[{post}]\n"+ )+ return preset_dir+++class TestReplayWrapsForCommand:+ """Tests for PresetManager._replay_wraps_for_command()."""++ def test_replay_no_op_when_no_wrap_presets(self, project_dir):+ """replay does nothing when no presets declare wrap_commands for the command."""+ manager = PresetManager(project_dir)+ # Should not raise+ manager._replay_wraps_for_command("speckit.specify")++ def test_replay_no_op_when_core_missing(self, project_dir, temp_dir):+ """replay exits gracefully when resolve_core returns None."""+ from specify_cli.agents import CommandRegistrar+ import copy++ preset_dir = _make_wrap_preset_dir(temp_dir, "preset-a", "speckit.nonexistent-cmd", "pre-a", "post-a")+ installed = project_dir / ".specify" / "presets" / "preset-a"+ import shutil as _shutil+ _shutil.copytree(preset_dir, installed)++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.nonexistent-cmd"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ # No core file exists for this command β replay should return without writing+ manager._replay_wraps_for_command("speckit.nonexistent-cmd")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ assert not (agent_dir / "speckit.nonexistent-cmd.md").exists()++ def test_replay_single_preset_writes_composed_output(self, project_dir, temp_dir):+ """Single wrap preset: replay writes pre + core + post to agent dirs."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ # Core template+ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\ncore body\n")++ # Install preset-a+ preset_dir = _make_wrap_preset_dir(temp_dir, "preset-a", "speckit.specify", "pre-a", "post-a")+ installed = project_dir / ".specify" / "presets" / "preset-a"+ _shutil.copytree(preset_dir, installed)++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)+ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager._replay_wraps_for_command("speckit.specify")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "[pre-a]" in written+ assert "core body" in written+ assert "[post-a]" in written+ assert "{CORE_TEMPLATE}" not in written+ assert "strategy" not in written++ def test_replay_uses_manifest_command_file_mapping(self, project_dir, temp_dir):+ """Replay reads wrapper files from preset.yml instead of assuming command-name paths."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ preset_dir = _make_wrap_preset_dir(+ temp_dir,+ "preset-a",+ "speckit.specify",+ "pre-a",+ "post-a",+ file_rel="commands/custom-wrapper.md",+ )+ installed = project_dir / ".specify" / "presets" / "preset-a"+ _shutil.copytree(preset_dir, installed)++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)+ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager._replay_wraps_for_command("speckit.specify")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ assert "[pre-a]" in written+ assert "CORE" in written+ assert "[post-a]" in written++ def test_replay_resolves_extension_core_via_manifest_mapping(self, project_dir, temp_dir):+ """Replay finds extension core commands whose manifest file differs from command name."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ ext_dir = project_dir / ".specify" / "extensions" / "selftest"+ cmd_dir = ext_dir / "commands"+ cmd_dir.mkdir(parents=True, exist_ok=True)+ (cmd_dir / "selftest.md").write_text(+ "---\ndescription: selftest core\n---\n\nEXTENSION-CORE\n"+ )+ (ext_dir / "extension.yml").write_text(+ "schema_version: '1.0'\n"+ "extension:\n id: selftest\n name: Self-Test\n version: 1.0.0\n"+ " description: test\n author: test\n repository: https://example.com\n"+ " license: MIT\n"+ "requires:\n speckit_version: '>=0.2.0'\n"+ "provides:\n"+ " commands:\n"+ " - name: speckit.selftest.extension\n"+ " file: commands/selftest.md\n"+ " description: Selftest command\n"+ )++ preset_dir = _make_wrap_preset_dir(+ temp_dir, "preset-a", "speckit.selftest.extension", "pre-a", "post-a"+ )+ installed = project_dir / ".specify" / "presets" / "preset-a"+ _shutil.copytree(preset_dir, installed)++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.selftest.extension"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)+ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager._replay_wraps_for_command("speckit.selftest.extension")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.selftest.extension.md").read_text()+ assert "[pre-a]" in written+ assert "EXTENSION-CORE" in written+ assert "[post-a]" in written++ def test_replay_priority_order_lower_number_outermost(self, project_dir, temp_dir):+ """Two wrap presets: lower priority number = outermost wrapper."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ for pid in ("preset-outer", "preset-inner"):+ src = _make_wrap_preset_dir(temp_dir, pid, "speckit.specify", f"pre-{pid}", f"post-{pid}")+ _shutil.copytree(src, project_dir / ".specify" / "presets" / pid)++ manager = PresetManager(project_dir)+ # preset-outer has priority 1 (highest precedence = outermost)+ # preset-inner has priority 10 (lowest precedence = innermost)+ for pid, pri in (("preset-outer", 1), ("preset-inner", 10)):+ manager.registry.add(pid, {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": pri, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)+ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager._replay_wraps_for_command("speckit.specify")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ # Outermost (preset-outer, p=1) wraps everything; innermost (preset-inner, p=10) is next+ outer_pre = written.index("[pre-preset-outer]")+ inner_pre = written.index("[pre-preset-inner]")+ core_pos = written.index("CORE")+ inner_post = written.index("[post-preset-inner]")+ outer_post = written.index("[post-preset-outer]")+ assert outer_pre < inner_pre < core_pos < inner_post < outer_post++ def test_replay_install_order_independent(self, project_dir, temp_dir):+ """Nesting order is determined by priority, not install order."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ for pid in ("preset-a", "preset-b"):+ src = _make_wrap_preset_dir(temp_dir, pid, "speckit.specify", f"pre-{pid}", f"post-{pid}")+ _shutil.copytree(src, project_dir / ".specify" / "presets" / pid)++ manager = PresetManager(project_dir)+ # preset-a priority=5 (outermost), preset-b priority=10 (innermost)+ # Install in reverse order to verify install order doesn't affect nesting+ for pid, pri in (("preset-b", 10), ("preset-a", 5)):+ manager.registry.add(pid, {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": pri, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True)+ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager._replay_wraps_for_command("speckit.specify")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ a_pre = written.index("[pre-preset-a]")+ b_pre = written.index("[pre-preset-b]")+ core_pos = written.index("CORE")+ b_post = written.index("[post-preset-b]")+ a_post = written.index("[post-preset-a]")+ # preset-a (p=5) is outermost regardless of install order+ assert a_pre < b_pre < core_pos < b_post < a_post++ def test_replay_updates_skill_outputs(self, project_dir, temp_dir):+ """Replay also rewrites SKILL.md-backed agent outputs."""+ import json+ import shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ preset_dir = _make_wrap_preset_dir(temp_dir, "preset-a", "speckit.specify", "pre-a", "post-a")+ _shutil.copytree(preset_dir, project_dir / ".specify" / "presets" / "preset-a")++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ skills_dir = project_dir / ".claude" / "skills"+ skill_subdir = skills_dir / "speckit-specify"+ skill_subdir.mkdir(parents=True)+ (skill_subdir / "SKILL.md").write_text("---\nname: speckit-specify\n---\n\nold\n")+ (project_dir / ".specify" / "init-options.json").write_text(+ json.dumps({"ai": "claude", "ai_skills": True})+ )++ manager._replay_wraps_for_command("speckit.specify")++ written = (skill_subdir / "SKILL.md").read_text()+ assert "[pre-a]" in written+ assert "CORE" in written+ assert "[post-a]" in written++ def test_replay_applies_integration_post_processing_to_skill(self, project_dir, temp_dir):+ """_replay_skill_override must call post_process_skill_content, matching _register_skills."""+ import json+ import shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ preset_dir = _make_wrap_preset_dir(temp_dir, "preset-a", "speckit.specify", "pre-a", "post-a")+ _shutil.copytree(preset_dir, project_dir / ".specify" / "presets" / "preset-a")++ manager = PresetManager(project_dir)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": ["speckit.specify"],+ })++ skills_dir = project_dir / ".claude" / "skills"+ skill_subdir = skills_dir / "speckit-specify"+ skill_subdir.mkdir(parents=True)+ (skill_subdir / "SKILL.md").write_text("---\nname: speckit-specify\n---\n\nold\n")+ (project_dir / ".specify" / "init-options.json").write_text(+ json.dumps({"ai": "claude", "ai_skills": True})+ )++ manager._replay_wraps_for_command("speckit.specify")++ # ClaudeIntegration.post_process_skill_content injects these flags.+ # Their presence proves the integration hook ran during replay.+ written = (skill_subdir / "SKILL.md").read_text()+ assert "disable-model-invocation: false" in written, (+ "_replay_skill_override must call post_process_skill_content "+ "(same as _register_skills)"+ )+++class TestInstallRemoveWrapLifecycle:+ """Tests for wrap_commands stored on install and replayed on remove."""++ def _setup_agent(self, project_dir, registrar, agent_configs_dict):+ """Register a test markdown agent and return its commands dir."""+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ agent_configs_dict["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ return agent_dir++ def test_install_stores_wrap_commands_in_registry(self, project_dir, temp_dir):+ """install_from_directory stores wrap_commands in the registry entry."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\ncore\n")++ preset_src = _make_wrap_preset_dir(temp_dir, "preset-a", "speckit.specify", "pre", "post")++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ manager.install_from_directory(preset_src, "0.1.0", priority=10)+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ meta = manager.registry.get("preset-a")+ assert "wrap_commands" in meta+ assert "speckit.specify" in meta["wrap_commands"]++ def test_install_replay_produces_correct_nested_output(self, project_dir, temp_dir):+ """After installing two wrap presets, agent file contains correctly nested output."""+ from specify_cli.agents import CommandRegistrar+ import copy, shutil as _shutil++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ # Install outermost first (priority=5), then innermost (priority=10)+ outer_src = _make_wrap_preset_dir(temp_dir, "preset-outer", "speckit.specify", "OUTER-PRE", "OUTER-POST")+ # Rename to avoid id conflict with fixture+ inner_src = _make_wrap_preset_dir(temp_dir, "preset-inner", "speckit.specify", "INNER-PRE", "INNER-POST")+ manager.install_from_directory(outer_src, "0.1.0", priority=5)+ manager.install_from_directory(inner_src, "0.1.0", priority=10)+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ outer_pre = written.index("OUTER-PRE")+ inner_pre = written.index("INNER-PRE")+ core_pos = written.index("CORE")+ inner_post = written.index("INNER-POST")+ outer_post = written.index("OUTER-POST")+ assert outer_pre < inner_pre < core_pos < inner_post < outer_post++ def test_remove_replays_remaining_wraps(self, project_dir, temp_dir):+ """Removing one wrap preset re-composes the remaining wraps correctly."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ outer_src = _make_wrap_preset_dir(temp_dir, "preset-outer", "speckit.specify", "OUTER-PRE", "OUTER-POST")+ inner_src = _make_wrap_preset_dir(temp_dir, "preset-inner", "speckit.specify", "INNER-PRE", "INNER-POST")+ manager.install_from_directory(outer_src, "0.1.0", priority=5)+ manager.install_from_directory(inner_src, "0.1.0", priority=10)+ manager.remove("preset-outer")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ written = (agent_dir / "speckit.specify.md").read_text()+ # Only inner wrap remains β should be: INNER-PRE + CORE + INNER-POST, no OUTER+ assert "INNER-PRE" in written+ assert "CORE" in written+ assert "INNER-POST" in written+ assert "OUTER-PRE" not in written+ assert "OUTER-POST" not in written++ def test_wrap_aliases_are_replayed_and_removed(self, project_dir, temp_dir):+ """Replay preserves wrap aliases across install/remove lifecycle changes."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ outer_src = _make_wrap_preset_dir(+ temp_dir,+ "preset-outer",+ "speckit.specify",+ "OUTER-PRE",+ "OUTER-POST",+ aliases=["speckit.alias"],+ )+ inner_src = _make_wrap_preset_dir(+ temp_dir, "preset-inner", "speckit.specify", "INNER-PRE", "INNER-POST"+ )+ manager.install_from_directory(outer_src, "0.1.0", priority=5)+ manager.install_from_directory(inner_src, "0.1.0", priority=10)++ alias_file = agent_dir / "speckit.alias.md"+ written = alias_file.read_text()+ assert "OUTER-PRE" in written+ assert "INNER-PRE" in written+ assert "INNER-POST" in written+ assert "OUTER-POST" in written++ manager.remove("preset-inner")+ written = alias_file.read_text()+ assert "OUTER-PRE" in written+ assert "OUTER-POST" in written+ assert "INNER-PRE" not in written+ assert "INNER-POST" not in written++ manager.remove("preset-outer")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ assert not (agent_dir / "speckit.alias.md").exists()++ def test_remove_last_wrap_preset_deletes_agent_file(self, project_dir, temp_dir):+ """Removing the only wrap preset deletes the agent command file."""+ from specify_cli.agents import CommandRegistrar+ import copy++ core_dir = project_dir / ".specify" / "templates" / "commands"+ core_dir.mkdir(parents=True, exist_ok=True)+ (core_dir / "specify.md").write_text("---\ndescription: core\n---\n\nCORE\n")++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ src = _make_wrap_preset_dir(temp_dir, "preset-only", "speckit.specify", "PRE", "POST")+ manager.install_from_directory(src, "0.1.0", priority=10)+ assert (agent_dir / "speckit.specify.md").exists()+ manager.remove("preset-only")+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ assert not (agent_dir / "speckit.specify.md").exists()++ def test_remove_keeps_registry_entry_when_directory_delete_fails(self, project_dir, monkeypatch):+ """A failed preset directory delete must not leave files untracked by the registry."""+ manager = PresetManager(project_dir)+ pack_dir = manager.presets_dir / "preset-a"+ pack_dir.mkdir(parents=True)+ manager.registry.add("preset-a", {+ "version": "1.0.0", "source": "local", "enabled": True,+ "priority": 10, "manifest_hash": "x",+ "registered_commands": {}, "registered_skills": [],+ "wrap_commands": [],+ })++ def fail_rmtree(_path):+ raise OSError("locked")++ monkeypatch.setattr(shutil, "rmtree", fail_rmtree)++ with pytest.raises(OSError, match="locked"):+ manager.remove("preset-a")++ assert manager.registry.is_installed("preset-a")+ assert pack_dir.exists()++ def test_non_wrap_commands_unaffected_by_wrap_lifecycle(self, project_dir, temp_dir):+ """wrap_commands is empty for a preset with no strategy:wrap commands."""+ from specify_cli.agents import CommandRegistrar+ import copy+ import yaml as _yaml++ # Create a preset with a non-wrap command+ preset_dir = temp_dir / "non-wrap-preset"+ cmd_dir = preset_dir / "commands"+ cmd_dir.mkdir(parents=True)+ manifest = {+ "schema_version": "1.0",+ "preset": {+ "id": "non-wrap-preset", "name": "Non-wrap", "version": "1.0.0",+ "description": "no wrap", "author": "test",+ "repository": "https://example.com", "license": "MIT",+ },+ "requires": {"speckit_version": ">=0.1.0"},+ "provides": {"templates": [+ {"type": "command", "name": "speckit.specify",+ "file": "commands/speckit.specify.md", "description": "override"},+ ]},+ "tags": [],+ }+ (preset_dir / "preset.yml").write_text(_yaml.dump(manifest))+ (cmd_dir / "speckit.specify.md").write_text(+ "---\ndescription: plain override\n---\n\nplain body\n"+ )++ registrar = CommandRegistrar()+ original = copy.deepcopy(registrar.AGENT_CONFIGS)+ agent_dir = project_dir / ".claude" / "commands"+ agent_dir.mkdir(parents=True, exist_ok=True)+ registrar.AGENT_CONFIGS["test-agent"] = {+ "dir": str(agent_dir.relative_to(project_dir)),+ "format": "markdown", "args": "$ARGUMENTS",+ "extension": ".md", "strip_frontmatter_keys": [],+ }+ try:+ manager = PresetManager(project_dir)+ manager.install_from_directory(preset_dir, "0.1.0", priority=10)+ finally:+ CommandRegistrar.AGENT_CONFIGS.clear()+ CommandRegistrar.AGENT_CONFIGS.update(original)++ meta = manager.registry.get("non-wrap-preset")+ assert meta.get("wrap_commands", []) == []+ written = (agent_dir / "speckit.specify.md").read_text()+ assert "plain body" in written