Skip to content

Commit 9731eca

Browse files
committed
feat(presets): let a preset declare a required extension
A preset whose command overrides call into an extension is inert without it, but the overrides fall through to the core workflow, so nothing errors -- the feature just silently does less than the user expects. Until now the only place that dependency could be stated was the README, which fails exactly the user who did not read it. Add an optional requires.extensions to preset.yml, accepting either a bare extension id or a mapping with an optional version specifier and an optional required flag. Validation mirrors the requires.speckit_version strictness from github#3980: a non-list, a member that is neither string nor mapping, a missing or malformed id, a non-string or unparseable version, and a non-boolean required each raise PresetValidationError rather than surfacing later as a bare TypeError from re.match or SpecifierSet. On `specify preset add`, warn once for each unsatisfied dependency, naming the extension and the command that installs it. The check runs at the single point where the --dev, --from, and catalog paths converge, so all three behave the same. It warns rather than fails: these presets are written to degrade safely, and three catalog entries already declare the dependency, so failing would break installs that work today. The field is optional, so every existing preset stays valid and silent. Closes github#4231 Assisted-by: Claude Code (model: Claude Opus 5, autonomous)
1 parent 31e6b84 commit 9731eca

4 files changed

Lines changed: 435 additions & 0 deletions

File tree

‎presets/PUBLISHING.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ preset:
6868

6969
requires:
7070
speckit_version: ">=0.1.0" # Required spec-kit version
71+
extensions: # Optional: extensions this preset needs
72+
- "companion-extension"
7173

7274
provides:
7375
templates:
@@ -93,6 +95,34 @@ tags: # 2-5 relevant tags
9395
- ✅ Command names use dot notation (e.g. `speckit.specify`)
9496
- ✅ Tags are lowercase and descriptive
9597

98+
#### Declaring extension dependencies
99+
100+
If your preset overrides commands that call into an extension, declare it in
101+
`requires.extensions`. Without the extension the preset still installs and the
102+
overrides fall through to the core workflow, so nothing errors — the feature
103+
just silently does less than the user expects. Declaring the dependency makes
104+
`specify preset add` say so, and name the command that fixes it.
105+
106+
Use a bare id, or a mapping when you need a version floor or an optional
107+
dependency:
108+
109+
```yaml
110+
requires:
111+
speckit_version: ">=0.9.0"
112+
extensions:
113+
- "companion-extension" # required, any version
114+
- id: "other-extension"
115+
version: ">=1.2.0" # optional PEP 440 specifier
116+
required: false # optional, defaults to true
117+
```
118+
119+
Notes:
120+
121+
- The field is optional. A preset that declares nothing behaves exactly as before.
122+
- A missing or version-unsatisfied dependency produces a **warning, not a failure** — the install still succeeds.
123+
- `required: false` documents an enhancing-but-optional extension and is never warned about.
124+
- Declare it in `preset.yml`, not only in your catalog entry. The catalog is not consulted for `--dev` and `--from <url>` installs, so the manifest is the only copy present on every install path.
125+
96126
### 3. Test Locally
97127

98128
```bash

‎src/specify_cli/presets/__init__.py‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,14 @@ def _validate(self):
381381
f"got {type(requires['speckit_version']).__name__}"
382382
)
383383

384+
# Validate the optional extension dependency list. A preset that
385+
# overrides commands calling into an extension is inert without it, and
386+
# until now the only place that could be said was the README -- see
387+
# issue #4231. Absent means "no dependencies", so every existing preset
388+
# stays valid.
389+
if "extensions" in requires:
390+
self._validate_requires_extensions(requires["extensions"])
391+
384392
# Validate provides section
385393
provides = self.data["provides"]
386394
if "templates" not in provides:
@@ -524,11 +532,116 @@ def author(self) -> str:
524532
"""Get preset author."""
525533
return self.data["preset"].get("author", "")
526534

535+
@staticmethod
536+
def _validate_requires_extensions(declared: Any) -> None:
537+
"""Validate the optional ``requires.extensions`` list.
538+
539+
Accepts either a bare extension id or a mapping carrying an optional
540+
version specifier and an optional ``required`` flag:
541+
542+
.. code-block:: yaml
543+
544+
requires:
545+
extensions:
546+
- speckit-inventory
547+
- id: other-ext
548+
version: ">=1.2.0"
549+
required: false
550+
551+
Raises:
552+
PresetValidationError: If the list or any entry is malformed.
553+
"""
554+
if not isinstance(declared, list):
555+
raise PresetValidationError(
556+
"Invalid requires.extensions: expected a list, "
557+
f"got {type(declared).__name__}"
558+
)
559+
560+
for index, entry in enumerate(declared):
561+
label = f"requires.extensions[{index}]"
562+
563+
if isinstance(entry, str):
564+
entry = {"id": entry}
565+
elif not isinstance(entry, dict):
566+
raise PresetValidationError(
567+
f"Invalid {label}: expected a string or a mapping, "
568+
f"got {type(entry).__name__}"
569+
)
570+
571+
if "id" not in entry:
572+
raise PresetValidationError(f"Missing {label}.id")
573+
extension_id = entry["id"]
574+
if not isinstance(extension_id, str):
575+
raise PresetValidationError(
576+
f"Invalid {label}.id: expected a string, "
577+
f"got {type(extension_id).__name__}"
578+
)
579+
# Same id shape the extension loader enforces, so a dependency can
580+
# never name something that could not be installed in the first place.
581+
if not re.match(r'^[a-z0-9-]+$', extension_id):
582+
raise PresetValidationError(
583+
f"Invalid {label}.id '{extension_id}': "
584+
"must be lowercase alphanumeric with hyphens only"
585+
)
586+
587+
if "version" in entry:
588+
constraint = entry["version"]
589+
# Mirrors the requires.speckit_version reasoning: a non-string
590+
# escapes InvalidSpecifier two ways -- scalars raise TypeError
591+
# from the constructor, and a list/dict is iterable so it
592+
# constructs and only fails later inside .contains().
593+
if not isinstance(constraint, str) or not constraint.strip():
594+
raise PresetValidationError(
595+
f"Invalid {label}.version: expected a non-empty string, "
596+
f"got {type(constraint).__name__}"
597+
)
598+
try:
599+
SpecifierSet(constraint)
600+
except InvalidSpecifier:
601+
raise PresetValidationError(
602+
f"Invalid {label}.version '{constraint}': "
603+
"not a valid version specifier"
604+
)
605+
606+
if "required" in entry and not isinstance(entry["required"], bool):
607+
raise PresetValidationError(
608+
f"Invalid {label}.required: expected a boolean, "
609+
f"got {type(entry['required']).__name__}"
610+
)
611+
527612
@property
528613
def requires_speckit_version(self) -> str:
529614
"""Get required spec-kit version range."""
530615
return self.data["requires"]["speckit_version"]
531616

617+
@property
618+
def requires_extensions(self) -> List[Dict[str, Any]]:
619+
"""Get declared extension dependencies, normalized to mappings.
620+
621+
Returns:
622+
One entry per dependency with ``id``, ``version`` (``None`` when
623+
unconstrained), and ``required`` (defaulting to ``True``). Empty
624+
when the manifest declares no dependencies.
625+
"""
626+
declared = self.data["requires"].get("extensions")
627+
if not isinstance(declared, list):
628+
return []
629+
630+
normalized: List[Dict[str, Any]] = []
631+
for entry in declared:
632+
if isinstance(entry, str):
633+
entry = {"id": entry}
634+
if not isinstance(entry, dict) or not isinstance(entry.get("id"), str):
635+
continue
636+
normalized.append(
637+
{
638+
"id": entry["id"],
639+
"version": entry.get("version"),
640+
"required": entry.get("required", True),
641+
}
642+
)
643+
return normalized
644+
532645
@property
533646
def templates(self) -> List[Dict[str, Any]]:
534647
"""Get list of provided templates."""
@@ -841,6 +954,65 @@ def check_compatibility(
841954

842955
return True
843956

957+
def find_unmet_extension_dependencies(
958+
self,
959+
manifest: PresetManifest
960+
) -> List[Dict[str, Any]]:
961+
"""Find declared extension dependencies that are not satisfied.
962+
963+
Reports rather than raises. A preset whose overrides call into an
964+
extension is written to degrade safely -- without the extension the
965+
core workflow still runs -- so a missing dependency is a warning, not
966+
an install failure. See issue #4231.
967+
968+
Args:
969+
manifest: Preset manifest to inspect
970+
971+
Returns:
972+
One entry per unsatisfied dependency, each with ``id``, the
973+
requested ``version`` specifier (``None`` when unconstrained), the
974+
``installed`` version (``None`` when absent), and a ``reason`` of
975+
either ``"missing"`` or ``"version"``. Optional dependencies
976+
(``required: false``) are never reported.
977+
"""
978+
# Defense in depth, mirroring check_compatibility(): this method is
979+
# public and also reachable with a hand-built manifest object that
980+
# predates this field. A manifest without it declares nothing.
981+
candidates = getattr(manifest, "requires_extensions", None)
982+
if not isinstance(candidates, list):
983+
return []
984+
985+
declared = [
986+
dep for dep in candidates
987+
if isinstance(dep, dict) and dep.get("required", True)
988+
]
989+
if not declared:
990+
return []
991+
992+
registry = ExtensionRegistry(self.project_root / ".specify" / "extensions")
993+
unmet: List[Dict[str, Any]] = []
994+
995+
for dep in declared:
996+
metadata = registry.get(dep["id"])
997+
if metadata is None:
998+
unmet.append({**dep, "installed": None, "reason": "missing"})
999+
continue
1000+
1001+
constraint = dep["version"]
1002+
if not constraint:
1003+
continue
1004+
1005+
installed = metadata.get("version")
1006+
if not isinstance(installed, str):
1007+
# A registry entry without a usable version cannot be compared.
1008+
# Treat it as satisfied rather than inventing a failure, since
1009+
# the extension is demonstrably installed.
1010+
continue
1011+
if not version_satisfies(installed, constraint):
1012+
unmet.append({**dep, "installed": installed, "reason": "version"})
1013+
1014+
return unmet
1015+
8441016
def _register_commands(
8451017
self,
8461018
manifest: PresetManifest,

‎src/specify_cli/presets/_commands.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,39 @@
4040
preset_app.add_typer(preset_catalog_app, name="catalog")
4141

4242

43+
def _warn_unmet_extension_dependencies(manager, manifest) -> None:
44+
"""Warn when a preset's declared extension dependencies are unsatisfied.
45+
46+
A preset whose command overrides call into an extension is inert without
47+
it, but the overrides still fall through to the core workflow, so nothing
48+
breaks -- it just silently does less than the user expects. Naming the
49+
missing extension and the command that installs it turns that silence into
50+
something actionable. See issue #4231.
51+
"""
52+
unmet = manager.find_unmet_extension_dependencies(manifest)
53+
if not unmet:
54+
return
55+
56+
console.print()
57+
console.print("[yellow]![/yellow] This preset depends on extensions that are not satisfied:")
58+
for dep in unmet:
59+
extension_id = _escape_markup(dep["id"])
60+
if dep["reason"] == "missing":
61+
console.print(f" [yellow]{extension_id}[/yellow] is not installed")
62+
else:
63+
console.print(
64+
f" [yellow]{extension_id}[/yellow] "
65+
f"{_escape_markup(dep['installed'])} does not satisfy "
66+
f"{_escape_markup(dep['version'])}"
67+
)
68+
console.print(f" Install with: specify extension add {extension_id}")
69+
console.print()
70+
console.print(
71+
"[dim]The preset is installed and safe to use; the parts that rely on "
72+
"these extensions will do nothing until they are present.[/dim]"
73+
)
74+
75+
4376
# ===== Preset Commands =====
4477

4578

@@ -283,6 +316,12 @@ def _validate_download_redirect(old_url, new_url):
283316
console.print("[red]Error:[/red] Specify a preset ID, --from URL, or --dev path")
284317
raise typer.Exit(1)
285318

319+
# Every install path above binds `manifest` and the no-source branch
320+
# exits, so one call here covers --dev, --from, and catalog installs
321+
# alike. Warns rather than fails: the preset is installed and its
322+
# overrides fall through to the core workflow without the extension.
323+
_warn_unmet_extension_dependencies(manager, manifest)
324+
286325
except PresetCompatibilityError as e:
287326
console.print(f"[red]Compatibility Error:[/red] {_escape_markup(str(e))}")
288327
raise typer.Exit(1)

0 commit comments

Comments
 (0)