Repository navigation
Description
Problem Statement
Spec Kit's extension lifecycle hooks (hooks.before_<cmd> / hooks.after_<cmd> in .specify/extensions.yml) currently rely entirely on static prompt boilerplate embedded in each core command template (templates/commands/*.md). This causes three concrete gaps:
presets/leanand customstrategy: replacepresets silently drop extension hooks:
Any preset overriding core command templates withstrategy: replaceeither duplicates ~65–75 lines of YAML-parsing hook instructions per template or silently ignores installed extensions (such asgitoragent-context). Today,specify preset add leanstopsbefore_*/after_*hooks from firing.HookExecutorexists in Python, but shipped prompts bypass it:
HookExecutorinsrc/specify_cli/extensions/__init__.py(get_hooks_for_event,should_execute_hook,check_hooks_for_event,format_hook_message,_render_hook_invocation) already implementsprioritysorting,conditionevaluation (config.*,env.*), and agent-specific invocation formatting. Shipped command templates instead instruct the LLM to read.specify/extensions.ymldirectly—ignoringpriorityand skipping hooks with non-emptyconditionexpressions (as noted indesign/extension.md).- Unconditional prompt overhead and output noise:
All nine core command templates carry pre- and post-hook boilerplate on every invocation even when zero extensions or hooks are configured.
Proposed Solution
Introduce an opt-in bundled companion extension (e.g., hook-bridge) powered by Spec Kit's existing runtime events: dispatcher (.specify/events.py / src/specify_cli/events/):
- Integration scope: Derived from the
eventsabstraction — support integrations with verified model-context injection onuser_prompt_submit(claude,codex,gemini,qwen,tabnine,devin,opencode); event support alone is insufficient.cursor-agent(suppress),vibe(nouser_prompt_submitevent), andcopilot(userPromptSubmittedcommand hooks dropstdout; see [Bug]: Copilot integration maps user_prompt_submit to additionalContext, which Copilot command hooks drop #5544), along with file-only integrations, are excluded in v1. Document the supported integrations and their event-specific delivery behavior. - Declare a
user_prompt_submithandler in the bundled extension'sextension.yml(backed by a standalone Python script with thinsh/pswrappers, following existing bundled extensions likegitandagent-contextwithout importingspecify_cliat runtime). - On
user_prompt_submit, deterministically parse the submitted prompt ({"prompt": ...}and OpenCodechat.messageoutput.parts) to detect Spec Kit phase commands (constitution,specify,clarify,plan,tasks,checklist,analyze,implement,converge, etc.) across slash (/speckit.<cmd>,/speckit-<cmd>), dollar-skill ($speckit-<cmd>), and/skill:speckit-<cmd>invocation styles. - Support optional command filtering in
hook-bridge-config.yml(withlocal-config.ymloverride) viainclude_commandsandexclude_commandsso users can scope the bridge to replaced commands (e.g., the 5 commands replaced bypresets/lean) without duplicate instructions on non-overridden core templates. - Resolve
before_<phase>andafter_<phase>with full contract parity toHookExecutor(enabled, ascendingpriority,config.*/env.*conditionexpressions, and agent-specific invocation rendering from.specify/init-options.json), usingPyYAMLwhen available and a lightweight stdlib reader for Spec Kit's configuration YAML subset whenPyYAMLis absent. - Zero-hook fast path: Emit
0 bytesonstdoutwhen the prompt is not an eligible phase command or no executable hooks match, adding zero context tokens. - Just-in-time context injection: Only when executable hooks exist for the detected phase, emit concise pre-/post-hook instructions (
EXECUTE_COMMAND/EXECUTE_COMMAND_INVOCATIONforoptional: false, prompt/hint foroptional: true), which.specify/events.pywraps in the supported integration's native context envelope foruser_prompt_submit. - Intended use and non-goals: Pair the bridge with
presets/leanand custom presets whose commands do not already handle extension hooks. Do not combine it on the same command with templates that already perform their own hook handling (useinclude_commands/exclude_commandsfor partial presets likelean). Automatic detection of hook-handling prompt content, deduplication, and changes to core command templates are out of scope. - Update extension & preset authoring documentation: Document the new bundled bridge in
docs/extensions/developing.md,docs/extensions/api.md,docs/presets/developing.md(plusdesign/extension.md,extensions/README.md, andpresets/lean/README.md) so extension and preset authors know:priorityandcondition(config.*,env.*) are evaluated deterministically when the bridge extension is installed on integrations supporting context injection atuser_prompt_submit(whereas core template boilerplate alone falls back to YAML order and skips hooks withcondition).- Presets without their own hook handling (like
lean) do not need to duplicate hook YAML-parsing boilerplate when paired with the bridge extension, and partial presets can scope commands viainclude_commands/exclude_commands. Commands that already handle hooks must not additionally use the bridge, to avoid duplicate hook instructions; no automatic detection or validation is provided. Integrations without context injection atuser_prompt_submit(including Cursor, Vibe, Copilot until [Bug]: Copilot integration maps user_prompt_submit to additionalContext, which Copilot command hooks drop #5544 is addressed, and file-only integrations) still require template-level hook handling.
Alternatives Considered
- Copying hook boilerplate into
presets/leantemplates: Defeats the purpose oflean("just the prompt, just the artifact"), keeps hook execution non-deterministic, and still ignorespriorityandcondition. - Removing hook boilerplate from core templates immediately: Breaks hooks on file-only integrations that do not support
user_prompt_submitruntime events. Shipping this as an opt-in bundled extension preserves existing behavior while enabling deterministic hook resolution on integrations supporting context injection atuser_prompt_submit. - Resolving
after_<phase>onstopevents:stophooks cannot reliably trigger a new slash-command/skill turn across all agents, whereas resolving bothbefore_<phase>andafter_<phase>duringuser_prompt_submitgives uniform pre/post obligations inside the active turn.
Component
Agent integrations (command files, workflows)
AI Agent (if applicable)
Integrations with verified context injection at user_prompt_submit (claude, codex, gemini, qwen, tabnine, devin, opencode). cursor-agent, vibe, copilot (#5544), and file-only integrations are excluded in v1.
Use Cases
- Using
presets/leantogether withextensions/git(before_specify,before_plan, etc.) andextensions/agent-context(after_specify,after_plan) so lifecycle hooks still run automatically without prompt boilerplate. - Authoring custom
strategy: replacepresets without their own hook handling that stay minimal without duplicating hook YAML-parsing instructions. - Defining extension hooks with
priorityordering andconditionexpressions (config.*/env.*) and having them evaluated deterministically.
Acceptance Criteria
- Bundled extension added under
extensions/and registered inextensions/catalog.json(plus packaging/tests as needed). - Supported integrations (
claude,codex,gemini,qwen,tabnine,devin,opencode) are documented and verified specifically for context injection atuser_prompt_submit; negative tests cover non-injecting event paths (cursor-agentsuppress,vibeomitted event) so event support alone is never treated as bridge support. -
user_prompt_submithandler detects Spec Kit phase commands across slash, skill-slash, and dollar-skill invocation formats from standard{"prompt": ...}payloads and OpenCodechat.messageoutput.partspayloads, honoring optionalinclude_commands/exclude_commandsconfig (hook-bridge-config.yml+local-config.yml). - Standalone handler (no runtime
specify_cliimport) resolvesbefore_<phase>andafter_<phase>with contract-testedHookExecutorparity (enabled,priority,condition, and invocation rendering), both with and withoutPyYAML. - Emits 0 bytes on
stdoutwhen the prompt is not an eligible Spec Kit phase command or no executable hooks match. - Emits agent-formatted pre/post hook instructions wrapped by
.specify/events.pywhen executable hooks match. - Documentation explicitly limits bridge use to commands without their own hook handling, provides
include_commands/exclude_commandsguidance (includingpresets/leanand custom preset migration), warns against combining it with existing hook-handling commands, and states that there is no automatic detection, validation, or deduplication. Core command templates remain unchanged. - Automated tests cover positive and negative cases (prompt matching across payload shapes,
include_commands/exclude_commands, zero-hook fast path,priorityordering,conditionevaluation,HookExecutorcontract parity with and withoutPyYAML, integration envelope conformance, and Windows PowerShell 5.1 compatibility if.ps1wrapper is included). - Extension and preset authoring docs updated (
docs/extensions/developing.md,docs/extensions/api.md,docs/presets/developing.md,design/extension.md,extensions/README.md,presets/lean/README.md) to explain the bundled bridge,priority/conditionevaluation on supported integrations vs. core templates, the event-specific support boundary, and guidance forstrategy: replacepreset authors.
Additional Context
- Approved in Discussion Deterministic HookExecutor bridge via user_prompt_submit runtime events (for lean and custom presets) #5527: Deterministic HookExecutor bridge via user_prompt_submit runtime events (for lean and custom presets) #5527
- Related prior issues and discussions: Issues [Feature]: Automatically run extensions #2104, Proposal: compress command templates ~23% (same semantics, fewer tokens per invocation) #2943, [Feature]: Let extensions contribute always-on instructions (not just on-demand commands + hooks) #4200; Discussions Extension Hooks output tainting interaction #3128, Workflow extension points — how should downstream add deterministic steps without overriding installed YAML? #3473, Workflows calling agent commands — are two extension mechanisms in one run indended or something to be optimized? #4557
- Copilot
userPromptSubmittedoutput-handling bug tracked separately in [Bug]: Copilot integration maps user_prompt_submit to additionalContext, which Copilot command hooks drop #5544
AI Disclosure
Drafted with the pi coding agent (provider: github-copilot, model: gemini-4-hydrogen, reasoning effort: high, human-supervised) based on Discussion #5527 and codebase inspection. The issue was posted on behalf of @markuswondrak without prior review of its text.
Disclosure correction by the pi coding agent (GitHub Copilot, model: gpt-6.1-terra, reasoning effort: high, interactive mode); removed an unsupported claim of prior review.
Scope clarification on behalf of @markuswondrak by the pi coding agent (provider: github-copilot, model: gpt-6.1-sol, reasoning effort: high, interactive/human-supervised mode): applied the agreed event-specific integration support boundary and corresponding documentation/test requirements.
Usage-boundary clarification on behalf of @markuswondrak by the pi coding agent (provider: github-copilot, model: gpt-6.1-sol, reasoning effort: high, interactive/human-supervised mode): recorded the agreed documentation-only boundary for commands without existing hook handling; no prompt inspection, validation, deduplication, or core-template changes.
Assessment clarifications synced on behalf of @markuswondrak by the pi coding agent (provider: github-copilot, model: gemini-4-carbon, reasoning effort: high, interactive/human-supervised mode): aligned v1 integration matrix (referencing #5544), added optional include_commands/exclude_commands config, and simplified runtime execution to a standalone script without importing specify_cli.
Activity
github-actions commentedon Nov 23, 2026
Feature assessment — deterministic-hook-bridge · Stage 1/5: Intake
Idea Intake: Deterministic HookExecutor bridge for runtime hook injection
Idea (as captured)
Restated
Introduce an optional bridge extension that computes applicable lifecycle hooks at runtime for phase commands, using the existing hook execution model instead of template-embedded YAML parsing. This should preserve minimal prompts for lean/replace presets, keep current behavior for unsupported integrations, and document strict usage boundaries to avoid duplicate hook instructions.
Origin & Context
First-Glance Unknowns
specify_cliimportability differs between local and ephemeral runtime execution paths?]github-actions commentedon Nov 23, 2026
Feature assessment — deterministic-hook-bridge · Stage 2/5: Research
Idea Research: Deterministic HookExecutor bridge via user_prompt_submit events
Users & Demand
Prior Art
.specify/events.pydispatcher and integration mappings), so an event-triggered bridge aligns with existing architecture instead of introducing a new execution channel. — [source:src/specify_cli/events/__init__.py;docs/extensions/api.md] (confidence: high)HookExecutoralready implements core logic the issue wants reused (enabled filtering,conditionevaluation onconfig.*/env.*,priorityordering, and invocation rendering), and design docs explicitly state core templates do not use this executor today. — [source:design/extension.mdlines 326–334;src/specify_cli/extensions/__init__.py] (confidence: high).specify/extensions.ymlparsing in prompt text (including condition-skipping behavior), validating the duplication/drift risk called out by the request. — [source:templates/commands/specify.mdpre-execution hook section; similar pattern across command templates] (confidence: high)presets/lean/README.md] (confidence: high)Market & Context
newsletters/2026-July.md;docs/extensions/api.md] (confidence: medium)Data & Constraints
user_prompt_submitto an envelope that can inject context, while Cursor maps the same canonical event tosuppressoutput, making Cursor ineligible for context injection through this event in current architecture. — [source:src/specify_cli/integrations/copilot/__init__.py;src/specify_cli/integrations/cursor_agent/__init__.py;tests/specify_cli/events/test_events.py] (confidence: high)extensions/catalog.json), so adding an opt-in bundled bridge is mechanically compatible with current packaging/discovery flow. — [source:extensions/catalog.json] (confidence: high)docs/extensions/api.md“Extension Runtime Events”] (confidence: high)Evidence Against the Idea
templates/commands/*.md] (confidence: high)src/specify_cli/integrations/cursor_agent/__init__.py;tests/specify_cli/events/test_events.py] (confidence: high)specify_cliis unavailable, which may increase implementation and parity-testing burden beyond a narrow bridge MVP. — [source: [Feature]: Deterministic HookExecutor bridge via user_prompt_submit runtime events (for lean and custom presets) #5532 acceptance criteria; ASSUMPTION on engineering cost] (confidence: medium)Gaps & Open Questions
Sources
design/extension.md(repository source)templates/commands/specify.md(repository source)src/specify_cli/extensions/__init__.py(repository source)src/specify_cli/events/__init__.py(repository source)src/specify_cli/integrations/copilot/__init__.py(repository source)src/specify_cli/integrations/cursor_agent/__init__.py(repository source)tests/specify_cli/events/test_events.py(repository source)docs/extensions/api.md(repository source)presets/lean/README.md(repository source)extensions/catalog.json(repository source)github-actions commentedon Nov 23, 2026
Feature assessment — deterministic-hook-bridge · Stage 3/5: Problem
Problem Definition: Non-deterministic extension hook behavior across presets and integrations
Problem Statement
Spec Kit users who adopt lean or custom replace-style presets can lose reliable extension hook behavior because hook handling currently depends on template-embedded parsing that is duplicated, omitted, or semantically inconsistent with runtime hook rules. This creates unpredictable extension outcomes across integrations and increases maintenance burden at the moment teams are trying to simplify and standardize their workflow.
Affected Users & Stakeholders
strategy: replacecommand templates — they may silently lose expected hook behavior or receive inconsistent hook execution semantics.priorityand conditional hooks — their extension behavior may differ from declared intent when templates bypass runtime hook semantics.Goals
Non-Goals
Success Metrics
Cost of Inaction
Preset and extension authors continue to choose between duplicated boilerplate and unreliable hook behavior, leading to inconsistent user experiences, avoidable support/debug effort, and reduced trust that extension declarations map to real runtime behavior.
Open Questions
github-actions commentedon Nov 23, 2026
Feature assessment — deterministic-hook-bridge · Stage 4/5: Concept
Concept: Deterministic hook delivery for lean/custom preset workflows
Options
Option A — Template-only documentation hardening (smallest viable)
Option B — Opt-in runtime hook bridge extension
Option C — Unified runtime-only hook model across all commands/integrations
Recommendation
Recommend Option B. It directly targets the stated pain (lean/custom preset duplication and non-deterministic hook semantics) while containing scope through opt-in adoption and explicit integration boundaries. It best aligns with the goals of deterministic behavior, reduced boilerplate, and compatibility preservation, without requiring an all-at-once migration.
Out of Scope (for the recommended option)
Assumptions to Validate
user_prompt_submitwithout introducing malformed output or user-visible noise.github-actions commentedon Nov 23, 2026
Feature assessment — deterministic-hook-bridge · Stage 5/5: Decision — verdict needs-clarification
Decision: Deterministic hook bridge for preset workflows
Scorecard
Verdict & Rationale
Verdict: needs-clarification. The idea appears valuable and directionally feasible, but the current evidence package is not yet strong enough for a clean
gobecause key support boundaries and risk controls are unresolved. Specifically, confidence depends on an explicit integration support matrix, enforcement/mitigation for duplicate hook handling, and clearer parity expectations for runtime-vs-fallback behavior.If needs-clarification
user_prompt_submitcontext injection, with explicit exclusions and rationale.]specify_cliis unavailable.]If go — Handoff to
/speckit-specifyNot applicable until blocking clarifications above are resolved.
mnriem commentedon Nov 23, 2026
@markuswondrak As I stated before it is a go, but please keep in mind that I would like to see the open questions answered so we know what we specifically are targeting
markuswondrak commentedon Nov 23, 2026
Clarifications for the open questions from the feature assessment, posted on behalf of @markuswondrak. These are the decisions the implementation will be built and reviewed against.
1. Supported integrations (derived from the
eventsabstraction)events.user_prompt_submitmechanism (stdinJSON -> plain-textstdout->.specify/events.pycontext envelope). The extension itself contains no integration-specific branching or agent lists (beyond reading.specify/init-options.jsonto render the active agent's hook invocation syntax, matchingHookExecutor).user_prompt_submitis mapped inCANONICAL_TO_NATIVE, its resolvedevents_context_envelopeforuser_prompt_submitis not"suppress", and its native runtime actually consumes command-hook output as model context.claude,codex—UserPromptSubmitwithplainstdout passthroughgemini,tabnine—BeforeAgentwithhookSpecificOutput.additionalContextqwen,devin—UserPromptSubmitwithhookSpecificOutput.additionalContextopencode—chat.messageTS plugin injecting a syntheticTextPartintooutput.partscursor-agent— mapsuser_prompt_submittobeforeSubmitPromptwith envelope"suppress"(block/allow only, no context-injection channel).vibe— native hook schema (pre_tool,post_tool,post_agent) has nouser_prompt_submitevent.copilot— althoughCopilotIntegrationcurrently setsadditionalContextonuserPromptSubmitted, Copilot command hooks dropstdoutonuserPromptSubmitted(filed separately as [Bug]: Copilot integration maps user_prompt_submit to additionalContext, which Copilot command hooks drop #5544). Until Copilot per-prompt context injection is supported by Spec Kit's event layer,copilotis documented as unsupported for the bridge.generic,cline,pi,goose,zed, …) — do not install or run.specify/events.py; they continue to rely on template-level hook handling.additional_contexton workflowcommandsteps for curated context provisioning #5533 (additional_contexton workflowcommandsteps): Orthogonal, with no ordering dependency. [Feature]: Addadditional_contexton workflowcommandsteps for curated context provisioning #5533 uses a built-insession_starthandler scoped to child-process env (SPECKIT_ADDITIONAL_CONTEXT), while [Feature]: Deterministic HookExecutor bridge via user_prompt_submit runtime events (for lean and custom presets) #5532 is an opt-in bundled extension onuser_prompt_submit.2. Required conformance test matrix
Deterministic CI tests cover the two runtime boundaries without launching live agent CLIs:
stdinpayload extraction (handler unit tests):{"prompt": "..."}) used byclaude,codex,gemini,qwen,tabnine, anddevin.chat.messageplugin payload ({"input": ..., "output": {"parts": [{"type": "text", "text": "..."}]}})./speckit.<cmd>,/speckit-<cmd>,$speckit-<cmd>, and/skill:speckit-<cmd>(plus negative cases: ordinary chat text, non-phase commands, malformed/empty JSON -> exit0and0 bytesonstdout)..specify/events.pyoutput shape (plain,hookSpecificOutputwith the integration's nativehookEventName, and OpenCodechat.messagesyntheticTextPartgeneration).cursor-agent(suppress->0 bytes),vibe(user_prompt_submitskipped cleanly), and zero-hook fast path emitting0 bytesunder every envelope (never an empty JSON wrapper)..py,.sh, and Windows PowerShell 5.1.ps1.3. Duplicate-handling boundary, command filtering, and migration guidance
templates/commands/*.md) remain unchanged, and the bridge does not inspect Markdown files to guess whether a command already handles hooks.hook-bridge-config.yml+ gitignoredlocal-config.ymloverride):include_commands: []— empty by default (all recognized phase commands eligible); when non-empty, acts as an explicit allowlist.exclude_commands: []— explicit blocklist (takes precedence overinclude_commands), accepting short phase names (plan) or full command IDs (speckit.plan).replacepresets without magic: for example,presets/leanreplaces 5 of the 9 core commands (constitution,specify,plan,tasks,implement) while leavingclarify,checklist,analyze, andconvergeon core templates. Settinginclude_commands: [constitution, specify, plan, tasks, implement]prevents duplicate hook instructions on the 4 non-overridden core commands.presets/lean/README.md,docs/presets/developing.md,docs/extensions/developing.md):include_commandsconfiguration forpresets/lean.strategy: replacepresets that previously copied the YAML hook-parsing block: either remove the copied hook block when adoptinghook-bridgeon supported integrations, or list those commands inexclude_commands.4. Standalone runtime execution (no
specify_cliimport) & output formatspecify_cliimport dropped: Following existing bundled extensions (extensions/agent-context,extensions/git), the bridge script will not importspecify_cliat runtime. Importing the full CLI package on everyuser_prompt_submitturn adds unnecessary startup overhead and creates two divergent execution modes. Instead, the extension uses one lightweight Python implementation (PyYAMLwhen available in the interpreter, with a small stdlib reader for Spec Kit's configuration YAML subset whenPyYAMLis absent; if a hand-edited YAML file uses unsupported YAML constructs withoutPyYAML, report the parse error onstderrrather than silently skipping mandatory hooks or corruptingstdout).HookExecutor: Automated contract tests run identical.specify/extensions.yml,<ext>-config.yml/local-config.yml,env.*, and.specify/init-options.jsonfixtures through bothHookExecutorand the bridge script, asserting identical hook selection (enabled), ascendingpriorityordering (stable on ties), evaluation of all 5HookExecutorcondition forms (config.<path> is set,==,!=;env.<VAR> is set,==,!=), and agent-specific command invocation rendering.HookExecutor.format_hook_message()'s per-hook block syntax (**Automatic Hook**withEXECUTE_COMMAND/EXECUTE_COMMAND_INVOCATION, and**Optional Hook**withPrompt/To execute), framed by concise phase-level instructions distinguishingbefore_<phase>(run mandatory hooks and wait before starting the phase; surface optional hooks first) fromafter_<phase>(run/offer after the phase completes). When neitherbefore_<phase>norafter_<phase>has executable hooks (including when all conditions evaluate toFalse),stdoutis strictly0 bytes.5. Unresolved historical reference IDs (#3128, #3473, #4557)
AI disclosure: Drafted on behalf of @markuswondrak by the pi coding agent (provider:
github-copilot, model:gemini-4-carbon, reasoning effort:high, interactive and human-supervised). Each decision was discussed and approved by @markuswondrak based on codebase inspection.markuswondrak commentedon Nov 25, 2026
@mnriem does this work for you?