Skip to content
Open
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
32 changes: 31 additions & 1 deletion docs/extensions/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ extensions, plus normalized output-name collisions with core commands.

#### `hooks`

- **Type**: object
- Use a mapping keyed by event name, or a [list of bindings with `before` and `after` targets](#named-sections).
- **Keys**: Event names (e.g., `after_specify`, `after_plan`, `after_tasks`, `after_implement`, `before_analyze`)
- **Value**: A single hook mapping, or a list of hook mappings to register multiple commands on one event
- **Description**: Hooks that execute at lifecycle events
Expand Down Expand Up @@ -671,6 +671,36 @@ hooks:

Within a single manifest list, a repeated `command` is deduped as "last wins" and moved to the end, so it also breaks equal-priority ties in authoring order.

### Named sections

An extension can run a check between two parts of a command. This
`extension.yml` example registers a mandatory review after the design
artifacts are written and an optional review before task generation.

```yaml
hooks:
- after: plan.design
command: speckit.review.design
optional: false
- before: tasks.generate
command: speckit.review.inputs
prompt: "Review the inputs before generating tasks?"
```

Each binding takes exactly one of `before` and `after`. Use a command name on
its own for the whole command, or `command.section` for a marked section.
Both forms take the same hook options. A project can also use the existing
event mapping, for example `after_plan.design`. Installation writes this
as one key under `hooks` in the project's `.specify/extensions.yml`.

| Target | Before | After |
| --- | --- | --- |
| `plan.design` | After research, before generating the design artifacts | After the design artifacts, before the post-design constitution check |
| `tasks.generate` | After loading the design documents, before deriving tasks | After writing `tasks.md`, before whole-command post-hooks |

The command template marks where each section starts and ends. A template
without those markers continues to dispatch its whole-command hooks.

### Hook Events

Standard events (defined by core):
Expand Down
30 changes: 28 additions & 2 deletions src/specify_cli/extensions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,29 @@ def coerce_hook_entries(hook_config: Any) -> List[Any]:
return hook_config if isinstance(hook_config, list) else [hook_config]


def _hooks_by_position(bindings: list[Any]) -> dict[str, list[dict[str, Any]]]:
"""Group before/after bindings under the event keys used in extensions.yml."""
if not bindings:
raise ValidationError("Invalid hooks: a binding list must contain at least one entry")

events: dict[str, list[dict[str, Any]]] = {}
for binding in bindings:
if not isinstance(binding, dict):
raise ValidationError("Invalid hooks: each binding must be a mapping")
positions = binding.keys() & {"before", "after"}
if len(positions) != 1:
raise ValidationError("Invalid hooks: each binding needs exactly one of 'before' or 'after'")
position = positions.pop()
entry = binding.copy()
target = entry.pop(position)
if not isinstance(target, str) or not re.fullmatch(
r"[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)?", target
):
raise ValidationError(f"Invalid hooks: '{position}' must name a command or command.section")
events.setdefault(f"{position}_{target}", []).append(entry)
return events


@dataclass
class CatalogEntry(BaseCatalogEntry):
"""Represents a single catalog entry in the catalog stack."""
Expand Down Expand Up @@ -398,8 +421,11 @@ def _validate(self):
raise ValidationError("Invalid provides.templates: expected a list")
if "scripts" in provides and not isinstance(scripts, list):
raise ValidationError("Invalid provides.scripts: expected a list")
if "hooks" in self.data and not isinstance(hooks, dict):
raise ValidationError("Invalid hooks: expected a mapping")
if isinstance(hooks, list):
hooks = _hooks_by_position(hooks)
self.data["hooks"] = hooks
elif "hooks" in self.data and not isinstance(hooks, dict):
raise ValidationError("Invalid hooks: expected an event mapping or a list of bindings")
if "events" in self.data:
from ..events import validate_events
validate_events(self.data)
Expand Down
8 changes: 8 additions & 0 deletions templates/commands/plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ You **MUST** consider the user input before proceeding (if not empty).
## Outline
At the opening design marker, check the literal key `before_plan.design` under
`hooks` in `.specify/extensions.yml`. At its closing marker, check
`after_plan.design`. Follow the filtering and invocation rules in Pre-Execution
Checks for the hooks at each marker, in YAML order. Continue from the marker
after mandatory hooks finish, or immediately if no hooks apply.
1. **Setup**: Run `{SCRIPT}` from repo root and parse JSON for FEATURE_SPEC, IMPL_PLAN, FEATURE_DIR, BRANCH. For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load context**: Read FEATURE_SPEC and `/memory/constitution.md`. Load IMPL_PLAN template (already copied).
Expand All @@ -68,7 +74,9 @@ You **MUST** consider the user input before proceeding (if not empty).
- Fill Constitution Check section from constitution
- Evaluate gates (ERROR if violations unjustified)
- Phase 0: Generate research.md (resolve all NEEDS CLARIFICATION)
<!-- section: design -->
- Phase 1: Generate data-model.md, contracts/, quickstart.md
<!-- /section: design -->
- Re-evaluate Constitution Check post-design
## Mandatory Post-Execution Hooks
Expand Down
8 changes: 8 additions & 0 deletions templates/commands/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ You **MUST** consider the user input before proceeding (if not empty).
## Outline
At the opening generate marker, check the literal key `before_tasks.generate`
under `hooks` in `.specify/extensions.yml`. At its closing marker, check
`after_tasks.generate`. Follow the filtering and invocation rules in
Pre-Execution Checks for the hooks at each marker, in YAML order. Continue
from the marker after mandatory hooks finish, or immediately if no hooks apply.
1. **Setup**: Run `{SCRIPT}` from repo root and parse FEATURE_DIR, TASKS_TEMPLATE_CONTENT, TASKS_TEMPLATE, and AVAILABLE_DOCS list. `FEATURE_DIR` and `TASKS_TEMPLATE` must be absolute paths when provided. `AVAILABLE_DOCS` is a list of document names/relative paths available under `FEATURE_DIR` (for example `research.md` or `contracts/`). For single quotes in args like "I'm Groot", use escape syntax: e.g 'I'\''m Groot' (or double-quote if possible: "I'm Groot").
2. **Load design documents**: Read from FEATURE_DIR:
Expand All @@ -68,6 +74,7 @@ You **MUST** consider the user input before proceeding (if not empty).
- **IF EXISTS**: Load `/memory/constitution.md` for project principles and governance constraints
- Note: Not all projects have all documents. Generate tasks based on what's available.
<!-- section: generate -->
3. **Execute task generation workflow**:
- Load plan.md and extract tech stack, libraries, project structure
- Load spec.md and extract user stories with their priorities (P1, P2, P3, etc.)
Expand All @@ -92,6 +99,7 @@ You **MUST** consider the user input before proceeding (if not empty).
- Dependencies section showing story completion order
- Parallel execution examples per story
- Implementation strategy section (MVP first, incremental delivery)
<!-- /section: generate -->
## Mandatory Post-Execution Hooks
Expand Down
20 changes: 20 additions & 0 deletions tests/test_command_template_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,26 @@ def test_hook_templates_discovered():
)


@pytest.mark.parametrize(
("command", "section", "before", "inside", "after"),
[
("plan", "design", "Phase 0: Generate research.md", "Phase 1: Generate data-model.md",
"Re-evaluate Constitution Check post-design"),
("tasks", "generate", "**Load design documents**", "**Generate tasks.md**",
"## Mandatory Post-Execution Hooks"),
],
)
def test_section_hooks_bracket_the_intended_work(command, section, before, inside, after):
text = (TEMPLATES_DIR / f"{command}.md").read_text(encoding="utf-8")
opening = f"<!-- section: {section} -->"
closing = f"<!-- /section: {section} -->"
assert text.count(opening) == text.count(closing) == 1
assert f"`before_{command}.{section}`" in text
assert f"`after_{command}.{section}`" in text
assert text.index(before) < text.index(opening) < text.index(inside)
assert text.index(inside) < text.index(closing) < text.index(after)


@pytest.mark.parametrize("name", HOOK_TEMPLATES)
def test_unreadable_manifest_is_never_skipped_silently(name: str):
text = (TEMPLATES_DIR / name).read_text(encoding="utf-8")
Expand Down
40 changes: 38 additions & 2 deletions tests/test_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -889,8 +889,44 @@ def test_empty_provides_and_no_hooks_keeps_its_own_message(
):
ExtensionManifest(manifest_path)

def test_hooks_not_dict_rejected(self, temp_dir, valid_manifest_data):
"""Test manifest with hooks as a list is rejected."""
def test_section_hook_bindings(self, temp_dir, valid_manifest_data):
import yaml

command = "speckit.test-ext.hello"
review = "speckit.test-ext.review"
valid_manifest_data["provides"]["commands"].append({"name": review, "file": "commands/review.md"})
valid_manifest_data["hooks"] = [
{"before": "plan", "command": command},
{"before": "plan.design", "command": command, "optional": False},
{"after": "tasks.generate", "command": command, "prompt": "Review tasks?"},
{"before": "plan.design", "command": review},
]
manifest_path = temp_dir / "extension.yml"
manifest_path.write_text(yaml.safe_dump(valid_manifest_data), encoding="utf-8")
executor = HookExecutor(temp_dir)
executor.register_hooks(ExtensionManifest(manifest_path))

assert [h["command"] for h in executor.get_hooks_for_event("before_plan")] == [command]
design_hooks = executor.get_hooks_for_event("before_plan.design")
assert [(h["command"], h["optional"]) for h in design_hooks] == [(command, False), (review, True)]
assert executor.get_hooks_for_event("after_tasks.generate")[0]["prompt"] == "Review tasks?"
assert not executor.get_hooks_for_event("after_tasks")

@pytest.mark.parametrize("target", [
{}, {"before": "plan.design", "after": "tasks.generate"},
{"after": None}, {"before": "plan."},
])
def test_invalid_hook_position(self, temp_dir, valid_manifest_data, target):
import yaml

valid_manifest_data["hooks"] = [{"command": "speckit.test-ext.hello", **target}]
manifest_path = temp_dir / "extension.yml"
manifest_path.write_text(yaml.safe_dump(valid_manifest_data), encoding="utf-8")
with pytest.raises(ValidationError, match="Invalid hooks"):
ExtensionManifest(manifest_path)

def test_hook_bindings_must_be_mappings(self, temp_dir, valid_manifest_data):
"""A list of strings is not a list of hook bindings."""
import yaml

valid_manifest_data["hooks"] = ["not", "a", "dict"]
Expand Down