Skip to content

πŸ’« Toolkit to help you get started with SDD or any other process!

feat: add JSON output to preset and extension lists (#4218)

WOLIKIMCHENG8b5ea9019696
diff --git a/docs/reference/extensions.md b/docs/reference/extensions.md
index 0473e7200..22357ccea 100644
--- a/docs/reference/extensions.md
+++ b/docs/reference/extensions.md
@@ -50,15 +50,31 @@ Removes an installed extension. Configuration files are backed up by default; us
```bash
specify extension list
+specify extension list --json
```
| Option | Description |
| ------------- | -------------------------------------------------- |
| `--available` | Show available (uninstalled) extensions |
| `--all` | Show both installed and available extensions |
+| `--json` | Write installed extensions as JSON |
Lists installed extensions with their status, version, and command counts.
+`--json` writes a JSON array to stdout. Every item has the keys `id`, `name`,
+`description`, `version`, `author`, `priority`, `enabled`, `source`, and
+`provides`. `author` is `null` when absent; `source` is `{"kind":"local"}`
+for local, legacy, or malformed provenance, or
+`{"kind":"catalog","catalog":"<catalog-name>"}` for a valid catalog source.
+Extension `provides` contains `commands`, `templates`, `scripts`, and `hooks`
+counts. `--available` and `--all` do not broaden JSON output beyond installed
+extensions. On success, `--json` writes exactly one array to stdout and exits
+0. A runtime failure after option parsing writes exactly one
+`{"error":"..."}` object to stderr and exits 1. If parsing raises a usage
+error and the raw `--json` token is present, it writes that JSON error object
+to stderr and preserves the usage exit code (normally 2). Without `--json`,
+including for help, the existing human-readable behavior is unchanged.
+
## Extension Info
```bash
diff --git a/docs/reference/presets.md b/docs/reference/presets.md
index 1098abfb4..0723200d6 100644
--- a/docs/reference/presets.md
+++ b/docs/reference/presets.md
@@ -43,10 +43,24 @@ Removes an installed preset and cleans up its registered commands.
```bash
specify preset list
+specify preset list --json
```
Lists installed presets with their versions, descriptions, template counts, and current status.
+`--json` writes a JSON array to stdout. Every item has the keys `id`, `name`,
+`description`, `version`, `author`, `priority`, `enabled`, `source`, and
+`provides`. `author` is `null` when absent; `source` is `{"kind":"local"}`
+for local, legacy, or malformed provenance, or
+`{"kind":"catalog","catalog":"<catalog-name>"}` for a valid catalog source.
+Preset `provides` contains `commands`, `templates`, and `scripts` counts. On
+success, `--json` writes exactly one array to stdout and exits 0. A runtime
+failure after option parsing writes exactly one `{"error":"..."}` object to
+stderr and exits 1. If parsing raises a usage error and the raw `--json` token
+is present, it writes that JSON error object to stderr and preserves the usage
+exit code (normally 2). Without `--json`, including for help, the existing
+human-readable behavior is unchanged.
+
Presets are printed in **resolution/precedence order**: the highest-precedence preset (lowest priority number) is listed first, and ties on priority are broken alphabetically by preset id. This matches the order used when composing commands and resolving templates, so the top entry is the one that wins for overlapping files.
## Preset Info
diff --git a/src/specify_cli/_installed_list_json.py b/src/specify_cli/_installed_list_json.py
new file mode 100644
index 000000000..da671b293
--- /dev/null
+++ b/src/specify_cli/_installed_list_json.py
@@ -0,0 +1,84 @@
+"""Private JSON output helpers for installed preset and extension lists.
+
+This module intentionally serves only the two installed-list commands. Their
+human-facing renderers retain the legacy manager records, while this adapter
+defines the public machine-readable wire contract.
+"""
+from __future__ import annotations
+
+import json
+from typing import Any, NoReturn
+
+import typer
+from typer.core import TyperCommand
+
+try:
+ from typer._click.exceptions import UsageError as _UsageError
+except ModuleNotFoundError as error:
+ if error.name != "typer._click":
+ raise
+ from click import UsageError as _UsageError
+
+
+class InstalledListJSONCommand(TyperCommand):
+ """Keep JSON list parse failures on the JSON error contract."""
+
+ def make_context(self, info_name, args, parent=None, **extra):
+ json_output = "--json" in args
+ try:
+ return super().make_context(info_name, args, parent=parent, **extra)
+ except _UsageError as error:
+ if json_output:
+ emit_json_error(error, exit_code=error.exit_code)
+ raise
+
+
+def _normalized_source(source: Any) -> dict[str, str]:
+ """Return the stable public source shape for an installed record."""
+ if not isinstance(source, dict):
+ return {"kind": "local"}
+
+ kind = source.get("kind")
+ if kind == "local":
+ return {"kind": "local"}
+ if kind == "catalog":
+ catalog = source.get("catalog")
+ if isinstance(catalog, str) and catalog.strip():
+ return {"kind": "catalog", "catalog": catalog}
+
+ return {"kind": "local"}
+
+
+def installed_list_item(record: dict[str, Any], *, include_hooks: bool) -> dict[str, Any]:
+ """Return the canonical public JSON object for one installed record."""
+ provides = record["_json_provides"]
+ if not include_hooks:
+ provides = {
+ "commands": provides["commands"],
+ "templates": provides["templates"],
+ "scripts": provides["scripts"],
+ }
+
+ return {
+ "id": record["id"],
+ "name": record["name"],
+ "description": record["description"],
+ "version": record["version"],
+ "author": record["_json_author"],
+ "priority": record["priority"],
+ "enabled": record["enabled"],
+ "source": _normalized_source(record["_json_source"]),
+ "provides": provides,
+ }
+
+
+def emit_json(value: Any) -> None:
+ """Write one JSON value to stdout without Rich rendering."""
+ typer.echo(json.dumps(value, ensure_ascii=False))
+
+
+def emit_json_error(error: Exception, exit_code: int = 1) -> NoReturn:
+ """Write the list-command error contract and terminate unsuccessfully."""
+ message = str(error).strip() or error.__class__.__name__
+ typer.echo(json.dumps({"error": message}, ensure_ascii=False), err=True)
+ raise typer.Exit(code=exit_code)
diff --git a/src/specify_cli/_project.py b/src/specify_cli/_project.py
index 1a583809b..9ed2fe150 100644
--- a/src/specify_cli/_project.py
+++ b/src/specify_cli/_project.py
@@ -10,6 +10,28 @@ import typer
from ._console import err_console
+class ProjectResolutionError(RuntimeError):
+ """A project-root error that callers can render for their own surface."""
+
+
+def _resolve_init_dir_override_unrendered() -> Path | None:
+ """Resolve ``SPECIFY_INIT_DIR`` without emitting user-facing output."""
+ raw = os.environ.get("SPECIFY_INIT_DIR", "")
+ if not raw:
+ return None
+ init_root = (Path.cwd() / raw).resolve()
+ if not init_root.is_dir():
+ raise ProjectResolutionError(
+ f"SPECIFY_INIT_DIR does not point to an existing directory: {raw}"
+ )
+ if not (init_root / ".specify").is_dir():
+ raise ProjectResolutionError(
+ "SPECIFY_INIT_DIR is not a Spec Kit project "
+ f"(no .specify/ directory): {init_root}"
+ )
+ return init_root
+
+
def _resolve_init_dir_override() -> Path | None:
"""Resolve the ``SPECIFY_INIT_DIR`` project override for the Python CLI.
@@ -33,21 +55,24 @@ def _resolve_init_dir_override() -> Path | None:
here (a stable project identity), so this is a deliberate, documented variance,
not a parity guarantee on the resolved string.
"""
- raw = os.environ.get("SPECIFY_INIT_DIR", "")
- if not raw:
- return None
- # Relative values resolve against cwd; an absolute value stands alone (Path's
- # `/` drops the left operand when the right is absolute). resolve() also
- # collapses a trailing slash and canonicalizes symlinks.
- init_root = (Path.cwd() / raw).resolve()
- if not init_root.is_dir():
- err_console.print(
- f"[red]Error:[/red] SPECIFY_INIT_DIR does not point to an existing directory: {raw}"
- )
+ try:
+ return _resolve_init_dir_override_unrendered()
+ except ProjectResolutionError as error:
+ err_console.print(f"[red]Error:[/red] {error}")
raise typer.Exit(1)
- if not (init_root / ".specify").is_dir():
- err_console.print(
- f"[red]Error:[/red] SPECIFY_INIT_DIR is not a Spec Kit project (no .specify/ directory): {init_root}"
- )
- raise typer.Exit(1)
- return init_root
+
+
+def resolve_specify_project_root() -> Path:
+ """Return the active project root without rendering errors.
+
+ This is deliberately separate from ``_require_specify_project`` so the
+ installed-list JSON contract can send structured failures to stderr without
+ changing the Rich diagnostics used by every other project-scoped command.
+ """
+ override = _resolve_init_dir_override_unrendered()
+ if override is not None:
+ return override
+ project_root = Path.cwd()
+ if not (project_root / ".specify").is_dir():
+ raise ProjectResolutionError("Not a Spec Kit project (no .specify/ directory)")
+ return project_root
diff --git a/src/specify_cli/bundler/services/primitives.py b/src/specify_cli/bundler/services/primitives.py
index 68a9c4763..6c1b23897 100644
--- a/src/specify_cli/bundler/services/primitives.py
+++ b/src/specify_cli/bundler/services/primitives.py
@@ -209,7 +209,11 @@ class _PresetKindManager:
zip_path = catalog.download_pack(component.id)
try:
self._manager.install_from_zip(
- zip_path, speckit_version, priority, **({"force": True} if force else {})
+ zip_path,
+ speckit_version,
+ priority,
+ catalog_name=info.get("_catalog_name"),
+ **({"force": True} if force else {}),
)
finally:
with contextlib.suppress(Exception):
@@ -295,7 +299,11 @@ class _ExtensionKindManager:
zip_path = catalog.download_extension(component.id)
try:
manifest = self._manager.install_from_zip(
- zip_path, speckit_version, priority=priority, force=force
+ zip_path,
+ speckit_version,
+ priority=priority,
+ force=force,
+ catalog_name=info.get("_catalog_name"),
)
self._manager.scaffold_config(manifest.id)
finally:
diff --git a/src/specify_cli/commands/init.py b/src/specify_cli/commands/init.py
index dfce1b3d1..9cdd86d1d 100644
--- a/src/specify_cli/commands/init.py
+++ b/src/specify_cli/commands/init.py
@@ -179,7 +179,11 @@ def _install_extension_during_init(project_path: Path, ext_spec: str, speckit_ve
zip_path = catalog.download_extension(resolved_id)
try:
- manifest = manager.install_from_zip(zip_path, speckit_version)
+ manifest = manager.install_from_zip(
+ zip_path,
+ speckit_version,
+ catalog_name=ext_info.get("_catalog_name"),
+ )
finally:
zip_path.unlink(missing_ok=True)
return f"{manifest.name} v{manifest.version} installed"
@@ -862,7 +866,9 @@ def register(app: typer.Typer) -> None:
try:
zip_path = preset_catalog.download_pack(preset)
preset_manager.install_from_zip(
- zip_path, speckit_ver
+ zip_path,
+ speckit_ver,
+ catalog_name=pack_info.get("_catalog_name"),
)
except PresetError as preset_err:
_print_cli_warning(
diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py
index cb78f0ea8..c20160c16 100644
--- a/src/specify_cli/extensions/__init__.py
+++ b/src/specify_cli/extensions/__init__.py
@@ -2053,6 +2053,8 @@ class ExtensionManager:
priority: int = 10,
link_commands: bool = False,
force: bool = False,
+ *,
+ catalog_name: str | None = None,
) -> ExtensionManifest:
"""Install extension from a local directory.
@@ -2613,11 +2615,19 @@ class ExtensionManager:
backup_config_dir.unlink()
# Update registry
+ normalized_catalog_name = (
+ catalog_name.strip() if isinstance(catalog_name, str) else ""
+ )
+ source = (
+ {"kind": "catalog", "catalog": normalized_catalog_name}
+ if normalized_catalog_name
+ else "local"
+ )
self.registry.add(
manifest.id,
{
"version": manifest.version,
- "source": "local",
+ "source": source,
"manifest_hash": manifest.get_hash(),
"enabled": True,
"priority": priority,
@@ -2674,6 +2684,7 @@ class ExtensionManager:
archive_file: BinaryIO | None = None,
source_name: str | None = None,
content_type: str | None = None,
+ catalog_name: str | None = None,
) -> ExtensionManifest:
"""Install an extension from a supported archive.
@@ -2725,7 +2736,11 @@ class ExtensionManager:
# Install from extracted directory
return self.install_from_directory(
- extension_dir, speckit_version, priority=priority, force=force
+ extension_dir,
+ speckit_version,
+ priority=priority,
+ force=force,
+ catalog_name=catalog_name,
)
def _config_root_is_contained(self, specify_dir: Path) -> bool:
@@ -2881,6 +2896,7 @@ class ExtensionManager:
archive_file: BinaryIO | None = None,
source_name: str | None = None,
content_type: str | None = None,
+ catalog_name: str | None = None,
) -> ExtensionManifest:
"""Backward-compatible wrapper for archive installation."""
return self.install_from_archive(
@@ -2891,6 +2907,7 @@ class ExtensionManager:
archive_file=archive_file,
source_name=source_name,
content_type=content_type,
+ catalog_name=catalog_name,
)
def remove(self, extension_id: str, keep_config: bool = False) -> bool:
@@ -3491,6 +3508,8 @@ class ExtensionManager:
try:
manifest = ExtensionManifest(manifest_path)
+ author = manifest.data["extension"].get("author")
+ hook_count = len(manifest.hooks)
result.append(
{
"id": ext_id,
@@ -3501,7 +3520,15 @@ class ExtensionManager:
"priority": normalize_priority(metadata.get("priority")),
"installed_at": metadata.get("installed_at"),
"command_count": len(manifest.commands),
- "hook_count": len(manifest.hooks),
+ "hook_count": hook_count,
+ "_json_author": author if isinstance(author, str) and author else None,
+ "_json_source": metadata.get("source"),
+ "_json_provides": {
+ "commands": len(manifest.commands),
+ "templates": len(manifest.templates),
+ "scripts": len(manifest.scripts),
+ "hooks": hook_count,
+ },
}
)
except ValidationError:
@@ -3517,6 +3544,9 @@ class ExtensionManager:
"installed_at": metadata.get("installed_at"),
"command_count": 0,
"hook_count": 0,
+ "_json_author": None,
+ "_json_source": metadata.get("source"),
+ "_json_provides": {"commands": 0, "templates": 0, "scripts": 0, "hooks": 0},
}
)
diff --git a/src/specify_cli/extensions/_commands.py b/src/specify_cli/extensions/_commands.py
index 11ab50385..454482d05 100644
--- a/src/specify_cli/extensions/_commands.py
+++ b/src/specify_cli/extensions/_commands.py
@@ -28,6 +28,13 @@ from rich.panel import Panel
from rich.table import Table
from .._console import console
+from .._installed_list_json import (
+ InstalledListJSONCommand,
+ emit_json,
+ emit_json_error,
+ installed_list_item,
+)
+from .._project import resolve_specify_project_root
from .._assets import get_speckit_version
from .._download_security import (
archive_format_from_name,
@@ -470,13 +477,33 @@ def _resolve_catalog_extension(
return (None, e)
-@extension_app.command("list")
+@extension_app.command("list", cls=InstalledListJSONCommand)
def extension_list(
available: bool = typer.Option(False, "--available", help="Show available extensions from catalog"),
all_extensions: bool = typer.Option(False, "--all", help="Show both installed and available"),
+ json_output: bool = typer.Option(False, "--json", help="Output installed extensions as JSON"),
):
"""List installed extensions."""
- from . import ExtensionManager
+ from . import ExtensionManager, normalize_priority
+
+ if json_output:
+ try:
+ project_root = resolve_specify_project_root()
+ manager = ExtensionManager(project_root)
+ installed = manager.list_installed()
+ installed = sorted(
+ installed,
+ key=lambda extension: (
+ normalize_priority(extension.get("priority")),
+ str(extension.get("id", "")),
+ ),
+ )
+ emit_json(
+ [installed_list_item(ext, include_hooks=True) for ext in installed]
+ )
+ return
+ except Exception as error:
+ emit_json_error(error)
project_root = _require_specify_project()
manager = ExtensionManager(project_root)
@@ -1142,6 +1169,7 @@ def extension_add(
speckit_version,
priority=priority,
force=force,
+ catalog_name=ext_info.get("_catalog_name"),
)
finally:
archive_path.unlink(missing_ok=True)
@@ -1748,6 +1776,7 @@ def extension_update(
"available": str(available_version),
"download_url": download_url,
"bundled_dir": bundled_dir,
+ "catalog_name": ext_info.get("_catalog_name"),
}
)
else:
@@ -2360,7 +2389,11 @@ def extension_update(
manager.remove(extension_id, keep_config=True)
# 8. Install new version
- _ = manager.install_from_zip(archive_path, speckit_version)
+ _ = manager.install_from_zip(
+ archive_path,
+ speckit_version,
+ catalog_name=update["catalog_name"],
+ )
# Restore user config files from backup after successful install.
new_extension_dir = manager.extensions_dir / extension_id
diff --git a/src/specify_cli/presets/__init__.py b/src/specify_cli/presets/__init__.py
index 2c6470be5..b22a44066 100644
--- a/src/specify_cli/presets/__init__.py
+++ b/src/specify_cli/presets/__init__.py
@@ -3836,6 +3836,8 @@ class PresetManager:
speckit_version: str,
priority: int = 10,
force: bool = False,
+ *,
+ catalog_name: str | None = None,
) -> PresetManifest:
"""Install preset from a local directory.
@@ -3877,9 +3879,17 @@ class PresetManager:
# Pre-register the preset so that composition resolution can see it
# in the priority stack when resolving composed command content.
+ normalized_catalog_name = (
+ catalog_name.strip() if isinstance(catalog_name, str) else ""
+ )
+ source = (
+ {"kind": "catalog", "catalog": normalized_catalog_name}
+ if normalized_catalog_name
+ else "local"
+ )
self.registry.add(manifest.id, {
"version": manifest.version,
- "source": "local",
+ "source": source,
"manifest_hash": manifest.get_hash(),
"enabled": True,
"priority": priority,
@@ -4018,6 +4028,8 @@ class PresetManager:
speckit_version: str,
priority: int = 10,
force: bool = False,
+ *,
+ catalog_name: str | None = None,
) -> PresetManifest:
"""Install a preset from a supported archive.
@@ -4061,7 +4073,13 @@ class PresetManager:
"No preset.yml found in archive"
)
- return self.install_from_directory(pack_dir, speckit_version, priority, force=force)
+ return self.install_from_directory(
+ pack_dir,
+ speckit_version,
+ priority,
+ force=force,
+ catalog_name=catalog_name,
+ )
def install_from_zip(
self,
@@ -4069,6 +4087,8 @@ class PresetManager:
speckit_version: str,
priority: int = 10,
force: bool = False,
+ *,
+ catalog_name: str | None = None,
) -> PresetManifest:
"""Backward-compatible wrapper for archive installation."""
return self.install_from_archive(
@@ -4076,6 +4096,7 @@ class PresetManager:
speckit_version,
priority,
force=force,
+ catalog_name=catalog_name,
)
def remove(self, pack_id: str) -> bool:
@@ -4362,6 +4383,10 @@ class PresetManager:
try:
manifest = PresetManifest(manifest_path)
+ provided_counts = {"commands": 0, "templates": 0, "scripts": 0, "hooks": 0}
+ for template in manifest.templates:
+ provided_counts[f"{template['type']}s"] += 1
+ author = manifest.author
result.append({
"id": pack_id,
"name": manifest.name,
@@ -4372,6 +4397,9 @@ class PresetManager:
"template_count": len(manifest.templates),
"tags": manifest.tags,
"priority": normalize_priority(metadata.get("priority")),
+ "_json_author": author if isinstance(author, str) and author else None,
+ "_json_source": metadata.get("source"),
+ "_json_provides": provided_counts,
})
except PresetValidationError:
result.append({
@@ -4384,6 +4412,9 @@ class PresetManager:
"template_count": 0,
"tags": [],
"priority": normalize_priority(metadata.get("priority")),
+ "_json_author": None,
+ "_json_source": metadata.get("source"),
+ "_json_provides": {"commands": 0, "templates": 0, "scripts": 0, "hooks": 0},
})
return result
@@ -4648,9 +4679,14 @@ class PresetCatalog:
install_allowed = raw_install.strip().lower() in ("true", "yes", "1")
else:
install_allowed = bool(raw_install)
+ raw_name = item.get("name")
+ name = str(raw_name).strip() if raw_name is not None else ""
+ if not name:
+ name = f"catalog-{len(entries) + 1}"
+
entries.append(PresetCatalogEntry(
url=url,
- name=str(item.get("name", f"catalog-{idx + 1}")),
+ name=name,
priority=priority,
install_allowed=install_allowed,
description=str(item.get("description", "")),
diff --git a/src/specify_cli/presets/_commands.py b/src/specify_cli/presets/_commands.py
index ab74a8e02..c5dbf0ddc 100644
--- a/src/specify_cli/presets/_commands.py
+++ b/src/specify_cli/presets/_commands.py
@@ -17,6 +17,13 @@ import yaml
from rich.markup import escape as _escape_markup
from .._console import console
+from .._installed_list_json import (
+ InstalledListJSONCommand,
+ emit_json,
+ emit_json_error,
+ installed_list_item,
+)
+from .._project import resolve_specify_project_root
from .._download_security import (
archive_format_from_name,
archive_suffix,
@@ -149,12 +156,30 @@ def _warn_unmet_extension_dependencies(manager, manifest) -> None:
# ===== Preset Commands =====
-@preset_app.command("list")
-def preset_list():
+@preset_app.command("list", cls=InstalledListJSONCommand)
+def preset_list(
+ json_output: bool = typer.Option(False, "--json", help="Output installed presets as JSON"),
+):
"""List installed presets."""
from .. import _require_specify_project
from . import PresetManager
+ if json_output:
+ try:
+ project_root = resolve_specify_project_root()
+ manager = PresetManager(project_root)
+ installed = manager.list_installed()
+ installed = sorted(
+ installed,
+ key=lambda pack: (pack.get("priority", 10), str(pack.get("id", ""))),
+ )
+ emit_json(
+ [installed_list_item(pack, include_hooks=False) for pack in installed]
+ )
+ return
+ except Exception as error:
+ emit_json_error(error)
+
project_root = _require_specify_project()
manager = PresetManager(project_root)
installed = manager.list_installed()
@@ -380,6 +405,7 @@ def preset_add(
archive_path,
speckit_version,
priority,
+ catalog_name=pack_info.get("_catalog_name"),
)
console.print(f"[green]βœ“[/green] Preset '{manifest.name}' v{manifest.version} installed (priority {priority})")
finally:
diff --git a/tests/integrations/test_cli.py b/tests/integrations/test_cli.py
index 640d12a5f..2beb411a2 100644
--- a/tests/integrations/test_cli.py
+++ b/tests/integrations/test_cli.py
@@ -2710,6 +2710,82 @@ class TestExtensionFlag:
normalized = _normalize_cli_output(result.output)
assert "Install extension: git" in normalized
+ def test_catalog_extension_init_forwards_catalog_name(self, tmp_path, monkeypatch):
+ """The init catalog branch keeps the catalog provenance at install time."""
+ from types import SimpleNamespace
+
+ import specify_cli._assets as assets
+ import specify_cli.commands.init as init_module
+ from specify_cli.extensions import ExtensionCatalog, ExtensionManager
+
+ project = tmp_path / "project"
+ project.mkdir()
+ archive = tmp_path / "extension.zip"
+ archive.write_bytes(b"archive")
+ captured = {}
+
+ monkeypatch.setattr(assets, "_locate_bundled_extension", lambda _id: None)
+ monkeypatch.setattr(
+ ExtensionCatalog,
+ "get_extension_info",
+ lambda _self, _id: {
+ "id": "catalog-extension",
+ "_install_allowed": True,
+ "_catalog_name": "init-catalog",
+ },
+ )
+ monkeypatch.setattr(
+ ExtensionCatalog,
+ "download_extension",
+ lambda _self, _id: archive,
+ )
+
+ def fake_install_from_zip(self, _archive, _version, *, catalog_name=None):
+ captured["catalog_name"] = catalog_name
+ return SimpleNamespace(name="Catalog Extension", version="1.0.0")
+
+ monkeypatch.setattr(ExtensionManager, "install_from_zip", fake_install_from_zip)
+
+ result = init_module._install_extension_during_init(
+ project, "catalog-extension", "1.0.0"
+ )
+
+ assert result == "Catalog Extension v1.0.0 installed"
+ assert captured == {"catalog_name": "init-catalog"}
+
+ def test_catalog_preset_init_forwards_catalog_name(self, tmp_path, monkeypatch):
+ """The init preset catalog branch keeps resolved provenance."""
+ import specify_cli._assets as assets
+ from specify_cli.presets import PresetCatalog, PresetManager
+
+ captured = {}
+
+ monkeypatch.setattr(assets, "_locate_bundled_preset", lambda _id: None)
+ monkeypatch.setattr(
+ PresetCatalog,
+ "get_pack_info",
+ lambda _self, _id: {
+ "_install_allowed": True,
+ "_catalog_name": "init-preset-catalog",
+ },
+ )
+ archive = tmp_path / "preset.zip"
+ archive.write_bytes(b"archive")
+ monkeypatch.setattr(PresetCatalog, "download_pack", lambda _self, _id: archive)
+
+ def fake_install_from_zip(self, _archive, _version, *, catalog_name=None):
+ captured["catalog_name"] = catalog_name
+
+ monkeypatch.setattr(PresetManager, "install_from_zip", fake_install_from_zip)
+ _project, result = self._run_init(
+ tmp_path,
+ ["--preset", "catalog-preset"],
+ project_name="preset-catalog",
+ )
+
+ assert result.exit_code == 0, result.output
+ assert captured == {"catalog_name": "init-preset-catalog"}
+
def test_multiple_extensions_installed(self, tmp_path):
"""--extension can be specified multiple times."""
project, result = self._run_init(
diff --git a/tests/test_extensions.py b/tests/test_extensions.py
index b38554cb3..e7ded4560 100644
--- a/tests/test_extensions.py
+++ b/tests/test_extensions.py
@@ -2818,11 +2818,15 @@ class TestExtensionManager:
# Force-reinstall from ZIP
manifest = manager.install_from_zip(
- zip_path, "0.1.0", force=True
+ zip_path, "0.1.0", force=True, catalog_name="extension-catalog"
)
assert manifest.id == "test-ext"
assert manager.registry.is_installed("test-ext")
+ assert manager.registry.get("test-ext")["source"] == {
+ "kind": "catalog",
+ "catalog": "extension-catalog",
+ }
ext_dir = project_dir / ".specify" / "extensions" / "test-ext"
assert ext_dir.exists()
@@ -2893,10 +2897,16 @@ class TestExtensionManager:
archive.add(file_path, arcname=arcname)
manager = ExtensionManager(project_dir)
- manifest = manager.install_from_archive(archive_path, "0.1.0")
+ manifest = manager.install_from_archive(
+ archive_path, "0.1.0", catalog_name="extension-catalog"
+ )
assert manifest.id == "test-ext"
assert manager.registry.is_installed("test-ext")
+ assert manager.registry.get("test-ext")["source"] == {
+ "kind": "catalog",
+ "catalog": "extension-catalog",
+ }
def test_install_from_tar_rejects_symlink_entry(
self, extension_dir, project_dir, temp_dir
@@ -7910,6 +7920,46 @@ class TestExtensionAddCLI:
f"but was called with '{download_called_with[0]}'"
)
+ def test_catalog_add_forwards_catalog_name(self, tmp_path):
+ """The extension catalog branch passes resolved provenance to the manager."""
+ from types import SimpleNamespace
+ from typer.testing import CliRunner
+ from unittest.mock import patch
+ from specify_cli import app
+
+ project_dir = tmp_path / "project"
+ (project_dir / ".specify").mkdir(parents=True)
+ archive = tmp_path / "extension.zip"
+ archive.write_bytes(b"archive")
+ captured = {}
+
+ def fake_install_from_zip(self, _archive, _version, **kwargs):
+ captured.update(kwargs)
+ return SimpleNamespace(
+ id="catalog-extension",
+ name="Catalog Extension",
+ version="1.0.0",
+ description="catalog extension",
+ warnings=[],
+ commands=[],
+ )
+
+ with patch.object(Path, "cwd", return_value=project_dir), \
+ patch.object(ExtensionCatalog, "get_extension_info", return_value={
+ "id": "catalog-extension",
+ "name": "Catalog Extension",
+ "version": "1.0.0",
+ "_install_allowed": True,
+ "_catalog_name": "extension-catalog",
+ }), \
+ patch.object(ExtensionCatalog, "download_extension", return_value=archive), \
+ patch.object(ExtensionManager, "install_from_zip", fake_install_from_zip), \
+ patch("specify_cli.extensions._commands._refresh_events_and_warn"):
+ result = CliRunner().invoke(app, ["extension", "add", "catalog-extension"])
+
+ assert result.exit_code == 0, result.output
+ assert captured["catalog_name"] == "extension-catalog"
+
def test_add_discovery_only_error_suggests_resolved_id(self, tmp_path):
"""The not-installable error must suggest a copy-pasteable command using
the resolved catalog ID, not a display name that may contain spaces."""
@@ -8931,7 +8981,9 @@ class TestExtensionUpdateCLI:
manager = ExtensionManager(project_dir)
v1_dir = self._create_extension_source(tmp_path, "1.0.0")
- manager.install_from_directory(v1_dir, "0.1.0")
+ manager.install_from_directory(
+ v1_dir, "0.1.0", catalog_name="previous-catalog"
+ )
installed_extension_dir = manager.extensions_dir / "test-ext"
removed_paths = []
real_rmtree = shutil.rmtree
@@ -9167,15 +9219,20 @@ class TestExtensionUpdateCLI:
)
v2_dir = self._create_extension_source(tmp_path, "2.0.0")
- def fake_install_from_zip(self_obj, _zip_path, speckit_version):
- return self_obj.install_from_directory(v2_dir, speckit_version)
+ def fake_install_from_zip(
+ self_obj, _zip_path, speckit_version, *, catalog_name=None
+ ):
+ return self_obj.install_from_directory(
+ v2_dir, speckit_version, catalog_name=catalog_name
+ )
with patch.object(Path, "cwd", return_value=project_dir), \
patch.object(ExtensionCatalog, "get_extension_info", return_value={
"id": "test-ext",
- "name": "Test Extension",
- "version": "2.0.0",
- "_install_allowed": True,
+ "name": "Test Extension",
+ "version": "2.0.0",
+ "_install_allowed": True,
+ "_catalog_name": "updated-catalog",
}), \
patch.object(ExtensionCatalog, "download_extension", return_value=zip_path), \
patch.object(ExtensionManager, "install_from_zip", fake_install_from_zip):
@@ -9186,6 +9243,10 @@ class TestExtensionUpdateCLI:
updated = ExtensionManager(project_dir).registry.get("test-ext")
assert updated["version"] == "2.0.0"
assert updated["installed_at"] == original_installed_at
+ assert updated["source"] == {
+ "kind": "catalog",
+ "catalog": "updated-catalog",
+ }
restored_config_content = (
project_dir / ".specify" / "extensions" / "test-ext" / "linear-config.yml"
).read_text()
@@ -9419,7 +9480,9 @@ class TestExtensionUpdateCLI:
manager = ExtensionManager(project_dir)
v1_dir = self._create_extension_source(tmp_path, "1.0.0")
- manager.install_from_directory(v1_dir, "0.1.0")
+ manager.install_from_directory(
+ v1_dir, "0.1.0", catalog_name="original-catalog"
+ )
backup_registry_entry = manager.registry.get("test-ext")
hooks_before = yaml.safe_load((project_dir / ".specify" / "extensions.yml").read_text())
diff --git a/tests/test_installed_list_json.py b/tests/test_installed_list_json.py
new file mode 100644
index 000000000..b0dcee84a
--- /dev/null
+++ b/tests/test_installed_list_json.py
@@ -0,0 +1,480 @@
+"""Public JSON contracts for installed preset and extension lists."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from typer.testing import CliRunner
+
+from specify_cli import app
+from specify_cli._installed_list_json import _normalized_source
+from specify_cli.extensions import ExtensionManager
+from specify_cli.presets import PresetManager
+from tests.conftest import strip_ansi
+
+
+runner = CliRunner()
+
+
+def _project(tmp_path):
+ project = tmp_path / "project"
+ (project / ".specify").mkdir(parents=True)
+ return project
+
+
+def _preset(project, preset_id, *, author="Preset Author"):
+ preset_dir = project / ".specify" / "presets" / preset_id
+ preset_dir.mkdir(parents=True)
+ author_line = f' author: "{author}"\n' if author is not None else ""
+ (preset_dir / "preset.yml").write_text(
+ "schema_version: \"1.0\"\n"
+ "preset:\n"
+ f" id: {preset_id}\n"
+ f" name: {preset_id} name\n"
+ " version: \"1.0.0\"\n"
+ " description: preset description\n"
+ f"{author_line}"
+ "requires:\n"
+ " speckit_version: \">=0.1.0\"\n"
+ "provides:\n"
+ " templates:\n"
+ " - type: template\n"
+ " name: base-template\n"
+ " file: templates/base.md\n"
+ " - type: command\n"
+ " name: speckit.example\n"
+ " file: commands/example.md\n"
+ " - type: script\n"
+ " name: setup-script\n"
+ " file: scripts/setup.py\n",
+ encoding="utf-8",
+ )
+
+
+def _extension(project, extension_id, *, author=None):
+ extension_dir = project / ".specify" / "extensions" / extension_id
+ extension_dir.mkdir(parents=True)
+ author_line = f' author: "{author}"\n' if author is not None else ""
+ (extension_dir / "extension.yml").write_text(
+ "schema_version: \"1.0\"\n"
+ "extension:\n"
+ f" id: {extension_id}\n"
+ f" name: {extension_id} name\n"
+ " version: \"1.0.0\"\n"
+ " description: extension description\n"
+ f"{author_line}"
+ "requires:\n"
+ " speckit_version: \">=0.1.0\"\n"
+ "provides:\n"
+ " commands:\n"
+ " - name: speckit.example-ext.example\n"
+ " file: commands/example.md\n",
+ encoding="utf-8",
+ )
+
+
+def _json_result(result):
+ assert result.exit_code == 0, result.output
+ assert result.stderr == ""
+ return json.loads(result.stdout)
+
+
+def test_preset_list_json_uses_canonical_wire_object_and_keeps_flat_manager_keys(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ _preset(project, "test-preset")
+ manager = PresetManager(project)
+ source = {"kind": "catalog", "catalog": "speckit-official"}
+ manager.registry.add("test-preset", {"version": "1.0.0", "source": source, "priority": 3})
+
+ record = manager.list_installed()[0]
+ assert record["template_count"] == 3
+ assert record["_json_source"] == source
+ assert record["_json_provides"] == {"commands": 1, "templates": 1, "scripts": 1, "hooks": 0}
+
+ monkeypatch.chdir(project)
+ payload = _json_result(runner.invoke(app, ["preset", "list", "--json"]))
+
+ assert len(payload) == 1
+ item = payload[0]
+ assert set(item) == {
+ "id", "name", "description", "version", "author", "priority", "enabled", "source", "provides"
+ }
+ assert item["author"] == "Preset Author"
+ assert item["source"] == source
+ assert item["provides"] == {"commands": 1, "templates": 1, "scripts": 1}
+ assert "hooks" not in item["provides"]
+
+
+def test_preset_list_json_defaults_legacy_source_and_author(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ _preset(project, "legacy-preset", author=None)
+ PresetManager(project).registry.add("legacy-preset", {"version": "1.0.0"})
+
+ monkeypatch.chdir(project)
+ item = _json_result(runner.invoke(app, ["preset", "list", "--json"]))[0]
+
+ assert item["author"] is None
+ assert item["source"] == {"kind": "local"}
+
+
+def test_catalog_install_producers_persist_structured_source_and_keep_local_default(
+ tmp_path, monkeypatch
+):
+ project = _project(tmp_path)
+ source_project = tmp_path / "sources"
+ (source_project / ".specify").mkdir(parents=True)
+ _preset(source_project, "catalog-preset")
+ _preset(source_project, "local-preset")
+ _extension(source_project, "catalog-extension")
+ _extension(source_project, "local-extension")
+ for extension_id in ("catalog-extension", "local-extension"):
+ manifest_path = (
+ source_project / ".specify" / "extensions" / extension_id / "extension.yml"
+ )
+ manifest_path.write_text(
+ manifest_path.read_text(encoding="utf-8").replace(
+ "speckit.example-ext.example", f"speckit.{extension_id}.example"
+ ),
+ encoding="utf-8",
+ )
+
+ preset_manager = PresetManager(project)
+ preset_manager.install_from_directory(
+ source_project / ".specify" / "presets" / "catalog-preset",
+ "1.0.0",
+ catalog_name=" preset-catalog ",
+ )
+ preset_manager.install_from_directory(
+ source_project / ".specify" / "presets" / "local-preset",
+ "1.0.0",
+ catalog_name=" ",
+ )
+
+ extension_manager = ExtensionManager(project)
+ extension_manager.install_from_directory(
+ source_project / ".specify" / "extensions" / "catalog-extension",
+ "1.0.0",
+ register_commands=False,
+ catalog_name=" extension-catalog ",
+ )
+ extension_manager.install_from_directory(
+ source_project / ".specify" / "extensions" / "local-extension",
+ "1.0.0",
+ register_commands=False,
+ catalog_name=" ",
+ )
+
+ assert preset_manager.registry.get("catalog-preset")["source"] == {
+ "kind": "catalog",
+ "catalog": "preset-catalog",
+ }
+ assert preset_manager.registry.get("local-preset")["source"] == "local"
+ assert extension_manager.registry.get("catalog-extension")["source"] == {
+ "kind": "catalog",
+ "catalog": "extension-catalog",
+ }
+ assert extension_manager.registry.get("local-extension")["source"] == "local"
+
+ monkeypatch.chdir(project)
+ presets = _json_result(runner.invoke(app, ["preset", "list", "--json"]))
+ extensions = _json_result(runner.invoke(app, ["extension", "list", "--json"]))
+ assert {item["id"]: item["source"] for item in presets} == {
+ "catalog-preset": {"kind": "catalog", "catalog": "preset-catalog"},
+ "local-preset": {"kind": "local"},
+ }
+ assert {item["id"]: item["source"] for item in extensions} == {
+ "catalog-extension": {"kind": "catalog", "catalog": "extension-catalog"},
+ "local-extension": {"kind": "local"},
+ }
+
+
+def test_preset_json_order_uses_priority_then_id_despite_install_order(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ source_project = tmp_path / "sources"
+ (source_project / ".specify").mkdir(parents=True)
+ for preset_id in ("zebra", "later", "alpha"):
+ _preset(source_project, preset_id)
+
+ manager = PresetManager(project)
+ manager.install_from_directory(
+ source_project / ".specify" / "presets" / "zebra", "1.0.0", priority=5
+ )
+ manager.install_from_directory(
+ source_project / ".specify" / "presets" / "later", "1.0.0", priority=9
+ )
+ manager.install_from_directory(
+ source_project / ".specify" / "presets" / "alpha", "1.0.0", priority=5
+ )
+
+ monkeypatch.chdir(project)
+ payload = _json_result(runner.invoke(app, ["preset", "list", "--json"]))
+ assert [item["id"] for item in payload] == ["alpha", "zebra", "later"]
+
+
+def test_extension_json_order_uses_priority_then_id_despite_install_order(
+ tmp_path, monkeypatch
+):
+ project = _project(tmp_path)
+ source_project = tmp_path / "sources"
+ (source_project / ".specify").mkdir(parents=True)
+ for extension_id in ("zebra", "later", "alpha"):
+ _extension(source_project, extension_id)
+ manifest_path = (
+ source_project / ".specify" / "extensions" / extension_id / "extension.yml"
+ )
+ manifest_path.write_text(
+ manifest_path.read_text(encoding="utf-8").replace(
+ "speckit.example-ext.example", f"speckit.{extension_id}.example"
+ ),
+ encoding="utf-8",
+ )
+
+ manager = ExtensionManager(project)
+ for extension_id, priority in (("zebra", 5), ("later", 9), ("alpha", 5)):
+ manager.install_from_directory(
+ source_project / ".specify" / "extensions" / extension_id,
+ "1.0.0",
+ register_commands=False,
+ priority=priority,
+ )
+ manager.registry.update("zebra", {"enabled": False})
+
+ monkeypatch.chdir(project)
+ payload = _json_result(runner.invoke(app, ["extension", "list", "--json"]))
+
+ assert [item["id"] for item in payload] == ["alpha", "zebra", "later"]
+ assert payload[1]["enabled"] is False
+
+
+def test_extension_list_json_is_installed_only_for_available_and_all(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ _extension(project, "example-ext")
+ source = {"kind": "catalog", "catalog": "speckit-official"}
+ ExtensionManager(project).registry.add("example-ext", {"version": "1.0.0", "source": source})
+
+ monkeypatch.chdir(project)
+ expected = _json_result(runner.invoke(app, ["extension", "list", "--json"]))
+ available = _json_result(runner.invoke(app, ["extension", "list", "--json", "--available"]))
+ all_extensions = _json_result(runner.invoke(app, ["extension", "list", "--json", "--all"]))
+
+ assert available == expected == all_extensions
+ item = expected[0]
+ assert set(item) == {
+ "id", "name", "description", "version", "author", "priority", "enabled", "source", "provides"
+ }
+ assert item["author"] is None
+ assert item["source"] == source
+ assert item["provides"] == {"commands": 1, "templates": 0, "scripts": 0, "hooks": 0}
+
+
+def test_empty_json_lists_are_successful_arrays(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ monkeypatch.chdir(project)
+
+ assert _json_result(runner.invoke(app, ["preset", "list", "--json"])) == []
+ assert _json_result(runner.invoke(app, ["extension", "list", "--json"])) == []
+
+
[email protected]("command", ["preset", "extension"])
+ "args",
+ [("--json", "--unknown"), ("--unknown", "--json")],
+)
+def test_json_usage_errors_are_stderr_only_and_preserve_exit_code(command, args):
+ result = runner.invoke(app, [command, "list", *args])
+
+ assert result.exit_code == 2
+ assert result.stdout == ""
+ assert json.loads(result.stderr) == {"error": "No such option: --unknown"}
+
+
+ ("command", "manager"),
+ [("preset", PresetManager), ("extension", ExtensionManager)],
+)
+def test_json_runtime_errors_are_stderr_only(command, manager, tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ monkeypatch.chdir(project)
+ monkeypatch.setattr(
+ manager, "list_installed", lambda _self: (_ for _ in ()).throw(RuntimeError("boom"))
+ )
+
+ result = runner.invoke(app, [command, "list", "--json"])
+
+ assert result.exit_code == 1
+ assert result.stdout == ""
+ assert result.stderr == '{"error": "boom"}\n'
+
+
[email protected]("command", ["preset", "extension"])
+def test_non_json_usage_errors_keep_human_output(command):
+ result = runner.invoke(app, [command, "list", "--unknown"])
+ output = strip_ansi(result.output)
+
+ assert result.exit_code == 2
+ assert "Usage:" in output
+ assert "No such option: --unknown" in output
+ assert '{"error":' not in output
+
+
[email protected]("command", ["preset", "extension"])
+def test_json_help_remains_human_help(command):
+ result = runner.invoke(app, [command, "list", "--json", "--help"])
+ output = strip_ansi(result.output)
+
+ assert result.exit_code == 0
+ assert "--json" in output
+ assert result.stderr == ""
+
+
[email protected]("command", ["preset", "extension"])
+def test_jsonish_does_not_enable_json_usage_errors(command):
+ result = runner.invoke(app, [command, "list", "--jsonish"])
+ output = strip_ansi(result.output)
+
+ assert result.exit_code == 2
+ assert "No such option: --jsonish" in output
+ assert '{"error":' not in output
+
+
+def test_preset_list_json_preserves_catalog_source_for_corrupt_records(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ source = {"kind": "catalog", "catalog": "speckit-official"}
+ PresetManager(project).registry.add("broken-preset", {"version": "1.0.0", "source": source})
+
+ monkeypatch.chdir(project)
+ item = _json_result(runner.invoke(app, ["preset", "list", "--json"]))[0]
+
+ assert item["author"] is None
+ assert item["source"] == source
+ assert item["provides"] == {"commands": 0, "templates": 0, "scripts": 0}
+
+
+def test_extension_list_json_preserves_catalog_source_for_corrupt_records(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ source = {"kind": "catalog", "catalog": "speckit-official"}
+ ExtensionManager(project).registry.add("broken-extension", {"version": "1.0.0", "source": source})
+
+ monkeypatch.chdir(project)
+ item = _json_result(runner.invoke(app, ["extension", "list", "--json"]))[0]
+
+ assert item["source"] == source
+ assert item["provides"] == {"commands": 0, "templates": 0, "scripts": 0, "hooks": 0}
+
+
+ ("source", "expected"),
+ [
+ ({"kind": "local", "catalog": "ignored", "extra": "ignored"}, {"kind": "local"}),
+ (
+ {"kind": "catalog", "catalog": "speckit-official", "extra": "ignored"},
+ {"kind": "catalog", "catalog": "speckit-official"},
+ ),
+ ([], {"kind": "local"}),
+ ({"kind": "catalog"}, {"kind": "local"}),
+ ({"kind": "catalog", "catalog": " "}, {"kind": "local"}),
+ ({"kind": "catalog", "catalog": 1}, {"kind": "local"}),
+ ],
+)
+def test_normalized_source_whitelists_valid_shapes_and_falls_back(source, expected):
+ assert _normalized_source(source) == expected
+
+
+def test_installed_list_json_falls_back_for_legacy_unknown_and_malformed_sources(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ _preset(project, "legacy-preset")
+ _preset(project, "malformed-preset")
+ _extension(project, "unknown-ext")
+ PresetManager(project).registry.add("legacy-preset", {"version": "1.0.0", "source": "catalog"})
+ PresetManager(project).registry.add(
+ "malformed-preset", {"version": "1.0.0", "source": {"kind": "catalog", "catalog": []}}
+ )
+ ExtensionManager(project).registry.add(
+ "unknown-ext", {"version": "1.0.0", "source": {"kind": "remote", "catalog": "other"}}
+ )
+
+ monkeypatch.chdir(project)
+ presets = _json_result(runner.invoke(app, ["preset", "list", "--json"]))
+ extension = _json_result(runner.invoke(app, ["extension", "list", "--json"]))[0]
+
+ assert {item["id"]: item["source"] for item in presets} == {
+ "legacy-preset": {"kind": "local"},
+ "malformed-preset": {"kind": "local"},
+ }
+ assert extension["source"] == {"kind": "local"}
+
+
+def test_extension_json_counts_hook_events_not_entries(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ extension_dir = project / ".specify" / "extensions" / "multi-hook"
+ extension_dir.mkdir(parents=True)
+ (extension_dir / "extension.yml").write_text(
+ "schema_version: \"1.0\"\n"
+ "extension:\n"
+ " id: multi-hook\n"
+ " name: Multi Hook\n"
+ " version: \"1.0.0\"\n"
+ " description: Multiple hooks on one event\n"
+ "requires:\n"
+ " speckit_version: \">=0.1.0\"\n"
+ "provides:\n"
+ " commands:\n"
+ " - name: speckit.multi-hook.one\n"
+ " file: commands/one.md\n"
+ "hooks:\n"
+ " after_plan:\n"
+ " - command: speckit.multi-hook.one\n"
+ " - command: speckit.multi-hook.two\n",
+ encoding="utf-8",
+ )
+ manager = ExtensionManager(project)
+ manager.registry.add("multi-hook", {"version": "1.0.0"})
+
+ assert manager.list_installed()[0]["hook_count"] == 1
+
+ monkeypatch.chdir(project)
+ item = _json_result(runner.invoke(app, ["extension", "list", "--json"]))[0]
+
+ assert item["provides"]["hooks"] == 1
+
+
+def test_text_list_rendering_retains_legacy_flat_counts(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ _preset(project, "text-preset")
+ PresetManager(project).registry.add("text-preset", {"version": "1.0.0"})
+ _extension(project, "example-ext")
+ ExtensionManager(project).registry.add("example-ext", {"version": "1.0.0"})
+
+ monkeypatch.chdir(project)
+ preset_result = runner.invoke(app, ["preset", "list"])
+ extension_result = runner.invoke(app, ["extension", "list"])
+
+ assert preset_result.exit_code == extension_result.exit_code == 0
+ assert "Templates: 3" in preset_result.stdout
+ assert "Commands: 1 | Hooks: 0" in extension_result.stdout
+
+
+def test_preset_json_project_resolution_error_is_stderr_only(tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+
+ result = runner.invoke(app, ["preset", "list", "--json"])
+
+ assert result.exit_code != 0
+ assert result.stdout == ""
+ assert json.loads(result.stderr) == {"error": "Not a Spec Kit project (no .specify/ directory)"}
+
+
+def test_extension_json_runtime_error_is_stderr_only(tmp_path, monkeypatch):
+ project = _project(tmp_path)
+ monkeypatch.chdir(project)
+
+ def fail_list(_self):
+ raise RuntimeError("list failed")
+
+ monkeypatch.setattr(ExtensionManager, "list_installed", fail_list)
+ result = runner.invoke(app, ["extension", "list", "--json"])
+
+ assert result.exit_code != 0
+ assert result.stdout == ""
+ assert json.loads(result.stderr) == {"error": "list failed"}
diff --git a/tests/test_presets.py b/tests/test_presets.py
index 33e74d2c2..17aef20dc 100644
--- a/tests/test_presets.py
+++ b/tests/test_presets.py
@@ -959,9 +959,15 @@ class TestPresetManager:
zf.write(file_path, arcname)
manager = PresetManager(project_dir)
- manifest = manager.install_from_zip(zip_path, "0.1.5")
+ manifest = manager.install_from_zip(
+ zip_path, "0.1.5", catalog_name="preset-catalog"
+ )
assert manifest.id == "test-pack"
assert manager.registry.is_installed("test-pack")
+ assert manager.registry.get("test-pack")["source"] == {
+ "kind": "catalog",
+ "catalog": "preset-catalog",
+ }
def test_install_from_zip_forwards_force(
self, project_dir, pack_dir, temp_dir
@@ -1044,10 +1050,16 @@ class TestPresetManager:
archive.add(file_path, arcname=arcname)
manager = PresetManager(project_dir)
- manifest = manager.install_from_archive(archive_path, "0.1.5")
+ manifest = manager.install_from_archive(
+ archive_path, "0.1.5", catalog_name="preset-catalog"
+ )
assert manifest.id == "test-pack"
assert manager.registry.is_installed("test-pack")
+ assert manager.registry.get("test-pack")["source"] == {
+ "kind": "catalog",
+ "catalog": "preset-catalog",
+ }
def test_install_from_tar_rejects_symlink_entry(
self, project_dir, pack_dir, temp_dir
@@ -4028,6 +4040,40 @@ class TestPresetCatalogMultiCatalog:
result = catalog._load_catalog_config(config_path)
assert result is None
+ def test_load_catalog_config_defaults_blank_names(self, project_dir):
+ """Blank and null names normalize by valid catalog order."""
+ config_path = project_dir / ".specify" / "preset-catalogs.yml"
+ config_path.write_text(
+ yaml.dump(
+ {
+ "catalogs": [
+ {"name": "skipped", "url": " "},
+ {
+ "name": None,
+ "url": "https://one.example.com/catalog.json",
+ },
+ {
+ "name": " ",
+ "url": "https://two.example.com/catalog.json",
+ },
+ {
+ "name": " padded-name ",
+ "url": "https://three.example.com/catalog.json",
+ },
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ entries = PresetCatalog(project_dir)._load_catalog_config(config_path)
+
+ assert [entry.name for entry in entries] == [
+ "catalog-1",
+ "catalog-2",
+ "padded-name",
+ ]
+
@pytest.mark.parametrize("bad", [[], False, 0, ""])
def test_load_catalog_config_rejects_falsy_non_mapping_root(
self, project_dir, bad
@@ -11482,6 +11528,36 @@ class TestBundledPresetLocator:
assert "Lean Workflow" in result.output
assert "installed" in result.output.lower()
+ def test_preset_add_catalog_forwards_catalog_name(self, project_dir, monkeypatch):
+ """Catalog installs pass resolved provenance into the manager boundary."""
+ from specify_cli.presets._commands import preset_add
+
+ captured = {}
+
+ def fake_install_from_zip(self, _archive, _version, priority=10, *, catalog_name=None):
+ captured.update(priority=priority, catalog_name=catalog_name)
+ return SimpleNamespace(name="Catalog Preset", version="1.0.0")
+
+ monkeypatch.setattr("specify_cli._require_specify_project", lambda: project_dir)
+ monkeypatch.setattr("specify_cli.get_speckit_version", lambda: "1.0.0")
+ monkeypatch.setattr(
+ PresetCatalog,
+ "get_pack_info",
+ lambda _self, _id: {
+ "name": "Catalog Preset",
+ "_install_allowed": True,
+ "_catalog_name": "preset-catalog",
+ },
+ )
+ archive = project_dir / "preset.zip"
+ archive.write_bytes(b"archive")
+ monkeypatch.setattr(PresetCatalog, "download_pack", lambda _self, _id: archive)
+ monkeypatch.setattr(PresetManager, "install_from_zip", fake_install_from_zip)
+
+ preset_add(preset_id="catalog-preset", from_url=None, dev=None, priority=7)
+
+ assert captured == {"priority": 7, "catalog_name": "preset-catalog"}
+
def test_preset_add_from_url_rejects_insecure_redirect(self, project_dir, monkeypatch):
"""URL installs reject redirects from HTTPS to non-loopback HTTP."""
import typer
diff --git a/tests/unit/test_bundler_primitives.py b/tests/unit/test_bundler_primitives.py
index a0fcb3c63..3a482881d 100644
--- a/tests/unit/test_bundler_primitives.py
+++ b/tests/unit/test_bundler_primitives.py
@@ -139,6 +139,96 @@ def test_preset_install_preserves_explicit_zero_priority(tmp_path: Path, monkeyp
assert calls["priority"] == 0
+def test_catalog_preset_install_and_refresh_forward_catalog_name(
+ tmp_path: Path, monkeypatch
+):
+ import specify_cli._assets as assets
+ from specify_cli.presets import PresetCatalog
+
+ archive = tmp_path / "preset.zip"
+ archive.write_bytes(b"placeholder")
+ calls = []
+
+ class _FakeManager:
+ def install_from_zip(self, *args, **kwargs):
+ calls.append(kwargs)
+
+ monkeypatch.setattr(assets, "_locate_bundled_preset", lambda _id: None)
+ monkeypatch.setattr(
+ PresetCatalog,
+ "get_pack_info",
+ lambda _self, _id: {
+ "version": "1.0.0",
+ "_install_allowed": True,
+ "_catalog_name": "bundle-preset-catalog",
+ },
+ )
+ monkeypatch.setattr(PresetCatalog, "download_pack", lambda _self, _id: archive)
+
+ manager = primitive_manager("presets", tmp_path, allow_network=True)
+ manager._manager = _FakeManager()
+ component = ComponentRef(kind="presets", id="catalog-preset", version="1.0.0")
+ manager.install(component)
+ archive.write_bytes(b"placeholder")
+ manager.refresh(component)
+
+ assert [call["catalog_name"] for call in calls] == [
+ "bundle-preset-catalog",
+ "bundle-preset-catalog",
+ ]
+ assert calls[1]["force"] is True
+
+
+def test_catalog_extension_install_and_refresh_forward_catalog_and_scaffolding(
+ tmp_path: Path, monkeypatch
+):
+ import specify_cli._assets as assets
+ from specify_cli.extensions import ExtensionCatalog
+
+ archive = tmp_path / "extension.zip"
+ archive.write_bytes(b"placeholder")
+ installs = []
+ scaffolded = []
+
+ class _FakeManager:
+ def install_from_zip(self, *args, **kwargs):
+ installs.append(kwargs)
+ return SimpleNamespace(id="catalog-extension")
+
+ def scaffold_config(self, extension_id):
+ scaffolded.append(extension_id)
+
+ monkeypatch.setattr(assets, "_locate_bundled_extension", lambda _id: None)
+ monkeypatch.setattr(
+ ExtensionCatalog,
+ "get_extension_info",
+ lambda _self, _id: {
+ "version": "1.0.0",
+ "_install_allowed": True,
+ "_catalog_name": "bundle-extension-catalog",
+ },
+ )
+ monkeypatch.setattr(
+ ExtensionCatalog, "download_extension", lambda _self, _id: archive
+ )
+
+ manager = primitive_manager("extensions", tmp_path, allow_network=True)
+ manager._manager = _FakeManager()
+ component = ComponentRef(
+ kind="extensions", id="catalog-extension", version="1.0.0"
+ )
+ manager.install(component)
+ archive.write_bytes(b"placeholder")
+ manager.refresh(component)
+
+ assert [call["catalog_name"] for call in installs] == [
+ "bundle-extension-catalog",
+ "bundle-extension-catalog",
+ ]
+ assert installs[1]["force"] is True
+ assert scaffolded == ["catalog-extension", "catalog-extension"]
+
+
def _write_manifest(path: Path, root_key: str, version: str) -> Path:
path.mkdir(parents=True, exist_ok=True)
(path / f"{root_key}.yml").write_text(