Skip to content

Commit 62283b7

Browse files
mbachorikclaude
andcommitted
feat(extensions): add scripts support, command filtering, and template discovery
Bring extension system to parity with presets across three areas: - github#1847: Extensions now support `provides.scripts` alongside commands, with name format and path safety validation, executable permissions, and CLI display in list/add/info. - github#1848: Add `_filter_commands_for_installed_extensions()` to CommandRegistrar for cross-boundary command filtering (matching the preset filtering at presets.py:518-529). - github#1846: Add `list_available()` to PresetResolver for template discovery across the 4-tier priority stack with source attribution, and a new `specify preset list-templates` CLI command. Closes github#1846, closes github#1847, closes github#1848 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent eeda669 commit 62283b7

5 files changed

Lines changed: 618 additions & 11 deletions

File tree

‎src/specify_cli/__init__.py‎

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2735,6 +2735,38 @@ def preset_resolve(
27352735
console.print(" [dim]No template with this name exists in the resolution stack[/dim]")
27362736

27372737

2738+
@preset_app.command("list-templates")
2739+
def preset_list_templates(
2740+
template_type: str = typer.Option(
2741+
"template", "--type", "-t",
2742+
help="Template type: template, command, or script",
2743+
),
2744+
):
2745+
"""List all available templates from the resolution stack."""
2746+
from .presets import PresetResolver
2747+
2748+
project_root = Path.cwd()
2749+
2750+
specify_dir = project_root / ".specify"
2751+
if not specify_dir.exists():
2752+
console.print("[red]Error:[/red] Not a spec-kit project (no .specify/ directory)")
2753+
console.print("Run this command from a spec-kit project root")
2754+
raise typer.Exit(1)
2755+
2756+
resolver = PresetResolver(project_root)
2757+
available = resolver.list_available(template_type)
2758+
2759+
if not available:
2760+
console.print(f"[yellow]No {template_type}s found in the resolution stack[/yellow]")
2761+
return
2762+
2763+
console.print(f"\n[bold]Available {template_type}s ({len(available)}):[/bold]\n")
2764+
for entry in available:
2765+
console.print(f" [bold]{entry['name']}[/bold]")
2766+
console.print(f" [dim]Source: {entry['source']}[/dim]")
2767+
console.print(f" [dim]Path: {entry['path']}[/dim]")
2768+
2769+
27382770
@preset_app.command("info")
27392771
def preset_info(
27402772
pack_id: str = typer.Argument(..., help="Preset ID to get info about"),
@@ -3281,7 +3313,7 @@ def extension_list(
32813313
console.print(f" [{status_color}]{status_icon}[/{status_color}] [bold]{ext['name']}[/bold] (v{ext['version']})")
32823314
console.print(f" [dim]{ext['id']}[/dim]")
32833315
console.print(f" {ext['description']}")
3284-
console.print(f" Commands: {ext['command_count']} | Hooks: {ext['hook_count']} | Priority: {ext['priority']} | Status: {'Enabled' if ext['enabled'] else 'Disabled'}")
3316+
console.print(f" Commands: {ext['command_count']} | Scripts: {ext['script_count']} | Hooks: {ext['hook_count']} | Priority: {ext['priority']} | Status: {'Enabled' if ext['enabled'] else 'Disabled'}")
32853317
console.print()
32863318

32873319
if available or all_extensions:
@@ -3590,9 +3622,15 @@ def extension_add(
35903622
console.print("\n[green]✓[/green] Extension installed successfully!")
35913623
console.print(f"\n[bold]{manifest.name}[/bold] (v{manifest.version})")
35923624
console.print(f" {manifest.description}")
3593-
console.print("\n[bold cyan]Provided commands:[/bold cyan]")
3594-
for cmd in manifest.commands:
3595-
console.print(f" • {cmd['name']} - {cmd.get('description', '')}")
3625+
if manifest.commands:
3626+
console.print("\n[bold cyan]Provided commands:[/bold cyan]")
3627+
for cmd in manifest.commands:
3628+
console.print(f" • {cmd['name']} - {cmd.get('description', '')}")
3629+
3630+
if manifest.scripts:
3631+
console.print("\n[bold cyan]Provided scripts:[/bold cyan]")
3632+
for script in manifest.scripts:
3633+
console.print(f" • {script['name']} - {script.get('description', '')}")
35963634

35973635
console.print("\n[yellow]⚠[/yellow] Configuration may be required")
35983636
console.print(f" Check: .specify/extensions/{manifest.id}/")
@@ -3890,6 +3928,8 @@ def _print_extension_info(ext_info: dict, manager):
38903928
provides = ext_info['provides']
38913929
if provides.get('commands'):
38923930
console.print(f" • Commands: {provides['commands']}")
3931+
if provides.get('scripts'):
3932+
console.print(f" • Scripts: {provides['scripts']}")
38933933
if provides.get('hooks'):
38943934
console.print(f" • Hooks: {provides['hooks']}")
38953935
console.print()

‎src/specify_cli/extensions.py‎

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -140,11 +140,15 @@ def _validate(self):
140140

141141
# Validate provides section
142142
provides = self.data["provides"]
143-
if "commands" not in provides or not provides["commands"]:
144-
raise ValidationError("Extension must provide at least one command")
143+
has_commands = "commands" in provides and provides["commands"]
144+
has_scripts = "scripts" in provides and provides["scripts"]
145+
if not has_commands and not has_scripts:
146+
raise ValidationError(
147+
"Extension must provide at least one command or script"
148+
)
145149

146150
# Validate commands
147-
for cmd in provides["commands"]:
151+
for cmd in provides.get("commands", []):
148152
if "name" not in cmd or "file" not in cmd:
149153
raise ValidationError("Command missing 'name' or 'file'")
150154

@@ -155,6 +159,27 @@ def _validate(self):
155159
"must follow pattern 'speckit.{extension}.{command}'"
156160
)
157161

162+
# Validate scripts
163+
for script in provides.get("scripts", []):
164+
if "name" not in script or "file" not in script:
165+
raise ValidationError("Script missing 'name' or 'file'")
166+
167+
# Validate script name format
168+
if not re.match(r'^[a-z0-9-]+$', script["name"]):
169+
raise ValidationError(
170+
f"Invalid script name '{script['name']}': "
171+
"must be lowercase alphanumeric with hyphens only"
172+
)
173+
174+
# Validate file path safety: must be relative, no parent traversal
175+
file_path = script["file"]
176+
normalized = os.path.normpath(file_path)
177+
if os.path.isabs(normalized) or normalized.startswith(".."):
178+
raise ValidationError(
179+
f"Invalid script file path '{file_path}': "
180+
"must be a relative path within the extension directory"
181+
)
182+
158183
@property
159184
def id(self) -> str:
160185
"""Get extension ID."""
@@ -183,7 +208,12 @@ def requires_speckit_version(self) -> str:
183208
@property
184209
def commands(self) -> List[Dict[str, Any]]:
185210
"""Get list of provided commands."""
186-
return self.data["provides"]["commands"]
211+
return self.data["provides"].get("commands", [])
212+
213+
@property
214+
def scripts(self) -> List[Dict[str, Any]]:
215+
"""Get list of provided scripts."""
216+
return self.data["provides"].get("scripts", [])
187217

188218
@property
189219
def hooks(self) -> Dict[str, Any]:
@@ -592,6 +622,12 @@ def install_from_directory(
592622
ignore_fn = self._load_extensionignore(source_dir)
593623
shutil.copytree(source_dir, dest_dir, ignore=ignore_fn)
594624

625+
# Set execute permissions on extension scripts
626+
for script in manifest.scripts:
627+
script_path = dest_dir / script["file"]
628+
if script_path.exists() and script_path.suffix == ".sh":
629+
script_path.chmod(script_path.stat().st_mode | 0o755)
630+
595631
# Register commands with AI agents
596632
registered_commands = {}
597633
if register_commands:
@@ -770,6 +806,7 @@ def list_installed(self) -> List[Dict[str, Any]]:
770806
"priority": normalize_priority(metadata.get("priority")),
771807
"installed_at": metadata.get("installed_at"),
772808
"command_count": len(manifest.commands),
809+
"script_count": len(manifest.scripts),
773810
"hook_count": len(manifest.hooks)
774811
})
775812
except ValidationError:
@@ -783,6 +820,7 @@ def list_installed(self) -> List[Dict[str, Any]]:
783820
"priority": normalize_priority(metadata.get("priority")),
784821
"installed_at": metadata.get("installed_at"),
785822
"command_count": 0,
823+
"script_count": 0,
786824
"hook_count": 0
787825
})
788826

@@ -870,6 +908,38 @@ def _render_toml_command(self, frontmatter, body, ext_id):
870908
context_lines = f"# Extension: {ext_id}\n# Config: .specify/extensions/{ext_id}/\n"
871909
return base.rstrip("\n") + "\n" + context_lines
872910

911+
@staticmethod
912+
def _filter_commands_for_installed_extensions(
913+
commands: List[Dict[str, Any]],
914+
project_root: Path,
915+
) -> List[Dict[str, Any]]:
916+
"""Filter out commands targeting extensions that are not installed.
917+
918+
Command names follow the pattern: speckit.<ext-id>.<cmd-name>
919+
Core commands (e.g. speckit.specify) have only two parts — always kept.
920+
Extension-specific commands are only kept if the target extension
921+
directory exists under .specify/extensions/.
922+
923+
If the extensions directory does not exist, no filtering is applied.
924+
925+
Note: This method is not applied during extension self-registration
926+
(all commands in an extension's own manifest are always registered).
927+
It is designed for cross-boundary filtering, e.g. when presets provide
928+
commands for extensions that may not be installed.
929+
"""
930+
extensions_dir = project_root / ".specify" / "extensions"
931+
if not extensions_dir.is_dir():
932+
return commands
933+
filtered = []
934+
for cmd in commands:
935+
parts = cmd["name"].split(".")
936+
if len(parts) >= 3 and parts[0] == "speckit":
937+
ext_id = parts[1]
938+
if not (extensions_dir / ext_id).is_dir():
939+
continue
940+
filtered.append(cmd)
941+
return filtered
942+
873943
def register_commands_for_agent(
874944
self,
875945
agent_name: str,

‎src/specify_cli/presets.py‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1714,3 +1714,94 @@ def resolve_with_source(
17141714
continue
17151715

17161716
return {"path": resolved_str, "source": "core"}
1717+
1718+
def list_available(
1719+
self,
1720+
template_type: str = "template",
1721+
) -> List[Dict[str, str]]:
1722+
"""List all available templates of a given type with source attribution.
1723+
1724+
Walks the full priority stack and collects all discoverable templates.
1725+
For templates that exist in multiple sources, only the winning (highest
1726+
priority) source is included.
1727+
1728+
Args:
1729+
template_type: Template type ("template", "command", or "script")
1730+
1731+
Returns:
1732+
List of dicts with 'name', 'path', and 'source' keys, sorted by name.
1733+
"""
1734+
seen: set[str] = set()
1735+
results: List[Dict[str, str]] = []
1736+
1737+
# Determine file extension and subdirectory mapping
1738+
ext = ".sh" if template_type == "script" else ".md"
1739+
if template_type == "template":
1740+
subdirs = ["templates", ""]
1741+
elif template_type == "command":
1742+
subdirs = ["commands"]
1743+
elif template_type == "script":
1744+
subdirs = ["scripts"]
1745+
else:
1746+
subdirs = [""]
1747+
1748+
def _collect(directory: Path, source: str):
1749+
"""Collect template files from a directory."""
1750+
if not directory.is_dir():
1751+
return
1752+
for f in sorted(directory.iterdir()):
1753+
if f.is_file() and f.suffix == ext:
1754+
name = f.stem
1755+
if name not in seen:
1756+
seen.add(name)
1757+
results.append({
1758+
"name": name,
1759+
"path": str(f),
1760+
"source": source,
1761+
})
1762+
1763+
# Priority 1: Project-local overrides
1764+
if template_type == "script":
1765+
_collect(self.overrides_dir / "scripts", "project override")
1766+
else:
1767+
_collect(self.overrides_dir, "project override")
1768+
1769+
# Priority 2: Installed presets (sorted by priority)
1770+
if self.presets_dir.exists():
1771+
registry = PresetRegistry(self.presets_dir)
1772+
for pack_id, metadata in registry.list_by_priority():
1773+
pack_dir = self.presets_dir / pack_id
1774+
version = metadata.get("version", "?") if metadata else "?"
1775+
source_label = f"{pack_id} v{version}"
1776+
for subdir in subdirs:
1777+
if subdir:
1778+
_collect(pack_dir / subdir, source_label)
1779+
else:
1780+
_collect(pack_dir, source_label)
1781+
1782+
# Priority 3: Extension-provided templates (sorted by priority)
1783+
for _priority, ext_id, ext_meta in self._get_all_extensions_by_priority():
1784+
ext_dir = self.extensions_dir / ext_id
1785+
if not ext_dir.is_dir():
1786+
continue
1787+
if ext_meta:
1788+
version = ext_meta.get("version", "?")
1789+
source_label = f"extension:{ext_id} v{version}"
1790+
else:
1791+
source_label = f"extension:{ext_id} (unregistered)"
1792+
for subdir in subdirs:
1793+
if subdir:
1794+
_collect(ext_dir / subdir, source_label)
1795+
else:
1796+
_collect(ext_dir, source_label)
1797+
1798+
# Priority 4: Core templates
1799+
if template_type == "template":
1800+
_collect(self.templates_dir, "core")
1801+
elif template_type == "command":
1802+
_collect(self.templates_dir / "commands", "core")
1803+
elif template_type == "script":
1804+
_collect(self.templates_dir / "scripts", "core")
1805+
1806+
results.sort(key=lambda x: x["name"])
1807+
return results

0 commit comments

Comments
 (0)