Repository navigation
feat(events): add portable hook interpreter fallback and pre-flight checks #5721
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dlwlgnsrhy
wants to merge
2
commits into
github:main
Choose a base branch
from
dlwlgnsrhy:feat/portable-hook-interpreter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,827
−46
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """Explicit MCP dispositions for the complete ``specify event`` hierarchy. | ||
| Neither ``event.check`` nor ``event.run`` has a shared typed operation and | ||
| MCP adapter yet; unavailable records declare their conservative capability and | ||
| network-access union alongside concrete reasons per ``design/mcp.md``. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import Literal | ||
|
|
||
| from mcp.server import MCPServer | ||
|
|
||
| EventOperationId = Literal["event.check", "event.run"] | ||
| EventCliPath = Literal["specify event check", "specify event run"] | ||
| EventToolName = Literal["specify_event_check", "specify_event_run"] | ||
| EventDisposition = Literal["available", "unavailable", "excluded"] | ||
| EventCapability = Literal[ | ||
| "local-read", "project-write", "execution", "self-modifying" | ||
| ] | ||
| EventNetworkAccess = Literal["none", "optional", "required"] | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class EventToolInventory: | ||
| """One hierarchy-owned MCP disposition for a registered event CLI leaf.""" | ||
|
|
||
| operation_id: EventOperationId | ||
| cli_path: EventCliPath | ||
| mcp_tool_name: EventToolName | ||
| contract_version: str | None | ||
| disposition: EventDisposition | ||
| disposition_reason: str | None | ||
| capabilities: frozenset[EventCapability] | ||
| network_access: EventNetworkAccess | ||
|
|
||
|
|
||
| EVENT_TOOLS = ( | ||
| EventToolInventory( | ||
| operation_id="event.check", | ||
| cli_path="specify event check", | ||
| mcp_tool_name="specify_event_check", | ||
| contract_version=None, | ||
| disposition="unavailable", | ||
| disposition_reason=( | ||
| "The event.check CLI leaf performs project resolution, adapter " | ||
| "loading, and output rendering in command_check without a shared " | ||
| "typed operation or MCP adapter yet." | ||
| ), | ||
| capabilities=frozenset({"local-read", "execution"}), | ||
| network_access="none", | ||
| ), | ||
| EventToolInventory( | ||
| operation_id="event.run", | ||
| cli_path="specify event run", | ||
| mcp_tool_name="specify_event_run", | ||
| contract_version=None, | ||
| disposition="unavailable", | ||
| disposition_reason=( | ||
| "The event.run CLI leaf reads raw stdin and executes project event " | ||
| "command scripts directly from command_run; no shared typed " | ||
| "operation or MCP adapter is defined." | ||
| ), | ||
| capabilities=frozenset({"local-read", "project-write", "execution"}), | ||
| network_access="optional", | ||
| ), | ||
| ) | ||
|
|
||
|
|
||
| def register(server: MCPServer, *, launch_directory: Path) -> None: | ||
| """Register available event tools from the explicit inventory (none yet).""" | ||
| _ = (server, launch_directory) | ||
| for item in EVENT_TOOLS: | ||
| if item.disposition == "available": | ||
| raise NotImplementedError( | ||
| f"No MCP adapter registered for available event tool {item.operation_id!r}" | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| """CLI adapter for ``specify event check``.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import typer | ||
|
|
||
| from . import event_app | ||
|
|
||
|
|
||
| @event_app.command("check") | ||
| def event_check( | ||
| integration: str | None = typer.Option( | ||
| None, | ||
| "--integration", | ||
| "-i", | ||
| help="Check a specific event-capable integration instead of all installed integrations.", | ||
| ), | ||
| json_output: bool = typer.Option( | ||
| False, | ||
| "--json", | ||
| help="Emit machine-readable JSON output.", | ||
| ), | ||
| ) -> None: | ||
| """Verify that generated event hooks can resolve a runnable Python interpreter.""" | ||
| from .._project import ( | ||
| ProjectResolutionError, | ||
| _resolve_init_dir_override, | ||
| preflight_project_policy, | ||
| render_project_error, | ||
| ) | ||
| from ..integrations.installer import IntegrationInstallError, project_integrations | ||
| from . import ( | ||
| EventCheckError, | ||
| check_project_event_interpreters, | ||
| format_missing_hook_interpreter_message, | ||
| ) | ||
|
|
||
| try: | ||
| project_root = _resolve_init_dir_override() | ||
| if project_root is None: | ||
| project_root = Path.cwd() | ||
| preflight_project_policy(project_root) | ||
| except ProjectResolutionError as exc: | ||
| render_project_error(exc) | ||
|
|
||
| try: | ||
| with project_integrations(project_root): | ||
| results = check_project_event_interpreters( | ||
| project_root, integration_key=integration | ||
| ) | ||
| except (EventCheckError, IntegrationInstallError, OSError, ValueError) as exc: | ||
| if json_output: | ||
| error_payload: dict[str, Any] = { | ||
| "ok": False, | ||
| "project_root": str(project_root), | ||
| "error": str(exc), | ||
| "integrations": [], | ||
| } | ||
| if isinstance(exc, EventCheckError): | ||
| error_payload["error_code"] = exc.code | ||
| error_payload["error_details"] = exc.details | ||
| error_payload["retryable"] = exc.retryable | ||
| typer.echo(json.dumps(error_payload, indent=2)) | ||
| else: | ||
| typer.echo(f"Error: {exc}", err=True) | ||
| raise typer.Exit(code=1) from None | ||
|
|
||
| all_ok = all(status.available for _, _, status in results) | ||
| entries = [ | ||
| { | ||
| "integration": key, | ||
| "hooks_installed": installed, | ||
| "available": status.available, | ||
| "interpreter": status.interpreter, | ||
| "resolved_path": status.resolved_path, | ||
| "resolution_kind": status.resolution_kind, | ||
| "tried": list(status.tried), | ||
| "message": ( | ||
| None | ||
| if status.available | ||
| else (status.message or format_missing_hook_interpreter_message(status, key)) | ||
| ), | ||
| } | ||
| for key, installed, status in results | ||
| ] | ||
|
|
||
| if json_output: | ||
| typer.echo( | ||
| json.dumps( | ||
| { | ||
| "ok": all_ok, | ||
| "project_root": str(project_root), | ||
| "integrations": entries, | ||
| }, | ||
| indent=2, | ||
| ) | ||
| ) | ||
| raise typer.Exit(code=0 if all_ok else 1) | ||
|
|
||
| if not entries: | ||
| typer.echo("No event-capable integrations are installed in this project.") | ||
| raise typer.Exit(code=0) | ||
|
|
||
| for entry in entries: | ||
| hooks_note = "hooks installed" if entry["hooks_installed"] else "no hooks installed" | ||
| if entry["available"]: | ||
| detail = entry["resolved_path"] or entry["interpreter"] | ||
| typer.echo( | ||
| f"[OK] {entry['integration']} ({hooks_note}): " | ||
| f"{entry['interpreter']} -> {detail} [{entry['resolution_kind']}]" | ||
| ) | ||
| else: | ||
| typer.echo( | ||
| f"[FAIL] {entry['integration']} ({hooks_note}): {entry['message']}", | ||
| err=True, | ||
| ) | ||
|
|
||
| raise typer.Exit(code=0 if all_ok else 1) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """Shared hook-interpreter pre-flight checks for workflow steps that dispatch CLIs. | ||
|
|
||
| When a workflow ``command`` or ``prompt`` step relies on Specify event hooks — | ||
| either because the step explicitly requests hook-delivered behavior (such as | ||
| ``additional_context``) or because the target integration has active Specify | ||
| hooks installed in the project — dispatching the agent CLI without a runnable | ||
| hook Python interpreter would fail open inside the agent and silently drop hook | ||
| behavior. This module validates interpreter availability before the CLI starts. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Mapping | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| from specify_cli.events import ( | ||
| HookInterpreterError, | ||
| HookInterpreterStatus, | ||
| has_installed_integration_events, | ||
| preflight_hook_interpreter, | ||
| ) | ||
| from specify_cli.integrations.base import IntegrationBase | ||
|
|
||
|
|
||
| def step_requires_hooks( | ||
| config: Mapping[str, Any] | None, | ||
| integration: IntegrationBase, | ||
| project_root: Path | None, | ||
| ) -> bool: | ||
| """Return True when dispatching *config* through *integration* relies on hooks.""" | ||
| if not integration.supports_events(): | ||
| return False | ||
| if config and _has_explicit_hook_dependency(config): | ||
| return True | ||
| target_root = project_root if project_root is not None else Path.cwd() | ||
| return has_installed_integration_events(integration, target_root) | ||
|
|
||
|
|
||
| def _has_explicit_hook_dependency(config: Mapping[str, Any]) -> bool: | ||
| """Return True when *config* declares a hook-dependent step field.""" | ||
| additional_context = config.get("additional_context") | ||
| if isinstance(additional_context, str): | ||
| return bool(additional_context.strip()) | ||
| if isinstance(additional_context, (list, dict)): | ||
| return bool(additional_context) | ||
| return bool(additional_context) | ||
|
|
||
|
|
||
| def check_step_hook_interpreter( | ||
| config: Mapping[str, Any] | None, | ||
| integration: IntegrationBase, | ||
| project_root: Path | None, | ||
| ) -> HookInterpreterStatus | None: | ||
| """Run the hook-interpreter pre-flight check before spawning an agent CLI. | ||
|
|
||
| Returns ``None`` when the step does not depend on event hooks, returns the | ||
| resolved :class:`HookInterpreterStatus` when the interpreter is available, | ||
| and raises :class:`HookInterpreterError` with an actionable remediation | ||
| message when the interpreter cannot be resolved. | ||
| """ | ||
| if not integration.supports_events(): | ||
| return None | ||
| explicit = bool(config and _has_explicit_hook_dependency(config)) | ||
| target_root = project_root if project_root is not None else Path.cwd() | ||
| return preflight_hook_interpreter(integration, target_root, required=explicit) | ||
|
|
||
|
|
||
| def hook_preflight_failure( | ||
| label: str, | ||
| config: Mapping[str, Any], | ||
| error: HookInterpreterError, | ||
| ) -> str: | ||
| """Format an actionable workflow step failure for a missing hook interpreter.""" | ||
| return f"{label} step {config.get('id', '?')!r}: {error}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.