Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/reference/presets.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,35 @@ specify preset add team-workflow --priority 10

For any file that both provide, `compliance` wins (priority 5 < 10). For files only one provides, that one is used. For files neither provides, the core default is used.

## Contribution Identifiers

Every command, template, and script contributed by a preset (or an extension, or the core layer) is addressable at read time by a deterministic opaque identifier of the form:

```text
{layer}:{sourceId}:{kind}:{name}
```

- `layer` is one of `core`, `preset`, or `extension`.
Comment thread
nicolehaugen marked this conversation as resolved.
- `sourceId` is `_` for `core`, the preset pack id for `preset`, or the extension id for `extension`.
- `kind` is one of `command`, `template`, or `script` (see below for hooks).
- `name` is the entry's declared `name` field.

`sourceId` is the source's own stable system identifier:

| Layer | `sourceId` value | Where it comes from |
| --- | --- | --- |
| `core` | `_` (literal underscore) | Placeholder because core has no manifest id |
| `preset` | The preset pack's `id` | The manifest's `preset.id` field — the same value used by `PresetManifest.id`, the install directory, registries, and resolver layer metadata |
| `extension` | The extension's `id` | The manifest's `extension.id` field — the value used by `ExtensionManifest.id` and manifest-backed `lookupId` values; the extension directory or registry key may differ for unregistered local copies |

Preset contribution identifiers cover named artifacts (`command`, `template`, and `script`). Extension hooks are treated separately because their lookup name is derived from the hook event and command instead of a single `name` field.

Identifiers are computed on demand from author-declared manifest content and are never persisted to `.specify/` or any cache. Copying a preset to another machine (or touching its files) does not change the identifiers it produces.

`PresetResolver.collect_all_layers()` returns layer dicts that each include a `lookupId` field pointing back to the originating contribution's `id`. Project-local overrides in `.specify/templates/overrides/` are a resolver-only concept — they carry a synthetic `project:_:{kind}:{name}` `lookupId` that intentionally does not match any manifest contribution.

For the full grammar, including the hook name-component convention and extension hook duplicate collapse semantics, see the [Extension API Reference — Contribution Identifiers](../../extensions/EXTENSION-API-REFERENCE.md#contribution-identifiers) section.

## FAQ

### Can I use multiple presets at the same time?
Expand Down
61 changes: 60 additions & 1 deletion extensions/EXTENSION-API-REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Technical reference for Spec Kit extension system APIs and manifest schema.
4. [Configuration Schema](#configuration-schema)
5. [Hook System](#hook-system)
6. [CLI Commands](#cli-commands)
7. [Contribution Identifiers](#contribution-identifiers)

---

Expand Down Expand Up @@ -859,7 +860,65 @@ satisfied = version_satisfies("1.2.3", ">=1.0.0,<2.0.0") # bool

---

## File System Layout
## Contribution Identifiers

Every command, template, script, and hook contributed by an extension (or a preset, or the core layer) is addressable at read time by a deterministic opaque identifier. Resolved artifact-stack layers carry a matching `lookupId` field that points back to the contribution the layer came from. Identifiers are **computed on demand from author-declared manifest content** and are **never persisted** to `.specify/` or to any cache file.

### Grammar

Named contributions (commands, templates, scripts) follow:

```text
{layer}:{sourceId}:{kind}:{name}
```

- `layer` is one of `core`, `preset`, or `extension`.
- `sourceId` is `_` for `core`, the preset pack id for `preset`, or the extension id for `extension`.
- `kind` is one of `command`, `template`, `script`, or `hook`.
- `name` is the contribution's declared `name` field.

`sourceId` is the source's own stable manifest identifier: `_` for the manifest-less core layer, `preset.id` from `preset.yml` for presets, and `extension.id` from `extension.yml` for extensions. Manifest-backed extension contributions and resolver `lookupId` values use `extension.id` even when an unregistered local copy has a different directory or registry key, which makes identifiers stable join keys back to their originating manifest.

Hook contributions use a compound name-component built from the event and command:

```text
{layer}:{sourceId}:hook:{eventName}:{command}
```

If an extension declares multiple hooks with the same `(eventName, command)` pair, the final declaration wins, matching hook installation. `iter_contributions()` emits only that final hook, so every emitted hook identifier corresponds to an installed hook.

### Reserved character

`:` is reserved as the identifier component separator. It cannot appear inside any of `layer`, `sourceId`, `kind`, `name`, `eventName`, or `command`. Extension ids, command names, template names, and script names are already constrained by their existing regex patterns (`^[a-z0-9-]+$` and friends), which forbid `:`. In addition, every value that appears in an identifier — contribution names (commands, templates, scripts) as well as hook event names (mapping keys) and hook `command` values — is explicitly validated to reject `:` at manifest load, so the guarantee holds uniformly.

### The `project:` sentinel

Project-local overrides in `.specify/templates/overrides/` are a resolver-only concept — they have no backing manifest and cannot appear in `iter_contributions()`. Layers of that kind carry a synthetic `lookupId` of the form `project:_:{kind}:{name}` so consumers that reverse-lookup the id always see "not found", which is the intended behaviour: overrides are addressable at the stack level, not as first-class contributions.

### Python API

```python
class ExtensionManifest:
def iter_contributions(self) -> list[dict]: ...
def contribution_id(self, kind: str, name: str) -> str | None: ...


class PresetManifest:
def iter_contributions(self) -> list[dict]: ...
def contribution_id(self, kind: str, name: str) -> str | None: ...
```

Each contribution dict carries `{layer, sourceId, kind, name, id, ...author-declared fields}`; `id` is the computed identifier. `contribution_id(kind, name)` returns the id for a single lookup, or `None` if no contribution matches.

`PresetResolver.collect_all_layers()` returns layer dicts that include a `lookupId` field for every layer type (`project override`, preset, extension, core, and bundled core).

### Determinism guarantees

Identifier derivation reads only the in-memory declared manifest content. No filesystem paths, no `os.environ`, no timestamps, and no file-content hashes contribute to any id. Copying an extension or preset to a different machine (or renaming its directory, or touching its files) does not change the identifiers it produces.

### Opacity guidance

Identifiers are stable, but treat them as **opaque strings** in stored data (registries, cache files, external tooling). Parse them with the helpers in `specify_cli._identifier` (`derive_named_id`, `derive_hook_id`) rather than by string-splitting on `:` so future grammar extensions do not break consumers.

```text
.specify/
Expand Down
99 changes: 99 additions & 0 deletions src/specify_cli/_identifier.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Deterministic identifiers for Spec Kit contributions and resolved stack layers.

Every command, template, script, and hook contribution surfaced by a preset or
extension manifest carries a computed opaque ``id`` string, and every layer of a
resolved artifact stack carries a matching ``lookupId``. The identifier value is
derived only from author-declared manifest data — it never depends on file
contents, timestamps, archive hashes, installation directory paths, install-time
random values, or list positions. That is what makes identifiers portable
across machines, project locations, and reinstalls, and what lets consumers use
them as stable join keys.

Grammar for named contributions (commands, templates, scripts)::

id = "{layer}:{sourceId}:{kind}:{name}"

layer ∈ {"core", "preset", "extension"}
sourceId = "_" when layer == "core"; the preset id or extension id otherwise
kind ∈ {"command", "template", "script", "hook"}
name = the contribution's declared ``name``

Hook identifiers use ``{eventName}:{command}`` as the name component::

id = "{layer}:{sourceId}:hook:{eventName}:{command}"

Extension hook contributions use the same last-write-wins behavior as hook
installation, so at most one contribution exists for each
``(eventName, command)`` pair.

The functions in this module are pure — inputs are strings or in-memory
mappings parsed from a manifest, outputs are strings. None of them read from
disk, look at ``os.environ``, call ``datetime``, or hash file contents. That
guarantee is what preserves portability, and it is enforced by inspection
rather than by runtime checks: any change here that adds an ambient input is a
change that breaks the identifier contract.
"""

from __future__ import annotations

from typing import Any


PROJECT_OVERRIDE_LAYER = "project"
"""Resolver-only layer label for project-local override layers.

Project overrides are a resolver feature — they are not backed by any manifest
contribution. When a resolved artifact stack contains a project-override layer,
its ``lookupId`` uses this label so the round-trip invariant (every layer
carries a ``lookupId``) still holds. No manifest ``iter_contributions()`` will
ever emit a matching ``id``, so consumers see "not found" for the lookup, which
is the correct outcome for a layer with no originating manifest entry.
"""

class IdentifierComponentError(ValueError):
"""Raised when a manifest component would break identifier grammar."""


def validate_component(value: Any, field_label: str) -> str:
"""Return ``value`` unchanged if it is a non-empty ``:``-free string.

Manifest components that appear in an identifier (``layer``, ``sourceId``,
``kind``, ``name``, ``eventName``, ``command``) may not contain the ``:``
delimiter — the grammar has no escape rule. This function is the guard used
by manifest validators to reject offending values at load time with a clear
message naming the field.
"""
if not isinstance(value, str):
raise IdentifierComponentError(
f"Invalid {field_label}: expected a string, got {type(value).__name__}"
)
if not value:
raise IdentifierComponentError(
f"Invalid {field_label}: value must not be empty"
)
if ":" in value:
raise IdentifierComponentError(
f"Invalid {field_label} '{value}': ':' is reserved as an identifier delimiter"
)
return value


def derive_named_id(layer: str, source_id: str, kind: str, name: str) -> str:
"""Build the identifier string for a named contribution kind.

Callers are expected to have already validated each component with
:func:`validate_component` at manifest-load time; this function does not
revalidate — it is a pure string join so the identifier can be computed
cheaply on every read.
"""
return f"{layer}:{source_id}:{kind}:{name}"


def derive_hook_id(
layer: str,
source_id: str,
event_name: str,
command: str,
) -> str:
"""Build the identifier string for a hook contribution."""
return f"{layer}:{source_id}:hook:{event_name}:{command}"
Loading