diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 66bef8154c..bdeb15f544 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -4,12 +4,13 @@ - ``resolve_events`` — layered event resolution (CLI flag → YAML override → extension-declared → built-in). - ``collect_extension_events`` — scan installed extension.yml files for ``events:``. - ``install_integration_events`` / ``remove_integration_events`` — entry points called from ``IntegrationBase.setup()`` / ``teardown()``. +- ``check_hook_interpreter`` / ``check_integration_hook_interpreter`` / ``preflight_hook_interpreter`` — interpreter availability checks shared by installation, workflow pre-flight, and ``specify event check``. The singular CLI namespace intentionally maps to the plural Python package. ``specify_cli.events`` is an established domain API and monkeypatch boundary, so preserving it takes precedence over matching the CLI spelling on disk. -``command_run`` contains the nested CLI adapter; this module owns the domain -API, Typer application, and registration. +``command_run`` and ``command_check`` contain the nested CLI adapters; this +module owns the domain API, Typer application, and registration. """ from __future__ import annotations @@ -18,19 +19,23 @@ import json import logging import os +import platform import re import shlex import shutil -import sys +import stat import subprocess -import platform +import sys +import tomllib +from dataclasses import dataclass from pathlib import Path, PurePosixPath, PureWindowsPath from typing import TYPE_CHECKING, Any -import yaml import typer +import yaml -from ..integrations._file_changes import unlink as _unlink_file, write_text as _write_text +from ..integrations._file_changes import unlink as _unlink_file +from ..integrations._file_changes import write_text as _write_text if TYPE_CHECKING: from collections.abc import Iterable @@ -461,6 +466,7 @@ def main(): // another workspace, in which case process.cwd() points at the wrong project. let DISPATCHER = ''; let INTERPRETER = ''; +let INTERPRETER_ARGS: string[] = []; function canImportSpecifyCli(py: string): boolean {{ // R2: a project-local venv commonly lacks Spec Kit (installed globally or @@ -477,18 +483,54 @@ def main(): }} }} +function canRunPython(cmd: string, prefixArgs: string[] = []): boolean {{ + try {{ + execFileSync(cmd, [...prefixArgs, '-I', '-S', '-c', 'pass'], {{ + stdio: ['ignore', 'ignore', 'ignore'], + timeout: 10000, + }}); + return true; + }} catch (e) {{ + return false; + }} +}} + function resolveDispatcher(directory: string): void {{ DISPATCHER = path.join(directory, '.specify', 'events.py'); + INTERPRETER_ARGS = []; // Prefer a project-local venv interpreter that can import specify_cli (R2), - // then fall back to a platform-appropriate PATH interpreter (S2: python on - // Windows, where python3 is commonly absent; python3 on POSIX). + // then a runnable PATH interpreter (S2: python -> py -3 on Windows; + // python3 -> python on POSIX), then any runnable project venv interpreter. + const fs = require('fs'); const venvPy = path.join(directory, '.venv', 'bin', 'python'); const venvWin = path.join(directory, '.venv', 'Scripts', 'python.exe'); - INTERPRETER = ( - (require('fs').existsSync(venvPy) && canImportSpecifyCli(venvPy) && venvPy) || - (require('fs').existsSync(venvWin) && canImportSpecifyCli(venvWin) && venvWin) || - (process.platform === 'win32' ? 'python' : 'python3') - ) as string; + if (fs.existsSync(venvPy) && canImportSpecifyCli(venvPy)) {{ + INTERPRETER = venvPy; + return; + }} + if (fs.existsSync(venvWin) && canImportSpecifyCli(venvWin)) {{ + INTERPRETER = venvWin; + return; + }} + const candidates: Array<[string, string[]]> = process.platform === 'win32' + ? [['python', []], ['py', ['-3']]] + : [['python3', []], ['python', []]]; + for (const [cmd, args] of candidates) {{ + if (canRunPython(cmd, args)) {{ + INTERPRETER = cmd; + INTERPRETER_ARGS = args; + return; + }} + }} + if (fs.existsSync(venvPy) && canRunPython(venvPy)) {{ + INTERPRETER = venvPy; + return; + }} + if (fs.existsSync(venvWin) && canRunPython(venvWin)) {{ + INTERPRETER = venvWin; + return; + }} + INTERPRETER = process.platform === 'win32' ? 'python' : 'python3'; }} function runEvent(command: string, event: string, input: any, output: any, timeoutSec: number): string {{ @@ -502,7 +544,7 @@ def main(): // returned so context-injection hooks (experimental.chat.system.transform, // chat.message) can push it into their outputs; stderr stays inherited so // dispatcher errors remain visible (C11). - return execFileSync(INTERPRETER, [DISPATCHER, command, event, String(timeoutSec)], {{ + return execFileSync(INTERPRETER, [...INTERPRETER_ARGS, DISPATCHER, command, event, String(timeoutSec)], {{ input: JSON.stringify({{ input, output }}), stdio: ['pipe', 'pipe', 'inherit'], encoding: 'utf-8', @@ -1172,15 +1214,1176 @@ def collect_extension_events(project_root: Path) -> ResolvedEvents: # -- Writing/Merging Config (Integration domain) --------------------------- +_PY_LAUNCHER_SENTINEL = "py -3" +_STDLIB_WHICH = shutil.which +_IO_REPARSE_TAG_APPEXECLINK = 0x8000001B +_KNOWN_PYTHON_CMD_RE = re.compile( + r"^(?:python(?:3(?:\.\d+)?)?|py)(?:\.exe)?$", re.IGNORECASE +) + + +@dataclass(frozen=True) +class HookInterpreterStatus: + """Availability status of the Python interpreter used by generated hooks.""" + + available: bool + interpreter: str + resolved_path: str | None = None + resolution_kind: str = "missing" + tried: tuple[str, ...] = () + message: str | None = None + + +class HookInterpreterError(RuntimeError): + """Raised when a required event hook's Python interpreter cannot be resolved.""" + + def __init__( + self, + message: str, + *, + status: HookInterpreterStatus, + integration_key: str, + ) -> None: + super().__init__(message) + self.status = status + self.integration_key = integration_key + + +class EventCheckError(ValueError): + """Expected transport-neutral error from event interpreter checks.""" + + def __init__( + self, + code: str, + message: str, + *, + details: dict[str, Any] | None = None, + retryable: bool = False, + ) -> None: + self.code = code + self.message = message + self.details = dict(details) if details is not None else {} + self.retryable = retryable + super().__init__(message) + + +def _is_windows() -> bool: + """Return True when running on Windows.""" + return sys.platform == "win32" + + +def _is_known_python_command(command: str) -> bool: + """Return True when bare *command* names a standard Python interpreter or launcher.""" + return bool(_KNOWN_PYTHON_CMD_RE.fullmatch(command)) + + +def _is_path_inside_project( + candidate_path: str | Path, project_root: Path | None +) -> bool: + """Return True when *candidate_path* lies inside *project_root* (or cwd).""" + raw = str(candidate_path) + if not raw: + return False + base = project_root if project_root is not None else Path.cwd() + # When running mocked-Windows tests on POSIX, a Windows drive/UNC path is + # not absolute to POSIX Path and must not be joined against a POSIX root. + if ( + os.name != "nt" + and PureWindowsPath(raw).is_absolute() + and not Path(raw).is_absolute() + ): + if ( + PureWindowsPath(str(base)).is_absolute() + and not Path(str(base)).is_absolute() + ): + cand_win = PureWindowsPath(os.path.normcase(raw)) + base_win = PureWindowsPath(os.path.normcase(str(base))) + return cand_win == base_win or cand_win.is_relative_to(base_win) + return False + + cand = Path(raw) + if not cand.is_absolute(): + cand = base / cand + try: + base_abs = base.absolute() + cand_abs = cand.absolute() + if cand_abs == base_abs or cand_abs.is_relative_to(base_abs): + return True + except (OSError, ValueError): + pass + try: + base_res = base.resolve() + cand_res = cand.resolve() + if cand_res == base_res or cand_res.is_relative_to(base_res): + return True + except (OSError, RuntimeError, ValueError): + # Fail closed so unreadable or looping symlink chains are never probed. + return True + return False + + +def _is_windows_app_exec_alias(candidate: Path) -> bool: + """Return True if *candidate* is a Windows Store AppExecutionAlias stub.""" + try: + lstat_res = os.lstat(candidate) + except OSError: + return False + if getattr(lstat_res, "st_reparse_tag", 0) == _IO_REPARSE_TAG_APPEXECLINK: + return True + parts_lower = {part.lower() for part in candidate.parts} + return "windowsapps" in parts_lower and lstat_res.st_size == 0 + + +def _check_executable_path_static(candidate: Path) -> bool: + """Validate *candidate* as an executable file without spawning it.""" + try: + if not candidate.is_file(): + return False + except OSError: + return False + if _is_windows(): + if _is_windows_app_exec_alias(candidate): + return False + try: + st = candidate.stat() + except OSError: + return False + return stat.S_ISREG(st.st_mode) and st.st_size > 0 + return os.access(candidate, os.X_OK) + + +def _iter_windows_path_candidates(command: str) -> list[str]: + """Enumerate matching PATH/PATHEXT files for *command* (matching Get-Command -All). + + Preserves monkeypatched ``shutil.which`` hooks in tests while enumerating + every ``PATH`` directory and ``PATHEXT`` extension in production so a + Microsoft Store alias preceding a real ``python.exe`` does not hide it. + Unlike ``shutil.which`` on Windows, does not implicitly prepend ``os.curdir``. + """ + if shutil.which is not _STDLIB_WHICH: + found = shutil.which(command) + return [found] if found else [] + + raw_path = os.environ.get("PATH", "") + if not raw_path: + return [] + raw_pathext = os.environ.get("PATHEXT") or ".COM;.EXE;.BAT;.CMD" + exts = [ + ext if ext.startswith(".") else f".{ext}" + for ext in (segment.strip() for segment in raw_pathext.split(";")) + if ext + ] + if not exts: + exts = [".COM", ".EXE", ".BAT", ".CMD"] + lower_exts = {ext.lower() for ext in exts} + cmd_has_ext = Path(command).suffix.lower() in lower_exts + + seen: set[str] = set() + matches: list[str] = [] + for entry in raw_path.split(os.pathsep): + cleaned_dir = entry.strip().strip('"') + if not cleaned_dir: + continue + dir_path = Path(cleaned_dir) + raw_names = ( + [command, *(f"{command}{ext}" for ext in exts)] + if cmd_has_ext + else [f"{command}{ext}" for ext in exts] + ) + for name in raw_names: + variants = (name,) if name == name.lower() else (name.lower(), name) + for variant in variants: + candidate = dir_path / variant + norm = os.path.normpath(str(candidate)).lower() + if norm in seen: + continue + try: + is_file = candidate.is_file() + except OSError: + is_file = False + if is_file: + seen.add(norm) + matches.append(str(candidate)) + return matches + + +def _py_launcher_runs(path: str) -> bool: + """Return True when the Windows ``py`` launcher runs a Python 3 interpreter.""" + try: + return ( + subprocess.run( + [path, "-3", "-I", "-S", "-c", "pass"], + check=False, + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=15, + ).returncode + == 0 + ) + except (OSError, subprocess.SubprocessError): + return False + + +def _find_project_venv_interpreter(project_root: Path | None) -> str | None: + """Return the project-relative ``.venv`` Python path if one exists.""" + if project_root is None: + return None + posix_entry = (project_root / ".venv" / "bin" / "python", ".venv/bin/python") + win_entry = ( + project_root / ".venv" / "Scripts" / "python.exe", + ".venv/Scripts/python.exe", + ) + candidates = (win_entry, posix_entry) if _is_windows() else (posix_entry, win_entry) + for candidate, relative in candidates: + if candidate.is_file(): + return relative + return None + + +def _interpreter_tokens(interpreter: str) -> list[str]: + """Return command tokens for *interpreter*, preserving paths with spaces.""" + if interpreter == _PY_LAUNCHER_SENTINEL: + return ["py", "-3"] + return [interpreter] + + +def _is_absolute_interpreter(interpreter: str) -> bool: + """Return True when *interpreter* is an absolute POSIX or Windows path.""" + return ( + Path(interpreter).is_absolute() + or PurePosixPath(interpreter).is_absolute() + or PureWindowsPath(interpreter).is_absolute() + ) + + +def _is_relative_interpreter_path(interpreter: str) -> bool: + """Return True when *interpreter* is a project-relative path (contains separators).""" + return ("/" in interpreter or "\\" in interpreter) and not _is_absolute_interpreter(interpreter) + + +def _check_executable_path( + candidate: Path, + *, + allow_probe_untrusted: bool = False, + probe_posix: bool = False, +) -> bool: + """Return True if *candidate* is a valid interpreter file on this platform. + + Project-controlled and explicit paths are validated statically without + spawning them unless *allow_probe_untrusted* is explicitly True. + """ + from ..integrations.base import IntegrationBase + + if not _check_executable_path_static(candidate): + return False + if not allow_probe_untrusted: + return True + if _is_windows() or probe_posix: + return IntegrationBase._interpreter_runs(str(candidate)) + return True + + +def _validate_path_match( + found: str, + *, + command_name: str, + is_py_launcher: bool, + project_root: Path | None, + probe_posix: bool, + allow_probe_untrusted: bool, +) -> bool: + """Validate one PATH-resolved candidate without probing untrusted project binaries.""" + from ..integrations.base import IntegrationBase + + inside_project = _is_path_inside_project(found, project_root) + known_python = is_py_launcher or _is_known_python_command(command_name) + if not allow_probe_untrusted and (inside_project or not known_python): + candidate_path = Path(found) + if inside_project: + return _check_executable_path_static(candidate_path) + if candidate_path.exists(): + return _check_executable_path_static(candidate_path) + if _is_windows(): + parts_lower = {part.lower() for part in PureWindowsPath(found).parts} + return "windowsapps" not in parts_lower + return True + + if not (_is_windows() or probe_posix): + return True + if is_py_launcher: + return _py_launcher_runs(found) + return IntegrationBase._interpreter_runs(found) + + +def check_hook_interpreter( + interpreter: str, + project_root: Path | None = None, + *, + allow_probe_untrusted: bool = False, +) -> HookInterpreterStatus: + """Check whether *interpreter* resolves the same way a generated hook invokes it. + + Supports: + - ``"py -3"`` — resolved via ``PATH`` lookup for ``py`` (and verified + runnable on Windows when resolved outside *project_root*). + - Absolute paths — validated statically without executing untrusted + binaries unless *allow_probe_untrusted* is explicitly True. + - Project-relative paths (e.g. ``.venv/bin/python``, + ``.venv/Scripts/python.exe``) — resolved against *project_root* (or + ``Path.cwd()`` when omitted) and validated statically unless + *allow_probe_untrusted* is explicitly True. + - Bare command names (e.g. ``python3``, ``python``) — resolved via + ``shutil.which`` (with Microsoft Store AppExecutionAlias stub rejection + on Windows for system ``PATH`` binaries outside *project_root*). + """ + cleaned = interpreter.strip() + if not cleaned: + return HookInterpreterStatus( + available=False, + interpreter=interpreter, + resolution_kind="missing", + tried=(), + ) + + if cleaned == _PY_LAUNCHER_SENTINEL: + found = shutil.which("py") + if found and _validate_path_match( + found, + command_name="py", + is_py_launcher=True, + project_root=project_root, + probe_posix=False, + allow_probe_untrusted=allow_probe_untrusted, + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=found, + resolution_kind="path", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + if _is_absolute_interpreter(cleaned): + candidate = Path(cleaned) + if _check_executable_path( + candidate, allow_probe_untrusted=allow_probe_untrusted + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=str(candidate), + resolution_kind="absolute", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + if _is_relative_interpreter_path(cleaned): + base = project_root if project_root is not None else Path.cwd() + rel = Path(cleaned.replace("\\", "/")) if os.name != "nt" else Path(cleaned) + candidate = base / rel + if _check_executable_path( + candidate, allow_probe_untrusted=allow_probe_untrusted + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=str(candidate), + resolution_kind="venv", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + found = shutil.which(cleaned) + if found and _validate_path_match( + found, + command_name=cleaned, + is_py_launcher=False, + project_root=project_root, + probe_posix=False, + allow_probe_untrusted=allow_probe_untrusted, + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=found, + resolution_kind="path", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + +def format_missing_hook_interpreter_message( + status: HookInterpreterStatus, + integration_key: str, +) -> str: + """Build an actionable message naming the missing hook interpreter and remedy.""" + tried_detail = "" + if len(status.tried) > 1: + tried_detail = f" (tried: {', '.join(status.tried)})" + return ( + f"Hook interpreter '{status.interpreter}' for '{integration_key}' " + f"could not be resolved{tried_detail}; event hooks will not run. " + f"Install Python 3 on PATH, or create a project .venv and rerun " + f"'specify integration upgrade {integration_key}'." + ) + + +def _check_chain_candidate( + candidate: str, + project_root: Path | None, + *, + probe_posix: bool, + enumerate_windows_path: bool, + allow_probe_untrusted: bool, +) -> HookInterpreterStatus: + """Evaluate one entry in a portable fallback chain.""" + cleaned = candidate.strip() + if not cleaned: + return HookInterpreterStatus( + available=False, + interpreter=candidate, + resolution_kind="missing", + tried=(), + ) + if _is_absolute_interpreter(cleaned): + candidate_path = Path(cleaned) + if _check_executable_path( + candidate_path, + allow_probe_untrusted=allow_probe_untrusted, + probe_posix=probe_posix, + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=str(candidate_path), + resolution_kind="absolute", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + if _is_relative_interpreter_path(cleaned): + base = project_root if project_root is not None else Path.cwd() + rel = Path(cleaned.replace("\\", "/")) if os.name != "nt" else Path(cleaned) + candidate_path = base / rel + if _check_executable_path( + candidate_path, + allow_probe_untrusted=allow_probe_untrusted, + probe_posix=probe_posix, + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=str(candidate_path), + resolution_kind="venv", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + is_py_launcher = cleaned == _PY_LAUNCHER_SENTINEL + cmd_name = "py" if is_py_launcher else cleaned + if _is_windows() and enumerate_windows_path: + path_matches = _iter_windows_path_candidates(cmd_name) + else: + found = shutil.which(cmd_name) + path_matches = [found] if found else [] + + for match in path_matches: + if _validate_path_match( + match, + command_name=cmd_name, + is_py_launcher=is_py_launcher, + project_root=project_root, + probe_posix=probe_posix, + allow_probe_untrusted=allow_probe_untrusted, + ): + return HookInterpreterStatus( + available=True, + interpreter=cleaned, + resolved_path=match, + resolution_kind="path", + tried=(cleaned,), + ) + return HookInterpreterStatus( + available=False, + interpreter=cleaned, + resolution_kind="missing", + tried=(cleaned,), + ) + + +def _check_candidate_chain( + candidates: tuple[str, ...], + project_root: Path | None, + *, + primary: str, + probe_posix: bool = True, + enumerate_windows_path: bool = True, + allow_probe_untrusted: bool = False, +) -> HookInterpreterStatus: + """Evaluate a portable fallback chain of interpreters in priority order.""" + for idx, candidate in enumerate(candidates): + status = _check_chain_candidate( + candidate, + project_root, + probe_posix=probe_posix, + enumerate_windows_path=enumerate_windows_path, + allow_probe_untrusted=allow_probe_untrusted, + ) + if status.available: + kind = status.resolution_kind + if idx > 0 and kind == "path" and candidate != primary: + kind = "fallback" + return HookInterpreterStatus( + available=True, + interpreter=status.interpreter, + resolved_path=status.resolved_path, + resolution_kind=kind, + tried=candidates[: idx + 1], + ) + return HookInterpreterStatus( + available=False, + interpreter=primary, + resolution_kind="missing", + tried=candidates, + ) + + +def _tokenize_powershell_head(command: str, max_tokens: int = 2) -> list[str]: + """Tokenize up to *max_tokens* leading PowerShell tokens (handling ``&`` and quotes).""" + stripped = command.strip() + if stripped.startswith("&") and (len(stripped) == 1 or stripped[1].isspace()): + stripped = stripped[1:].lstrip() + tokens: list[str] = [] + i = 0 + n = len(stripped) + while i < n and len(tokens) < max_tokens: + while i < n and stripped[i].isspace(): + i += 1 + if i >= n: + break + if stripped[i] == "'": + i += 1 + buf: list[str] = [] + while i < n: + if stripped[i] == "'": + if i + 1 < n and stripped[i + 1] == "'": + buf.append("'") + i += 2 + continue + i += 1 + break + buf.append(stripped[i]) + i += 1 + tokens.append("".join(buf)) + elif stripped[i] == '"': + i += 1 + buf = [] + while i < n: + if stripped[i] == "`" and i + 1 < n: + buf.append(stripped[i + 1]) + i += 2 + continue + if stripped[i] == '"': + if i + 1 < n and stripped[i + 1] == '"': + buf.append('"') + i += 2 + continue + i += 1 + break + buf.append(stripped[i]) + i += 1 + tokens.append("".join(buf)) + else: + start = i + while i < n and not stripped[i].isspace(): + i += 1 + tokens.append(stripped[start:i]) + return tokens + + +def _extract_interpreter_from_command( + command: str, *, cmd_quoting: bool = False, powershell_quoting: bool = False +) -> str | None: + """Extract the leading interpreter token (or ``'py -3'``) from a hook command. + + Returns ``None`` when *command* is a portable runtime fallback script + (PowerShell ``& { ... }`` or POSIX ``set -- ...``) or cannot be parsed. + """ + stripped = command.strip() + if not stripped: + return None + if stripped.startswith(("& {", "set -- ")): + return None + if powershell_quoting: + tokens = _tokenize_powershell_head(stripped, max_tokens=2) + elif cmd_quoting: + tokens = [] + i = 0 + n = len(stripped) + while i < n and len(tokens) < 2: + while i < n and stripped[i].isspace(): + i += 1 + if i >= n: + break + if stripped[i] == '"': + i += 1 + buf: list[str] = [] + while i < n: + if stripped[i] == '"': + if i + 1 < n and stripped[i + 1] == '"': + buf.append('"') + i += 2 + continue + i += 1 + break + buf.append(stripped[i]) + i += 1 + tokens.append("".join(buf)) + else: + start = i + while i < n and not stripped[i].isspace(): + i += 1 + tokens.append(stripped[start:i]) + else: + try: + tokens = shlex.split(stripped) + except ValueError: + return None + if not tokens: + return None + if len(tokens) >= 2 and tokens[0] == "py" and tokens[1] == "-3": + return _PY_LAUNCHER_SENTINEL + return tokens[0] + + +def _is_portable_copilot_command(command: str) -> bool: + """Return True if *command* uses the generated portable Copilot fallback wrapper.""" + stripped = command.strip() + if _is_windows(): + return stripped.startswith("& {") + return stripped.startswith("set -- ") + + +def _opencode_plugin_supports_portable_fallback(source: str) -> bool: + """Return True when installed OpenCode plugin source implements portable fallback.""" + if "function canRunPython(" not in source or "INTERPRETER_ARGS" not in source: + return False + if _is_windows(): + return "['python', []]" in source and "['py', ['-3']]" in source + return "['python3', []]" in source and "['python', []]" in source + + +def _extract_opencode_fixed_interpreter(source: str) -> str: + """Extract the fixed interpreter configured in a legacy or custom OpenCode plugin.""" + ternary = re.search( + r"process\.platform\s*===\s*['\"]win32['\"]\s*\?\s*(['\"])(.*?)\1\s*:\s*(['\"])(.*?)\3", + source, + ) + if ternary: + return ternary.group(2) if _is_windows() else ternary.group(4) + assigned = re.search(r"\bINTERPRETER\s*=\s*(['\"])([^'\"]+)\1", source) + if assigned: + return assigned.group(2) + return "python" if _is_windows() else "python3" + + +def _collect_installed_hook_commands( + integration: IntegrationBase, project_root: Path +) -> list[str]: + """Return Specify-owned native hook command strings installed for *integration*.""" + fmt = getattr(integration, "events_format", "json-nested") + config_file = getattr(integration, "events_config_file", None) + if not config_file: + return [] + config_path = project_root / config_file + if not config_path.is_file(): + return [] + + if fmt in ("json-nested", "json-flat", "copilot-json", "json-root-nested"): + try: + data = json.loads(config_path.read_text(encoding="utf-8")) + except (OSError, ValueError, json.JSONDecodeError): + return [] + if not isinstance(data, dict): + return [] + groups = data.values() if fmt == "json-root-nested" else ( + data.get("hooks", {}).values() if isinstance(data.get("hooks"), dict) else () + ) + commands: list[str] = [] + for entries in groups: + if not isinstance(entries, list): + continue + for entry in entries: + if not isinstance(entry, dict): + continue + inner = entry.get("hooks") + if isinstance(inner, list): + for item in inner: + if isinstance(item, dict) and item.get(_SPECKIT_MARKER) is True: + cmd = item.get("command") + if isinstance(cmd, str): + commands.append(cmd) + elif entry.get(_SPECKIT_MARKER) is True: + if fmt == "copilot-json": + key = "powershell" if _is_windows() else "bash" + cmd = entry.get(key) + else: + cmd = entry.get("command") + if isinstance(cmd, str): + commands.append(cmd) + return commands + + if fmt == "toml": + try: + data = tomllib.loads(config_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): + return [] + hooks_table = data.get("hooks", {}) + if not isinstance(hooks_table, dict): + return [] + commands = [] + for groups in hooks_table.values(): + if not isinstance(groups, list): + continue + for group in groups: + if not isinstance(group, dict): + continue + for item in group.get("hooks", []): + if isinstance(item, dict) and item.get("speckit_marker") is True: + cmd = item.get("command") + if isinstance(cmd, str): + commands.append(cmd) + return commands + + if fmt == "toml-vibe": + try: + data = tomllib.loads(config_path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): + return [] + hooks_list = data.get("hooks", []) + if not isinstance(hooks_list, list): + return [] + return [ + item["command"] + for item in hooks_list + if isinstance(item, dict) + and item.get("speckit_marker") is True + and isinstance(item.get("command"), str) + ] + + return [] + + +def has_installed_integration_events( + integration: IntegrationBase, project_root: Path +) -> bool: + """Return True if *integration* has active Specify event hooks in *project_root*.""" + if not integration.supports_events(): + return False + dispatcher = project_root / EVENTS_DISPATCHER_DIR / EVENTS_DISPATCHER_FILENAME + if not dispatcher.is_file(): + return False + fmt = getattr(integration, "events_format", "json-nested") + if fmt == "ts-plugin": + plugin_path = project_root / ".opencode/plugin/speckit-events.ts" + config_file = getattr(integration, "events_config_file", None) + if not plugin_path.is_file() or not config_file: + return False + config_path = project_root / config_file + if not config_path.is_file(): + return False + try: + data = json.loads(config_path.read_text(encoding="utf-8")) + except (OSError, ValueError, json.JSONDecodeError): + return False + plugins = data.get("plugin", []) if isinstance(data, dict) else [] + return isinstance(plugins, list) and "./.opencode/plugin/speckit-events.ts" in plugins + return bool(_collect_installed_hook_commands(integration, project_root)) + + +def check_integration_hook_interpreter( + integration: IntegrationBase, + project_root: Path, + *, + inspect_installed: bool = True, + allow_probe_untrusted: bool = False, +) -> HookInterpreterStatus: + """Check hook interpreter availability for *integration* in *project_root*. + + Mirrors the runtime resolution behavior of *integration*'s generated hooks: + - ``copilot-json`` inspects installed hooks when *inspect_installed* is True + and evaluates the portable fallback chain only when the installed hooks + use that wrapper (or no hooks are installed yet); legacy fixed commands + are validated directly against their recorded interpreter. + - ``ts-plugin`` (OpenCode) inspects ``.opencode/plugin/speckit-events.ts`` + when *inspect_installed* is True and evaluates the portable fallback chain + only when the installed plugin implements it (or no plugin is installed + yet); legacy plugins are validated against their fixed interpreter. + - Single-command-string formats check the interpreter recorded in installed + Specify hooks (when *inspect_installed* is True and hooks exist on disk), + or otherwise the interpreter selected by ``_resolve_interpreter``. + """ + fmt = getattr(integration, "events_format", "json-nested") + status: HookInterpreterStatus | None = None + if fmt == "copilot-json": + if _is_windows(): + candidates = (".venv/Scripts/python.exe", "python", _PY_LAUNCHER_SENTINEL) + primary = "python" + else: + candidates = (".venv/bin/python", "python3", "python", _PY_LAUNCHER_SENTINEL) + primary = "python3" + if inspect_installed: + installed_cmds = _collect_installed_hook_commands(integration, project_root) + if installed_cmds: + has_portable = False + fixed_interps: list[str] = [] + unparseable_cmd: str | None = None + for cmd in installed_cmds: + if _is_portable_copilot_command(cmd): + has_portable = True + continue + interp = _extract_interpreter_from_command( + cmd, powershell_quoting=_is_windows() + ) + if interp: + if interp not in fixed_interps: + fixed_interps.append(interp) + else: + unparseable_cmd = cmd + first_ok: HookInterpreterStatus | None = None + for interp in fixed_interps: + checked = check_hook_interpreter( + interp, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + if not checked.available: + status = checked + break + if first_ok is None: + first_ok = checked + if status is None and unparseable_cmd is not None: + status = HookInterpreterStatus( + available=False, + interpreter=unparseable_cmd.strip(), + resolution_kind="missing", + tried=(), + ) + if status is None and has_portable: + portable_status = _check_candidate_chain( + candidates, + project_root, + primary=primary, + probe_posix=True, + enumerate_windows_path=True, + allow_probe_untrusted=allow_probe_untrusted, + ) + if not portable_status.available or first_ok is None: + status = portable_status + if status is None: + status = first_ok + if status is None: + status = _check_candidate_chain( + candidates, + project_root, + primary=primary, + probe_posix=True, + enumerate_windows_path=True, + allow_probe_untrusted=allow_probe_untrusted, + ) + elif fmt == "ts-plugin": + if _is_windows(): + candidates = ( + ".venv/Scripts/python.exe", + ".venv/bin/python", + "python", + _PY_LAUNCHER_SENTINEL, + ) + primary = "python" + else: + candidates = ( + ".venv/bin/python", + ".venv/Scripts/python.exe", + "python3", + "python", + ) + primary = "python3" + use_portable_chain = True + fixed_opencode_interp: str | None = None + if inspect_installed: + plugin_path = project_root / ".opencode/plugin/speckit-events.ts" + if plugin_path.is_file(): + try: + plugin_source = plugin_path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + plugin_source = "" + if not _opencode_plugin_supports_portable_fallback(plugin_source): + use_portable_chain = False + fixed_opencode_interp = _extract_opencode_fixed_interpreter( + plugin_source + ) + if use_portable_chain: + status = _check_candidate_chain( + candidates, + project_root, + primary=primary, + probe_posix=True, + enumerate_windows_path=False, + allow_probe_untrusted=allow_probe_untrusted, + ) + else: + status = check_hook_interpreter( + fixed_opencode_interp or primary, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + else: + if inspect_installed: + cmd_quoting = fmt == "toml-vibe" and _is_windows() + installed_cmds = _collect_installed_hook_commands(integration, project_root) + seen_interps: list[str] = [] + for cmd in installed_cmds: + interp = _extract_interpreter_from_command(cmd, cmd_quoting=cmd_quoting) + if interp and interp not in seen_interps: + seen_interps.append(interp) + if seen_interps: + first_ok = None + for interp in seen_interps: + checked = check_hook_interpreter( + interp, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + if not checked.available: + status = checked + break + if first_ok is None: + first_ok = checked + if status is None: + status = first_ok + if status is None: + interpreter = _resolve_interpreter(project_root) + status = check_hook_interpreter( + interpreter, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + + if not status.available and status.message is None: + return HookInterpreterStatus( + available=False, + interpreter=status.interpreter, + resolved_path=status.resolved_path, + resolution_kind=status.resolution_kind, + tried=status.tried, + message=format_missing_hook_interpreter_message(status, integration.key), + ) + return status + + +def preflight_hook_interpreter( + integration: IntegrationBase, + project_root: Path, + *, + required: bool = False, + allow_probe_untrusted: bool = False, +) -> HookInterpreterStatus | None: + """Fail fast before agent CLI dispatch when required event hooks lack Python. + + When *required* is ``False`` (the default), runs only if *integration* has + active Specify event hooks installed in *project_root*. When *required* is + ``True`` (for workflow steps that explicitly depend on hook-delivered + behavior such as ``additional_context``), always validates the hook + interpreter for an event-capable integration. + + Raises :class:`HookInterpreterError` with an actionable message if the + interpreter cannot be resolved. + """ + if not integration.supports_events(): + return None + if not required and not has_installed_integration_events(integration, project_root): + return None + status = check_integration_hook_interpreter( + integration, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + if not status.available: + message = status.message or format_missing_hook_interpreter_message( + status, integration.key + ) + raise HookInterpreterError( + message, status=status, integration_key=integration.key + ) + return status + + +def _raise_integration_state_check_error(read_error: Any) -> None: + """Translate an ``IntegrationReadError`` into a structured ``EventCheckError``.""" + from ..integration_state import INTEGRATION_JSON, INTEGRATION_STATE_SCHEMA + + kind = read_error.kind + detail = read_error.detail + details: dict[str, Any] = {"path": INTEGRATION_JSON, "kind": kind} + if kind == "decode": + suffix = f": {detail}" if detail else "" + raise EventCheckError( + "invalid_integration_state", + f"{INTEGRATION_JSON} contains invalid JSON or is not valid UTF-8{suffix}", + details=details, + ) + if kind == "os": + suffix = f": {detail}" if detail else "" + raise EventCheckError( + "integration_state_unreadable", + f"Could not read {INTEGRATION_JSON}{suffix}", + details=details, + ) + if kind == "not_object": + raise EventCheckError( + "invalid_integration_state", + f"{INTEGRATION_JSON} must contain a JSON object, got {detail}", + details=details, + ) + if kind == "schema_too_new": + details["schema"] = read_error.schema + details["supported_schema"] = INTEGRATION_STATE_SCHEMA + raise EventCheckError( + "unsupported_integration_schema", + ( + f"{INTEGRATION_JSON} uses integration state schema {read_error.schema}, " + f"which is newer than this CLI supports (supported schema: {INTEGRATION_STATE_SCHEMA})" + ), + details=details, + ) + raise EventCheckError( + "invalid_integration_state", + f"Could not inspect {INTEGRATION_JSON}", + details=details, + ) + + +def check_project_event_interpreters( + project_root: Path, + *, + integration_key: str | None = None, + allow_probe_untrusted: bool = False, +) -> list[tuple[str, bool, HookInterpreterStatus]]: + """Inspect hook interpreter status for installed event-capable integrations. + + When *integration_key* is provided, inspects only that integration (raising + :class:`EventCheckError` if unknown or not event-capable). Otherwise reads + ``.specify/integration.json`` via the non-rendering state reader (raising + :class:`EventCheckError` on malformed or unreadable state) and inspects + every installed event-capable integration. + """ + from ..integration_state import installed_integration_keys, try_read_integration_json + from ..integrations import get_integration + + if integration_key is not None: + integration = get_integration(integration_key) + if integration is None: + raise EventCheckError( + "unknown_integration", + f"Unknown integration '{integration_key}'", + details={"integration": integration_key}, + ) + if not integration.supports_events(): + raise EventCheckError( + "events_not_supported", + f"Integration '{integration_key}' does not support runtime events", + details={"integration": integration_key}, + ) + targets = [integration] + else: + state, read_error = try_read_integration_json(project_root) + if read_error is not None: + _raise_integration_state_check_error(read_error) + targets = [] + for key in installed_integration_keys(state or {}): + integration = get_integration(key) + if integration is not None and integration.supports_events(): + targets.append(integration) + + results: list[tuple[str, bool, HookInterpreterStatus]] = [] + for integration in targets: + installed = has_installed_integration_events(integration, project_root) + status = check_integration_hook_interpreter( + integration, + project_root, + allow_probe_untrusted=allow_probe_untrusted, + ) + results.append((integration.key, installed, status)) + return results + + def _resolve_interpreter(project_root: Path) -> str: """Resolve a portable Python interpreter for native hook commands (#16). - Delegates to ``IntegrationBase.resolve_python_interpreter`` so generated - commands honor the project venv and never hard-code ``python3`` (which is - commonly absent on Windows even when ``py.exe``/``python.exe`` exist). + Prefers a project-local ``.venv`` interpreter (relative to *project_root*), + then a runnable ``python3`` or ``python`` on ``PATH``. On Windows, falls + back to ``py -3`` when ``python3`` and ``python`` are absent or are + Microsoft Store stubs. Avoids embedding a host-specific ``sys.executable`` + path into generated hook configs so ephemeral environments (such as + ``uvx``) surface a diagnostic instead of baking in a transient path. """ from ..integrations.base import IntegrationBase - return IntegrationBase.resolve_python_interpreter(project_root) + + venv_rel = _find_project_venv_interpreter(project_root) + if venv_rel is not None: + return venv_rel + for name in ("python3", "python"): + found = shutil.which(name) + if not found: + continue + if _is_windows(): + if _is_path_inside_project(found, project_root): + if not _check_executable_path_static(Path(found)): + continue + elif not IntegrationBase._interpreter_runs(found): + continue + return name + if _is_windows(): + py_launcher = shutil.which("py") + if py_launcher: + if _is_path_inside_project(py_launcher, project_root): + if _check_executable_path_static(Path(py_launcher)): + return _PY_LAUNCHER_SENTINEL + elif _py_launcher_runs(py_launcher): + return _PY_LAUNCHER_SENTINEL + return "python" + return "python3" def _resolve_interpreter_for_target(target_os: str) -> str: @@ -1195,13 +2398,92 @@ def _resolve_interpreter_for_target(target_os: str) -> str: resolution at runtime. """ if target_os == "windows": - # Windows: ``python`` is the most portable on PATH; the py launcher - # (``py -3``) is the recommended fallback when ``python`` is absent. + # Windows: ``python`` is the primary name on PATH; generated PowerShell + # hooks also fall back to ``py -3`` when ``python`` is absent or a stub. return "python" - # POSIX (bash): ``python3`` is universally available. + # POSIX (bash): ``python3`` is the primary name; generated POSIX hooks also + # fall back to ``.venv/bin/python``, ``python``, and ``py -3``. return "python3" +def _build_powershell_fallback_command( + dispatcher: str, quoted_args: list[str] +) -> str: + """Build a Windows PowerShell 5.1 command with portable Python 3 fallback. + + Resolution order: runnable ``.venv\\Scripts\\python.exe`` → runnable + ``python`` on ``PATH`` (skipping Microsoft Store AppExecutionAlias stubs) → + runnable ``py -3`` launcher. Probes pipe ``$null`` into stdin and discard + output so piped hook JSON reaches the dispatcher untouched, and the + dispatcher's exit code is propagated via ``exit $global:LASTEXITCODE``. + """ + arg_list = " ".join([dispatcher, *quoted_args]) + return ( + "& { " + "$py = $null; $pre = @(); $venv = '.venv\\Scripts\\python.exe'; " + "if (Test-Path -LiteralPath $venv -PathType Leaf) { " + "& { $ErrorActionPreference = 'Continue'; $global:LASTEXITCODE = 1; " + "try { $null | & $venv '-I' '-S' '-c' 'pass' 1>$null 2>$null } " + "catch { $global:LASTEXITCODE = 1 } }; " + "if ($global:LASTEXITCODE -eq 0) { $py = $venv } " + "}; " + "if (-not $py) { " + "foreach ($c in @(Get-Command 'python' -All -ErrorAction SilentlyContinue)) { " + "& { $ErrorActionPreference = 'Continue'; $global:LASTEXITCODE = 1; " + "try { $null | & $c '-I' '-S' '-c' 'pass' 1>$null 2>$null } " + "catch { $global:LASTEXITCODE = 1 } }; " + "if ($global:LASTEXITCODE -eq 0) { $py = $c; break } " + "} " + "}; " + "if (-not $py) { " + "foreach ($c in @(Get-Command 'py' -All -ErrorAction SilentlyContinue)) { " + "& { $ErrorActionPreference = 'Continue'; $global:LASTEXITCODE = 1; " + "try { $null | & $c '-3' '-I' '-S' '-c' 'pass' 1>$null 2>$null } " + "catch { $global:LASTEXITCODE = 1 } }; " + "if ($global:LASTEXITCODE -eq 0) { $py = $c; $pre = @('-3'); break } " + "} " + "}; " + "if (-not $py) { " + "[Console]::Error.WriteLine('Spec Kit hook error: no Python 3 interpreter found " + "(tried .venv\\Scripts\\python.exe, python, py -3).'); " + "exit 127 " + "}; " + "$global:LASTEXITCODE = 0; " + f"& $py @pre {arg_list}; " + "exit $global:LASTEXITCODE " + "}" + ) + + +def _build_posix_fallback_command( + dispatcher: str, quoted_args: list[str] +) -> str: + """Build a POSIX ``sh`` command with portable Python 3 fallback. + + Resolution order: runnable regular file ``.venv/bin/python`` → runnable + ``python3`` → runnable ``python`` → runnable ``py -3`` (for Git Bash on + Windows). Probes close stdin (``/dev/null 2>&1; ' + 'then exec "$_venv" "$@"; ' + "elif command -v python3 >/dev/null 2>&1 " + '&& python3 -I -S -c pass /dev/null 2>&1; then exec python3 "$@"; ' + "elif command -v python >/dev/null 2>&1 " + '&& python -I -S -c pass /dev/null 2>&1; then exec python "$@"; ' + "elif command -v py >/dev/null 2>&1 " + '&& py -3 -I -S -c pass /dev/null 2>&1; then exec py -3 "$@"; ' + "else echo 'Spec Kit hook error: no Python 3 interpreter found " + "(tried .venv/bin/python, python3, python, py -3).' >&2; exit 127; fi" + ) + + def _native_timeout(integration: IntegrationBase, timeout_seconds: Any) -> int: """Return the timeout in the unit the integration's native config expects. @@ -1300,14 +2582,6 @@ def _dispatcher_command( shape the agent's hook protocol requires. Plain-passthrough agents (Claude/Codex) declare no envelope and get no extra argument. """ - if target_os in ("host", "cmd"): - # "cmd" is host-resolved too (venv-aware): it is selected only when - # generating on a Windows host for an agent that runs hooks through - # cmd.exe (Vibe), and differs from "host" purely in quoting style. - interpreter = _resolve_interpreter(project_root) - else: - interpreter = _resolve_interpreter_for_target(target_os) - q_interp = _shell_quote(interpreter, target_os) q_command = _shell_quote(command_name, target_os) q_event = _shell_quote(event_name, target_os) if integration.key == "claude": @@ -1317,10 +2591,6 @@ def _dispatcher_command( dispatcher = '"${CLAUDE_PROJECT_DIR}/' + EVENTS_DISPATCHER_REL + '"' else: dispatcher = _shell_quote(EVENTS_DISPATCHER_REL, target_os) - # C1: PowerShell won't invoke a single-quoted command without the call - # operator. Prefix & for the explicit windows target only. - prefix = "& " if target_os == "windows" else "" - base = f"{prefix}{q_interp} {dispatcher} {q_command} {q_event}" # Always emit the timeout (4th positional arg) so the dispatcher's argv # parsing stays aligned when an envelope (5th) or native_event (6th) # follows. Without it the envelope would land in the timeout slot and @@ -1331,10 +2601,10 @@ def _dispatcher_command( # Gemini/Qwen/Tabnine and would yield 60000 seconds). The buffer is # applied to the native hook timeout field (in the adapter formatters) # so the agent's outer cap fires after the inner subprocess timeout. - base += f" {_shell_quote(str(resolved_timeout), target_os)}" + quoted_args = [q_command, q_event, _shell_quote(str(resolved_timeout), target_os)] envelope = _context_envelope_for(integration, event_name) if envelope: - base += f" {_shell_quote(envelope, target_os)}" + quoted_args.append(_shell_quote(envelope, target_os)) # hookSpecificOutput requires the native hookEventName inside the # envelope (Qwen's hooks spec marks it mandatory; the Claude Code # hooks spec that Gemini/Tabnine/Devin derive from includes it). @@ -1343,8 +2613,20 @@ def _dispatcher_command( if envelope == "hookSpecificOutput": native_event = getattr(integration, "CANONICAL_TO_NATIVE", {}).get(event_name, "") if native_event: - base += f" {_shell_quote(native_event, target_os)}" - return base + quoted_args.append(_shell_quote(native_event, target_os)) + + if target_os == "windows": + return _build_powershell_fallback_command(dispatcher, quoted_args) + if target_os == "posix": + return _build_posix_fallback_command(dispatcher, quoted_args) + + # "host" and "cmd" resolve against the current project/host (venv-aware, + # with Windows py -3 fallback) and differ purely in shell quoting style. + interpreter = _resolve_interpreter(project_root) + q_interp = " ".join( + _shell_quote(token, target_os) for token in _interpreter_tokens(interpreter) + ) + return " ".join([q_interp, dispatcher, *quoted_args]) def _context_envelope_for(integration: IntegrationBase, canonical_event: str) -> str | None: @@ -1634,6 +2916,15 @@ def install_integration_events( manifest.record_existing(rel, ownership="partial") created.append(config_path) + status = check_integration_hook_interpreter( + integration, project_root, inspect_installed=False + ) + if not status.available: + message = status.message or format_missing_hook_interpreter_message( + status, integration.key + ) + print(f"\u26a0\ufe0f {message}", file=sys.stderr) + return created @@ -2636,6 +3927,6 @@ def _has_marked_entry(groups: Iterable[Any]) -> bool: def register(app: typer.Typer) -> None: """Attach the event command group to the root application.""" - from . import command_run # noqa: F401 -- registers handler + from . import command_check, command_run # noqa: F401 -- registers handlers app.add_typer(event_app, name="event") diff --git a/src/specify_cli/events/_mcp.py b/src/specify_cli/events/_mcp.py new file mode 100644 index 0000000000..24a3f03b60 --- /dev/null +++ b/src/specify_cli/events/_mcp.py @@ -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}" + ) diff --git a/src/specify_cli/events/command_check.py b/src/specify_cli/events/command_check.py new file mode 100644 index 0000000000..98cbad4df1 --- /dev/null +++ b/src/specify_cli/events/command_check.py @@ -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) diff --git a/src/specify_cli/mcp_server/server.py b/src/specify_cli/mcp_server/server.py index 708410c79a..93ad0f1c93 100644 --- a/src/specify_cli/mcp_server/server.py +++ b/src/specify_cli/mcp_server/server.py @@ -9,6 +9,7 @@ from mcp.types import CallToolResult, TextContent from ..artifacts._mcp import register as register_artifacts +from ..events._mcp import register as register_events from ..mcp_version import register as register_version from ..workflows._mcp import register as register_workflows from .catalog import ( @@ -90,6 +91,7 @@ def specify_run_command(command: str) -> VersionResult: register_version(server) register_artifacts(server, launch_directory=server_launch_directory) + register_events(server, launch_directory=server_launch_directory) register_workflows(server, launch_directory=server_launch_directory) return server diff --git a/src/specify_cli/workflows/step/_hook_preflight.py b/src/specify_cli/workflows/step/_hook_preflight.py new file mode 100644 index 0000000000..db0f08d738 --- /dev/null +++ b/src/specify_cli/workflows/step/_hook_preflight.py @@ -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}" diff --git a/src/specify_cli/workflows/step/command/__init__.py b/src/specify_cli/workflows/step/command/__init__.py index ba9e35f377..cda7eecc6a 100644 --- a/src/specify_cli/workflows/step/command/__init__.py +++ b/src/specify_cli/workflows/step/command/__init__.py @@ -4,9 +4,11 @@ import inspect import shutil +from collections.abc import Mapping from pathlib import Path from typing import Any +from specify_cli.events import HookInterpreterError from specify_cli.integrations.base import ( DispatchSettingsError, check_dispatch_settings, @@ -27,6 +29,10 @@ dispatch_settings_failure, resolve_dispatch_settings, ) +from specify_cli.workflows.step._hook_preflight import ( + check_step_hook_interpreter, + hook_preflight_failure, +) _DEFAULT_CAPTURE_TIMEOUT = 600 @@ -211,6 +217,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: integration_options, capture_max_bytes=capture_max_bytes, timeout=timeout, + step_config=config, **dispatch.settings, ) except DispatchSettingsError as exc: @@ -223,6 +230,14 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: "Command", config, exc, dispatch.sources ), ) + except HookInterpreterError as exc: + output["exit_code"] = 1 + output["dispatched"] = False + return StepResult( + status=StepStatus.FAILED, + output=output, + error=hook_preflight_failure("Command", config, exc), + ) except ValueError as exc: output["exit_code"] = 1 output["dispatched"] = False @@ -290,6 +305,7 @@ def _try_dispatch( timeout: float = _DEFAULT_CAPTURE_TIMEOUT, reasoning_effort: str | None = None, context_size: str | None = None, + step_config: Mapping[str, Any] | None = None, ) -> dict[str, Any] | None: """Invoke *command* by name through the integration CLI. @@ -374,6 +390,8 @@ def _try_dispatch( f"'capture: true'." ) + check_step_hook_interpreter(step_config, impl, project_root) + try: return impl.dispatch_command( command, diff --git a/src/specify_cli/workflows/step/prompt/__init__.py b/src/specify_cli/workflows/step/prompt/__init__.py index 7a21c3ced8..1c8ff88880 100644 --- a/src/specify_cli/workflows/step/prompt/__init__.py +++ b/src/specify_cli/workflows/step/prompt/__init__.py @@ -4,9 +4,11 @@ import math import shutil +from collections.abc import Mapping from pathlib import Path from typing import Any +from specify_cli.events import HookInterpreterError from specify_cli.integrations._capture import run_captured from specify_cli.integrations.base import ( DispatchSettingsError, @@ -27,6 +29,10 @@ dispatch_settings_failure, resolve_dispatch_settings, ) +from specify_cli.workflows.step._hook_preflight import ( + check_step_hook_interpreter, + hook_preflight_failure, +) class PromptStep(StepBase): @@ -148,6 +154,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: context, timeout=timeout, capture_max_bytes=capture_max_bytes, + step_config=config, **dispatch.settings, ) except DispatchSettingsError as exc: @@ -160,6 +167,14 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: "Prompt", config, exc, dispatch.sources ), ) + except HookInterpreterError as exc: + output["exit_code"] = 1 + output["dispatched"] = False + return StepResult( + status=StepStatus.FAILED, + output=output, + error=hook_preflight_failure("Prompt", config, exc), + ) if dispatch_result is not None: output["exit_code"] = dispatch_result["exit_code"] @@ -251,6 +266,7 @@ def _try_dispatch( *, reasoning_effort: str | None = None, context_size: str | None = None, + step_config: Mapping[str, Any] | None = None, ) -> dict[str, Any] | None: """Dispatch *prompt* directly through the integration CLI. @@ -318,6 +334,8 @@ def _try_dispatch( if fallback_cli_path: exec_args = [fallback_cli_path, *exec_args[1:]] + check_step_hook_interpreter(step_config, impl, project_root) + import subprocess if capture_max_bytes is not None: diff --git a/tests/specify_cli/events/test_command_check.py b/tests/specify_cli/events/test_command_check.py new file mode 100644 index 0000000000..7c01ff985d --- /dev/null +++ b/tests/specify_cli/events/test_command_check.py @@ -0,0 +1,301 @@ +"""Tests for ``specify event check`` CLI diagnostic command.""" + +from __future__ import annotations + +import json + +from typer.testing import CliRunner + +from specify_cli import app +from specify_cli.events import install_integration_events +from specify_cli.integrations.base import IntegrationBase +from specify_cli.integrations.claude import ClaudeIntegration +from specify_cli.integrations.copilot import CopilotIntegration +from specify_cli.integrations.manifest import IntegrationManifest + + +def _write_integration_state(project_root, integrations: list[str]) -> None: + specify_dir = project_root / ".specify" + specify_dir.mkdir(parents=True, exist_ok=True) + (specify_dir / "integration.json").write_text( + json.dumps( + { + "integration": integrations[0] if integrations else "", + "default_integration": integrations[0] if integrations else "", + "installed_integrations": integrations, + } + ), + encoding="utf-8", + ) + + +def test_event_check_succeeds_for_healthy_integrations(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: False) + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: path == "/usr/bin/python3"), + ) + + _write_integration_state(tmp_path, ["claude", "copilot"]) + claude = ClaudeIntegration() + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + claude, tmp_path, manifest, {"session_start": [{"command": "speckit.boot"}]} + ) + + result = CliRunner().invoke(app, ["event", "check"]) + assert result.exit_code == 0, result.output + assert "[OK] claude (hooks installed)" in result.output + assert "[OK] copilot (no hooks installed)" in result.output + + +def test_event_check_fails_with_actionable_remedy_when_missing(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: False) + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + _write_integration_state(tmp_path, ["copilot"]) + + result = CliRunner().invoke(app, ["event", "check"]) + assert result.exit_code == 1 + assert "[FAIL] copilot" in result.stderr + assert "python3" in result.stderr + assert "specify integration upgrade copilot" in result.stderr + + +def test_event_check_json_output_ok_and_missing(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: False) + + _write_integration_state(tmp_path, ["claude"]) + claude = ClaudeIntegration() + manifest = IntegrationManifest("claude", tmp_path) + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: path == "/usr/bin/python3"), + ) + install_integration_events( + claude, tmp_path, manifest, {"session_start": [{"command": "speckit.boot"}]} + ) + + ok_res = CliRunner().invoke(app, ["event", "check", "--json"]) + assert ok_res.exit_code == 0, ok_res.output + payload = json.loads(ok_res.output) + assert payload["ok"] is True + assert len(payload["integrations"]) == 1 + entry = payload["integrations"][0] + assert entry["integration"] == "claude" + assert entry["hooks_installed"] is True + assert entry["available"] is True + assert entry["interpreter"] == "python3" + assert entry["resolved_path"] == "/usr/bin/python3" + assert entry["resolution_kind"] == "path" + assert entry["message"] is None + + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + fail_res = CliRunner().invoke(app, ["event", "check", "--json"]) + assert fail_res.exit_code == 1 + fail_payload = json.loads(fail_res.output) + assert fail_payload["ok"] is False + fail_entry = fail_payload["integrations"][0] + assert fail_entry["available"] is False + assert fail_entry["resolution_kind"] == "missing" + assert "specify integration upgrade claude" in fail_entry["message"] + + +def test_event_check_specific_integration_and_invalid_key(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: True) + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + + copilot_res = CliRunner().invoke( + app, ["event", "check", "--integration", "copilot", "--json"] + ) + assert copilot_res.exit_code == 0, copilot_res.output + payload = json.loads(copilot_res.output) + assert payload["ok"] is True + assert payload["integrations"][0]["interpreter"] == "py -3" + assert payload["integrations"][0]["resolution_kind"] == "fallback" + + unknown_res = CliRunner().invoke(app, ["event", "check", "--integration", "nope"]) + assert unknown_res.exit_code == 1 + assert "Unknown integration 'nope'" in unknown_res.stderr + + non_event_res = CliRunner().invoke( + app, ["event", "check", "--integration", "amp", "--json"] + ) + assert non_event_res.exit_code == 1 + err_payload = json.loads(non_event_res.output) + assert err_payload["ok"] is False + assert "does not support runtime events" in err_payload["error"] + + +def test_event_check_no_event_integrations_installed(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + _write_integration_state(tmp_path, ["amp"]) + + result = CliRunner().invoke(app, ["event", "check"]) + assert result.exit_code == 0, result.output + assert "No event-capable integrations" in result.output + + +def test_event_check_respects_specify_init_dir_override(tmp_path, monkeypatch): + other_dir = tmp_path / "other" + other_dir.mkdir() + proj = tmp_path / "project" + (proj / ".specify").mkdir(parents=True) + _write_integration_state(proj, ["copilot"]) + + venv_py = proj / ".venv" / "bin" / "python" + venv_py.parent.mkdir(parents=True) + venv_py.write_text("#!/bin/sh\n", encoding="utf-8") + venv_py.chmod(0o755) + + monkeypatch.chdir(other_dir) + monkeypatch.setenv("SPECIFY_INIT_DIR", str(proj)) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: False) + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + manifest = IntegrationManifest("copilot", proj) + install_integration_events( + CopilotIntegration(), proj, manifest, {"session_start": [{"command": "speckit.boot"}]} + ) + + result = CliRunner().invoke(app, ["event", "check", "--json"]) + assert result.exit_code == 0, result.output + payload = json.loads(result.output) + assert payload["ok"] is True + assert payload["integrations"][0]["resolution_kind"] == "venv" + assert payload["integrations"][0]["interpreter"] == ".venv/bin/python" + + +def test_event_check_json_serializes_malformed_and_unsupported_integration_state( + tmp_path, monkeypatch +): + """Malformed, unreadable, or newer integration.json produces structured JSON.""" + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + specify_dir = tmp_path / ".specify" + specify_dir.mkdir(parents=True) + state_file = specify_dir / "integration.json" + + # 1. Malformed JSON + state_file.write_text("{not valid json", encoding="utf-8") + res = CliRunner().invoke(app, ["event", "check", "--json"]) + assert res.exit_code == 1 + payload = json.loads(res.output) + assert payload["ok"] is False + assert payload["error_code"] == "invalid_integration_state" + assert payload["error_details"]["kind"] == "decode" + assert payload["retryable"] is False + assert payload["integrations"] == [] + + # Human mode prints a plain error without Rich markup or crash. + human = CliRunner().invoke(app, ["event", "check"]) + assert human.exit_code == 1 + assert "Error:" in human.stderr + assert "invalid JSON" in human.stderr + + # 2. Non-object JSON + state_file.write_text("[]", encoding="utf-8") + res_arr = CliRunner().invoke(app, ["event", "check", "--json"]) + assert res_arr.exit_code == 1 + payload_arr = json.loads(res_arr.output) + assert payload_arr["ok"] is False + assert payload_arr["error_code"] == "invalid_integration_state" + assert payload_arr["error_details"]["kind"] == "not_object" + + # 3. Schema too new + state_file.write_text(json.dumps({"integration_state_schema": 999}), encoding="utf-8") + res_schema = CliRunner().invoke(app, ["event", "check", "--json"]) + assert res_schema.exit_code == 1 + payload_schema = json.loads(res_schema.output) + assert payload_schema["ok"] is False + assert payload_schema["error_code"] == "unsupported_integration_schema" + assert payload_schema["error_details"]["schema"] == 999 + + # 4. Unreadable (directory at integration.json path) + state_file.unlink() + state_file.mkdir() + res_dir = CliRunner().invoke(app, ["event", "check", "--json"]) + assert res_dir.exit_code == 1 + payload_dir = json.loads(res_dir.output) + assert payload_dir["ok"] is False + assert payload_dir["error_code"] == "integration_state_unreadable" + assert payload_dir["error_details"]["kind"] == "os" + + +def test_event_check_never_executes_untrusted_repo_hook_binary_on_windows( + tmp_path, monkeypatch +): + """`specify event check --integration claude` never probes untrusted binaries.""" + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("SPECIFY_INIT_DIR", raising=False) + monkeypatch.setattr("specify_cli.events._is_windows", lambda: True) + + (tmp_path / ".specify").mkdir(parents=True) + (tmp_path / ".specify" / "events.py").write_text("", encoding="utf-8") + evil_bin = tmp_path / ".venv" / "Scripts" / "python.exe" + evil_bin.parent.mkdir(parents=True) + evil_bin.write_bytes(b"MZ\x90\x00") + claude_cfg = tmp_path / ".claude" / "settings.json" + claude_cfg.parent.mkdir(parents=True) + claude_cfg.write_text( + json.dumps( + { + "hooks": { + "SessionStart": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": ".venv/Scripts/python.exe .specify/events.py speckit.boot session_start 60", + "__speckit_event__": True, + } + ], + } + ] + } + } + ), + encoding="utf-8", + ) + + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod( + lambda path: (_ for _ in ()).throw( + AssertionError(f"must not execute untrusted binary: {path}") + ) + ), + ) + + res = CliRunner().invoke( + app, ["event", "check", "--integration", "claude", "--json"] + ) + assert res.exit_code == 0, res.output + payload = json.loads(res.output) + assert payload["ok"] is True + assert payload["integrations"][0]["interpreter"] == ".venv/Scripts/python.exe" diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index f5f7183702..88c4479e4d 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -663,11 +663,19 @@ def test_copilot_json_generation(self, tmp_path): # args are shell-quoted for each target shell. assert "speckit.agent-context.update" in entry["powershell"] assert entry["bash"] != entry["powershell"] - # bash uses POSIX interpreter python3 (shlex.quote leaves safe tokens - # bare); powershell uses python single-quoted with the & call operator - # so the quoted command is actually invoked (C1). - assert entry["bash"].startswith("python3 ") - assert entry["powershell"].startswith("& 'python' ") + # bash uses POSIX portable fallback (.venv/bin/python -> python3 -> python -> py -3); + # powershell uses Windows PowerShell 5.1 portable fallback starting with & { ... } + # (.venv\Scripts\python.exe -> python -> py -3). + assert entry["bash"].startswith("set -- ") + assert ".venv/bin/python" in entry["bash"] + assert "python3" in entry["bash"] + assert "python" in entry["bash"] + assert "py -3" in entry["bash"] + assert entry["powershell"].startswith("& { ") + assert ".venv\\Scripts\\python.exe" in entry["powershell"] + assert "'python'" in entry["powershell"] + assert "'py'" in entry["powershell"] + assert "'-3'" in entry["powershell"] # PowerShell always single-quotes; POSIX leaves metacharacter-free # identifiers bare (shlex.quote only quotes when needed). assert "'speckit.agent-context.update'" in entry["powershell"] @@ -676,9 +684,10 @@ def test_copilot_json_generation(self, tmp_path): # outer cap fires after the dispatcher's inner subprocess timeout. assert entry["timeoutSec"] == 65 prompt = data["hooks"]["userPromptSubmitted"][0] - for shell in ("bash", "powershell"): - assert shlex.split(entry[shell])[-2:] == ["60", "additionalContext"] - assert shlex.split(prompt[shell])[-2:] == ["60", "suppress"] + assert "'.specify/events.py' 'speckit.agent-context.update' 'session_start' '60' 'additionalContext'" in entry["powershell"] + assert ".specify/events.py speckit.agent-context.update session_start 60 additionalContext" in entry["bash"] + assert "'.specify/events.py' 'speckit.agent-context.update' 'user_prompt_submit' '60' 'suppress'" in prompt["powershell"] + assert ".specify/events.py speckit.agent-context.update user_prompt_submit 60 suppress" in prompt["bash"] # -- Cursor hooks.json version + matcher grouping (#7, S3) ------------------- diff --git a/tests/specify_cli/events/test_hook_interpreter.py b/tests/specify_cli/events/test_hook_interpreter.py new file mode 100644 index 0000000000..3a1b69a1dd --- /dev/null +++ b/tests/specify_cli/events/test_hook_interpreter.py @@ -0,0 +1,1274 @@ +"""Tests for portable hook interpreter fallback and availability checks.""" + +from __future__ import annotations + +import json +import os +import shlex +import shutil +import stat +import subprocess +import sys +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from specify_cli.events import ( + EVENTS_DISPATCHER_REL, + HookInterpreterError, + _dispatcher_command, + _extract_interpreter_from_command, + _resolve_interpreter, + check_hook_interpreter, + check_integration_hook_interpreter, + format_missing_hook_interpreter_message, + has_installed_integration_events, + install_integration_events, + preflight_hook_interpreter, + refresh_integration_events, +) +from specify_cli.integrations.base import IntegrationBase +from specify_cli.integrations.claude import ClaudeIntegration +from specify_cli.integrations.codex import CodexIntegration +from specify_cli.integrations.copilot import CopilotIntegration +from specify_cli.integrations.cursor_agent import CursorAgentIntegration +from specify_cli.integrations.devin import DevinIntegration +from specify_cli.integrations.manifest import IntegrationManifest +from specify_cli.integrations.opencode import OpencodeIntegration +from specify_cli.integrations.vibe import VibeIntegration + +def _select_powershell_exe( + platform_name: str = sys.platform, + which=shutil.which, +) -> str | None: + """Select Windows PowerShell 5.1 explicitly on Windows, or pwsh on POSIX.""" + if platform_name == "win32": + return which("powershell.exe") or which("powershell") or which("pwsh") + return which("pwsh") + + +HAS_SH = sys.platform != "win32" and os.access("/bin/sh", os.X_OK) +POWERSHELL_EXE = _select_powershell_exe() + + +def _write_exec_shim(path: Path, body: str) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body, encoding="utf-8", newline="\n") + path.chmod(0o755) + return path + + +def _install_echo_dispatcher_project(tmp_path: Path, *, exit_code: int = 0) -> None: + """Create a tiny .specify/events.py that records argv and piped stdin.""" + dispatcher = tmp_path / EVENTS_DISPATCHER_REL + dispatcher.parent.mkdir(parents=True, exist_ok=True) + dispatcher.write_text( + "import json, os, sys\n" + "payload = sys.stdin.read()\n" + "out = {\n" + " 'tag': os.environ.get('SHIM_TAG', 'real'),\n" + " 'argv': sys.argv[1:],\n" + " 'stdin': payload,\n" + "}\n" + "sys.stdout.write(json.dumps(out))\n" + f"sys.exit({exit_code})\n", + encoding="utf-8", + ) + + +# -- check_hook_interpreter: PATH, project-relative venv, absolute path ----- + + +class TestCheckHookInterpreterPath: + """Positive and negative tests for bare PATH command resolution.""" + + def test_posix_path_command_found(self, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + # POSIX must not spawn a liveness subprocess. + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: (_ for _ in ()).throw(AssertionError("unexpected probe"))), + ) + + status = check_hook_interpreter("python3") + assert status.available is True + assert status.interpreter == "python3" + assert status.resolved_path == "/usr/bin/python3" + assert status.resolution_kind == "path" + assert status.tried == ("python3",) + + def test_posix_path_command_missing(self, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + status = check_hook_interpreter("python3") + assert status.available is False + assert status.interpreter == "python3" + assert status.resolved_path is None + assert status.resolution_kind == "missing" + + def test_windows_path_command_working(self, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Python312\python.exe" if name == "python" else None, + ) + monkeypatch.setattr( + IntegrationBase, "_interpreter_runs", staticmethod(lambda path: True) + ) + + status = check_hook_interpreter("python") + assert status.available is True + assert status.resolved_path == r"C:\Python312\python.exe" + assert status.resolution_kind == "path" + + def test_windows_rejects_store_app_execution_alias_stub(self, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: ( + r"C:\Users\dev\AppData\Local\Microsoft\WindowsApps\python.exe" + if name == "python" + else None + ), + ) + monkeypatch.setattr( + IntegrationBase, "_interpreter_runs", staticmethod(lambda path: False) + ) + + status = check_hook_interpreter("python") + assert status.available is False + assert status.resolution_kind == "missing" + + def test_windows_py_launcher_positive_and_negative(self, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + ok = check_hook_interpreter("py -3") + assert ok.available is True + assert ok.interpreter == "py -3" + assert ok.resolved_path == r"C:\Windows\py.exe" + assert ok.resolution_kind == "path" + + # py.exe present but no Python 3 runtime installed. + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: False) + no_py3 = check_hook_interpreter("py -3") + assert no_py3.available is False + assert no_py3.resolution_kind == "missing" + + # py.exe missing from PATH altogether. + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + missing = check_hook_interpreter("py -3") + assert missing.available is False + + +class TestCheckHookInterpreterRelativeVenv: + """Positive and negative tests for project-relative .venv paths.""" + + def test_posix_relative_venv_executable_found(self, tmp_path, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + venv_py = _write_exec_shim(tmp_path / ".venv" / "bin" / "python", "#!/bin/sh\n") + + # Resolve against project_root even when cwd is somewhere else. + other = tmp_path / "elsewhere" + other.mkdir() + monkeypatch.chdir(other) + + status = check_hook_interpreter(".venv/bin/python", tmp_path) + assert status.available is True + assert status.resolution_kind == "venv" + assert status.resolved_path == str(venv_py) + + def test_posix_relative_venv_missing_or_not_executable_or_dir( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + assert check_hook_interpreter(".venv/bin/python", tmp_path).available is False + + if os.name != "nt": + non_exec = tmp_path / ".venv" / "bin" / "python" + non_exec.parent.mkdir(parents=True) + non_exec.write_text("#!/bin/sh\n", encoding="utf-8") + non_exec.chmod(stat.S_IRUSR | stat.S_IWUSR) + assert check_hook_interpreter(".venv/bin/python", tmp_path).available is False + non_exec.unlink() + + as_dir = tmp_path / ".venv" / "bin" / "python" + as_dir.mkdir(parents=True, exist_ok=True) + assert check_hook_interpreter(".venv/bin/python", tmp_path).available is False + + def test_windows_relative_venv_positive_and_negative(self, tmp_path, monkeypatch): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + venv_py = tmp_path / ".venv" / "Scripts" / "python.exe" + venv_py.parent.mkdir(parents=True) + venv_py.write_bytes(b"MZ\x90\x00") + + # Static default must never execute untrusted project-local binaries. + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod( + lambda path: (_ for _ in ()).throw(AssertionError(f"unexpected probe: {path}")) + ), + ) + for spelling in (".venv/Scripts/python.exe", r".venv\Scripts\python.exe"): + status = check_hook_interpreter(spelling, tmp_path) + assert status.available is True + assert status.resolution_kind == "venv" + + # 0-byte stub is rejected statically without executing it. + venv_py.write_bytes(b"") + assert ( + check_hook_interpreter(".venv/Scripts/python.exe", tmp_path).available + is False + ) + + # Explicit opt-in allows liveness probing of the venv interpreter. + venv_py.write_bytes(b"MZ\x90\x00") + probed: list[str] = [] + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: (probed.append(path), False)[1]), + ) + assert ( + check_hook_interpreter( + ".venv/Scripts/python.exe", tmp_path, allow_probe_untrusted=True + ).available + is False + ) + assert probed == [str(venv_py)] + + +class TestCheckHookInterpreterAbsolutePath: + """Positive and negative tests for absolute interpreter paths.""" + + def test_posix_absolute_path_with_spaces_positive_and_negative( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + exe = _write_exec_shim( + tmp_path / "my python dir" / "bin" / "python3", "#!/bin/sh\n" + ) + ok = check_hook_interpreter(str(exe), tmp_path) + assert ok.available is True + assert ok.resolution_kind == "absolute" + assert ok.resolved_path == str(exe) + + missing = check_hook_interpreter(str(tmp_path / "nope" / "python3"), tmp_path) + assert missing.available is False + assert missing.resolution_kind == "missing" + + if os.name != "nt": + exe.chmod(0o644) + assert check_hook_interpreter(str(exe), tmp_path).available is False + + def test_windows_absolute_path_positive_and_stub_negative( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + exe = tmp_path / "Python312" / "python.exe" + exe.parent.mkdir(parents=True) + exe.write_bytes(b"MZ\x90\x00") + + # Default static validation must not execute an arbitrary explicit binary. + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod( + lambda path: (_ for _ in ()).throw(AssertionError(f"unexpected probe: {path}")) + ), + ) + ok = check_hook_interpreter(str(exe), tmp_path) + assert ok.available is True + assert ok.resolution_kind == "absolute" + + # 0-byte WindowsApps Store stub is rejected statically without executing it. + store_stub = tmp_path / "Microsoft" / "WindowsApps" / "python.exe" + store_stub.parent.mkdir(parents=True) + store_stub.write_bytes(b"") + assert check_hook_interpreter(str(store_stub), tmp_path).available is False + + # Explicit opt-in runs the liveness probe. + monkeypatch.setattr( + IntegrationBase, "_interpreter_runs", staticmethod(lambda path: False) + ) + assert ( + check_hook_interpreter( + str(exe), tmp_path, allow_probe_untrusted=True + ).available + is False + ) + + # Windows drive path is treated as absolute even when checked on POSIX. + assert check_hook_interpreter(r"C:\Missing\python.exe", tmp_path).available is False + + def test_blank_interpreter_is_missing(self): + assert check_hook_interpreter("").available is False + assert check_hook_interpreter(" ").available is False + + +# -- Portable fallback generation and execution ----------------------------- + + +class TestPortableFallbackCommands: + """Portable fallback for Windows PowerShell 5.1, POSIX sh, host/cmd, and OpenCode.""" + + def test_windows_powershell_5_1_syntax_and_quoting(self, tmp_path): + cmd = _dispatcher_command( + CopilotIntegration(), + tmp_path, + "speckit.my 'cmd' $x; whoami", + "session_start", + target_os="windows", + timeout_seconds=90, + ) + # Strict Windows PowerShell 5.1 compatibility invariants. + assert cmd.startswith("& { ") + assert cmd.endswith(" }") + assert cmd.count("{") == cmd.count("}") + assert cmd.count("(") == cmd.count(")") + assert "&&" not in cmd + assert "||" not in cmd + assert "??" not in cmd + assert '"' not in cmd + # Avoids PS 5.1 empty-argument drop bug by using non-empty -c 'pass'. + assert "'-I' '-S' '-c' 'pass'" in cmd + # Probes isolate stdin via $null | so piped JSON reaches dispatcher intact. + assert "$null | & $venv '-I' '-S' '-c' 'pass' 1>$null 2>$null" in cmd + assert "$null | & $c '-I' '-S' '-c' 'pass' 1>$null 2>$null" in cmd + # Broken venv falls through to PATH python and py -3 (no else blocking fallthrough). + assert "} else {" not in cmd + # Propagates dispatcher exit code via $global:LASTEXITCODE. + assert "exit $global:LASTEXITCODE" in cmd + # Fallback order: .venv\Scripts\python.exe -> python -> py -3. + idx_venv = cmd.index(".venv\\Scripts\\python.exe") + idx_python = cmd.index("Get-Command 'python'") + idx_py = cmd.index("Get-Command 'py'") + assert idx_venv < idx_python < idx_py + assert "'-3'" in cmd + # Host-specific paths are never hard-coded into shared configs. + assert str(tmp_path) not in cmd + if sys.executable: + assert sys.executable not in cmd + # Command argument with spaces, single quotes, $, and ; is safely escaped. + assert "'speckit.my ''cmd'' $x; whoami'" in cmd + assert "'session_start' '90' 'additionalContext'" in cmd + + def test_host_and_cmd_use_py_launcher_on_windows_when_python_absent( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + + assert _resolve_interpreter(tmp_path) == "py -3" + claude_cmd = _dispatcher_command( + ClaudeIntegration(), tmp_path, "speckit.boot", "session_start", target_os="host" + ) + assert claude_cmd.startswith("py -3 ") + assert '"${CLAUDE_PROJECT_DIR}/.specify/events.py"' in claude_cmd + + vibe_cmd = _dispatcher_command( + VibeIntegration(), tmp_path, "speckit.guard", "pre_tool_use", target_os="cmd" + ) + assert vibe_cmd.startswith("py -3 ") + assert "'py -3'" not in vibe_cmd + assert '"py -3"' not in vibe_cmd + + def test_host_skips_windows_store_stubs_and_picks_py_launcher( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: { + "python3": r"C:\Users\dev\AppData\Local\Microsoft\WindowsApps\python3.exe", + "python": r"C:\Users\dev\AppData\Local\Microsoft\WindowsApps\python.exe", + "py": r"C:\Windows\py.exe", + }.get(name), + ) + monkeypatch.setattr( + IntegrationBase, "_interpreter_runs", staticmethod(lambda path: False) + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + + assert _resolve_interpreter(tmp_path) == "py -3" + + def test_host_prefers_project_venv_over_path_and_py_launcher( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + venv_py = tmp_path / ".venv" / "Scripts" / "python.exe" + venv_py.parent.mkdir(parents=True) + venv_py.write_bytes(b"MZ\x90\x00") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + assert _resolve_interpreter(tmp_path) == ".venv/Scripts/python.exe" + + def test_host_never_hardcodes_ephemeral_sys_executable_when_path_empty( + self, tmp_path, monkeypatch + ): + """Under uvx with no system Python on PATH, emit portable default instead of uvx path.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + monkeypatch.setattr( + "specify_cli.events.sys.executable", + "/tmp/uv-ephemeral/archive-v0/abc/bin/python", + ) + assert _resolve_interpreter(tmp_path) == "python3" + + def test_opencode_ts_plugin_includes_py_launcher_and_posix_fallbacks( + self, tmp_path + ): + manifest = MagicMock(spec=IntegrationManifest) + manifest.files = {} + manifest.record_file = MagicMock() + manifest.record_existing = MagicMock() + install_integration_events( + OpencodeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + content = (tmp_path / ".opencode/plugin/speckit-events.ts").read_text( + encoding="utf-8" + ) + assert "INTERPRETER_ARGS" in content + assert "canRunPython" in content + assert "['py', ['-3']]" in content + assert "['python3', []]" in content + assert "['python', []]" in content + + @pytest.mark.skipif(not HAS_SH, reason="POSIX sh unavailable") + def test_posix_fallback_real_execution_prefers_venv_then_python3_then_python_then_py3( + self, tmp_path + ): + """Execute generated target_os='posix' command under real /bin/sh.""" + _install_echo_dispatcher_project(tmp_path) + cmd = _dispatcher_command( + CopilotIntegration(), + tmp_path, + "speckit.a b; touch should_not_exist", + "session_start", + target_os="posix", + timeout_seconds=45, + ) + real_py = shlex.quote(sys.executable) + + def run_with_bin(bin_dir: Path, payload: str = '{"hello": "world"}'): + # Include /bin:/usr/bin so sh builtins/basic env work cleanly, + # while only exposing our controlled shims for python3/python/py. + env = { + "PATH": str(bin_dir), + "HOME": str(tmp_path), + } + return subprocess.run( + ["/bin/sh", "-c", cmd], + check=False, + input=payload, + capture_output=True, + text=True, + cwd=tmp_path, + env=env, + timeout=15, + ) + + # 1. Stub python3 + stub python + working py -3 -> picks py -3! + bin_py3_only = tmp_path / "bin_py3_only" + _write_exec_shim(bin_py3_only / "python3", "#!/bin/sh\nexit 49\n") + _write_exec_shim(bin_py3_only / "python", "#!/bin/sh\nexit 49\n") + _write_exec_shim( + bin_py3_only / "py", + f"#!/bin/sh\n" + f'if [ "$1" = "-3" ]; then shift; SHIM_TAG=py3 exec {real_py} "$@"; fi\n' + f"exit 103\n", + ) + res = run_with_bin(bin_py3_only, '{"from": "py-launcher"}') + assert res.returncode == 0, res.stderr + data = json.loads(res.stdout) + assert data["tag"] == "py3" + assert data["stdin"] == '{"from": "py-launcher"}' + assert data["argv"] == [ + "speckit.a b; touch should_not_exist", + "session_start", + "45", + "additionalContext", + ] + assert not (tmp_path / "should_not_exist").exists() + + # 2. Stub python3 + working python -> picks python! + bin_python_only = tmp_path / "bin_python_only" + _write_exec_shim(bin_python_only / "python3", "#!/bin/sh\nexit 49\n") + _write_exec_shim( + bin_python_only / "python", + f'#!/bin/sh\nSHIM_TAG=python exec {real_py} "$@"\n', + ) + res = run_with_bin(bin_python_only) + assert res.returncode == 0, res.stderr + assert json.loads(res.stdout)["tag"] == "python" + + # 3. Working python3 -> picks python3! + bin_python3 = tmp_path / "bin_python3" + _write_exec_shim( + bin_python3 / "python3", + f'#!/bin/sh\nSHIM_TAG=python3 exec {real_py} "$@"\n', + ) + res = run_with_bin(bin_python3) + assert res.returncode == 0, res.stderr + assert json.loads(res.stdout)["tag"] == "python3" + + # 4. Project .venv/bin/python as a directory or broken executable falls through! + venv_dir = tmp_path / ".venv" / "bin" / "python" + venv_dir.mkdir(parents=True) + res = run_with_bin(bin_python3) + assert res.returncode == 0, res.stderr + assert json.loads(res.stdout)["tag"] == "python3" + venv_dir.rmdir() + + _write_exec_shim(tmp_path / ".venv" / "bin" / "python", "#!/bin/sh\nexit 1\n") + res = run_with_bin(bin_python3) + assert res.returncode == 0, res.stderr + assert json.loads(res.stdout)["tag"] == "python3" + (tmp_path / ".venv" / "bin" / "python").unlink() + + # 5. Working project .venv/bin/python takes precedence over PATH python3! + _write_exec_shim( + tmp_path / ".venv" / "bin" / "python", + f'#!/bin/sh\nSHIM_TAG=venv exec {real_py} "$@"\n', + ) + res = run_with_bin(bin_python3) + assert res.returncode == 0, res.stderr + assert json.loads(res.stdout)["tag"] == "venv" + (tmp_path / ".venv" / "bin" / "python").unlink() + + # 6. Missing all interpreters -> actionable stderr and exit 127. + empty_bin = tmp_path / "bin_empty" + empty_bin.mkdir() + res = run_with_bin(empty_bin) + assert res.returncode == 127 + assert "no Python 3 interpreter found" in res.stderr + + # 7. Non-zero exit code from dispatcher propagates (no fallback re-run). + _install_echo_dispatcher_project(tmp_path, exit_code=7) + res = run_with_bin(bin_python3) + assert res.returncode == 7 + assert json.loads(res.stdout)["tag"] == "python3" + + @pytest.mark.skipif(not POWERSHELL_EXE, reason="PowerShell not available on this host") + def test_powershell_fallback_real_execution_with_py_launcher(self, tmp_path): + """End-to-end execution of the generated PowerShell 5.1 command when only py works.""" + _install_echo_dispatcher_project(tmp_path) + cmd = _dispatcher_command( + CopilotIntegration(), + tmp_path, + "speckit.my 'cmd'", + "session_start", + target_os="windows", + timeout_seconds=30, + ) + shim_dir = tmp_path / "shims" + shim_dir.mkdir() + if os.name == "nt": + # Broken .venv/Scripts/python.exe must be probed and skipped rather than + # shadowing working PATH / py -3 fallbacks. + broken_venv = tmp_path / ".venv" / "Scripts" / "python.exe" + broken_venv.parent.mkdir(parents=True) + broken_venv.write_bytes(b"not a valid PE executable") + # Stub python.cmd exits 9009 (Store alias); py.cmd forwards -3 to sys.executable. + (shim_dir / "python.cmd").write_text("@echo off\r\nexit /b 9009\r\n", encoding="utf-8") + (shim_dir / "py.cmd").write_text( + f'@echo off\r\nif not "%~1"=="-3" exit /b 103\r\n' + f'set SHIM_TAG=win-py3\r\n' + f'"{sys.executable}" %2 %3 %4 %5 %6 %7 %8 %9\r\n' + f'exit /b %ERRORLEVEL%\r\n', + encoding="utf-8", + ) + system_root = Path(os.environ.get("SystemRoot", r"C:\Windows")) + isolated_path = os.pathsep.join( + [ + str(shim_dir), + str(system_root / "System32"), + str(system_root / "System32" / "WindowsPowerShell" / "v1.0"), + ] + ) + env = os.environ.copy() + env["PATH"] = isolated_path + else: + _write_exec_shim(shim_dir / "python", "#!/bin/sh\nexit 9009\n") + _write_exec_shim( + shim_dir / "py", + f'#!/bin/sh\nif [ "$1" = "-3" ]; then shift; SHIM_TAG=win-py3 exec {shlex.quote(sys.executable)} "$@"; fi\nexit 103\n', + ) + env = {**os.environ, "PATH": str(shim_dir)} + + res = subprocess.run( + [POWERSHELL_EXE, "-NoProfile", "-Command", cmd], + check=False, + input='{"win": true}', + capture_output=True, + text=True, + cwd=tmp_path, + env=env, + timeout=20, + ) + assert res.returncode == 0, res.stderr + data = json.loads(res.stdout) + assert data["tag"] == "win-py3" + assert data["stdin"] == '{"win": true}' + assert data["argv"] == [ + "speckit.my 'cmd'", + "session_start", + "30", + "additionalContext", + ] + + +# -- Install / upgrade / refresh warnings ----------------------------------- + + +class TestInstallAndRefreshInterpreterWarnings: + """Missing hook interpreter warns at install/upgrade/refresh without failing.""" + + @pytest.mark.parametrize( + "integration_cls", + [ + ClaudeIntegration, + CopilotIntegration, + CodexIntegration, + CursorAgentIntegration, + DevinIntegration, + OpencodeIntegration, + ], + ) + def test_install_warns_when_no_interpreter_available( + self, tmp_path, monkeypatch, capsys, integration_cls + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + integration = integration_cls() + manifest = IntegrationManifest(integration.key, tmp_path) + created = install_integration_events( + integration, + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + # Installation succeeds despite missing interpreter. + assert created + err = capsys.readouterr().err + assert "python3" in err + assert integration.key in err + assert "PATH" in err + assert f"specify integration upgrade {integration.key}" in err + + def test_install_no_warning_when_interpreter_available( + self, tmp_path, monkeypatch, capsys + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: path == "/usr/bin/python3"), + ) + for integration in (ClaudeIntegration(), CopilotIntegration()): + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events( + integration, + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + assert capsys.readouterr().err == "" + + def test_install_no_warning_on_windows_with_py_launcher_only( + self, tmp_path, monkeypatch, capsys + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + + for integration in (CopilotIntegration(), ClaudeIntegration()): + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events( + integration, + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + assert capsys.readouterr().err == "" + + def test_install_no_warning_when_events_disabled( + self, tmp_path, monkeypatch, capsys + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + manifest = IntegrationManifest("claude", tmp_path) + created = install_integration_events(ClaudeIntegration(), tmp_path, manifest, {}) + assert created == [] + assert capsys.readouterr().err == "" + + def test_refresh_integration_events_warns_on_missing_interpreter( + self, tmp_path, monkeypatch, capsys + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + specify_dir = tmp_path / ".specify" + specify_dir.mkdir(parents=True) + (specify_dir / "integration.json").write_text( + json.dumps( + { + "integration": "copilot", + "default_integration": "copilot", + "installed_integrations": ["copilot"], + } + ), + encoding="utf-8", + ) + ext_dir = specify_dir / "extensions" / "demo" + ext_dir.mkdir(parents=True) + (ext_dir / "extension.yml").write_text( + "schema_version: '1.0'\n" + "extension:\n id: demo\n name: Demo\n version: 1.0.0\n description: Demo\n" + "requires:\n speckit_version: '>=0.1.0'\n" + "provides:\n commands: []\n" + "events:\n session_start:\n command: speckit.demo.boot\n", + encoding="utf-8", + ) + manifest = IntegrationManifest("copilot", tmp_path) + manifest.save() + + refresh_integration_events(tmp_path) + err = capsys.readouterr().err + assert "python3" in err + assert "specify integration upgrade copilot" in err + + +# -- Installed hook inspection & preflight_hook_interpreter ----------------- + + +class TestInstalledHookInspectionAndPreflight: + """Verify helper parity across formats and preflight error behavior.""" + + def test_extract_interpreter_from_command_handles_quoting_and_fallbacks(self): + assert _extract_interpreter_from_command("python3 .specify/events.py cmd ev 60") == "python3" + assert _extract_interpreter_from_command("py -3 .specify/events.py cmd ev 60") == "py -3" + assert ( + _extract_interpreter_from_command( + "'.venv/bin/python' \"${CLAUDE_PROJECT_DIR}/.specify/events.py\" cmd ev 60" + ) + == ".venv/bin/python" + ) + assert ( + _extract_interpreter_from_command( + '"C:\\Program Files\\Python\\python.exe" .specify/events.py cmd ev 60', + cmd_quoting=True, + ) + == r"C:\Program Files\Python\python.exe" + ) + assert ( + _extract_interpreter_from_command( + "py -3 .specify/events.py cmd ev 60", cmd_quoting=True + ) + == "py -3" + ) + assert ( + _extract_interpreter_from_command( + "& 'python' '.specify/events.py' 'cmd' 'ev' '60'", + powershell_quoting=True, + ) + == "python" + ) + assert ( + _extract_interpreter_from_command( + "& 'C:\\Bob''s Python\\python.exe' '.specify/events.py' 'cmd'", + powershell_quoting=True, + ) + == r"C:\Bob's Python\python.exe" + ) + assert ( + _extract_interpreter_from_command( + "& 'py' '-3' '.specify/events.py' 'cmd'", + powershell_quoting=True, + ) + == "py -3" + ) + # Portable fallback wrappers delegate to candidate chain checks. + assert _extract_interpreter_from_command("& { $py = $null }") is None + assert _extract_interpreter_from_command("set -- .specify/events.py; fi") is None + + def test_has_installed_integration_events_detects_installed_vs_absent( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + for integration in ( + ClaudeIntegration(), + CopilotIntegration(), + CodexIntegration(), + CursorAgentIntegration(), + DevinIntegration(), + OpencodeIntegration(), + VibeIntegration(), + ): + proj = tmp_path / integration.key + proj.mkdir() + assert has_installed_integration_events(integration, proj) is False + manifest = IntegrationManifest(integration.key, proj) + ev = "pre_tool_use" if integration.key == "vibe" else "session_start" + install_integration_events( + integration, proj, manifest, {ev: [{"command": "speckit.boot"}]} + ) + assert has_installed_integration_events(integration, proj) is True + + def test_preflight_hook_interpreter_raises_actionable_error( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + copilot = CopilotIntegration() + with pytest.raises(HookInterpreterError) as exc_info: + preflight_hook_interpreter(copilot, tmp_path, required=True) + + err = exc_info.value + assert err.integration_key == "copilot" + assert err.status.available is False + assert "python" in str(err) + assert "py -3" in str(err) + assert "specify integration upgrade copilot" in str(err) + + def test_check_integration_hook_interpreter_uses_installed_venv_path( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + venv_py = _write_exec_shim(tmp_path / ".venv" / "bin" / "python", "#!/bin/sh\n") + claude = ClaudeIntegration() + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + claude, tmp_path, manifest, {"session_start": [{"command": "speckit.boot"}]} + ) + + # Installed hook pins .venv/bin/python: removing it must fail even if PATH has python3. + venv_py.unlink() + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + status = check_integration_hook_interpreter(claude, tmp_path) + assert status.available is False + assert status.interpreter == ".venv/bin/python" + assert ".venv/bin/python" in (status.message or "") + assert format_missing_hook_interpreter_message(status, "claude") == status.message + + +class TestSecurityAndCrossPlatformEdgeCases: + """Regression tests for untrusted binary safety, fallback probing, and installed-hook inspection.""" + + def test_windows_checked_in_hook_binary_is_never_probed_without_opt_in( + self, tmp_path, monkeypatch + ): + """Checked-in hook JSON binaries and inside-project PATH entries never execute.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + proj = tmp_path / "untrusted_repo" + proj.mkdir() + evil_exe = proj / "evil.exe" + evil_exe.write_bytes(b"MZ\x90\x00") + (proj / ".specify").mkdir() + (proj / ".specify" / "events.py").write_text("", encoding="utf-8") + claude_cfg = proj / ".claude" / "settings.json" + claude_cfg.parent.mkdir(parents=True) + claude_cfg.write_text( + json.dumps( + { + "hooks": { + "SessionStart": [ + { + "matcher": "*", + "hooks": [ + { + "type": "command", + "command": f'"{evil_exe}" .specify/events.py speckit.boot session_start 60', + "__speckit_event__": True, + } + ], + } + ] + } + } + ), + encoding="utf-8", + ) + + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod( + lambda path: (_ for _ in ()).throw( + AssertionError(f"must not execute untrusted binary: {path}") + ) + ), + ) + monkeypatch.setattr( + "specify_cli.events._py_launcher_runs", + lambda path: (_ for _ in ()).throw( + AssertionError(f"must not execute untrusted launcher: {path}") + ), + ) + + status = check_integration_hook_interpreter(ClaudeIntegration(), proj) + assert status.available is True + assert status.resolved_path == str(evil_exe) + + # PATH entry resolving inside project_root must also never be spawned. + local_py = proj / "python.exe" + local_py.write_bytes(b"MZ\x90\x00") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: str(local_py) if name == "python" else None, + ) + path_status = check_hook_interpreter("python", proj) + assert path_status.available is True + assert path_status.resolved_path == str(local_py) + assert _resolve_interpreter(proj) == "python" + + # 0-byte WindowsApps AppExecutionAlias reparse tag is rejected statically. + class _FakeAppExecStat: + st_reparse_tag = 0x8000001B + st_size = 128 + + monkeypatch.setattr("specify_cli.events.os.lstat", lambda p: _FakeAppExecStat()) + assert check_hook_interpreter(str(evil_exe), proj).available is False + + def test_posix_fallback_chain_probes_system_path_and_skips_failing_shims( + self, tmp_path, monkeypatch + ): + """POSIX fallback checker probes system PATH candidates outside project_root.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + proj = tmp_path / "project" + proj.mkdir() + ext_bin = tmp_path / "external_bin" + ext_bin.mkdir() + + if os.name == "nt": + pytest.skip("POSIX executable shims require a non-Windows host") + + # Failing python3 shim + working python shim -> Copilot and OpenCode pick python. + _write_exec_shim(ext_bin / "python3", "#!/bin/sh\nexit 1\n") + _write_exec_shim( + ext_bin / "python", + f'#!/bin/sh\nexec {shlex.quote(sys.executable)} "$@"\n', + ) + monkeypatch.setenv("PATH", str(ext_bin)) + + copilot_status = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ) + assert copilot_status.available is True + assert copilot_status.interpreter == "python" + assert copilot_status.resolution_kind == "fallback" + + opencode_status = check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=False + ) + assert opencode_status.available is True + assert opencode_status.interpreter == "python" + assert opencode_status.resolution_kind == "fallback" + + # Failing python3 + failing python + working py -3 -> Copilot picks py -3, OpenCode fails. + _write_exec_shim(ext_bin / "python", "#!/bin/sh\nexit 1\n") + _write_exec_shim( + ext_bin / "py", + f'#!/bin/sh\nif [ "$1" = "-3" ]; then shift; exec {shlex.quote(sys.executable)} "$@"; fi\nexit 103\n', + ) + copilot_py = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ) + assert copilot_py.available is True + assert copilot_py.interpreter == "py -3" + assert copilot_py.resolution_kind == "fallback" + + assert ( + check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=False + ).available + is False + ) + + # Failing py shim as well -> Copilot preflight fails cleanly. + _write_exec_shim(ext_bin / "py", "#!/bin/sh\nexit 103\n") + assert ( + check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ).available + is False + ) + + # Fixed-command check_hook_interpreter still preserves non-probing POSIX behavior. + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod( + lambda path: (_ for _ in ()).throw(AssertionError("unexpected probe")) + ), + ) + fixed = check_hook_interpreter("python3", proj) + assert fixed.available is True + assert fixed.resolved_path == str(ext_bin / "python3") + + def test_inspect_installed_copilot_rejects_legacy_fixed_hook_fallback( + self, tmp_path, monkeypatch + ): + """Legacy fixed Copilot hooks do not pass via the new portable fallback chain.""" + proj = tmp_path / "project" + (proj / ".specify").mkdir(parents=True) + (proj / ".specify" / "events.py").write_text("", encoding="utf-8") + hooks_path = proj / ".github" / "hooks" / "speckit.json" + hooks_path.parent.mkdir(parents=True) + hooks_path.write_text( + json.dumps( + { + "version": 1, + "hooks": { + "sessionStart": [ + { + "type": "command", + "bash": "python3 .specify/events.py speckit.boot session_start 60", + "powershell": "& 'python' '.specify/events.py' 'speckit.boot' 'session_start' '60'", + "__speckit_event__": True, + } + ] + }, + } + ), + encoding="utf-8", + ) + + # POSIX: only `python` exists, not `python3` -> legacy bash hook must fail! + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python" if name == "python" else None, + ) + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: path == "/usr/bin/python"), + ) + legacy_posix = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=True + ) + assert legacy_posix.available is False + assert legacy_posix.interpreter == "python3" + assert ( + check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ).available + is True + ) + + # Windows: only `py -3` exists, not `python` -> legacy powershell hook must fail! + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + legacy_win = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=True + ) + assert legacy_win.available is False + assert legacy_win.interpreter == "python" + assert ( + check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ).available + is True + ) + + # Re-installing with portable hooks allows inspect_installed=True to use fallback. + manifest = IntegrationManifest("copilot", proj) + install_integration_events( + CopilotIntegration(), + proj, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + portable_win = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=True + ) + assert portable_win.available is True + assert portable_win.interpreter == "py -3" + assert portable_win.resolution_kind == "fallback" + + def test_inspect_installed_opencode_rejects_legacy_plugin_fallback( + self, tmp_path, monkeypatch + ): + """Legacy OpenCode plugins without canRunPython do not use the new fallback chain.""" + proj = tmp_path / "project" + plugin_path = proj / ".opencode" / "plugin" / "speckit-events.ts" + plugin_path.parent.mkdir(parents=True) + plugin_path.write_text( + "let INTERPRETER = '';\n" + "function resolveDispatcher(directory: string): void {\n" + " INTERPRETER = (process.platform === 'win32' ? 'python' : 'python3') as string;\n" + "}\n", + encoding="utf-8", + ) + + # Windows with py -3 only: legacy plugin only knows 'python' -> fails. + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + legacy_win = check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=True + ) + assert legacy_win.available is False + assert legacy_win.interpreter == "python" + + # POSIX with python only: legacy plugin only knows 'python3' -> fails. + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python" if name == "python" else None, + ) + monkeypatch.setattr( + IntegrationBase, + "_interpreter_runs", + staticmethod(lambda path: path == "/usr/bin/python"), + ) + legacy_posix = check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=True + ) + assert legacy_posix.available is False + assert legacy_posix.interpreter == "python3" + + # Re-installing portable OpenCode plugin enables fallback chain inspection. + manifest = IntegrationManifest("opencode", proj) + install_integration_events( + OpencodeIntegration(), + proj, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + portable_posix = check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=True + ) + assert portable_posix.available is True + assert portable_posix.interpreter == "python" + assert portable_posix.resolution_kind == "fallback" + + # Custom fixed INTERPRETER assignment in plugin source is checked directly. + custom_py = _write_exec_shim(tmp_path / "custom" / "python3", "#!/bin/sh\n") + plugin_path.write_text( + f"let INTERPRETER = '{custom_py}';\n", + encoding="utf-8", + ) + custom_status = check_integration_hook_interpreter( + OpencodeIntegration(), proj, inspect_installed=True + ) + assert custom_status.available is True + assert custom_status.interpreter == str(custom_py) + assert custom_status.resolution_kind == "absolute" + + def test_windows_portable_chain_enumerates_all_path_entries_after_store_alias( + self, tmp_path, monkeypatch + ): + """Store alias preceding real python.exe passes Copilot fallback and fails fixed lookup.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + proj = tmp_path / "project" + proj.mkdir() + store_dir = tmp_path / "WindowsApps" + real_dir = tmp_path / "Python312" + store_dir.mkdir() + real_dir.mkdir() + store_py = store_dir / "python.exe" + real_py = real_dir / "python.exe" + store_py.write_bytes(b"") + real_py.write_bytes(b"MZ\x90\x00") + + monkeypatch.setenv("PATH", os.pathsep.join([str(store_dir), str(real_dir)])) + monkeypatch.setenv("PATHEXT", ".COM;.EXE;.BAT;.CMD") + + probed: list[str] = [] + + def fake_runs(path: str) -> bool: + probed.append(path) + return Path(path) == real_py + + monkeypatch.setattr(IntegrationBase, "_interpreter_runs", staticmethod(fake_runs)) + + # Portable Copilot fallback enumerates all PATH entries and finds real_py. + copilot_status = check_integration_hook_interpreter( + CopilotIntegration(), proj, inspect_installed=False + ) + assert copilot_status.available is True + assert copilot_status.interpreter == "python" + assert copilot_status.resolved_path == str(real_py) + assert copilot_status.resolution_kind == "path" + assert probed == [str(store_py), str(real_py)] + + # Fixed command lookup preserves first-match semantics (store_py first -> fails). + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: str(store_py) if name == "python" else None, + ) + fixed_status = check_hook_interpreter("python", proj) + assert fixed_status.available is False + + def test_posix_fallback_command_checks_regular_file_and_probes_venv(self, tmp_path): + """Generated POSIX sh fallback requires -f, -x, and a stdin-isolated probe.""" + cmd = _dispatcher_command( + CopilotIntegration(), + tmp_path, + "speckit.boot", + "session_start", + target_os="posix", + ) + assert "_venv=.venv/bin/python;" in cmd + assert '[ -f "$_venv" ] && [ -x "$_venv" ]' in cmd + assert '"$_venv" -I -S -c pass /dev/null 2>&1' in cmd + + def test_windows_powershell_selector_prefers_windows_powershell_5_1(self): + """On Windows, prefer powershell.exe / powershell over pwsh.""" + both = { + "pwsh": r"C:\Program Files\PowerShell\7\pwsh.exe", + "powershell.exe": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", + "powershell": r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", + } + assert _select_powershell_exe("win32", both.get) == both["powershell.exe"] + assert _select_powershell_exe("linux", both.get) == both["pwsh"] + if sys.platform == "win32" and POWERSHELL_EXE is not None: + exe_name = Path(POWERSHELL_EXE).name.lower() + if shutil.which("powershell.exe") or shutil.which("powershell"): + assert exe_name in ("powershell.exe", "powershell") diff --git a/tests/specify_cli/events/test_mcp.py b/tests/specify_cli/events/test_mcp.py new file mode 100644 index 0000000000..a88e20553d --- /dev/null +++ b/tests/specify_cli/events/test_mcp.py @@ -0,0 +1,179 @@ +"""Parity between real ``specify event`` CLI registration and its explicit MCP inventory.""" + +from __future__ import annotations + +import asyncio +from collections import Counter +from collections.abc import Sequence +from dataclasses import FrozenInstanceError, replace + +import pytest +from mcp.types import Tool +from typer.core import TyperGroup +from typer.main import get_command + +from specify_cli import app +from specify_cli.events import _mcp, event_app +from specify_cli.mcp_server.server import create_server + + +def _event_cli_paths() -> list[str]: + """Walk the registered ``specify event`` CLI tree without executing handlers.""" + root = get_command(app) + + def walk(group: TyperGroup, prefix: str) -> list[str]: + paths: list[str] = [] + for name, command in group.commands.items(): + path = f"{prefix} {name}" + if isinstance(command, TyperGroup): + paths.extend(walk(command, path)) + else: + paths.append(path) + return paths + + return walk(root.commands["event"], "specify event") + + +def _assert_inventory( + records: Sequence[_mcp.EventToolInventory], + cli_paths: Sequence[str], + tools: Sequence[Tool], +) -> None: + for label, values in ( + ("operation IDs", [item.operation_id for item in records]), + ("CLI paths", [item.cli_path for item in records]), + ("tool names", [item.mcp_tool_name for item in records]), + ): + duplicates = sorted( + value for value, count in Counter(values).items() if count > 1 + ) + assert not duplicates, f"Duplicate {label}: {duplicates}" + + inventory_paths = {item.cli_path for item in records} + missing = sorted(set(cli_paths) - inventory_paths) + stale = sorted(inventory_paths - set(cli_paths)) + assert not missing, f"Missing CLI paths: {missing}" + assert not stale, f"Stale CLI paths: {stale}" + + for item in records: + assert item.cli_path.startswith("specify event "), item.cli_path + expected_id = item.cli_path.removeprefix("specify ").replace(" ", ".") + assert item.operation_id == expected_id, ( + f"Invalid operation ID: {item.operation_id}" + ) + expected_tool = "specify_" + expected_id.replace(".", "_").replace("-", "_") + assert item.mcp_tool_name == expected_tool, ( + f"Invalid tool name: {item.mcp_tool_name}" + ) + assert item.disposition in {"available", "unavailable", "excluded"}, ( + f"Invalid disposition: {item.operation_id}" + ) + assert isinstance(item.capabilities, frozenset) and item.capabilities, ( + f"Invalid capabilities: {item.operation_id}" + ) + assert item.capabilities <= { + "local-read", + "project-write", + "execution", + "self-modifying", + }, f"Invalid capabilities: {item.operation_id}" + assert item.network_access in {"none", "optional", "required"}, ( + f"Invalid network access: {item.operation_id}" + ) + assert item.contract_version is None or ( + isinstance(item.contract_version, str) and item.contract_version.strip() + ), f"Invalid contract version: {item.operation_id}" + + matching = [tool for tool in tools if tool.name == item.mcp_tool_name] + if item.disposition == "available": + assert item.contract_version, f"Missing contract: {item.operation_id}" + assert item.disposition_reason is None, ( + f"Available reason: {item.operation_id}" + ) + assert len(matching) == 1, f"Expected registered tool: {item.operation_id}" + else: + assert item.contract_version is None, ( + f"Nonavailable tool has contract version: {item.operation_id}" + ) + assert ( + isinstance(item.disposition_reason, str) + and item.disposition_reason.strip() + ), f"Missing disposition reason: {item.operation_id}" + assert not matching, f"Nonavailable tool registered: {item.operation_id}" + + inventory_names = {item.mcp_tool_name for item in records} + unexpected = sorted( + tool.name + for tool in tools + if tool.name.startswith("specify_event_") + and tool.name not in inventory_names + ) + assert not unexpected, f"Uninventoried event tools: {unexpected}" + + +def test_event_inventory_matches_actual_cli_and_server(tmp_path): + server = create_server(launch_directory=tmp_path) + tools = asyncio.run(server.list_tools()) + + _assert_inventory(_mcp.EVENT_TOOLS, _event_cli_paths(), tools) + + +def test_event_inventory_records_are_immutable(): + with pytest.raises(FrozenInstanceError): + _mcp.EVENT_TOOLS[0].disposition = "available" + + +def test_event_check_and_run_capabilities_and_dispositions(): + by_id = {item.operation_id: item for item in _mcp.EVENT_TOOLS} + assert set(by_id) == {"event.check", "event.run"} + + check = by_id["event.check"] + assert check.cli_path == "specify event check" + assert check.mcp_tool_name == "specify_event_check" + assert check.disposition == "unavailable" + assert check.contract_version is None + assert check.disposition_reason and "event.check" in check.disposition_reason + assert check.capabilities == frozenset({"local-read", "execution"}) + assert check.network_access == "none" + + run = by_id["event.run"] + assert run.cli_path == "specify event run" + assert run.mcp_tool_name == "specify_event_run" + assert run.disposition == "unavailable" + assert run.contract_version is None + assert run.disposition_reason and "event.run" in run.disposition_reason + assert run.capabilities == frozenset({"local-read", "project-write", "execution"}) + assert run.network_access == "optional" + + +def test_new_event_cli_leaf_requires_inventory_disposition(monkeypatch): + monkeypatch.setattr( + event_app, "registered_commands", list(event_app.registered_commands) + ) + + @event_app.command("inventory-probe") + def probe(): + raise AssertionError("CLI traversal must not execute handlers") + + paths = _event_cli_paths() + assert "specify event inventory-probe" in paths + with pytest.raises(AssertionError, match="Missing CLI paths"): + _assert_inventory(_mcp.EVENT_TOOLS, paths, []) + + +def test_missing_or_stale_or_unexplained_event_inventory_is_rejected(): + with pytest.raises(AssertionError, match="Missing CLI paths"): + _assert_inventory(_mcp.EVENT_TOOLS[1:], _event_cli_paths(), []) + + stale = replace( + _mcp.EVENT_TOOLS[0], + operation_id="event.removed", + cli_path="specify event removed", + mcp_tool_name="specify_event_removed", + ) + with pytest.raises(AssertionError, match="Stale CLI paths"): + _assert_inventory((*_mcp.EVENT_TOOLS, stale), _event_cli_paths(), []) + + no_reason = replace(_mcp.EVENT_TOOLS[0], disposition_reason="") + with pytest.raises(AssertionError, match="Missing disposition reason"): + _assert_inventory([no_reason], [no_reason.cli_path], []) diff --git a/tests/workflows/test_hook_preflight.py b/tests/workflows/test_hook_preflight.py new file mode 100644 index 0000000000..1a3480b8d8 --- /dev/null +++ b/tests/workflows/test_hook_preflight.py @@ -0,0 +1,413 @@ +"""Tests for workflow step hook-interpreter pre-flight checks.""" + +from __future__ import annotations + +from unittest.mock import MagicMock, patch + +from specify_cli.events import install_integration_events +from specify_cli.integrations.claude import ClaudeIntegration +from specify_cli.integrations.copilot import CopilotIntegration +from specify_cli.integrations.manifest import IntegrationManifest +from specify_cli.workflows.base import StepContext, StepStatus +from specify_cli.workflows.step.command import CommandStep +from specify_cli.workflows.step.prompt import PromptStep + + +class TestCommandStepHookPreflight: + """Command steps that depend on event hooks fail fast before CLI startup.""" + + def test_fails_before_cli_spawn_when_installed_hook_interpreter_missing( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + # Now python3 is absent from PATH when the workflow runs. + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = {"id": "specify", "command": "speckit.specify"} + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "specify_cli.integrations.base.IntegrationBase.dispatch_command", + side_effect=AssertionError("agent CLI must not start on failed hook preflight"), + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert result.output["exit_code"] == 1 + assert "specify" in (result.error or "") + assert "python3" in (result.error or "") + assert "specify integration upgrade claude" in (result.error or "") + assert not mock_dispatch.called + + def test_fails_before_cli_spawn_when_installed_venv_was_deleted( + self, tmp_path, monkeypatch + ): + """Even if python3 is on PATH, a hook pinned to a deleted .venv fails preflight.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + venv_py = tmp_path / ".venv" / "bin" / "python" + venv_py.parent.mkdir(parents=True) + venv_py.write_text("#!/bin/sh\n", encoding="utf-8") + venv_py.chmod(0o755) + + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + # Delete the project venv while leaving python3 available on PATH. + venv_py.unlink() + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = {"id": "plan", "command": "speckit.plan"} + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "specify_cli.integrations.base.IntegrationBase.dispatch_command", + side_effect=AssertionError("agent CLI must not start when venv interpreter is gone"), + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert ".venv/bin/python" in (result.error or "") + assert "specify integration upgrade claude" in (result.error or "") + assert not mock_dispatch.called + + def test_fails_before_cli_spawn_when_additional_context_requires_hook( + self, tmp_path, monkeypatch + ): + """A step declaring additional_context fails fast even without installed hooks.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = { + "id": "contextual", + "command": "speckit.plan", + "additional_context": "Inject workflow context via session_start hook.", + } + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "specify_cli.integrations.base.IntegrationBase.dispatch_command", + side_effect=AssertionError("agent CLI must not start when hook interpreter is missing"), + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert "contextual" in (result.error or "") + assert "python3" in (result.error or "") + assert "specify integration upgrade claude" in (result.error or "") + assert not mock_dispatch.called + + def test_passes_and_dispatches_on_windows_copilot_with_py_launcher_only( + self, tmp_path, monkeypatch + ): + """On Windows without python but with py -3, Copilot hook preflight passes.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "win32") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: r"C:\Windows\py.exe" if name == "py" else None, + ) + monkeypatch.setattr("specify_cli.events._py_launcher_runs", lambda path: True) + + manifest = IntegrationManifest("copilot", tmp_path) + install_integration_events( + CopilotIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + step = CommandStep() + ctx = StepContext(default_integration="copilot", project_root=str(tmp_path)) + config = { + "id": "win-copilot", + "command": "speckit.plan", + "additional_context": "extra context", + } + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: { + "copilot": r"C:\Tools\copilot.exe", + "py": r"C:\Windows\py.exe", + }.get(name), + ), + patch.object( + CopilotIntegration, + "dispatch_command", + return_value={"exit_code": 0, "stdout": "ok", "stderr": ""}, + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.COMPLETED + assert result.output["dispatched"] is True + assert mock_dispatch.called + + def test_skips_hook_preflight_when_no_hooks_installed_and_no_additional_context( + self, tmp_path, monkeypatch + ): + """Projects without installed hooks do not fail if Python is absent from PATH.""" + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = {"id": "plain", "command": "speckit.plan"} + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch.object( + ClaudeIntegration, + "dispatch_command", + return_value={"exit_code": 0, "stdout": "", "stderr": ""}, + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.COMPLETED + assert result.output["dispatched"] is True + assert mock_dispatch.called + + +class TestPromptStepHookPreflight: + """Prompt steps also gate on hook interpreter availability when hooks are active.""" + + def test_prompt_step_fails_before_subprocess_when_hooks_lack_interpreter( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = PromptStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = {"id": "review", "type": "prompt", "prompt": "Review this diff"} + + with ( + patch( + "specify_cli.workflows.step.prompt.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "subprocess.run", + side_effect=AssertionError("subprocess.run must not be called"), + ) as mock_run, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert "review" in (result.error or "") + assert "python3" in (result.error or "") + assert "specify integration upgrade claude" in (result.error or "") + assert not mock_run.called + + def test_prompt_step_dispatches_when_hook_interpreter_is_available( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + step = PromptStep() + ctx = StepContext(default_integration="claude", project_root=str(tmp_path)) + config = {"id": "review", "type": "prompt", "prompt": "Review this diff"} + + mock_proc = MagicMock(returncode=0) + with ( + patch( + "specify_cli.workflows.step.prompt.shutil.which", + lambda name: { + "claude": "/usr/local/bin/claude", + "python3": "/usr/bin/python3", + }.get(name), + ), + patch("subprocess.run", return_value=mock_proc) as mock_run, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.COMPLETED + assert result.output["dispatched"] is True + assert mock_run.called + + +class TestOmittedProjectRootPreflight: + """Omitted context.project_root resolves cwd for hook preflight.""" + + def test_command_step_resolves_cwd_when_project_root_is_none( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + # Now run from tmp_path with project_root=None while python3 is missing. + monkeypatch.chdir(tmp_path) + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=None) + config = {"id": "cwd-cmd", "command": "speckit.plan"} + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "specify_cli.integrations.base.IntegrationBase.dispatch_command", + side_effect=AssertionError("agent CLI must not start when cwd hooks lack python"), + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert "cwd-cmd" in (result.error or "") + assert "python3" in (result.error or "") + assert not mock_dispatch.called + + def test_prompt_step_resolves_cwd_when_project_root_is_none( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr( + "specify_cli.events.shutil.which", + lambda name: "/usr/bin/python3" if name == "python3" else None, + ) + manifest = IntegrationManifest("claude", tmp_path) + install_integration_events( + ClaudeIntegration(), + tmp_path, + manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + + monkeypatch.chdir(tmp_path) + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + + step = PromptStep() + ctx = StepContext(default_integration="claude", project_root=None) + config = {"id": "cwd-prompt", "type": "prompt", "prompt": "Check cwd hooks"} + + with ( + patch( + "specify_cli.workflows.step.prompt.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch( + "subprocess.run", + side_effect=AssertionError("subprocess.run must not start when cwd hooks lack python"), + ) as mock_run, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.FAILED + assert result.output["dispatched"] is False + assert "cwd-prompt" in (result.error or "") + assert "python3" in (result.error or "") + assert not mock_run.called + + def test_omitted_project_root_skips_when_cwd_has_no_hooks( + self, tmp_path, monkeypatch + ): + monkeypatch.setattr("specify_cli.events.sys.platform", "linux") + monkeypatch.setattr("specify_cli.events.shutil.which", lambda name: None) + monkeypatch.chdir(tmp_path) + + step = CommandStep() + ctx = StepContext(default_integration="claude", project_root=None) + config = {"id": "no-hooks-cwd", "command": "speckit.plan"} + + with ( + patch( + "specify_cli.workflows.step.command.shutil.which", + lambda name: "/usr/local/bin/claude" if name == "claude" else None, + ), + patch.object( + ClaudeIntegration, + "dispatch_command", + return_value={"exit_code": 0, "stdout": "", "stderr": ""}, + ) as mock_dispatch, + ): + result = step.execute(config, ctx) + + assert result.status is StepStatus.COMPLETED + assert result.output["dispatched"] is True + assert mock_dispatch.called