From d47034ba6c72ded3e658e38706dbf7af64bd9854 Mon Sep 17 00:00:00 2001 From: Yui1x <233574355+Yui1x@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:54:47 +0800 Subject: [PATCH] feat(extensions): run hooks at named command sections Allow extension authors to register before/after bindings at the design and task-generation boundaries without replacing a core template. Assisted-by: OpenAI Codex (model: GPT-6, autonomous) --- docs/extensions/api.md | 32 ++++++++++++++++++++- src/specify_cli/extensions/__init__.py | 30 +++++++++++++++++-- templates/commands/plan.md | 8 ++++++ templates/commands/tasks.md | 8 ++++++ tests/test_command_template_hooks.py | 20 +++++++++++++ tests/test_extensions.py | 40 ++++++++++++++++++++++++-- 6 files changed, 133 insertions(+), 5 deletions(-) diff --git a/docs/extensions/api.md b/docs/extensions/api.md index 2bc3b5256f..9e6024d089 100644 --- a/docs/extensions/api.md +++ b/docs/extensions/api.md @@ -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 @@ -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): diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index dc0ab5a7ee..67743af2a4 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -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.""" @@ -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) diff --git a/templates/commands/plan.md b/templates/commands/plan.md index d559e517ae..8da64a3b71 100644 --- a/templates/commands/plan.md +++ b/templates/commands/plan.md @@ -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). @@ -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) + - Phase 1: Generate data-model.md, contracts/, quickstart.md + - Re-evaluate Constitution Check post-design ## Mandatory Post-Execution Hooks diff --git a/templates/commands/tasks.md b/templates/commands/tasks.md index d2dca80933..69c5f1390e 100644 --- a/templates/commands/tasks.md +++ b/templates/commands/tasks.md @@ -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: @@ -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. + 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.) @@ -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) + ## Mandatory Post-Execution Hooks diff --git a/tests/test_command_template_hooks.py b/tests/test_command_template_hooks.py index d1c7677bae..0eca6d25d8 100644 --- a/tests/test_command_template_hooks.py +++ b/tests/test_command_template_hooks.py @@ -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"" + closing = f"" + 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") diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 77a2a0525e..4c7e7871a0 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -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"]