From 4822dd6d32ec96097566bb700de4c0e95bd337c1 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 17:10:49 +0100 Subject: [PATCH 01/20] feat(workflows): add additional_context to command steps A command step can now carry additional_context, a string (literal or expression) that the dispatched agent receives as model context once per session_start, without changing $ARGUMENTS, the prompt, or the installed command templates (#5533). - Transport: the value is passed only to the child process in SPECKIT_ADDITIONAL_CONTEXT. Every dispatch removes an inherited value first (base and Copilot dispatch_command, and prompt steps), so nested runs cannot leak context. os.environ is never changed. - Delivery: a reserved built-in session_start handler emits the value through the integration's existing envelope. The generated events.py handles it before importing specify_cli, so a stale global install cannot drop it. - Support is an explicit opt-in: context_delivery_events on the integration, effective only with a session_start mapping, an envelope other than suppress, and a dispatch_command that accepts the keyword. Copilot declares it. Declaring integrations install the built-in handler by default. - The step fails before the CLI starts when the value is invalid (type, NUL, encoding, more than 16,384 UTF-8 bytes) or the integration cannot deliver it (not declared, events disabled, handler overridden, hooks missing or outdated). Errors never include the text. - Event lifecycle: event config writes accept linked ancestors above the project root (symlinks inside the project are still rejected), and removing a native hook file prunes the directories it leaves empty. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous) --- design/integration.md | 18 ++ docs/integrations/api.md | 10 + docs/integrations/cli.md | 7 +- docs/integrations/copilot.md | 9 + docs/workflow-steps/types.md | 44 +++ src/specify_cli/events/__init__.py | 230 +++++++++----- src/specify_cli/integrations/_capture.py | 10 +- src/specify_cli/integrations/_context.py | 18 ++ src/specify_cli/integrations/base.py | 23 ++ .../integrations/copilot/__init__.py | 8 + src/specify_cli/integrations/manifest.py | 32 +- src/specify_cli/workflows/step/_env_values.py | 18 ++ .../workflows/step/command/__init__.py | 44 +++ .../workflows/step/prompt/__init__.py | 4 + .../workflows/step/shell/__init__.py | 12 +- tests/integrations/test_capture.py | 2 +- tests/integrations/test_context.py | 73 +++++ .../integrations/test_integration_copilot.py | 6 + .../events/test_context_delivery.py | 291 +++++++++++++++++ tests/specify_cli/events/test_events.py | 126 ++++++++ .../test_command_additional_context.py | 298 ++++++++++++++++++ tests/workflows/test_step_capture.py | 28 ++ 22 files changed, 1207 insertions(+), 104 deletions(-) create mode 100644 src/specify_cli/integrations/_context.py create mode 100644 src/specify_cli/workflows/step/_env_values.py create mode 100644 tests/integrations/test_context.py create mode 100644 tests/specify_cli/events/test_context_delivery.py create mode 100644 tests/workflows/test_command_additional_context.py diff --git a/design/integration.md b/design/integration.md index bee007d1c5..6f0276f2b6 100644 --- a/design/integration.md +++ b/design/integration.md @@ -111,6 +111,24 @@ setting. An integration that declares support and then ignores the value, for example by absorbing it in `**kwargs`, drops it silently: a declaration is a promise to translate the setting. +### Context delivery for command steps + +An integration may declare `context_delivery_events` as a set or frozenset of +canonical events. This is a promise that its non-interactive CLI loads the +project hooks, fires the event, passes its environment to the hook, and feeds +the envelope output to the model. Effective support also requires a native +mapping, an envelope other than `suppress`, and a `dispatch_command` accepting +`additional_context` (or `**kwargs`). Declarations inherit normally; an +overriding adapter must honor the promise. Test declaration consistency and +provide live evidence for the agent-side behavior. + +Spec Kit installs the hook, runs the handler and writes the envelope. Agent-side +preconditions such as trust, feature flags and authentication belong in each +integration's guide; Spec Kit does not bypass them. The base dispatch removes +inherited context from the child environment even when unset. Legacy overrides +that do not accept the keyword cannot receive context and must clear inherited +context themselves when unset. + ## Output flavors Choose the smallest base class that matches the agent's native format. The diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 13795ea708..5883c9f298 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -364,3 +364,13 @@ see [runtime events](cli.md#runtime-events) for supported events and options. - [Descriptor and catalog schemas](catalog.md) - [Integration CLI and trust](cli.md) - [Per-step workflow integration configuration](../workflow-steps/types.md#per-step-integration-configuration) + +## Context delivery declaration + +External adapters can declare `context_delivery_events = frozenset({"session_start"})` +only when their non-interactive CLI loads and fires the hook, passes the +environment through, and injects its output into the model. The event must be +mapped to a native event with a non-suppressing envelope, and +`dispatch_command` must accept and honor `additional_context`. Document trust, +authentication, or feature-flag preconditions and provide live evidence. See +[the integration contract](../../design/integration.md#context-delivery-for-command-steps). diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index c8bdf3f843..a29056f1e2 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -434,9 +434,10 @@ Other agent-specific details are listed in the Event-capable integrations accept `--events true|false` through the setup `--integration-options` string; the default is enabled. Handler definitions come from integration defaults, installed extensions, and -`.specify/integration-events.yml`. Enabling events does not create handlers -where none are configured, and an integration emits only the native events -it supports. +`.specify/integration-events.yml`. Integrations that declare context delivery +install a built-in `session_start` handler by default. Otherwise enabling +events does not create handlers where none are configured. An integration +emits only the native events it supports. To configure project overrides, create `.specify/integration-events.yml`. Replace `` with your integration key and the example command with an diff --git a/docs/integrations/copilot.md b/docs/integrations/copilot.md index 4b917c8985..c439c7f1a8 100644 --- a/docs/integrations/copilot.md +++ b/docs/integrations/copilot.md @@ -17,6 +17,15 @@ specify init my-project --integration copilot For an existing Spec Kit project, use `specify integration install copilot`. See [integration management](cli.md) for activation, upgrades, and removal. +## Additional Context and Folder Trust + +Copilot CLI loads repository hooks in `-p` mode only in a trusted folder. +Trust the folder through Copilot's trust prompt or `trustedFolders`, or use +`--trust-folder` for a single run. `COPILOT_ALLOW_ALL=true` also trusts the +folder but approves all tools. In an untrusted folder Copilot skips hooks, +drops additional context, and still exits successfully. Spec Kit does not +add trust flags automatically. + ## Default Skills Layout Skills are installed as `.github/skills/speckit-/SKILL.md`. diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index 5108d7a65f..d3c5b274f3 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -40,6 +40,50 @@ For positional arguments and named runtime options, see `reasoning_effort` and `context_size`, see [Reasoning effort and context size](#reasoning-effort-and-context-size). +## Additional Context for Command Steps + +A `command` step can send extra text to the agent separately from its command +arguments and prompt: + +```yaml +- id: plan + command: speckit.plan + additional_context: "{{ inputs.background }}" +``` + +The value must resolve to a string of at most 16,384 UTF-8 bytes, without NUL +characters. Null and an empty string mean unset. The text is delivered once +per `session_start`; if the agent fires that event again (for example after +compaction), it is delivered again. The prompt and `$ARGUMENTS` are unchanged. +The integration must have events enabled and its current hooks installed; run +`specify integration upgrade ` after upgrading Spec Kit. An override in +`.specify/integration-events.yml` must retain the built-in handler, for example: + +```yaml +integrations: + copilot: + events: + session_start: + command: __speckit_additional_context__ +``` + +An override replaces the integration's entire event map, so include any other +handlers you want to keep. + +| Integration | Guide and agent-side preconditions | +| ----------- | ---------------------------------- | +| `copilot` | [Copilot](../integrations/copilot.md#additional-context-and-folder-trust) | + +An integration's agent-side trust, authentication, and feature gates are +outside Spec Kit's control. Older external adapters that override +`dispatch_command` without the context keyword cannot receive context; when +unset, those legacy overrides are responsible for clearing inherited context. + +> **Plain-text state:** The resolved value is recorded as +> `steps..output.additional_context` in the run's `state.json` for resume. +> It is not written to `log.jsonl`. Do not put secrets in this field unless you +> are comfortable with them being stored in plain text. + ## Prompt Steps Send an arbitrary inline prompt to an integration CLI (no command file needed): diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 47f86a5cb7..c1fe8f729c 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -30,6 +30,7 @@ import yaml import typer +from ..integrations._context import ADDITIONAL_CONTEXT_ENV from ..integrations._file_changes import unlink as _unlink_file, write_text as _write_text if TYPE_CHECKING: @@ -65,6 +66,8 @@ YAML_OVERRIDE_FILENAME = Path(".specify") / "integration-events.yml" +ADDITIONAL_CONTEXT_HANDLER = "__speckit_additional_context__" + _SPECKIT_MARKER = "__speckit_event__" # Buffer (seconds) added to the native hook timeout so the agent's outer cap @@ -415,6 +418,9 @@ def main(): payload = raw.decode("utf-8") else: payload = "{}" + if command_name == __ADDITIONAL_CONTEXT_HANDLER_LITERAL__: + _emit(os.environ.get(__ADDITIONAL_CONTEXT_ENV_LITERAL__, ""), envelope, native_event) + sys.exit(0) project_root = Path(__file__).parent.parent.resolve() # Preferred path: specify_cli is importable (durable install) — delegate to @@ -443,7 +449,9 @@ def main(): if __name__ == "__main__": main() -''' +'''.replace("__ADDITIONAL_CONTEXT_HANDLER_LITERAL__", repr(ADDITIONAL_CONTEXT_HANDLER)).replace( + "__ADDITIONAL_CONTEXT_ENV_LITERAL__", repr(ADDITIONAL_CONTEXT_ENV) +) # -- TS plugin template (opencode) ---------------------------------------- @@ -789,6 +797,9 @@ def resolve_and_run_event_command( by the Claude Code hooks spec Gemini/Tabnine/Devin derive from). Only used when *envelope* is ``hookSpecificOutput``. """ + if command_name == ADDITIONAL_CONTEXT_HANDLER: + _emit_event_stdout(os.environ.get(ADDITIONAL_CONTEXT_ENV, ""), envelope, native_event) + return 0 template_path, ext_id = _find_command_template(command_name, project_root) if not template_path: logger.warning("Event command '%s' not found", command_name) @@ -961,6 +972,14 @@ def resolve_events( events: ResolvedEvents = {} + # Layer 2: the built-in context handler is installed only for declarers. + from ..integrations import get_integration + from ..integrations.base import supports_context_delivery + + integration = get_integration(integration_key) + if integration is not None and supports_context_delivery(integration, "session_start"): + events.setdefault("session_start", []).append({"command": ADDITIONAL_CONTEXT_HANDLER}) + # Layer 2: built-in defaults from integration config if integration_config and isinstance(integration_config.get("events"), dict): for ev, cfg in integration_config["events"].items(): @@ -1046,6 +1065,71 @@ def resolve_events( return events +def context_delivery_error(integration: IntegrationBase, project_root: Path | None) -> str | None: + """Return an actionable reason why session context cannot be delivered.""" + from ..integration_state import installed_integration_keys, try_read_integration_json + from ..integrations import INTEGRATION_REGISTRY + from ..integrations._helpers import _resolve_integration_options + from ..integrations.base import _accepts_keyword, supports_context_delivery + from ..integrations.installer import dispatch_registry + + event = "session_start" + declared = integration.context_delivery_events + reason = None + remedy = "" + if not isinstance(declared, (set, frozenset)) or event not in declared: + reason = "context delivery is not declared" + elif event not in getattr(integration, "CANONICAL_TO_NATIVE", {}) or context_envelope_for(integration, event) == "suppress": + reason = "the event mapping or envelope contradicts the declaration" + elif not _accepts_keyword(integration.dispatch_command, "additional_context"): + reason = "dispatch_command does not accept additional_context" + elif project_root is None: + reason = "a project root is required" + else: + state, state_error = try_read_integration_json(project_root) + state = state or {} + if state_error is not None or integration.key not in installed_integration_keys(state): + reason = "the integration is not installed or its state cannot be read" + remedy = f"Run 'specify integration upgrade {integration.key}'." + else: + _, options = _resolve_integration_options(integration, state, integration.key, None) + if options and str(options.get("events", "true")).lower() in ("false", "0", "no", "off"): + reason = "events are disabled (--events false)" + remedy = "Check event configuration." + elif not any( + handler.get("command") == ADDITIONAL_CONTEXT_HANDLER + for handler in resolve_events(integration.key, integration.config, project_root, options).get(event, []) + ): + reason = "the session_start handler was removed by an override" + remedy = "Check event configuration." + else: + config = getattr(integration, "events_config_file", None) + paths = [project_root / EVENTS_DISPATCHER_REL] + if config: + paths.append(project_root / config) + try: + current = bool(config) and all( + ADDITIONAL_CONTEXT_HANDLER in path.read_text(encoding="utf-8") for path in paths + ) + except (OSError, UnicodeError): + current = False + if not current: + reason = "the event dispatcher or native events config is missing or outdated" + remedy = f"Run 'specify integration upgrade {integration.key}'." + if reason is None: + return None + registry = dispatch_registry.get() + if registry is None: + registry = INTEGRATION_REGISTRY + supporters = sorted(key for key, candidate in registry.items() if supports_context_delivery(candidate, event)) + listing = ", ".join(supporters) if supporters else "none" + return ( + f"Integration {integration.key!r} cannot deliver additional_context: {reason}. " + f"Supporting integrations: {listing}." + + (f" {remedy}" if remedy else "") + ) + + def _disabled_extension_ids(project_root: Path) -> set[str]: """Return the set of explicitly-disabled extension IDs. @@ -1323,7 +1407,7 @@ def _dispatcher_command( # 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)}" - envelope = _context_envelope_for(integration, event_name) + envelope = context_envelope_for(integration, event_name) if envelope: base += f" {_shell_quote(envelope, target_os)}" # hookSpecificOutput requires the native hookEventName inside the @@ -1338,6 +1422,11 @@ def _dispatcher_command( return base +def context_envelope_for(integration: IntegrationBase, canonical_event: str) -> str | None: + """Return the context-injection envelope for an integration and event.""" + return _context_envelope_for(integration, canonical_event) + + def _context_envelope_for(integration: IntegrationBase, canonical_event: str) -> str | None: """Resolve the context-injection envelope for an integration + event (C13). @@ -1397,7 +1486,7 @@ def install_integration_events( # 1. Generate events.py dispatcher script (#12: validate destination first) dispatcher_dir = project_root / EVENTS_DISPATCHER_DIR dispatcher_path = dispatcher_dir / EVENTS_DISPATCHER_FILENAME - _ensure_safe_destination(dispatcher_path) + _ensure_safe_destination(dispatcher_path, project_root) dispatcher_dir.mkdir(parents=True, exist_ok=True) _write_text(dispatcher_path, _EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") dispatcher_path.chmod(0o755) @@ -1415,13 +1504,14 @@ def install_integration_events( return created config_path = project_root / config_file + _ensure_safe_destination(config_path, project_root) manifest.set_ownership(config_file, "partial") if fmt == "ts-plugin": # Opencode TS plugin custom merge plugin_rel = ".opencode/plugin/speckit-events.ts" plugin_path = project_root / plugin_rel - _ensure_safe_destination(plugin_path) + _ensure_safe_destination(plugin_path, project_root) plugin_path.parent.mkdir(parents=True, exist_ok=True) _write_text( plugin_path, @@ -1438,7 +1528,7 @@ def install_integration_events( # file when the merge actually wrote; a skipped merge (JSONC/malformed) # must not be tracked or manifest.uninstall() would later delete the # user's untouched file. - if _merge_opencode_plugin_ref(config_path, f"./{plugin_rel}"): + if _merge_opencode_plugin_ref(config_path, f"./{plugin_rel}", project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1477,7 +1567,7 @@ def install_integration_events( ) copilot_hooks[native] = entries # S5: only track when the merge wrote (skips on JSONC/malformed). - if _merge_copilot_json(config_path, copilot_hooks): + if _merge_copilot_json(config_path, copilot_hooks, project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1501,7 +1591,7 @@ def install_integration_events( lines.append('speckit_marker = true') lines.append('') # S5: only track when the merge wrote (skips on unreadable file). - if _merge_toml_fragment(config_path, "\n".join(lines)): + if _merge_toml_fragment(config_path, "\n".join(lines), project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1525,7 +1615,7 @@ def install_integration_events( timeout_seconds=timeout, ), native_timeout=lambda seconds: _native_timeout(integration, seconds), - ensure_safe_destination=_ensure_safe_destination, + ensure_safe_destination=lambda path: _ensure_safe_destination(path, project_root), ): rel = config_path.relative_to(project_root).as_posix() manifest.record_existing(rel) @@ -1555,7 +1645,7 @@ def install_integration_events( # #7: Cursor's .cursor/hooks.json schema requires top-level # "version": 1; ensure it (preserving a user's value if present). # S5: only track when the merge wrote (skips on JSONC/malformed). - if _merge_json_fragment(config_path, cursor_hooks, version=1): + if _merge_json_fragment(config_path, cursor_hooks, version=1, project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1591,7 +1681,7 @@ def install_integration_events( for matcher, inner in by_matcher.items() ] # S5: only track when the merge wrote (skips on JSONC/malformed). - if _merge_json_fragment(config_path, nested_hooks): + if _merge_json_fragment(config_path, nested_hooks, project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1620,7 +1710,7 @@ def install_integration_events( {"matcher": matcher, "hooks": inner} for matcher, inner in by_matcher.items() ] - if _merge_json_root(config_path, root_hooks): + if _merge_json_root(config_path, root_hooks, project_root=project_root): rel = str(config_path.relative_to(project_root)) manifest.record_existing(rel, ownership="partial") created.append(config_path) @@ -1644,27 +1734,32 @@ def _remove_native_event_hooks( if not config_file: return config_path = project_root / config_file + _ensure_safe_destination(config_path, project_root) if not config_path.exists(): return - _ensure_safe_destination(config_path) + removed = False if fmt == "copilot-json": - _remove_copilot_entries(config_path) + removed = _remove_copilot_entries(config_path, project_root=project_root) elif fmt == "toml": - _remove_toml_entries(config_path) + removed = _remove_toml_entries(config_path, project_root=project_root) elif fmt == "toml-vibe": remove_vibe_hooks = getattr(integration, "remove_vibe_event_hooks", None) if not callable(remove_vibe_hooks): raise TypeError("toml-vibe integrations must implement remove_vibe_event_hooks") - remove_vibe_hooks( + removed = remove_vibe_hooks( project_root, - ensure_safe_destination=_ensure_safe_destination, + ensure_safe_destination=lambda path: _ensure_safe_destination(path, project_root), ) elif fmt in ("json-nested", "json-flat"): - _remove_json_entries(config_path) + removed = _remove_json_entries(config_path, project_root=project_root) elif fmt == "json-root-nested": - _remove_json_root_entries(config_path) + removed = _remove_json_root_entries(config_path, project_root=project_root) elif fmt == "ts-plugin": - _remove_opencode_entries(config_path) + removed = _remove_opencode_entries(config_path, project_root=project_root) + if removed: + from ..integrations.manifest import _prune_empty_parents + + _prune_empty_parents(project_root, config_path.parent, {project_root}) # Always drop this integration's manifest claim on the native config, # whether the file was deleted or retained with user content (S9). If we # kept a retained file tracked, teardown()'s manifest.uninstall(force=True) @@ -1738,7 +1833,7 @@ def _cleanup_shared_dispatcher( return dispatcher_path = project_root / dispatcher_rel if dispatcher_path.exists(): - _ensure_safe_destination(dispatcher_path) + _ensure_safe_destination(dispatcher_path, project_root) if not force: try: content = dispatcher_path.read_bytes() @@ -1777,8 +1872,11 @@ def remove_integration_events( if plugin_rel in manifest.files: plugin_path = project_root / plugin_rel if plugin_path.exists(): - _ensure_safe_destination(plugin_path) + _ensure_safe_destination(plugin_path, project_root) _unlink_file(plugin_path, missing_ok=True) + from ..integrations.manifest import _prune_empty_parents + + _prune_empty_parents(project_root, plugin_path.parent, {project_root}) manifest.remove(plugin_rel) @@ -2132,7 +2230,7 @@ def _build_opencode_plugin( ) -def _merge_opencode_plugin_ref(config_path: Path, ref: str) -> bool: +def _merge_opencode_plugin_ref(config_path: Path, ref: str, *, project_root: Path) -> bool: """Merge the speckit-events plugin ref into opencode.json. Aborts with a warning (#23) when the file cannot be parsed (e.g. JSONC or @@ -2148,17 +2246,17 @@ def _merge_opencode_plugin_ref(config_path: Path, ref: str) -> bool: if ref not in plugins: plugins.append(ref) existing["plugin"] = plugins - _safe_write_json(config_path, existing) + _safe_write_json(config_path, existing, project_root=project_root) return True -def _remove_opencode_entries(config_path: Path) -> bool: +def _remove_opencode_entries(config_path: Path, *, project_root: Path) -> bool: """Remove the speckit-events plugin ref from opencode.json (#23). Returns True if the file was deleted (now empty of user content), False otherwise. Aborts without writing when the file cannot be parsed. """ - _ensure_safe_destination(config_path) + _ensure_safe_destination(config_path, project_root) existing = _load_user_json(config_path) if existing is None: return False @@ -2175,11 +2273,11 @@ def _remove_opencode_entries(config_path: Path) -> bool: if not existing: _unlink_file(config_path, missing_ok=True) return True - _safe_write_json(config_path, existing) + _safe_write_json(config_path, existing, project_root=project_root) return False -def _merge_toml_fragment(dst: Path, fragment: str) -> bool: +def _merge_toml_fragment(dst: Path, fragment: str, *, project_root: Path) -> bool: """Merge Specify-owned TOML entries into *dst*, regenerating the file. An unreadable or undecodable pre-existing file aborts the merge instead @@ -2190,7 +2288,7 @@ def _merge_toml_fragment(dst: Path, fragment: str) -> bool: translation, mangle the line endings of) an untouched pre-existing file (#4563). """ - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) existing = "" if dst.exists(): try: @@ -2216,7 +2314,7 @@ def _merge_toml_fragment(dst: Path, fragment: str) -> bool: return True -def _remove_toml_entries(dst: Path) -> bool: +def _remove_toml_entries(dst: Path, *, project_root: Path) -> bool: """Remove Specify-marked TOML entries; delete the file if now empty (#14). Returns True if the file was deleted (no user content remained). @@ -2231,7 +2329,7 @@ def _remove_toml_entries(dst: Path) -> bool: # R3: validate the destination before reading/writing so a symlink swap of # the config after install can't make teardown overwrite a file outside # the project (the merge/write path already validates; teardown must too). - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) try: existing = dst.read_text(encoding="utf-8") except (OSError, UnicodeDecodeError) as exc: @@ -2267,7 +2365,7 @@ def _remove_toml_entries(dst: Path) -> bool: return False -def _merge_copilot_json(dst: Path, new_hooks: dict[str, list]) -> bool: +def _merge_copilot_json(dst: Path, new_hooks: dict[str, list], *, project_root: Path) -> bool: """Merge Specify-owned hooks into Copilot's dedicated hooks JSON (#8). A pre-existing user-authored ``.github/hooks/speckit.json`` is merged @@ -2298,17 +2396,17 @@ def _merge_copilot_json(dst: Path, new_hooks: dict[str, list]) -> bool: existing["hooks"] = cleaned_hooks else: existing.pop("hooks", None) - _safe_write_json(dst, existing) + _safe_write_json(dst, existing, project_root=project_root) return True -def _remove_copilot_entries(dst: Path) -> bool: +def _remove_copilot_entries(dst: Path, *, project_root: Path) -> bool: """Remove Specify-owned hooks from Copilot's hooks JSON (#8, #14). Deletes the file when no user-authored hooks remain; otherwise keeps the file with user content. Aborts (no write) on parse failure (#22). """ - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) existing = _load_user_json(dst) if existing is None: return False @@ -2335,11 +2433,13 @@ def _remove_copilot_entries(dst: Path) -> bool: if not user_keys: _unlink_file(dst, missing_ok=True) return True - _safe_write_json(dst, existing) + _safe_write_json(dst, existing, project_root=project_root) return False -def _merge_json_fragment(dst: Path, new_hooks: dict, *, version: int | None = None) -> bool: +def _merge_json_fragment( + dst: Path, new_hooks: dict, *, project_root: Path, version: int | None = None +) -> bool: """Merge Specify-authored hook entries into a native JSON config. Idempotent: removes ALL prior Specify-marked entries from every event in @@ -2391,11 +2491,11 @@ def _merge_json_fragment(dst: Path, new_hooks: dict, *, version: int | None = No existing[hooks_key] = cleaned_hooks else: existing.pop(hooks_key, None) - _safe_write_json(dst, existing) + _safe_write_json(dst, existing, project_root=project_root) return True -def _merge_json_root(dst: Path, new_hooks: dict) -> bool: +def _merge_json_root(dst: Path, new_hooks: dict, *, project_root: Path) -> bool: """Merge Specify-authored hooks into a root-nested JSON config (Devin U2). Devin's ``.devin/hooks.v1.json`` is a root event map @@ -2432,16 +2532,16 @@ def _merge_json_root(dst: Path, new_hooks: dict) -> bool: if not existing: _unlink_file(dst, missing_ok=True) return True - _safe_write_json(dst, existing) + _safe_write_json(dst, existing, project_root=project_root) return True -def _remove_json_root_entries(dst: Path) -> bool: +def _remove_json_root_entries(dst: Path, *, project_root: Path) -> bool: """Remove Specify-authored entries from a root-nested JSON config (Devin U2). Deletes the file when no user content remains (C5/#14 mirror). """ - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) existing = _load_user_json(dst) if existing is None: return False @@ -2459,7 +2559,7 @@ def _remove_json_root_entries(dst: Path) -> bool: if not cleaned: _unlink_file(dst, missing_ok=True) return True - _safe_write_json(dst, cleaned) + _safe_write_json(dst, cleaned, project_root=project_root) return False @@ -2517,9 +2617,9 @@ def _load_user_json(path: Path) -> dict | None: return data -def _safe_write_json(dst: Path, data: dict) -> None: +def _safe_write_json(dst: Path, data: dict, *, project_root: Path) -> None: """Write *data* as JSON to *dst* after validating the destination (#12).""" - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) dst.parent.mkdir(parents=True, exist_ok=True) # A lone surrogate (\ud800) can't be UTF-8 encoded; write it back as its JSON escape. _write_text( @@ -2530,40 +2630,28 @@ def _safe_write_json(dst: Path, data: dict) -> None: ) -def _ensure_safe_destination(dst: Path) -> None: - """Validate a write target is a regular path inside the project (#12). +def _ensure_safe_destination(dst: Path, project_root: Path) -> None: + """Reject traversal and symlinks at or below the project root.""" + from ..integrations.manifest import _validate_record_path - Walks each path component and rejects symlinks (which could escape the - project — e.g. a symlinked ``.claude`` or ``.specify`` directory pointing - outside the repo would redirect writes to external files). Then validates - lexical containment so ``..`` traversal is also rejected. - """ - from ..agents import CommandRegistrar - - # Walk each component so a symlinked ancestor (e.g. ``.claude`` → outside) - # cannot be silently followed. Mirrors IntegrationManifest.record_existing. - walked = dst.anchor and Path(dst.anchor) or Path("/") - for part in dst.relative_to(dst.anchor).parts if dst.anchor else dst.parts: - walked = walked / part - if walked.is_symlink(): - raise ValueError( - f"Refusing to write event config through a symlink: {walked}" - ) - - # Containment check against the nearest existing ancestor directory. - base = dst.parent - while not base.exists() and base != base.parent: - base = base.parent - CommandRegistrar._ensure_inside(dst, base) + root = project_root.absolute() + dst = dst.absolute() + if root.is_symlink(): + raise ValueError(f"Refusing event config through a symlinked project root: {root}") + try: + relative = dst.relative_to(root) + except ValueError: + raise ValueError(f"Event config escapes project root: {dst}") from None + _validate_record_path(relative, root) -def _remove_json_entries(dst: Path) -> bool: +def _remove_json_entries(dst: Path, *, project_root: Path) -> bool: """Remove Specify-authored entries; delete the file if now empty (#14). Returns True if the file was deleted (Spec Kit created it and no user content remains), False otherwise. """ - _ensure_safe_destination(dst) + _ensure_safe_destination(dst, project_root) existing = _load_user_json(dst) if existing is None: return False @@ -2594,7 +2682,7 @@ def _remove_json_entries(dst: Path) -> bool: if not user_keys: _unlink_file(dst, missing_ok=True) return True - _safe_write_json(dst, existing) + _safe_write_json(dst, existing, project_root=project_root) return False diff --git a/src/specify_cli/integrations/_capture.py b/src/specify_cli/integrations/_capture.py index 93d8a10fb7..c169ee62e1 100644 --- a/src/specify_cli/integrations/_capture.py +++ b/src/specify_cli/integrations/_capture.py @@ -14,7 +14,7 @@ import subprocess import threading import time -from collections.abc import Iterator, Sequence +from collections.abc import Iterator, Mapping, Sequence from contextlib import contextmanager from dataclasses import dataclass from typing import Any @@ -161,7 +161,9 @@ class _ProcessTree: directly: the interrupt is handled here, by killing the group or job. """ - def __init__(self, args: Sequence[str], cwd: str | None) -> None: + def __init__( + self, args: Sequence[str], cwd: str | None, env: Mapping[str, str] | None = None + ) -> None: isolation: dict[str, Any] = ( {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | _CREATE_SUSPENDED} if os.name == "nt" @@ -172,6 +174,7 @@ def __init__(self, args: Sequence[str], cwd: str | None) -> None: stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, + env=env, **isolation, ) self._job: Any = None @@ -439,6 +442,7 @@ def run_captured( cwd: str | None = None, timeout: float | None = None, max_bytes: int = DEFAULT_CAPTURE_MAX_BYTES, + env: Mapping[str, str] | None = None, ) -> CapturedProcess: """Run *args* and capture stdout and stderr, each capped at *max_bytes*. @@ -462,7 +466,7 @@ def run_captured( try: try: with _deferred_interrupt() as pending_interrupt: - tree = _ProcessTree(args, cwd) + tree = _ProcessTree(args, cwd, env) _register(tree) for pipe, sink in zip((tree.proc.stdout, tree.proc.stderr), sinks): reader = threading.Thread( diff --git a/src/specify_cli/integrations/_context.py b/src/specify_cli/integrations/_context.py new file mode 100644 index 0000000000..83c7e7c99d --- /dev/null +++ b/src/specify_cli/integrations/_context.py @@ -0,0 +1,18 @@ +"""Child environment for command context delivery.""" + +import os + +ADDITIONAL_CONTEXT_ENV = "SPECKIT_ADDITIONAL_CONTEXT" + + +def dispatch_environment(additional_context: str | None) -> dict[str, str]: + """Copy the environment without inheriting another dispatch's context.""" + env = dict(os.environ) + for key in list(env): + if key == ADDITIONAL_CONTEXT_ENV or ( + os.name == "nt" and key.upper() == ADDITIONAL_CONTEXT_ENV + ): + del env[key] + if additional_context: + env[ADDITIONAL_CONTEXT_ENV] = additional_context + return env diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index c8ee01b730..eaa2838152 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -33,6 +33,7 @@ from .._toml_string import has_illegal_toml_control as _has_illegal_toml_control from ..events import install_integration_events, remove_integration_events from ._capture import run_captured +from ._context import dispatch_environment if TYPE_CHECKING: from .manifest import IntegrationManifest @@ -211,6 +212,20 @@ def _accepts_keyword(function: Any, name: str) -> bool: ) +def supports_context_delivery(integration: IntegrationBase, event: str) -> bool: + """Whether the integration promises context delivery on this event.""" + from ..events import context_envelope_for + + declared = integration.context_delivery_events + return ( + isinstance(declared, (set, frozenset)) + and event in declared + and event in getattr(integration, "CANONICAL_TO_NATIVE", {}) + and context_envelope_for(integration, event) != "suppress" + and _accepts_keyword(integration.dispatch_command, "additional_context") + ) + + def _dispatch_setting_supporters(name: str, via: str) -> list[str]: from . import INTEGRATION_REGISTRY from .installer import dispatch_registry @@ -362,6 +377,9 @@ class IntegrationBase(ABC): and command directory. Registry tests enforce these invariants. """ + context_delivery_events: frozenset[str] = frozenset() + """Canonical events on which non-interactive dispatch delivers context.""" + supported_dispatch_settings: frozenset[str] = frozenset() """Per-step dispatch settings (``DISPATCH_SETTINGS``) this integration translates. @@ -705,6 +723,7 @@ def dispatch_command( capture_max_bytes: int | None = None, reasoning_effort: str | None = None, context_size: str | None = None, + additional_context: str | None = None, ) -> dict[str, Any]: """Dispatch a Spec Kit command through this integration's CLI. @@ -789,6 +808,7 @@ def dispatch_command( exec_args = [resolved, *exec_args[1:]] cwd = str(project_root) if project_root else None + env = dispatch_environment(additional_context) if stream: # No timeout when streaming — the user sees live output and @@ -799,6 +819,7 @@ def dispatch_command( exec_args, text=True, cwd=cwd, + env=env, ) except KeyboardInterrupt: return { @@ -818,6 +839,7 @@ def dispatch_command( cwd=cwd, timeout=timeout, max_bytes=capture_max_bytes, + env=env, ).as_dispatch_result() result = subprocess.run( @@ -828,6 +850,7 @@ def dispatch_command( errors="replace", cwd=cwd, timeout=timeout, + env=env, ) return { "exit_code": result.returncode, diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 5df793987c..7f77de42d2 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -30,6 +30,7 @@ import typer from .._capture import run_captured +from .._context import dispatch_environment from ..base import ( IntegrationBase, IntegrationOption, @@ -171,6 +172,8 @@ class CopilotIntegration(IntegrationBase): # for prompt steps and dispatch_command() for command steps. supported_dispatch_settings = frozenset({"reasoning_effort", "context_size"}) + context_delivery_events = frozenset({"session_start"}) + CANONICAL_TO_NATIVE = { "session_start": "sessionStart", "pre_tool_use": "preToolUse", @@ -463,6 +466,7 @@ def dispatch_command( capture_max_bytes: int | None = None, reasoning_effort: str | None = None, context_size: str | None = None, + additional_context: str | None = None, ) -> dict[str, Any]: """Dispatch via ``--agent speckit.`` instead of slash-commands. @@ -522,6 +526,7 @@ def dispatch_command( cli_args.extend(["--output-format", "json"]) cwd = str(project_root) if project_root else None + env = dispatch_environment(additional_context) if stream: try: @@ -529,6 +534,7 @@ def dispatch_command( cli_args, text=True, cwd=cwd, + env=env, ) except KeyboardInterrupt: return { @@ -548,6 +554,7 @@ def dispatch_command( cwd=cwd, timeout=timeout, max_bytes=capture_max_bytes, + env=env, ).as_dispatch_result() result = subprocess.run( @@ -558,6 +565,7 @@ def dispatch_command( errors="replace", cwd=cwd, timeout=timeout, + env=env, ) return { "exit_code": result.returncode, diff --git a/src/specify_cli/integrations/manifest.py b/src/specify_cli/integrations/manifest.py index 8bbe77a0e2..7ab2497f09 100644 --- a/src/specify_cli/integrations/manifest.py +++ b/src/specify_cli/integrations/manifest.py @@ -98,6 +98,19 @@ def _ensure_safe_manifest_removal(root: Path, path: Path) -> None: raise ValueError(f"Refusing deletion through symlinked manifest directory: {current}") +def _prune_empty_parents(root: Path, parent: Path, stop_dirs: set[Path]) -> None: + """Remove empty parents without following links, stopping at a boundary.""" + while parent not in stop_dirs: + try: + _ensure_safe_manifest_removal(root, parent) + if parent.is_symlink(): + break + parent.rmdir() + except (ValueError, OSError): + break + parent = parent.parent + + def _ensure_safe_manifest_directory(root: Path, directory: Path) -> None: """Create a manifest directory without following symlinked parents.""" root_resolved = root.resolve() @@ -453,14 +466,7 @@ def uninstall( removed.append(path) after_file_change(path) # Clean up empty parent directories up to project root or stop_dirs - parent = path.parent - while parent not in stop_set: - try: - _ensure_safe_manifest_removal(root, parent) - parent.rmdir() # only succeeds if empty - except (ValueError, OSError): - break - parent = parent.parent + _prune_empty_parents(root, path.parent, stop_set) # Remove the manifest file itself manifest = root / ".specify" / "integrations" / f"{self.key}.manifest.json" @@ -485,14 +491,8 @@ def uninstall( # manifest still on disk its parent is non-empty, so the first # rmdir() raises and breaks immediately. skipped.append(manifest) - parent = manifest.parent - while manifest_present and parent != root: - try: - _ensure_safe_manifest_removal(root, parent) - parent.rmdir() - except (ValueError, OSError): - break - parent = parent.parent + if manifest_present: + _prune_empty_parents(root, manifest.parent, {root}) return removed, skipped diff --git a/src/specify_cli/workflows/step/_env_values.py b/src/specify_cli/workflows/step/_env_values.py new file mode 100644 index 0000000000..edbdad96a6 --- /dev/null +++ b/src/specify_cli/workflows/step/_env_values.py @@ -0,0 +1,18 @@ +"""Validation for values passed through a process environment.""" + +import os +from typing import Any + + +def environment_value_error(label: str, value: Any) -> str | None: + """Return an error without including the value itself.""" + if not isinstance(value, str): + return f"{label} must be a string, got {type(value).__name__}." + if "\x00" in value: + return f"{label} must not contain NUL characters." + if os.name == "posix": + try: + os.fsencode(value) + except UnicodeEncodeError: + return f"{label} cannot be encoded for the process environment." + return None diff --git a/src/specify_cli/workflows/step/command/__init__.py b/src/specify_cli/workflows/step/command/__init__.py index ba9e35f377..4417926e87 100644 --- a/src/specify_cli/workflows/step/command/__init__.py +++ b/src/specify_cli/workflows/step/command/__init__.py @@ -22,6 +22,7 @@ record_capture, timeout_error, ) +from specify_cli.workflows.step._env_values import environment_value_error from specify_cli.workflows.step._dispatch_settings import ( dispatch_setting_errors, dispatch_settings_failure, @@ -29,6 +30,22 @@ ) _DEFAULT_CAPTURE_TIMEOUT = 600 +_MAX_ADDITIONAL_CONTEXT_BYTES = 16_384 + + +def _additional_context_error(value: Any) -> str | None: + if value is None or value == "": + return None + error = environment_value_error("additional_context", value) + if error is not None: + return error + try: + length = len(value.encode("utf-8")) + except UnicodeEncodeError: + return "additional_context cannot be encoded as UTF-8." + if length > _MAX_ADDITIONAL_CONTEXT_BYTES: + return f"additional_context must be at most {_MAX_ADDITIONAL_CONTEXT_BYTES} UTF-8 bytes, got {length}." + return None class CommandStep(StepBase): @@ -137,6 +154,18 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: ), ) + additional_context = config.get("additional_context") + if isinstance(additional_context, str) and "{{" in additional_context: + additional_context = evaluate_expression(additional_context, context) + context_error = _additional_context_error(additional_context) + if context_error is not None: + return StepResult( + status=StepStatus.FAILED, + error=f"Command step {config.get('id', '?')!r}: {context_error}", + ) + if additional_context == "": + additional_context = None + dispatch = resolve_dispatch_settings(config, context, "Command") if isinstance(dispatch, str): return StepResult(status=StepStatus.FAILED, error=dispatch) @@ -191,6 +220,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: "integration": integration, "model": model, **dispatch.outputs, + "additional_context": additional_context, "options": options, "input": resolved_input, "integration_args": integration_args, @@ -212,6 +242,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: capture_max_bytes=capture_max_bytes, timeout=timeout, **dispatch.settings, + **({"additional_context": additional_context} if additional_context is not None else {}), ) except DispatchSettingsError as exc: output["exit_code"] = 1 @@ -290,6 +321,7 @@ def _try_dispatch( timeout: float = _DEFAULT_CAPTURE_TIMEOUT, reasoning_effort: str | None = None, context_size: str | None = None, + additional_context: str | None = None, ) -> dict[str, Any] | None: """Invoke *command* by name through the integration CLI. @@ -336,6 +368,12 @@ def _try_dispatch( check_dispatch_settings(impl, dispatch_settings, via="dispatch_command") project_root = Path(context.project_root) if context.project_root else None + if additional_context is not None: + from specify_cli.events import context_delivery_error + + reason = context_delivery_error(impl, project_root) + if reason is not None: + raise ValueError(reason) # Build sample args for fallback executable detection when impl.key is not executable. exec_args = impl.build_exec_args( @@ -384,6 +422,7 @@ def _try_dispatch( integration_options=integration_options, **capture_kwargs, **dispatch_settings, + **({"additional_context": additional_context} if additional_context is not None else {}), ) except (NotImplementedError, OSError): return None @@ -505,6 +544,11 @@ def validate(self, config: dict[str, Any]) -> list[str]: f"Command step {config.get('id', '?')!r}: 'model' must be a " f"string, got {type(model).__name__}." ) + additional_context = config.get("additional_context") + if not isinstance(additional_context, str) or "{{" not in additional_context: + context_error = _additional_context_error(additional_context) + if context_error is not None: + errors.append(f"Command step {config.get('id', '?')!r}: {context_error}") errors.extend(dispatch_setting_errors(config, "Command")) errors.extend(capture_errors(config, "Command")) # 'timeout' is only applied to a captured step, so a streaming step's diff --git a/src/specify_cli/workflows/step/prompt/__init__.py b/src/specify_cli/workflows/step/prompt/__init__.py index 7a21c3ced8..9817147c0f 100644 --- a/src/specify_cli/workflows/step/prompt/__init__.py +++ b/src/specify_cli/workflows/step/prompt/__init__.py @@ -8,6 +8,7 @@ from typing import Any from specify_cli.integrations._capture import run_captured +from specify_cli.integrations._context import dispatch_environment from specify_cli.integrations.base import ( DispatchSettingsError, check_dispatch_settings, @@ -320,6 +321,7 @@ def _try_dispatch( import subprocess + env = dispatch_environment(None) if capture_max_bytes is not None: try: return run_captured( @@ -327,6 +329,7 @@ def _try_dispatch( cwd=str(project_root), timeout=timeout, max_bytes=capture_max_bytes, + env=env, ).as_dispatch_result() except OSError: return None @@ -337,6 +340,7 @@ def _try_dispatch( text=True, cwd=str(project_root), timeout=timeout, + env=env, ) return { "exit_code": result.returncode, diff --git a/src/specify_cli/workflows/step/shell/__init__.py b/src/specify_cli/workflows/step/shell/__init__.py index 968f65a914..e18eb672ab 100644 --- a/src/specify_cli/workflows/step/shell/__init__.py +++ b/src/specify_cli/workflows/step/shell/__init__.py @@ -14,6 +14,7 @@ from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus from specify_cli.workflows.expressions import evaluate_expression +from specify_cli.workflows.step._env_values import environment_value_error def _reject_json_constant(value: str) -> Any: @@ -184,16 +185,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: @staticmethod def _environment_value_error(name: str, value: Any) -> str | None: - if not isinstance(value, str): - return f"env {name!r} must be a string, got {type(value).__name__}." - if "\x00" in value: - return f"env {name!r} must not contain NUL characters." - if os.name == "posix": - try: - os.fsencode(value) - except UnicodeEncodeError: - return f"env {name!r} cannot be encoded for the process environment." - return None + return environment_value_error(f"env {name!r}", value) @classmethod def _binding_errors(cls, config: dict[str, Any]) -> list[str]: diff --git a/tests/integrations/test_capture.py b/tests/integrations/test_capture.py index 556eed4f6f..117d498100 100644 --- a/tests/integrations/test_capture.py +++ b/tests/integrations/test_capture.py @@ -234,7 +234,7 @@ def test_interrupt_during_process_setup_is_reported_not_raised( self, monkeypatch ): class InterruptedSetup: - def __init__(self, args, cwd): + def __init__(self, args, cwd, env=None): raise KeyboardInterrupt monkeypatch.setattr(_capture, "_ProcessTree", InterruptedSetup) diff --git a/tests/integrations/test_context.py b/tests/integrations/test_context.py new file mode 100644 index 0000000000..1f7a5bb273 --- /dev/null +++ b/tests/integrations/test_context.py @@ -0,0 +1,73 @@ +"""Child-only environment transport across dispatch paths.""" + +import os +import sys +from types import SimpleNamespace + +import pytest + +from specify_cli.integrations._capture import CapturedProcess, run_captured +from specify_cli.integrations._context import ( + ADDITIONAL_CONTEXT_ENV, + dispatch_environment, +) +from specify_cli.integrations.claude import ClaudeIntegration +from specify_cli.integrations.copilot import CopilotIntegration + + +@pytest.mark.parametrize("integration", ["base", "copilot"]) +@pytest.mark.parametrize("path", ["stream", "bounded", "unbounded"]) +@pytest.mark.parametrize("value", [None, "", "private-context"]) +def test_dispatch_environment_all_paths(monkeypatch, integration, path, value): + monkeypatch.setenv(ADDITIONAL_CONTEXT_ENV, "inherited") + seen = [] + + def run(args, **kwargs): + seen.append((args, kwargs["env"])) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + def capture(args, **kwargs): + seen.append((args, kwargs["env"])) + return CapturedProcess(exit_code=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + if integration == "base": + import specify_cli.integrations.base as module + + impl = ClaudeIntegration() + monkeypatch.setattr( + impl, "build_exec_args", lambda prompt, **kwargs: ["agent", prompt] + ) + else: + import specify_cli.integrations.copilot as module + + impl = CopilotIntegration() + monkeypatch.setattr(module, "run_captured", capture) + kwargs = {"stream": path == "stream"} + if path == "bounded": + kwargs["capture_max_bytes"] = 100 + impl.dispatch_command( + "speckit.plan", args="same arguments", additional_context=value, **kwargs + ) + assert len(seen) == 1 + assert seen[0][1].get(ADDITIONAL_CONTEXT_ENV) == (value or None) + assert os.environ[ADDITIONAL_CONTEXT_ENV] == "inherited" + + +def test_windows_case_insensitive_removal(monkeypatch): + import specify_cli.integrations._context as module + + monkeypatch.setattr( + module.os, "environ", {"speckit_additional_context": "old", "OTHER": "ok"} + ) + monkeypatch.setattr(module.os, "name", "nt") + assert dispatch_environment(None) == {"OTHER": "ok"} + assert dispatch_environment("new") == {"OTHER": "ok", ADDITIONAL_CONTEXT_ENV: "new"} + + +def test_bounded_capture_receives_explicit_environment(): + result = run_captured( + [sys.executable, "-c", 'import os; print(os.environ.get("ONLY_TEST_VALUE"))'], + env={"ONLY_TEST_VALUE": "ok"}, + ) + assert result.stdout == "ok\n" diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 033406db42..79d9777f15 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -329,6 +329,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", + ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -339,6 +340,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", + ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -393,6 +395,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", + ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -403,6 +406,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", + ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -913,6 +917,8 @@ def test_complete_file_inventory_skills_sh(self, tmp_path): assert result.exit_code == 0, f"init failed: {result.output}" actual = sorted(p.relative_to(project).as_posix() for p in project.rglob("*") if p.is_file() and ".git" not in p.parts) expected = sorted([ + ".github/hooks/speckit.json", + ".specify/events.py", # Skill files (core commands) *[f".github/skills/speckit-{cmd}/SKILL.md" for cmd in self._SKILL_COMMANDS], # Integration metadata diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py new file mode 100644 index 0000000000..c9b44bb7cd --- /dev/null +++ b/tests/specify_cli/events/test_context_delivery.py @@ -0,0 +1,291 @@ +"""Context handler, capability, and installation contract.""" + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from specify_cli.events import ( + ADDITIONAL_CONTEXT_HANDLER, + CANONICAL_EVENTS, + _EVENTS_DISPATCHER_TEMPLATE, + context_delivery_error, + install_integration_events, + resolve_and_run_event_command, + resolve_events, +) +from specify_cli.integrations import INTEGRATION_REGISTRY, get_integration +from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV +from specify_cli.integrations.base import supports_context_delivery +from specify_cli.integrations.copilot import CopilotIntegration +from specify_cli.integrations.manifest import IntegrationManifest + + +@pytest.fixture +def installed(tmp_path): + integration = CopilotIntegration() + root = tmp_path / ".specify" + root.mkdir() + (root / "integration.json").write_text( + json.dumps( + {"default_integration": "copilot", "installed_integrations": ["copilot"]} + ) + ) + manifest = IntegrationManifest("copilot", tmp_path, version="test") + install_integration_events( + integration, + tmp_path, + manifest, + resolve_events("copilot", integration.config, tmp_path, None), + ) + return integration + + +@pytest.mark.parametrize( + "envelope", + [ + "plain", + "additionalContext", + "additional_context", + "hookSpecificOutput", + "hook_specific_output", + "suppress", + ], +) +@pytest.mark.parametrize("value", [None, "", "unique-context-α"]) +def test_handler_both_paths(tmp_path, monkeypatch, capsys, envelope, value): + if value is None: + monkeypatch.delenv(ADDITIONAL_CONTEXT_ENV, raising=False) + else: + monkeypatch.setenv(ADDITIONAL_CONTEXT_ENV, value) + assert ( + resolve_and_run_event_command( + ADDITIONAL_CONTEXT_HANDLER, + "session_start", + "{}", + tmp_path, + envelope=envelope, + native_event="SessionStart", + ) + == 0 + ) + direct = capsys.readouterr().out + script = tmp_path / "events.py" + script.write_text(_EVENTS_DISPATCHER_TEMPLATE) + # An importable, stale specify_cli must not intercept this handler. + stale = tmp_path / "specify_cli" + stale.mkdir(exist_ok=True) + (stale / "__init__.py").write_text("") + (stale / "events.py").write_text('raise RuntimeError("stale import")') + result = subprocess.run( + [ + sys.executable, + str(script), + ADDITIONAL_CONTEXT_HANDLER, + "session_start", + "120", + envelope, + "SessionStart", + ], + input="{}", + text=True, + capture_output=True, + env={**os.environ, "PYTHONPATH": str(tmp_path)}, + ) + assert result.returncode == 0, result.stderr + assert result.stdout == direct + if value and envelope != "suppress": + assert direct.count("unique-context") == 1 + if envelope != "plain": + assert "unique-context-α" in json.dumps( + json.loads(direct), ensure_ascii=False + ) + else: + assert direct == value + else: + assert direct == "" + + +@pytest.mark.parametrize("value", [None, "unique-context-α"]) +def test_generated_context_handler_drains_piped_stdin(tmp_path, value): + script = tmp_path / "events.py" + script.write_text(_EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") + env = dict(os.environ) + env.pop(ADDITIONAL_CONTEXT_ENV, None) + if value is not None: + env[ADDITIONAL_CONTEXT_ENV] = value + args = [ + sys.executable, + str(script), + ADDITIONAL_CONTEXT_HANDLER, + "session_start", + "120", + "additionalContext", + ] + # The upper-bound payload exceeds the OS pipe buffer and exercises the + # same cap as other generated-dispatcher commands. + result = subprocess.run( + args, input=b"x" * (1024 * 1024), capture_output=True, env=env, timeout=10 + ) + assert result.returncode == 0, result.stderr + if value is None: + assert result.stdout == b"" + else: + assert json.loads(result.stdout) == {"additionalContext": value} + assert result.stdout.count(b"unique-context") == 1 + + oversized = subprocess.run( + args, input=b"x" * (1024 * 1024 + 1), capture_output=True, env=env, timeout=10 + ) + assert oversized.returncode == 1 + assert oversized.stdout == b"" + assert b"stdin payload exceeds 1 MiB limit" in oversized.stderr + + +def test_resolution_and_override(tmp_path): + assert resolve_events("claude", None, tmp_path, None) == {} + assert resolve_events("copilot", None, tmp_path, None) == { + "session_start": [{"command": ADDITIONAL_CONTEXT_HANDLER}] + } + assert resolve_events("copilot", None, tmp_path, {"events": "false"}) == {} + override = tmp_path / ".specify/integration-events.yml" + override.parent.mkdir() + override.write_text("integrations:\n copilot:\n events: {}\n") + assert resolve_events("copilot", None, tmp_path, None) == {} + override.write_text( + f"integrations:\n copilot:\n events:\n session_start:\n command: {ADDITIONAL_CONTEXT_HANDLER}\n" + ) + assert ( + resolve_events("copilot", None, tmp_path, None)["session_start"][0]["command"] + == ADDITIONAL_CONTEXT_HANDLER + ) + + +def test_registry_declarations_and_docs(): + for integration in INTEGRATION_REGISTRY.values(): + declared = integration.context_delivery_events + assert isinstance(declared, (set, frozenset)) + assert declared <= CANONICAL_EVENTS + assert all(supports_context_delivery(integration, event) for event in declared) + doc = ( + Path(__file__).resolve().parents[3] / "docs/workflow-steps/types.md" + ).read_text() + table = doc.split("## Additional Context for Command Steps")[1].split( + "## Prompt Steps" + )[0] + documented = { + line.split("`")[1] for line in table.splitlines() if line.startswith("| `") + } + assert documented == { + key + for key, integration in INTEGRATION_REGISTRY.items() + if supports_context_delivery(integration, "session_start") + } + + +def test_predicate_negative_cases(): + assert supports_context_delivery(CopilotIntegration(), "session_start") + assert not supports_context_delivery(get_integration("claude"), "session_start") + + class InvalidDeclaration(CopilotIntegration): + context_delivery_events = ["session_start"] + + class InvalidMapping(CopilotIntegration): + CANONICAL_TO_NATIVE = {} + + class Suppressed(CopilotIntegration): + events_context_envelope = {"session_start": "suppress"} + + class Legacy(CopilotIntegration): + def dispatch_command(self, command_name): + pass + + for instance in (InvalidDeclaration(), InvalidMapping(), Suppressed(), Legacy()): + assert not supports_context_delivery(instance, "session_start") + + +def test_installation_check(tmp_path, installed): + assert context_delivery_error(installed, tmp_path) is None + missing_root = context_delivery_error(installed, None) + assert "project root" in missing_root and "upgrade" not in missing_root + undeclared = context_delivery_error(get_integration("claude"), tmp_path) + assert "not declared" in undeclared and "upgrade" not in undeclared + native = tmp_path / installed.events_config_file + native.unlink() + assert "outdated" in context_delivery_error(installed, tmp_path) + assert "specify integration upgrade copilot" in context_delivery_error( + installed, tmp_path + ) + + +def test_disabled_and_override_check(tmp_path, installed): + state = tmp_path / ".specify/integration.json" + state.write_text( + json.dumps( + { + "default_integration": "copilot", + "installed_integrations": ["copilot"], + "integration_settings": { + "copilot": {"parsed_options": {"events": "false"}} + }, + } + ) + ) + disabled = context_delivery_error(installed, tmp_path) + assert "disabled" in disabled and "event configuration" in disabled + assert "upgrade" not in disabled + state.write_text( + json.dumps( + {"default_integration": "copilot", "installed_integrations": ["copilot"]} + ) + ) + (tmp_path / ".specify/integration-events.yml").write_text( + "integrations:\n copilot:\n events: {}\n" + ) + override = context_delivery_error(installed, tmp_path) + assert "override" in override and "event configuration" in override + assert "upgrade" not in override + + +def test_copilot_installs_one_native_handler_with_compatible_commands( + tmp_path, installed +): + native = json.loads((tmp_path / installed.events_config_file).read_text()) + hooks = native["hooks"]["sessionStart"] + assert len(hooks) == 1 + entry = hooks[0] + for key in ("bash", "powershell"): + assert entry[key].count(ADDITIONAL_CONTEXT_HANDLER) == 1 + assert "additionalContext" in entry[key] + # The generated PowerShell command uses the PS 5.1 call operator and + # single-quoted arguments; it does not depend on PowerShell 7 features. + assert entry["powershell"].startswith("& 'python' ") + assert f"'{ADDITIONAL_CONTEXT_HANDLER}'" in entry["powershell"] + + +def test_distinct_capability_reasons(tmp_path, installed): + class BadMapping(CopilotIntegration): + CANONICAL_TO_NATIVE = {} + + class Suppressed(CopilotIntegration): + events_context_envelope = {"session_start": "suppress"} + + class Legacy(CopilotIntegration): + def dispatch_command(self, command_name): + pass + + for integration in (BadMapping(), Suppressed()): + error = context_delivery_error(integration, tmp_path) + assert "contradicts" in error and "upgrade" not in error + legacy_error = context_delivery_error(Legacy(), tmp_path) + assert "does not accept" in legacy_error and "upgrade" not in legacy_error + (tmp_path / ".specify/events.py").write_text("# stale dispatcher") + outdated = context_delivery_error(installed, tmp_path) + assert "outdated" in outdated and "specify integration upgrade copilot" in outdated + (tmp_path / ".specify/integration.json").unlink() + not_installed = context_delivery_error(installed, tmp_path) + assert "not installed" in not_installed + assert "specify integration upgrade copilot" in not_installed diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index c6373bdf35..b6ba3e86fe 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -2736,6 +2736,61 @@ def test_dispatcher_kept_when_other_integration_references_it(self, tmp_path): class TestSafeWriteDestination: """#12: write targets are validated before any bytes are written.""" + def test_linked_parent_outside_project_is_allowed(self, tmp_path): + real_parent = tmp_path / "real" + project = real_parent / "project" + project.mkdir(parents=True) + alias = tmp_path / "alias" + try: + alias.symlink_to(real_parent, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + linked_project = alias / "project" + integration = CopilotIntegration() + manifest = IntegrationManifest(integration.key, linked_project) + events = {"session_start": [{"command": "speckit.boot"}]} + install_integration_events(integration, linked_project, manifest, events) + assert (project / ".github/hooks/speckit.json").is_file() + remove_integration_events(integration, linked_project, manifest) + assert not (project / ".github/hooks/speckit.json").exists() + + def test_parent_traversal_is_rejected(self, tmp_path): + from specify_cli.events import _ensure_safe_destination + + with pytest.raises(ValueError, match="(?i)outside|escape|canonical"): + _ensure_safe_destination(tmp_path / ".." / "outside.json", tmp_path) + with pytest.raises(ValueError, match="(?i)canonical"): + _ensure_safe_destination(tmp_path / ".github" / ".." / "hooks.json", tmp_path) + + def test_symlinked_project_root_is_rejected(self, tmp_path): + from specify_cli.events import _ensure_safe_destination + + target = tmp_path / "real" + target.mkdir() + root = tmp_path / "linked-project" + try: + root.symlink_to(target, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + with pytest.raises(ValueError, match="(?i)symlink"): + _ensure_safe_destination(root / ".github/hooks/speckit.json", root) + + @pytest.mark.parametrize("directory", [".github", ".specify"]) + def test_symlink_inside_project_is_rejected(self, tmp_path, directory): + outside = tmp_path / "outside" + outside.mkdir() + try: + (tmp_path / directory).symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + integration = CopilotIntegration() + with pytest.raises(ValueError, match="(?i)symlink|escapes|outside"): + install_integration_events( + integration, tmp_path, IntegrationManifest(integration.key, tmp_path), + {"session_start": [{"command": "speckit.boot"}]}, + ) + assert not any(outside.iterdir()) + def test_symlinked_config_dir_rejected(self, tmp_path): integration = ClaudeIntegration() # Create a symlinked .claude directory pointing outside the project. @@ -2820,6 +2875,77 @@ def test_plugin_remover_rejects_symlinked_plugin(self, tmp_path): assert outside.read_text() == "// external" +class TestNativeEventDirectoryCleanup: + @pytest.mark.parametrize("operation", ["remove", "disable"]) + @pytest.mark.parametrize("user_file", [False, True]) + def test_prunes_empty_parents_but_preserves_user_files(self, tmp_path, operation, user_file): + integration = CopilotIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + events = {"session_start": [{"command": "speckit.boot"}]} + install_integration_events(integration, tmp_path, manifest, events) + preserved = tmp_path / ".github" / "user.txt" + if user_file: + preserved.write_text("user content") + if operation == "remove": + remove_integration_events(integration, tmp_path, manifest) + else: + install_integration_events(integration, tmp_path, manifest, {}) + assert not (tmp_path / ".github/hooks").exists() + assert (tmp_path / ".github").exists() is user_file + if user_file: + assert preserved.read_text() == "user content" + + @pytest.mark.parametrize("user_file", [False, True]) + def test_prunes_owned_opencode_plugin_parents(self, tmp_path, user_file): + integration = OpencodeIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events( + integration, tmp_path, manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + preserved = tmp_path / ".opencode/user.txt" + if user_file: + preserved.write_text("user content") + remove_integration_events(integration, tmp_path, manifest) + assert not (tmp_path / ".opencode/plugin").exists() + assert (tmp_path / ".opencode").exists() is user_file + if user_file: + assert preserved.read_text() == "user content" + + def test_pruning_does_not_follow_replaced_directory_link(self, tmp_path, monkeypatch): + import specify_cli.events as events_module + + integration = CopilotIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events( + integration, tmp_path, manifest, + {"session_start": [{"command": "speckit.boot"}]}, + ) + outside = tmp_path / "outside" + outside.mkdir() + user_file = outside / "user.txt" + user_file.write_text("user content") + probe = tmp_path / "link-probe" + try: + probe.symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + probe.unlink() + hook_dir = tmp_path / ".github/hooks" + original = events_module._remove_copilot_entries + + def remove_then_swap(path, **kwargs): + deleted = original(path, **kwargs) + hook_dir.rmdir() + hook_dir.symlink_to(outside, target_is_directory=True) + return deleted + + monkeypatch.setattr(events_module, "_remove_copilot_entries", remove_then_swap) + remove_integration_events(integration, tmp_path, manifest) + assert hook_dir.is_symlink() + assert user_file.read_text() == "user content" + + # -- Validation & lifecycle (Tier 4) ----------------------------------------- class TestValidateEventsCommandType: diff --git a/tests/workflows/test_command_additional_context.py b/tests/workflows/test_command_additional_context.py new file mode 100644 index 0000000000..cc9a4cabf2 --- /dev/null +++ b/tests/workflows/test_command_additional_context.py @@ -0,0 +1,298 @@ +"""Command additional_context validation, dispatch and run-state behavior.""" + +import json +from concurrent.futures import ThreadPoolExecutor + +import pytest +import yaml + +from specify_cli.events import install_integration_events, resolve_events +from specify_cli.integrations import get_integration +from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV +from specify_cli.integrations.manifest import IntegrationManifest +from specify_cli.workflows.base import StepContext, StepStatus +from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine +from specify_cli.workflows.step.command import CommandStep + + +@pytest.fixture +def installed(project_dir): + impl = get_integration("copilot") + state = project_dir / ".specify/integration.json" + state.parent.mkdir(parents=True, exist_ok=True) + state.write_text( + json.dumps( + {"default_integration": "copilot", "installed_integrations": ["copilot"]} + ) + ) + install_integration_events( + impl, + project_dir, + IntegrationManifest("copilot", project_dir, version="test"), + resolve_events("copilot", impl.config, project_dir, None), + ) + return impl + + +def config(value): + return {"id": "ask", "command": "speckit.plan", "additional_context": value} + + +@pytest.mark.parametrize( + "value", [None, "", "hello", "{{ inputs.ctx }}", "a" * 16384, "é" * 8192] +) +def test_validate_valid(value): + assert CommandStep().validate(config(value)) == [] + + +@pytest.mark.parametrize( + "value", [False, 0, [], "SECRET\x00", "SECRET" + "a" * 16384, "\ud800"] +) +def test_validate_invalid_never_discloses_value(value): + errors = CommandStep().validate(config(value)) + assert errors + assert "SECRET" not in str(errors) + + +@pytest.mark.parametrize( + "value", [False, 0, [], "SECRET\x00", "SECRET" + "a" * 16384, "\ud800"] +) +def test_expression_invalid_before_dispatch(monkeypatch, value): + monkeypatch.setattr( + "shutil.which", lambda _: pytest.fail("must validate before executable lookup") + ) + result = CommandStep().execute( + config("{{ inputs.ctx }}"), + StepContext(inputs={"ctx": value}, default_integration="copilot"), + ) + assert result.status == StepStatus.FAILED + assert "SECRET" not in result.error + + +@pytest.mark.parametrize("value", [None, ""]) +def test_unset_skips_capability_check(monkeypatch, value): + called = [] + + def dispatch(*args, **kwargs): + called.append(kwargs) + return {"exit_code": 0, "stdout": "", "stderr": ""} + + monkeypatch.setattr(CommandStep, "_try_dispatch", dispatch) + result = CommandStep().execute( + config("{{ inputs.ctx }}"), StepContext(inputs={"ctx": value}) + ) + assert result.status == StepStatus.COMPLETED + assert result.output["additional_context"] is None + assert "additional_context" not in called[0] + + +def test_missing_root_and_unsupported_fail_before_executable(monkeypatch): + monkeypatch.setattr( + "shutil.which", + lambda _: pytest.fail("capability must precede executable lookup"), + ) + step = CommandStep() + result = step.execute(config("SECRET"), StepContext(default_integration="copilot")) + assert "project root" in result.error + assert "SECRET" not in result.error + result = step.execute(config("SECRET"), StepContext(default_integration="claude")) + assert "not declared" in result.error + assert "copilot" in result.error + assert "SECRET" not in result.error + + +def test_expression_dispatch_and_prompt_unchanged(project_dir, installed, monkeypatch): + calls = [] + + class Result: + returncode = 0 + + def fake_run(args, **kwargs): + calls.append((args, kwargs["env"])) + return Result() + + monkeypatch.setattr("shutil.which", lambda name: name) + monkeypatch.setattr("subprocess.run", fake_run) + step = CommandStep() + context = StepContext( + inputs={"ctx": "é" * 8192}, + default_integration="copilot", + project_root=str(project_dir), + ) + plain = step.execute( + {"id": "ask", "command": "speckit.plan", "input": {"args": "hello"}}, context + ) + with_context = step.execute( + {**config("{{ inputs.ctx }}"), "input": {"args": "hello"}}, context + ) + assert plain.status == with_context.status == StepStatus.COMPLETED + assert calls[0][0] == calls[1][0] + assert ADDITIONAL_CONTEXT_ENV not in calls[0][1] + assert calls[1][1][ADDITIONAL_CONTEXT_ENV] == "é" * 8192 + assert with_context.output["additional_context"] == "é" * 8192 + + +def test_old_override_rejected_only_when_set(project_dir, installed, monkeypatch): + cls = type(installed) + calls = [] + + def old( + self, + command, + args="", + *, + project_root=None, + model=None, + integration_args=None, + integration_options=None, + ): + calls.append(args) + return {"exit_code": 0, "stdout": "", "stderr": ""} + + monkeypatch.setattr(cls, "dispatch_command", old) + monkeypatch.setattr("shutil.which", lambda name: name) + context = StepContext(default_integration="copilot", project_root=str(project_dir)) + bad = CommandStep().execute(config("SECRET"), context) + assert bad.status == StepStatus.FAILED and "does not accept" in bad.error + assert "SECRET" not in bad.error and not calls + good = CommandStep().execute(config(None), context) + assert good.status == StepStatus.COMPLETED and len(calls) == 1 + + +def test_concurrent_dispatch_isolation(project_dir, installed, monkeypatch): + seen = [] + + def fake_run(args, **kwargs): + seen.append((args[2], kwargs["env"].get(ADDITIONAL_CONTEXT_ENV))) + return type("Result", (), {"returncode": 0})() + + monkeypatch.setattr("shutil.which", lambda name: name) + monkeypatch.setattr("subprocess.run", fake_run) + + def run(value): + context = StepContext( + item=value, default_integration="copilot", project_root=str(project_dir) + ) + return CommandStep().execute( + {**config("{{ item }}"), "input": {"args": "{{ item }}"}}, context + ) + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(run, ["one", "two"])) + assert all(result.status == StepStatus.COMPLETED for result in results) + assert sorted(seen) == [("/speckit-plan one", "one"), ("/speckit-plan two", "two")] + + +def test_resume_and_recording(project_dir, installed, monkeypatch): + calls = [] + + def fake_run(args, **kwargs): + calls.append(kwargs["env"][ADDITIONAL_CONTEXT_ENV]) + return type("Result", (), {"returncode": 1 if len(calls) == 1 else 0})() + + monkeypatch.setattr("shutil.which", lambda name: name) + monkeypatch.setattr("subprocess.run", fake_run) + definition = WorkflowDefinition.from_string( + yaml.safe_dump( + { + "schema_version": "1.0", + "workflow": { + "id": "context-resume", + "name": "Context Resume", + "version": "1.0.0", + }, + "inputs": {"ctx": {"type": "string", "default": "first-secret"}}, + "steps": [{**config("{{ inputs.ctx }}"), "integration": "copilot"}], + } + ) + ) + engine = WorkflowEngine(project_dir) + state = engine.execute(definition) + assert state.status.value == "failed" + resumed = engine.resume(state.run_id, {"ctx": "second-secret"}) + assert resumed.status.value == "completed" + assert calls == ["first-secret", "second-secret"] + run_dir = resumed.runs_dir + saved = json.loads((run_dir / "state.json").read_text()) + assert ( + saved["step_results"]["ask"]["output"]["additional_context"] == "second-secret" + ) + assert "secret" not in (run_dir / "log.jsonl").read_text() + + +def test_fan_out_with_distinct_contexts(project_dir, installed, monkeypatch): + seen = [] + + def fake_run(args, **kwargs): + seen.append((args[2], kwargs["env"][ADDITIONAL_CONTEXT_ENV])) + return type("Result", (), {"returncode": 0})() + + monkeypatch.setattr("shutil.which", lambda name: name) + monkeypatch.setattr("subprocess.run", fake_run) + definition = WorkflowDefinition.from_string( + yaml.safe_dump( + { + "schema_version": "1.0", + "workflow": { + "id": "context-fan", + "name": "Context Fan", + "version": "1.0.0", + }, + "steps": [ + { + "id": "fan", + "type": "fan-out", + "items": ["one", "two"], + "max_concurrency": 2, + "step": { + **config("{{ item }}"), + "integration": "copilot", + "input": {"args": "{{ item }}"}, + }, + } + ], + } + ) + ) + state = WorkflowEngine(project_dir).execute(definition) + assert state.status.value == "completed" + assert sorted(seen) == [("/speckit-plan one", "one"), ("/speckit-plan two", "two")] + + +def test_resume_does_not_repeat_completed_command(project_dir, installed, monkeypatch): + calls = [] + + def fake_run(args, **kwargs): + calls.append(kwargs["env"][ADDITIONAL_CONTEXT_ENV]) + return type("Result", (), {"returncode": 1 if len(calls) == 2 else 0})() + + monkeypatch.setattr("shutil.which", lambda name: name) + monkeypatch.setattr("subprocess.run", fake_run) + definition = WorkflowDefinition.from_string( + yaml.safe_dump( + { + "schema_version": "1.0", + "workflow": { + "id": "context-completed", + "name": "Context Completed", + "version": "1.0.0", + }, + "inputs": {"ctx": {"type": "string", "default": "first"}}, + "steps": [ + {**config("{{ inputs.ctx }}"), "integration": "copilot"}, + { + **config("{{ inputs.ctx }}"), + "id": "second", + "integration": "copilot", + }, + ], + } + ) + ) + engine = WorkflowEngine(project_dir) + state = engine.execute(definition) + assert state.status.value == "failed" + resumed = engine.resume(state.run_id, {"ctx": "changed"}) + assert resumed.status.value == "completed" + assert calls == ["first", "first", "changed"] + assert resumed.step_results["ask"]["output"]["additional_context"] == "first" diff --git a/tests/workflows/test_step_capture.py b/tests/workflows/test_step_capture.py index 101039da5e..e4cff661a9 100644 --- a/tests/workflows/test_step_capture.py +++ b/tests/workflows/test_step_capture.py @@ -644,3 +644,31 @@ def submit(self, *args, **kwargs): size = beat.stat().st_size time.sleep(1) assert beat.stat().st_size == size, "the capture kept running" + + +@pytest.mark.parametrize('capture', [False, True]) +@pytest.mark.parametrize('inherited', [None, 'parent-context']) +def test_prompt_dispatch_does_not_inherit_command_context( + project_dir, monkeypatch, capture, inherited +): + from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV + + if inherited is None: + monkeypatch.delenv(ADDITIONAL_CONTEXT_ENV, raising=False) + else: + monkeypatch.setenv(ADDITIONAL_CONTEXT_ENV, inherited) + seen = [] + def run(args, **kwargs): + seen.append(kwargs['env']) + return type('Result', (), {'returncode': 0})() + def bounded(args, **kwargs): + seen.append(kwargs['env']) + return CapturedProcess(exit_code=0, stdout='', stderr='') + monkeypatch.setattr('shutil.which', lambda name: name) + monkeypatch.setattr('subprocess.run', run) + monkeypatch.setattr('specify_cli.workflows.step.prompt.run_captured', bounded) + result = _execute('prompt', project_dir, capture=capture) + assert result.status == StepStatus.COMPLETED + assert len(seen) == 1 and ADDITIONAL_CONTEXT_ENV not in seen[0] + import os + assert os.environ.get(ADDITIONAL_CONTEXT_ENV) == inherited From ece26d615e65c8854bec3a199d23bde7dc555a4b Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 19:11:32 +0100 Subject: [PATCH 02/20] fix(workflows): address #5616 review round 1 Make this PR framework-only, per the integration delivery boundary in design/integration.md: no built-in integration declares context delivery here. Copilot keeps the additional_context transport in its dispatch_command override, and its declaration, trust docs, and init inventory move to a stacked follow-up PR. Tests use a fake declaring integration. - Installed-hook check: integrations report their installed handlers through installed_event_handlers(), the read counterpart of emit_events/remove_events. The default dispatches by events_format to per-format readers, which arrive with each declaring integration. Commands are parsed back only when they round-trip through _dispatcher_command. .specify/events.py must exactly match the current template (LF or CRLF), reusing the cleanup comparison. This replaces the substring checks. - Capability hints: an unreadable state says to fix or delete .specify/integration.json, and a missing integration says to run 'specify integration install', using the wording from integration status. Upgrade is suggested only for missing or outdated event files. - Shell steps start from dispatch_environment(None), so a nested run does not pass on an inherited SPECKIT_ADDITIONAL_CONTEXT; explicit env bindings still apply. - A failed additional_context expression fails the step with a message that does not include the value, so continue_on_error applies. - Document the additional_context contract on dispatch_command, and use UTF-8 explicitly in the context-delivery tests. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous) --- design/integration.md | 6 +- docs/integrations/api.md | 5 +- docs/integrations/copilot.md | 9 - docs/workflow-steps/types.md | 6 +- src/specify_cli/events/__init__.py | 95 +++++++-- src/specify_cli/integrations/base.py | 13 ++ .../integrations/copilot/__init__.py | 2 - .../workflows/step/command/__init__.py | 8 +- .../workflows/step/shell/__init__.py | 3 +- tests/fixtures/context_delivery.py | 43 ++++ .../integrations/test_integration_copilot.py | 6 - .../events/test_context_delivery.py | 192 ++++++++++++++---- .../test_command_additional_context.py | 63 ++++-- tests/workflows/test_shell_step.py | 24 ++- 14 files changed, 365 insertions(+), 110 deletions(-) create mode 100644 tests/fixtures/context_delivery.py diff --git a/design/integration.md b/design/integration.md index 6f0276f2b6..53df734221 100644 --- a/design/integration.md +++ b/design/integration.md @@ -120,7 +120,11 @@ the envelope output to the model. Effective support also requires a native mapping, an envelope other than `suppress`, and a `dispatch_command` accepting `additional_context` (or `**kwargs`). Declarations inherit normally; an overriding adapter must honor the promise. Test declaration consistency and -provide live evidence for the agent-side behavior. +provide live evidence for the agent-side behavior. The integration must also +report its installed canonical handlers through `installed_event_handlers()`, +either using a reader for its event format or overriding the method. `None` +means the installation cannot be inspected; a missing handler prevents dispatch. +The shared dispatcher must exactly match the current generated template. Spec Kit installs the hook, runs the handler and writes the envelope. Agent-side preconditions such as trust, feature flags and authentication belong in each diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 5883c9f298..12b45a1aa5 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -372,5 +372,8 @@ only when their non-interactive CLI loads and fires the hook, passes the environment through, and injects its output into the model. The event must be mapped to a native event with a non-suppressing envelope, and `dispatch_command` must accept and honor `additional_context`. Document trust, -authentication, or feature-flag preconditions and provide live evidence. See +authentication, or feature-flag preconditions and provide live evidence. Implement +`installed_event_handlers(project_root)` when the event format has no shared +reader; return canonical event names mapped to lists of installed handler names, +or `None` if the installation cannot be inspected. See [the integration contract](../../design/integration.md#context-delivery-for-command-steps). diff --git a/docs/integrations/copilot.md b/docs/integrations/copilot.md index c439c7f1a8..4b917c8985 100644 --- a/docs/integrations/copilot.md +++ b/docs/integrations/copilot.md @@ -17,15 +17,6 @@ specify init my-project --integration copilot For an existing Spec Kit project, use `specify integration install copilot`. See [integration management](cli.md) for activation, upgrades, and removal. -## Additional Context and Folder Trust - -Copilot CLI loads repository hooks in `-p` mode only in a trusted folder. -Trust the folder through Copilot's trust prompt or `trustedFolders`, or use -`--trust-folder` for a single run. `COPILOT_ALLOW_ALL=true` also trusts the -folder but approves all tools. In an untrusted folder Copilot skips hooks, -drops additional context, and still exits successfully. Spec Kit does not -add trust flags automatically. - ## Default Skills Layout Skills are installed as `.github/skills/speckit-/SKILL.md`. diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index d3c5b274f3..301c3ae0bd 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -61,7 +61,7 @@ The integration must have events enabled and its current hooks installed; run ```yaml integrations: - copilot: + example-agent: events: session_start: command: __speckit_additional_context__ @@ -70,9 +70,7 @@ integrations: An override replaces the integration's entire event map, so include any other handlers you want to keep. -| Integration | Guide and agent-side preconditions | -| ----------- | ---------------------------------- | -| `copilot` | [Copilot](../integrations/copilot.md#additional-context-and-folder-trust) | +No built-in integration declares support yet. An integration's agent-side trust, authentication, and feature gates are outside Spec Kit's control. Older external adapters that override diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index c1fe8f729c..1b78179e55 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -25,7 +25,7 @@ import subprocess import platform from pathlib import Path, PurePosixPath, PureWindowsPath -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Callable import yaml import typer @@ -39,6 +39,8 @@ from ..integrations.base import IntegrationBase from ..integrations.manifest import IntegrationManifest +_EVENT_HANDLER_READERS: dict[str, Callable[[IntegrationBase, Path], dict[str, list[str]] | None]] = {} + logger = logging.getLogger(__name__) event_app = typer.Typer( @@ -1088,9 +1090,12 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No else: state, state_error = try_read_integration_json(project_root) state = state or {} - if state_error is not None or integration.key not in installed_integration_keys(state): - reason = "the integration is not installed or its state cannot be read" - remedy = f"Run 'specify integration upgrade {integration.key}'." + if state_error is not None: + reason = "the integration state cannot be read" + remedy = "Fix or delete .specify/integration.json, then retry." + elif integration.key not in installed_integration_keys(state): + reason = "the integration is not installed" + remedy = f"Run 'specify integration install {integration.key}'." else: _, options = _resolve_integration_options(integration, state, integration.key, None) if options and str(options.get("events", "true")).lower() in ("false", "0", "no", "off"): @@ -1103,19 +1108,20 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No reason = "the session_start handler was removed by an override" remedy = "Check event configuration." else: - config = getattr(integration, "events_config_file", None) - paths = [project_root / EVENTS_DISPATCHER_REL] - if config: - paths.append(project_root / config) - try: - current = bool(config) and all( - ADDITIONAL_CONTEXT_HANDLER in path.read_text(encoding="utf-8") for path in paths - ) - except (OSError, UnicodeError): - current = False - if not current: - reason = "the event dispatcher or native events config is missing or outdated" - remedy = f"Run 'specify integration upgrade {integration.key}'." + handlers = integration.installed_event_handlers(project_root) + if handlers is None: + reason = "the integration cannot report installed handlers" + else: + try: + current = _dispatcher_matches_template((project_root / EVENTS_DISPATCHER_REL).read_bytes()) + except OSError: + current = False + installed = handlers.get(event) if isinstance(handlers, dict) else None + if not isinstance(installed, list) or ADDITIONAL_CONTEXT_HANDLER not in installed: + current = False + if not current: + reason = "the event dispatcher or native events config is missing or outdated" + remedy = f"Run 'specify integration upgrade {integration.key}'." if reason is None: return None registry = dispatch_registry.get() @@ -1422,6 +1428,48 @@ def _dispatcher_command( return base +def _parse_dispatcher_command(command: str, *, target_os: str = "host") -> tuple[str, str, str | None] | None: + """Recover handler, canonical event and envelope from a generated command. + + This parses the POSIX and PowerShell forms emitted by `_dispatcher_command`; + it does not execute the command or accept arbitrary shell syntax. + """ + if target_os == "windows": + if not command.startswith("& "): + return None + tokens = [] + remaining = command[2:] + while remaining: + match = re.match(r"'((?:[^']|'')*)'(?:\s+|$)", remaining) + if match is None: + return None + tokens.append(match.group(1).replace("''", "'")) + remaining = remaining[match.end():] + elif target_os in ("host", "posix"): + try: + tokens = shlex.split(command) + except ValueError: + return None + else: + return None + if not 5 <= len(tokens) <= 7 or not tokens[0] or not tokens[4].isdigit(): + return None + if tokens[1] not in (EVENTS_DISPATCHER_REL, "${CLAUDE_PROJECT_DIR}/" + EVENTS_DISPATCHER_REL): + return None + dispatcher = ( + '"${CLAUDE_PROJECT_DIR}/' + EVENTS_DISPATCHER_REL + '"' + if tokens[1].startswith("${CLAUDE_PROJECT_DIR}/") + else _shell_quote(tokens[1], target_os) + ) + rendered = " ".join([_shell_quote(tokens[0], target_os), dispatcher, + *(_shell_quote(token, target_os) for token in tokens[2:])]) + if target_os == "windows": + rendered = "& " + rendered + if rendered != command: + return None + return tokens[2], tokens[3], tokens[5] if len(tokens) >= 6 else None + + def context_envelope_for(integration: IntegrationBase, canonical_event: str) -> str | None: """Return the context-injection envelope for an integration and event.""" return _context_envelope_for(integration, canonical_event) @@ -1796,6 +1844,14 @@ def _other_event_integrations_reference_dispatcher( return False +def _dispatcher_matches_template(content: bytes) -> bool: + """Accept only the generated dispatcher, with LF or CRLF line endings.""" + return content in ( + _EVENTS_DISPATCHER_TEMPLATE.encode("utf-8"), + _EVENTS_DISPATCHER_TEMPLATE.replace("\n", "\r\n").encode("utf-8"), + ) + + def _cleanup_shared_dispatcher( integration: IntegrationBase, project_root: Path, manifest: IntegrationManifest, *, @@ -1842,10 +1898,7 @@ def _cleanup_shared_dispatcher( return # Another integration may have regenerated the shared file since # this manifest recorded it. Accept only exact generated LF/CRLF. - matches = hashlib.sha256(content).hexdigest() == expected_hash or content in ( - _EVENTS_DISPATCHER_TEMPLATE.encode("utf-8"), - _EVENTS_DISPATCHER_TEMPLATE.replace("\n", "\r\n").encode("utf-8"), - ) + matches = hashlib.sha256(content).hexdigest() == expected_hash or _dispatcher_matches_template(content) if not matches: logger.warning("Preserving modified dispatcher: %s", dispatcher_path) return diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index eaa2838152..e080029b91 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -760,6 +760,12 @@ def dispatch_command( validates it first and only the passed settings are forwarded to ``build_exec_args()``, so builders that predate them keep working. + *additional_context* uses child-only environment transport via + ``dispatch_environment()``; an inherited value is removed when unset. + Delivery requires a declaration and an installed hook. Overrides must + preserve this isolation. See ``design/integration.md``, "Context + delivery for command steps". + Returns a dict with ``exit_code``, ``stdout``, and ``stderr``. Raises ``NotImplementedError`` if the integration does not support CLI dispatch. @@ -1448,6 +1454,13 @@ def remove_events( """Remove Specify-authored event entries from native config.""" remove_integration_events(self, project_root, manifest, force=force) + def installed_event_handlers(self, project_root: Path) -> dict[str, list[str]] | None: + """Report installed canonical handlers, or None if the format cannot be read.""" + from ..events import _EVENT_HANDLER_READERS + + reader = _EVENT_HANDLER_READERS.get(getattr(self, "events_format", None)) + return reader(self, project_root) if reader is not None else None + def supports_events(self) -> bool: """Return True if this integration supports agent-native events.""" return bool(getattr(self, "CANONICAL_TO_NATIVE", None) and getattr(self, "events_config_file", None)) diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 7f77de42d2..7dcbaf642f 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -172,8 +172,6 @@ class CopilotIntegration(IntegrationBase): # for prompt steps and dispatch_command() for command steps. supported_dispatch_settings = frozenset({"reasoning_effort", "context_size"}) - context_delivery_events = frozenset({"session_start"}) - CANONICAL_TO_NATIVE = { "session_start": "sessionStart", "pre_tool_use": "preToolUse", diff --git a/src/specify_cli/workflows/step/command/__init__.py b/src/specify_cli/workflows/step/command/__init__.py index 4417926e87..57cd2d8a78 100644 --- a/src/specify_cli/workflows/step/command/__init__.py +++ b/src/specify_cli/workflows/step/command/__init__.py @@ -156,7 +156,13 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: additional_context = config.get("additional_context") if isinstance(additional_context, str) and "{{" in additional_context: - additional_context = evaluate_expression(additional_context, context) + try: + additional_context = evaluate_expression(additional_context, context) + except ValueError: + return StepResult( + status=StepStatus.FAILED, + error=f"Command step {config.get('id', '?')!r}: additional_context: expression could not be evaluated.", + ) context_error = _additional_context_error(additional_context) if context_error is not None: return StepResult( diff --git a/src/specify_cli/workflows/step/shell/__init__.py b/src/specify_cli/workflows/step/shell/__init__.py index e18eb672ab..56cf62f30b 100644 --- a/src/specify_cli/workflows/step/shell/__init__.py +++ b/src/specify_cli/workflows/step/shell/__init__.py @@ -12,6 +12,7 @@ import subprocess from typing import Any +from specify_cli.integrations._context import dispatch_environment from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus from specify_cli.workflows.expressions import evaluate_expression from specify_cli.workflows.step._env_values import environment_value_error @@ -89,7 +90,7 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: output={"exit_code": -1, "stdout": "", "stderr": "invalid timeout"}, ) - env = {**os.environ} + env = dispatch_environment(None) for name, template in config.get("env", {}).items(): try: value = evaluate_expression(template, context) diff --git a/tests/fixtures/context_delivery.py b/tests/fixtures/context_delivery.py new file mode 100644 index 0000000000..f5b25468db --- /dev/null +++ b/tests/fixtures/context_delivery.py @@ -0,0 +1,43 @@ +"""Test-only context delivery adapter; it is not a built-in integration.""" + +import json +import os + +from specify_cli.events import _parse_dispatcher_command +from specify_cli.integrations.base import MarkdownIntegration + + +class FakeContextIntegration(MarkdownIntegration): + key = "fake-context" + config = {"name": "Fake Context", "folder": ".fake", "commands_subdir": "commands", + "install_url": "https://example.com", "requires_cli": False} + registrar_config = {"dir": ".fake/commands", "format": "markdown", "args": "$ARGUMENTS", "extension": ".md"} + invoke_separator = "-" + CANONICAL_TO_NATIVE = {"session_start": "sessionStart"} + events_config_file = ".fake/hooks.json" + events_format = "copilot-json" + events_context_envelope = {"session_start": "additionalContext"} + context_delivery_events = frozenset({"session_start"}) + + def build_exec_args(self, prompt, **kwargs): + return [self.key, "-p", prompt] + + def installed_event_handlers(self, project_root): + try: + native = json.loads((project_root / self.events_config_file).read_text(encoding="utf-8")) + entries = native["hooks"]["sessionStart"] + if not isinstance(entries, list): + return {} + handlers = [] + for entry in entries: + if not isinstance(entry, dict) or entry.get("__speckit_event__") is not True: + continue + command = entry.get("powershell" if os.name == "nt" else "bash") + if not isinstance(command, str): + continue + parsed = _parse_dispatcher_command(command, target_os="windows" if os.name == "nt" else "posix") + if parsed and parsed[1:] == ("session_start", "additionalContext"): + handlers.append(parsed[0]) + return {"session_start": handlers} + except (OSError, UnicodeError, ValueError, KeyError, TypeError): + return {} diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 79d9777f15..033406db42 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -329,7 +329,6 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", - ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -340,7 +339,6 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", - ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -395,7 +393,6 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", - ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -406,7 +403,6 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", - ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -917,8 +913,6 @@ def test_complete_file_inventory_skills_sh(self, tmp_path): assert result.exit_code == 0, f"init failed: {result.output}" actual = sorted(p.relative_to(project).as_posix() for p in project.rglob("*") if p.is_file() and ".git" not in p.parts) expected = sorted([ - ".github/hooks/speckit.json", - ".specify/events.py", # Skill files (core commands) *[f".github/skills/speckit-{cmd}/SKILL.md" for cmd in self._SKILL_COMMANDS], # Integration metadata diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index c9b44bb7cd..41a7a3bf1c 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -12,6 +12,9 @@ ADDITIONAL_CONTEXT_HANDLER, CANONICAL_EVENTS, _EVENTS_DISPATCHER_TEMPLATE, + _EVENT_HANDLER_READERS, + _dispatcher_command, + _parse_dispatcher_command, context_delivery_error, install_integration_events, resolve_and_run_event_command, @@ -19,27 +22,28 @@ ) from specify_cli.integrations import INTEGRATION_REGISTRY, get_integration from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV -from specify_cli.integrations.base import supports_context_delivery -from specify_cli.integrations.copilot import CopilotIntegration +from specify_cli.integrations.base import IntegrationBase, supports_context_delivery +from tests.fixtures.context_delivery import FakeContextIntegration from specify_cli.integrations.manifest import IntegrationManifest @pytest.fixture -def installed(tmp_path): - integration = CopilotIntegration() +def installed(tmp_path, monkeypatch): + integration = FakeContextIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, integration.key, integration) root = tmp_path / ".specify" root.mkdir() (root / "integration.json").write_text( json.dumps( - {"default_integration": "copilot", "installed_integrations": ["copilot"]} - ) + {"default_integration": "fake-context", "installed_integrations": ["fake-context"]} + ), encoding="utf-8" ) - manifest = IntegrationManifest("copilot", tmp_path, version="test") + manifest = IntegrationManifest("fake-context", tmp_path, version="test") install_integration_events( integration, tmp_path, manifest, - resolve_events("copilot", integration.config, tmp_path, None), + resolve_events("fake-context", integration.config, tmp_path, None), ) return integration @@ -74,12 +78,12 @@ def test_handler_both_paths(tmp_path, monkeypatch, capsys, envelope, value): ) direct = capsys.readouterr().out script = tmp_path / "events.py" - script.write_text(_EVENTS_DISPATCHER_TEMPLATE) + script.write_text(_EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") # An importable, stale specify_cli must not intercept this handler. stale = tmp_path / "specify_cli" stale.mkdir(exist_ok=True) - (stale / "__init__.py").write_text("") - (stale / "events.py").write_text('raise RuntimeError("stale import")') + (stale / "__init__.py").write_text("", encoding="utf-8") + (stale / "events.py").write_text('raise RuntimeError("stale import")', encoding="utf-8") result = subprocess.run( [ sys.executable, @@ -91,9 +95,9 @@ def test_handler_both_paths(tmp_path, monkeypatch, capsys, envelope, value): "SessionStart", ], input="{}", - text=True, + encoding="utf-8", capture_output=True, - env={**os.environ, "PYTHONPATH": str(tmp_path)}, + env={**os.environ, "PYTHONPATH": str(tmp_path), "PYTHONIOENCODING": "utf-8"}, ) assert result.returncode == 0, result.stderr assert result.stdout == direct @@ -114,6 +118,7 @@ def test_generated_context_handler_drains_piped_stdin(tmp_path, value): script = tmp_path / "events.py" script.write_text(_EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") env = dict(os.environ) + env["PYTHONIOENCODING"] = "utf-8" env.pop(ADDITIONAL_CONTEXT_ENV, None) if value is not None: env[ADDITIONAL_CONTEXT_ENV] = value @@ -145,21 +150,22 @@ def test_generated_context_handler_drains_piped_stdin(tmp_path, value): assert b"stdin payload exceeds 1 MiB limit" in oversized.stderr -def test_resolution_and_override(tmp_path): +def test_resolution_and_override(tmp_path, monkeypatch): + monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-context", FakeContextIntegration()) assert resolve_events("claude", None, tmp_path, None) == {} - assert resolve_events("copilot", None, tmp_path, None) == { + assert resolve_events("fake-context", None, tmp_path, None) == { "session_start": [{"command": ADDITIONAL_CONTEXT_HANDLER}] } - assert resolve_events("copilot", None, tmp_path, {"events": "false"}) == {} + assert resolve_events("fake-context", None, tmp_path, {"events": "false"}) == {} override = tmp_path / ".specify/integration-events.yml" override.parent.mkdir() - override.write_text("integrations:\n copilot:\n events: {}\n") - assert resolve_events("copilot", None, tmp_path, None) == {} + override.write_text("integrations:\n fake-context:\n events: {}\n", encoding="utf-8") + assert resolve_events("fake-context", None, tmp_path, None) == {} override.write_text( - f"integrations:\n copilot:\n events:\n session_start:\n command: {ADDITIONAL_CONTEXT_HANDLER}\n" + f"integrations:\n fake-context:\n events:\n session_start:\n command: {ADDITIONAL_CONTEXT_HANDLER}\n", encoding="utf-8" ) assert ( - resolve_events("copilot", None, tmp_path, None)["session_start"][0]["command"] + resolve_events("fake-context", None, tmp_path, None)["session_start"][0]["command"] == ADDITIONAL_CONTEXT_HANDLER ) @@ -170,9 +176,12 @@ def test_registry_declarations_and_docs(): assert isinstance(declared, (set, frozenset)) assert declared <= CANONICAL_EVENTS assert all(supports_context_delivery(integration, event) for event in declared) + if declared: + assert (type(integration).installed_event_handlers is not IntegrationBase.installed_event_handlers + or getattr(integration, "events_format", None) in _EVENT_HANDLER_READERS) doc = ( Path(__file__).resolve().parents[3] / "docs/workflow-steps/types.md" - ).read_text() + ).read_text(encoding="utf-8") table = doc.split("## Additional Context for Command Steps")[1].split( "## Prompt Steps" )[0] @@ -187,19 +196,19 @@ def test_registry_declarations_and_docs(): def test_predicate_negative_cases(): - assert supports_context_delivery(CopilotIntegration(), "session_start") + assert supports_context_delivery(FakeContextIntegration(), "session_start") assert not supports_context_delivery(get_integration("claude"), "session_start") - class InvalidDeclaration(CopilotIntegration): + class InvalidDeclaration(FakeContextIntegration): context_delivery_events = ["session_start"] - class InvalidMapping(CopilotIntegration): + class InvalidMapping(FakeContextIntegration): CANONICAL_TO_NATIVE = {} - class Suppressed(CopilotIntegration): + class Suppressed(FakeContextIntegration): events_context_envelope = {"session_start": "suppress"} - class Legacy(CopilotIntegration): + class Legacy(FakeContextIntegration): def dispatch_command(self, command_name): pass @@ -216,7 +225,7 @@ def test_installation_check(tmp_path, installed): native = tmp_path / installed.events_config_file native.unlink() assert "outdated" in context_delivery_error(installed, tmp_path) - assert "specify integration upgrade copilot" in context_delivery_error( + assert "specify integration upgrade fake-context" in context_delivery_error( installed, tmp_path ) @@ -226,34 +235,34 @@ def test_disabled_and_override_check(tmp_path, installed): state.write_text( json.dumps( { - "default_integration": "copilot", - "installed_integrations": ["copilot"], + "default_integration": "fake-context", + "installed_integrations": ["fake-context"], "integration_settings": { - "copilot": {"parsed_options": {"events": "false"}} + "fake-context": {"parsed_options": {"events": "false"}} }, } - ) + ), encoding="utf-8" ) disabled = context_delivery_error(installed, tmp_path) assert "disabled" in disabled and "event configuration" in disabled assert "upgrade" not in disabled state.write_text( json.dumps( - {"default_integration": "copilot", "installed_integrations": ["copilot"]} - ) + {"default_integration": "fake-context", "installed_integrations": ["fake-context"]} + ), encoding="utf-8" ) (tmp_path / ".specify/integration-events.yml").write_text( - "integrations:\n copilot:\n events: {}\n" + "integrations:\n fake-context:\n events: {}\n", encoding="utf-8" ) override = context_delivery_error(installed, tmp_path) assert "override" in override and "event configuration" in override assert "upgrade" not in override -def test_copilot_installs_one_native_handler_with_compatible_commands( +def test_fake_installs_one_native_handler_with_compatible_commands( tmp_path, installed ): - native = json.loads((tmp_path / installed.events_config_file).read_text()) + native = json.loads((tmp_path / installed.events_config_file).read_text(encoding="utf-8")) hooks = native["hooks"]["sessionStart"] assert len(hooks) == 1 entry = hooks[0] @@ -267,13 +276,13 @@ def test_copilot_installs_one_native_handler_with_compatible_commands( def test_distinct_capability_reasons(tmp_path, installed): - class BadMapping(CopilotIntegration): + class BadMapping(FakeContextIntegration): CANONICAL_TO_NATIVE = {} - class Suppressed(CopilotIntegration): + class Suppressed(FakeContextIntegration): events_context_envelope = {"session_start": "suppress"} - class Legacy(CopilotIntegration): + class Legacy(FakeContextIntegration): def dispatch_command(self, command_name): pass @@ -282,10 +291,109 @@ def dispatch_command(self, command_name): assert "contradicts" in error and "upgrade" not in error legacy_error = context_delivery_error(Legacy(), tmp_path) assert "does not accept" in legacy_error and "upgrade" not in legacy_error - (tmp_path / ".specify/events.py").write_text("# stale dispatcher") + (tmp_path / ".specify/events.py").write_text("# stale dispatcher", encoding="utf-8") outdated = context_delivery_error(installed, tmp_path) - assert "outdated" in outdated and "specify integration upgrade copilot" in outdated + assert "outdated" in outdated and "specify integration upgrade fake-context" in outdated (tmp_path / ".specify/integration.json").unlink() not_installed = context_delivery_error(installed, tmp_path) assert "not installed" in not_installed - assert "specify integration upgrade copilot" in not_installed + assert "specify integration install fake-context" in not_installed + + +def test_unreadable_state_has_repair_hint(tmp_path, installed): + (tmp_path / ".specify/integration.json").write_text("{", encoding="utf-8") + error = context_delivery_error(installed, tmp_path) + assert "Fix or delete .specify/integration.json, then retry." in error + + +def test_modified_dispatcher_cannot_pass_by_containing_handler(tmp_path, installed): + (tmp_path / ".specify/events.py").write_text(ADDITIONAL_CONTEXT_HANDLER, encoding="utf-8") + assert "outdated" in context_delivery_error(installed, tmp_path) + + +@pytest.mark.parametrize("target", ["posix", "windows", "host"]) +@pytest.mark.parametrize("handler", [ADDITIONAL_CONTEXT_HANDLER, "name with 'quotes' and spaces"]) +def test_parse_dispatcher_command_round_trip(tmp_path, monkeypatch, target, handler): + monkeypatch.setattr("specify_cli.events._resolve_interpreter", lambda root: ".venv dir/bin/python") + integration = FakeContextIntegration() + command = _dispatcher_command(integration, tmp_path, handler, "session_start", target_os=target) + assert _parse_dispatcher_command(command, target_os=target) == (handler, "session_start", "additionalContext") + assert _parse_dispatcher_command(command + " ; echo bad", target_os=target) is None + + +def test_parse_dispatcher_plain_and_claude(tmp_path): + integration = get_integration("claude") + command = _dispatcher_command(integration, tmp_path, "handler name", "session_start") + assert _parse_dispatcher_command(command) == ("handler name", "session_start", None) + assert _parse_dispatcher_command("not a dispatcher") is None + assert _parse_dispatcher_command("& 'broken", target_os="windows") is None + + +@pytest.mark.parametrize("damage", ["wrong_event", "wrong_command", "wrong_envelope", "malformed", "unowned"]) +def test_invalid_installed_native_handler_is_rejected(tmp_path, installed, damage): + path = tmp_path / installed.events_config_file + native = json.loads(path.read_text(encoding="utf-8")) + entry = native["hooks"]["sessionStart"][0] + if damage == "wrong_event": + native["hooks"]["sessionEnd"] = native["hooks"].pop("sessionStart") + elif damage == "wrong_command": + for field in ("bash", "powershell"): + entry[field] = entry[field].replace(ADDITIONAL_CONTEXT_HANDLER, "other-handler") + native["elsewhere"] = ADDITIONAL_CONTEXT_HANDLER + elif damage == "wrong_envelope": + for field in ("bash", "powershell"): + entry[field] = entry[field].replace("additionalContext", "plain") + elif damage == "unowned": + entry.pop("__speckit_event__") + path.write_text("{" if damage == "malformed" else json.dumps(native), encoding="utf-8") + error = context_delivery_error(installed, tmp_path) + assert "outdated" in error and "specify integration upgrade fake-context" in error + + +def test_unreadable_handler_report_and_unknown_format(tmp_path, installed, monkeypatch): + assert IntegrationBase.installed_event_handlers(installed, tmp_path) is None + monkeypatch.setattr(installed, "installed_event_handlers", lambda root: None) + error = context_delivery_error(installed, tmp_path) + assert "cannot report installed handlers" in error + assert "upgrade" not in error + + +def test_installed_handlers_must_be_a_list(tmp_path, installed, monkeypatch): + monkeypatch.setattr(installed, "installed_event_handlers", lambda root: {"session_start": ADDITIONAL_CONTEXT_HANDLER}) + assert "outdated" in context_delivery_error(installed, tmp_path) + + +def test_dispatcher_crlf_matches_generated_template(tmp_path, installed): + (tmp_path / ".specify/events.py").write_bytes(_EVENTS_DISPATCHER_TEMPLATE.replace("\n", "\r\n").encode("utf-8")) + assert context_delivery_error(installed, tmp_path) is None + + +def test_default_handler_reader_dispatches_by_format(tmp_path, monkeypatch): + integration = FakeContextIntegration() + expected = {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + seen = [] + + def reader(adapter, root): + seen.append((adapter, root)) + return expected + + monkeypatch.setitem(_EVENT_HANDLER_READERS, integration.events_format, reader) + assert IntegrationBase.installed_event_handlers(integration, tmp_path) == expected + assert seen == [(integration, tmp_path)] + + +def test_copilot_is_not_a_context_delivery_declarer(tmp_path): + copilot = get_integration("copilot") + assert resolve_events("copilot", copilot.config, tmp_path, None) == {} + error = context_delivery_error(copilot, tmp_path) + assert "not declared" in error + assert "Supporting integrations: none" in error + + +def test_parse_dispatcher_with_project_venv_interpreter(tmp_path): + interpreter = tmp_path / ".venv/bin/python" + interpreter.parent.mkdir(parents=True) + interpreter.write_text("", encoding="utf-8") + command = _dispatcher_command(FakeContextIntegration(), tmp_path, "handler", "session_start") + assert command.startswith(".venv/bin/python ") + assert _parse_dispatcher_command(command) == ("handler", "session_start", "additionalContext") diff --git a/tests/workflows/test_command_additional_context.py b/tests/workflows/test_command_additional_context.py index cc9a4cabf2..94f274c1af 100644 --- a/tests/workflows/test_command_additional_context.py +++ b/tests/workflows/test_command_additional_context.py @@ -7,7 +7,8 @@ import yaml from specify_cli.events import install_integration_events, resolve_events -from specify_cli.integrations import get_integration +from specify_cli.integrations import INTEGRATION_REGISTRY +from tests.fixtures.context_delivery import FakeContextIntegration from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV from specify_cli.integrations.manifest import IntegrationManifest from specify_cli.workflows.base import StepContext, StepStatus @@ -16,20 +17,21 @@ @pytest.fixture -def installed(project_dir): - impl = get_integration("copilot") +def installed(project_dir, monkeypatch): + impl = FakeContextIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) state = project_dir / ".specify/integration.json" state.parent.mkdir(parents=True, exist_ok=True) state.write_text( json.dumps( - {"default_integration": "copilot", "installed_integrations": ["copilot"]} - ) + {"default_integration": "fake-context", "installed_integrations": ["fake-context"]} + ), encoding="utf-8" ) install_integration_events( impl, project_dir, - IntegrationManifest("copilot", project_dir, version="test"), - resolve_events("copilot", impl.config, project_dir, None), + IntegrationManifest("fake-context", project_dir, version="test"), + resolve_events("fake-context", impl.config, project_dir, None), ) return impl @@ -63,7 +65,7 @@ def test_expression_invalid_before_dispatch(monkeypatch, value): ) result = CommandStep().execute( config("{{ inputs.ctx }}"), - StepContext(inputs={"ctx": value}, default_integration="copilot"), + StepContext(inputs={"ctx": value}, default_integration="fake-context"), ) assert result.status == StepStatus.FAILED assert "SECRET" not in result.error @@ -87,17 +89,18 @@ def dispatch(*args, **kwargs): def test_missing_root_and_unsupported_fail_before_executable(monkeypatch): + monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-context", FakeContextIntegration()) monkeypatch.setattr( "shutil.which", lambda _: pytest.fail("capability must precede executable lookup"), ) step = CommandStep() - result = step.execute(config("SECRET"), StepContext(default_integration="copilot")) + result = step.execute(config("SECRET"), StepContext(default_integration="fake-context")) assert "project root" in result.error assert "SECRET" not in result.error result = step.execute(config("SECRET"), StepContext(default_integration="claude")) assert "not declared" in result.error - assert "copilot" in result.error + assert "fake-context" in result.error assert "SECRET" not in result.error @@ -116,7 +119,7 @@ def fake_run(args, **kwargs): step = CommandStep() context = StepContext( inputs={"ctx": "é" * 8192}, - default_integration="copilot", + default_integration="fake-context", project_root=str(project_dir), ) plain = step.execute( @@ -151,7 +154,7 @@ def old( monkeypatch.setattr(cls, "dispatch_command", old) monkeypatch.setattr("shutil.which", lambda name: name) - context = StepContext(default_integration="copilot", project_root=str(project_dir)) + context = StepContext(default_integration="fake-context", project_root=str(project_dir)) bad = CommandStep().execute(config("SECRET"), context) assert bad.status == StepStatus.FAILED and "does not accept" in bad.error assert "SECRET" not in bad.error and not calls @@ -171,7 +174,7 @@ def fake_run(args, **kwargs): def run(value): context = StepContext( - item=value, default_integration="copilot", project_root=str(project_dir) + item=value, default_integration="fake-context", project_root=str(project_dir) ) return CommandStep().execute( {**config("{{ item }}"), "input": {"args": "{{ item }}"}}, context @@ -180,7 +183,7 @@ def run(value): with ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(run, ["one", "two"])) assert all(result.status == StepStatus.COMPLETED for result in results) - assert sorted(seen) == [("/speckit-plan one", "one"), ("/speckit-plan two", "two")] + assert sorted(seen) == [("/speckit.plan one", "one"), ("/speckit.plan two", "two")] def test_resume_and_recording(project_dir, installed, monkeypatch): @@ -202,7 +205,7 @@ def fake_run(args, **kwargs): "version": "1.0.0", }, "inputs": {"ctx": {"type": "string", "default": "first-secret"}}, - "steps": [{**config("{{ inputs.ctx }}"), "integration": "copilot"}], + "steps": [{**config("{{ inputs.ctx }}"), "integration": "fake-context"}], } ) ) @@ -213,11 +216,11 @@ def fake_run(args, **kwargs): assert resumed.status.value == "completed" assert calls == ["first-secret", "second-secret"] run_dir = resumed.runs_dir - saved = json.loads((run_dir / "state.json").read_text()) + saved = json.loads((run_dir / "state.json").read_text(encoding="utf-8")) assert ( saved["step_results"]["ask"]["output"]["additional_context"] == "second-secret" ) - assert "secret" not in (run_dir / "log.jsonl").read_text() + assert "secret" not in (run_dir / "log.jsonl").read_text(encoding="utf-8") def test_fan_out_with_distinct_contexts(project_dir, installed, monkeypatch): @@ -246,7 +249,7 @@ def fake_run(args, **kwargs): "max_concurrency": 2, "step": { **config("{{ item }}"), - "integration": "copilot", + "integration": "fake-context", "input": {"args": "{{ item }}"}, }, } @@ -256,7 +259,7 @@ def fake_run(args, **kwargs): ) state = WorkflowEngine(project_dir).execute(definition) assert state.status.value == "completed" - assert sorted(seen) == [("/speckit-plan one", "one"), ("/speckit-plan two", "two")] + assert sorted(seen) == [("/speckit.plan one", "one"), ("/speckit.plan two", "two")] def test_resume_does_not_repeat_completed_command(project_dir, installed, monkeypatch): @@ -279,11 +282,11 @@ def fake_run(args, **kwargs): }, "inputs": {"ctx": {"type": "string", "default": "first"}}, "steps": [ - {**config("{{ inputs.ctx }}"), "integration": "copilot"}, + {**config("{{ inputs.ctx }}"), "integration": "fake-context"}, { **config("{{ inputs.ctx }}"), "id": "second", - "integration": "copilot", + "integration": "fake-context", }, ], } @@ -296,3 +299,21 @@ def fake_run(args, **kwargs): assert resumed.status.value == "completed" assert calls == ["first", "first", "changed"] assert resumed.step_results["ask"]["output"]["additional_context"] == "first" + + +def test_additional_context_expression_error_continues_without_disclosure(project_dir): + definition = WorkflowDefinition.from_string(yaml.safe_dump({ + "schema_version": "1.0", + "workflow": {"id": "context-error", "name": "Context Error", "version": "1.0.0"}, + "inputs": {"ctx": {"type": "string", "default": "NaN"}}, + "steps": [ + {**config("{{ inputs.ctx | from_json }}"), "continue_on_error": True}, + {"id": "after", "type": "shell", "run": "echo after"}, + ], + })) + state = WorkflowEngine(project_dir).execute(definition) + assert state.step_results["ask"]["status"] == "failed" + assert state.step_results["ask"]["error"] == "Command step 'ask': additional_context: expression could not be evaluated." + assert state.step_results["after"]["status"] == "completed" + assert "NaN" not in state.step_results["ask"]["error"] + assert "NaN" not in (state.runs_dir / "log.jsonl").read_text(encoding="utf-8") diff --git a/tests/workflows/test_shell_step.py b/tests/workflows/test_shell_step.py index d34faa215f..0aa1d42387 100644 --- a/tests/workflows/test_shell_step.py +++ b/tests/workflows/test_shell_step.py @@ -508,7 +508,10 @@ def test_windows_environment_override_is_case_insensitive(monkeypatch): import specify_cli.workflows.step.shell as shell_module parent_env = {"PATH": "inherited", "SPECKIT_WORKFLOW_DIR": "stale"} - monkeypatch.setattr(shell_module, "os", SimpleNamespace(name="nt", environ=parent_env)) + mocked_os = SimpleNamespace(name="nt", environ=parent_env) + monkeypatch.setattr(shell_module, "os", mocked_os) + import specify_cli.integrations._context as context_module + monkeypatch.setattr(context_module, "os", mocked_os) def capture_run(command, **kwargs): assert kwargs["env"] == {"PATH": "configured"} @@ -819,3 +822,22 @@ def test_captured_stdout_with_newline_compares_as_number( other_branch = "else-ran" if expected_branch == "then-ran" else "then-ran" assert expected_branch in state.step_results assert other_branch not in state.step_results + + +@pytest.mark.parametrize("inherited,binding,expected", [ + (None, None, None), ("parent", None, None), ("parent", "explicit", "explicit"), +]) +def test_shell_context_environment_isolation(project_dir, monkeypatch, inherited, binding, expected): + name = "SPECKIT_ADDITIONAL_CONTEXT" + if inherited is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, inherited) + run = _python_run(project_dir, "import os, json\nprint(json.dumps(os.environ.get('SPECKIT_ADDITIONAL_CONTEXT')))\n") + config = {"id": "shell", "run": run, "env": {"PYTHONIOENCODING": "utf-8"}} + if binding is not None: + config["env"][name] = binding + result = ShellStep().execute(config, StepContext(project_root=str(project_dir))) + assert result.status == StepStatus.COMPLETED + assert json.loads(result.output["stdout"]) == expected + assert os.environ.get(name) == inherited From feca1cbf7b8775ceccb1cacb357acc76c565e2db Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 21:24:39 +0100 Subject: [PATCH 03/20] fix(workflows): address #5616 review round 2 - Restore main's order in _remove_native_event_hooks: an absent native config returns before the destination check, so a symlinked hook directory without a Spec Kit config is a no-op again. An existing config is still validated before it is read or removed. - Document that shell steps drop an inherited SPECKIT_ADDITIONAL_CONTEXT unless an explicit env binding sets it. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous) --- design/workflow-step.md | 2 + docs/workflow-steps/types.md | 6 ++- src/specify_cli/events/__init__.py | 2 +- tests/specify_cli/events/test_events.py | 57 +++++++++++++++++++++++++ tests/specify_cli/test_command_init.py | 19 +++++++++ 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/design/workflow-step.md b/design/workflow-step.md index c56244da3f..6f286f9f9c 100644 --- a/design/workflow-step.md +++ b/design/workflow-step.md @@ -48,6 +48,8 @@ Per-step `strict: true` rejects expression markers in `run` during validation and execution. Its optional `env` mapping evaluates string templates separately, requires NUL-free string results encodable for the process environment on POSIX, and overrides only the child environment. +The shell step drops inherited `SPECKIT_ADDITIONAL_CONTEXT`, but an explicit +`env:` binding can set it. `SPECKIT_WORKFLOW_DIR` remains engine-owned. This prevents workflow expression values from becoming shell source in strict mode; it is not a sandbox or a guarantee that an authored script handles environment data safely. diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index 301c3ae0bd..e746390a5d 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -392,7 +392,9 @@ interpolation: `COUNT: "n={{ inputs.count }}"` produces `n=42` for integer representation. To serialize structured data explicitly, use `to_json`. Bindings override inherited environment values for that subprocess only; -they do not modify the parent process or subsequent steps. An empty string is +they do not modify the parent process or subsequent steps. The shell step drops +inherited `SPECKIT_ADDITIONAL_CONTEXT` (see [Additional Context for Command Steps](#additional-context-for-command-steps)), +but an explicit `env:` binding can set it. An empty string is valid. `SPECKIT_WORKFLOW_DIR` is reserved (case-insensitively) and cannot be overridden. Keep environment names and executable-loading settings under the workflow author's control: environment binding is a data channel, not a sandbox. @@ -413,7 +415,7 @@ For example, `PATH` selects executables, `PYTHONPATH` affects Python imports, startup behavior. Native loaders and other programs have their own settings; these examples are not an exhaustive list. A fixed `run` can therefore execute different code even with `strict: true` and no `eval`. Strict mode neither -filters execution-controlling bindings nor cleans the inherited environment. +filters execution-controlling bindings nor otherwise cleans the inherited environment. Keep those settings literal and author-vetted, or constrain dynamic values to an approved set of trusted paths/options. Use unconstrained input or agent output only for application-data variables whose consumers handle it as data. diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 1b78179e55..d2ce6f9ff8 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -1782,9 +1782,9 @@ def _remove_native_event_hooks( if not config_file: return config_path = project_root / config_file - _ensure_safe_destination(config_path, project_root) if not config_path.exists(): return + _ensure_safe_destination(config_path, project_root) removed = False if fmt == "copilot-json": removed = _remove_copilot_entries(config_path, project_root=project_root) diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index b6ba3e86fe..1bcb4cb012 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -2807,6 +2807,63 @@ def test_symlinked_config_dir_rejected(self, tmp_path): # No content written through the symlink. assert not (outside / "settings.json").exists() + @pytest.mark.parametrize("operation", ["remove", "disable"]) + @pytest.mark.parametrize("config_state", ["absent", "dangling", "present"]) + def test_copilot_cleanup_with_symlinked_config_parent(self, tmp_path, operation, config_state): + project = tmp_path / "project" + outside = tmp_path / "outside" + (project / ".github").mkdir(parents=True) + outside.mkdir() + hooks = project / ".github/hooks" + try: + hooks.symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + config = outside / "speckit.json" + content = '{"hooks": {"sessionStart": [{"__speckit_event__": true}]}}' + if config_state == "present": + config.write_text(content, encoding="utf-8") + elif config_state == "dangling": + try: + config.symlink_to(outside / "missing.json") + except (OSError, NotImplementedError): + pytest.skip("File links are unavailable") + integration = CopilotIntegration() + manifest = IntegrationManifest(integration.key, project) + + def cleanup(): + if operation == "remove": + remove_integration_events(integration, project, manifest) + else: + install_integration_events(integration, project, manifest, {}) + + if config_state == "present": + with pytest.raises(ValueError, match="(?i)symlink|escapes|outside"): + cleanup() + assert config.read_text(encoding="utf-8") == content + else: + cleanup() + assert not config.exists() + assert config.is_symlink() is (config_state == "dangling") + assert hooks.is_symlink() + + @pytest.mark.parametrize("operation", ["remove", "disable"]) + def test_copilot_cleanup_with_dangling_config_symlink(self, tmp_path, operation): + config = tmp_path / ".github/hooks/speckit.json" + config.parent.mkdir(parents=True) + try: + config.symlink_to(tmp_path / "missing.json") + except (OSError, NotImplementedError): + pytest.skip("File links are unavailable") + integration = CopilotIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + if operation == "remove": + remove_integration_events(integration, tmp_path, manifest) + else: + install_integration_events(integration, tmp_path, manifest, {}) + assert config.is_symlink() + assert not config.exists() + def test_toml_teardown_rejects_symlinked_config(self, tmp_path): """R3: TOML teardown validates the destination before read/write, so a symlink swap after install can't make uninstall overwrite an external diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 7dd683e4e7..4b24a86ec6 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -142,6 +142,25 @@ def test_reinit_preserves_feature_numbering(tmp_path: Path, monkeypatch, numberi assert updated["here"] is True +def test_init_copilot_with_missing_config_in_symlinked_hooks_dir(tmp_path, monkeypatch): + project = tmp_path / "project" + outside = tmp_path / "outside" + (project / ".github").mkdir(parents=True) + outside.mkdir() + hooks = project / ".github/hooks" + _symlink_or_skip(hooks, outside, directory=True) + monkeypatch.chdir(project) + + result = CliRunner().invoke(app, [ + "init", ".", "--integration", "copilot", "--script", "sh", + "--ignore-agent-tools", "--force", + ]) + + assert result.exit_code == 0, result.output + assert hooks.is_symlink() + assert not list(outside.iterdir()) + + @pytest.mark.parametrize("selected", ["claude", "codex", "gemini"]) def test_reinit_keeps_other_installed_integrations(tmp_path, monkeypatch, selected): """The upgrade-guide fallback must keep the other installed integrations.""" From 377d852c5a885d6647c6c6e146b1402e32c5cd6e Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 1 Dec 2026 18:00:01 +0100 Subject: [PATCH 04/20] fix(workflows): validate context hooks and JSON expressions Validate the full generated dispatcher command, including the interpreter and native event, and reject malformed timeout tokens. Reject unsupported context-delivery envelopes before dispatch. Normalize deeply nested JSON parsing failures to ValueError so additional_context respects continue_on_error. Link the integration contract to its published repository location. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- docs/integrations/api.md | 2 +- src/specify_cli/events/__init__.py | 57 +++++++++---- src/specify_cli/integrations/base.py | 4 +- src/specify_cli/workflows/_json.py | 41 ++++++++++ .../workflows/expressions/filters.py | 21 ++--- tests/fixtures/context_delivery.py | 7 +- .../events/test_context_delivery.py | 81 ++++++++++++++++--- .../test_command_additional_context.py | 26 ++++++ tests/workflows/test_json_helper.py | 35 ++++++++ 9 files changed, 232 insertions(+), 42 deletions(-) create mode 100644 src/specify_cli/workflows/_json.py create mode 100644 tests/workflows/test_json_helper.py diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 12b45a1aa5..2da3d04646 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -376,4 +376,4 @@ authentication, or feature-flag preconditions and provide live evidence. Impleme `installed_event_handlers(project_root)` when the event format has no shared reader; return canonical event names mapped to lists of installed handler names, or `None` if the installation cannot be inspected. See -[the integration contract](../../design/integration.md#context-delivery-for-command-steps). +[the integration contract](https://github.com/github/spec-kit/blob/main/design/integration.md#context-delivery-for-command-steps). diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index d2ce6f9ff8..97e798cd8d 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -79,6 +79,18 @@ # (no buffer); the native config field gets seconds + buffer (R2). EVENT_TIMEOUT_BUFFER = 5 +# Context-injection envelopes supported by the generated dispatcher when +# delivering model context (i.e. excluding "suppress"). ``None`` means no +# envelope is declared and the dispatcher passes plain stdout through. +CONTEXT_DELIVERY_ENVELOPES: frozenset[str | None] = frozenset({ + None, + "plain", + "hookSpecificOutput", + "additionalContext", + "additional_context", + "hook_specific_output", +}) + # Canonical event names (snake_case) CANONICAL_EVENTS = frozenset({ "session_start", @@ -1081,7 +1093,10 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No remedy = "" if not isinstance(declared, (set, frozenset)) or event not in declared: reason = "context delivery is not declared" - elif event not in getattr(integration, "CANONICAL_TO_NATIVE", {}) or context_envelope_for(integration, event) == "suppress": + elif ( + event not in getattr(integration, "CANONICAL_TO_NATIVE", {}) + or context_envelope_for(integration, event) not in CONTEXT_DELIVERY_ENVELOPES + ): reason = "the event mapping or envelope contradicts the declaration" elif not _accepts_keyword(integration.dispatch_command, "additional_context"): reason = "dispatch_command does not accept additional_context" @@ -1428,11 +1443,19 @@ def _dispatcher_command( return base -def _parse_dispatcher_command(command: str, *, target_os: str = "host") -> tuple[str, str, str | None] | None: +def _parse_dispatcher_command( + command: str, + integration: IntegrationBase, + project_root: Path, + *, + target_os: str = "host", +) -> tuple[str, str, str | None] | None: """Recover handler, canonical event and envelope from a generated command. - This parses the POSIX and PowerShell forms emitted by `_dispatcher_command`; - it does not execute the command or accept arbitrary shell syntax. + Validates the complete command — including the resolved interpreter, + dispatcher path, envelope, and ``hookSpecificOutput`` native event — + against ``_dispatcher_command`` for *integration*, *project_root*, and + *target_os*. Does not execute the command or accept arbitrary shell syntax. """ if target_os == "windows": if not command.startswith("& "): @@ -1452,22 +1475,24 @@ def _parse_dispatcher_command(command: str, *, target_os: str = "host") -> tuple return None else: return None - if not 5 <= len(tokens) <= 7 or not tokens[0] or not tokens[4].isdigit(): + if not 5 <= len(tokens) <= 7 or not tokens[4].isdigit(): return None - if tokens[1] not in (EVENTS_DISPATCHER_REL, "${CLAUDE_PROJECT_DIR}/" + EVENTS_DISPATCHER_REL): + handler, event = tokens[2], tokens[3] + try: + timeout = int(tokens[4]) + except ValueError: return None - dispatcher = ( - '"${CLAUDE_PROJECT_DIR}/' + EVENTS_DISPATCHER_REL + '"' - if tokens[1].startswith("${CLAUDE_PROJECT_DIR}/") - else _shell_quote(tokens[1], target_os) + expected = _dispatcher_command( + integration, + project_root, + handler, + event, + target_os=target_os, + timeout_seconds=timeout, ) - rendered = " ".join([_shell_quote(tokens[0], target_os), dispatcher, - *(_shell_quote(token, target_os) for token in tokens[2:])]) - if target_os == "windows": - rendered = "& " + rendered - if rendered != command: + if expected != command: return None - return tokens[2], tokens[3], tokens[5] if len(tokens) >= 6 else None + return handler, event, tokens[5] if len(tokens) >= 6 else None def context_envelope_for(integration: IntegrationBase, canonical_event: str) -> str | None: diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index e080029b91..1f458cf6d5 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -214,14 +214,14 @@ def _accepts_keyword(function: Any, name: str) -> bool: def supports_context_delivery(integration: IntegrationBase, event: str) -> bool: """Whether the integration promises context delivery on this event.""" - from ..events import context_envelope_for + from ..events import CONTEXT_DELIVERY_ENVELOPES, context_envelope_for declared = integration.context_delivery_events return ( isinstance(declared, (set, frozenset)) and event in declared and event in getattr(integration, "CANONICAL_TO_NATIVE", {}) - and context_envelope_for(integration, event) != "suppress" + and context_envelope_for(integration, event) in CONTEXT_DELIVERY_ENVELOPES and _accepts_keyword(integration.dispatch_command, "additional_context") ) diff --git a/src/specify_cli/workflows/_json.py b/src/specify_cli/workflows/_json.py new file mode 100644 index 0000000000..0489c05784 --- /dev/null +++ b/src/specify_cli/workflows/_json.py @@ -0,0 +1,41 @@ +"""Strict JSON loading helpers for workflow code. + +Centralizes ``json.loads`` / ``json.load`` error normalization so callers +relying on ``ValueError`` (for example step failure handling and +``continue_on_error``) do not crash on ``RecursionError`` from deeply nested +documents or accept Python's non-JSON numeric constants (``NaN``, ``Infinity``, +``-Infinity``). +""" + +from __future__ import annotations + +import json +from typing import Any, NoReturn + + +def safe_json_loads( + text: str, + *, + strict_constants: bool = True, + context: str | None = None, +) -> Any: + """Parse JSON *text*, normalizing ``RecursionError`` to ``ValueError``. + + When *strict_constants* is ``True`` (the default), non-JSON numeric + constants (``NaN``, ``Infinity``, ``-Infinity``) are rejected as + ``ValueError``. Optional *context* prefixes every raised ``ValueError`` + (e.g. ``"from_json"`` → ``"from_json: invalid JSON: ..."``). + """ + prefix = f"{context}: " if context else "" + kwargs: dict[str, Any] = {} + if strict_constants: + def _reject(value: str) -> NoReturn: + raise ValueError(f"{prefix}invalid JSON constant: {value}") + + kwargs["parse_constant"] = _reject + try: + return json.loads(text, **kwargs) + except json.JSONDecodeError as exc: + raise ValueError(f"{prefix}invalid JSON: {exc}") from exc + except RecursionError: + raise ValueError(f"{prefix}invalid JSON: nested too deeply") from None diff --git a/src/specify_cli/workflows/expressions/filters.py b/src/specify_cli/workflows/expressions/filters.py index 7dcee8d825..8e140ddf81 100644 --- a/src/specify_cli/workflows/expressions/filters.py +++ b/src/specify_cli/workflows/expressions/filters.py @@ -12,7 +12,9 @@ from collections.abc import Callable, Mapping from dataclasses import dataclass from types import MappingProxyType -from typing import Any, NoReturn +from typing import Any + +from .._json import safe_json_loads # -- Custom filters ------------------------------------------------------- @@ -102,26 +104,19 @@ def _filter_contains(value: Any, substring: Any) -> bool: return False -def _reject_json_constant(value: str) -> NoReturn: - """Reject the non-JSON numeric constants accepted by Python's decoder.""" - raise ValueError(f"from_json: invalid JSON constant: {value}") - - def _filter_from_json(value: Any) -> Any: """Parse a JSON string into a typed value (list/dict/scalar). - Raises ``ValueError`` on non-string input or invalid JSON — a parse - failure here means the pipeline wiring is wrong, and silently - passing the unparsed value through would hide it. + Raises ``ValueError`` on non-string input, invalid JSON, non-JSON + constants, or excessively nested JSON — a parse failure here means the + pipeline wiring is wrong, and silently passing the unparsed value through + would hide it. """ if not isinstance(value, str): raise ValueError( f"from_json: expected a JSON string, got {type(value).__name__}" ) - try: - return json.loads(value, parse_constant=_reject_json_constant) - except json.JSONDecodeError as exc: - raise ValueError(f"from_json: invalid JSON: {exc}") from exc + return safe_json_loads(value, context="from_json") def _filter_upper(value: Any) -> str: diff --git a/tests/fixtures/context_delivery.py b/tests/fixtures/context_delivery.py index f5b25468db..efc79ec97c 100644 --- a/tests/fixtures/context_delivery.py +++ b/tests/fixtures/context_delivery.py @@ -35,7 +35,12 @@ def installed_event_handlers(self, project_root): command = entry.get("powershell" if os.name == "nt" else "bash") if not isinstance(command, str): continue - parsed = _parse_dispatcher_command(command, target_os="windows" if os.name == "nt" else "posix") + parsed = _parse_dispatcher_command( + command, + self, + project_root, + target_os="windows" if os.name == "nt" else "posix", + ) if parsed and parsed[1:] == ("session_start", "additionalContext"): handlers.append(parsed[0]) return {"session_start": handlers} diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index 41a7a3bf1c..787c54b985 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -282,11 +282,15 @@ class BadMapping(FakeContextIntegration): class Suppressed(FakeContextIntegration): events_context_envelope = {"session_start": "suppress"} + class UnknownEnvelope(FakeContextIntegration): + events_context_envelope = {"session_start": "additionalcontext"} + class Legacy(FakeContextIntegration): def dispatch_command(self, command_name): pass - for integration in (BadMapping(), Suppressed()): + for integration in (BadMapping(), Suppressed(), UnknownEnvelope()): + assert not supports_context_delivery(integration, "session_start") error = context_delivery_error(integration, tmp_path) assert "contradicts" in error and "upgrade" not in error legacy_error = context_delivery_error(Legacy(), tmp_path) @@ -317,19 +321,74 @@ def test_parse_dispatcher_command_round_trip(tmp_path, monkeypatch, target, hand monkeypatch.setattr("specify_cli.events._resolve_interpreter", lambda root: ".venv dir/bin/python") integration = FakeContextIntegration() command = _dispatcher_command(integration, tmp_path, handler, "session_start", target_os=target) - assert _parse_dispatcher_command(command, target_os=target) == (handler, "session_start", "additionalContext") - assert _parse_dispatcher_command(command + " ; echo bad", target_os=target) is None + assert _parse_dispatcher_command(command, integration, tmp_path, target_os=target) == ( + handler, + "session_start", + "additionalContext", + ) + assert _parse_dispatcher_command(command + " ; echo bad", integration, tmp_path, target_os=target) is None def test_parse_dispatcher_plain_and_claude(tmp_path): integration = get_integration("claude") command = _dispatcher_command(integration, tmp_path, "handler name", "session_start") - assert _parse_dispatcher_command(command) == ("handler name", "session_start", None) - assert _parse_dispatcher_command("not a dispatcher") is None - assert _parse_dispatcher_command("& 'broken", target_os="windows") is None + assert _parse_dispatcher_command(command, integration, tmp_path) == ("handler name", "session_start", None) + assert _parse_dispatcher_command("not a dispatcher", integration, tmp_path) is None + assert _parse_dispatcher_command("& 'broken", integration, tmp_path, target_os="windows") is None -@pytest.mark.parametrize("damage", ["wrong_event", "wrong_command", "wrong_envelope", "malformed", "unowned"]) +def test_parse_dispatcher_rejects_wrong_interpreter_and_native_event(tmp_path): + integration = FakeContextIntegration() + posix_cmd = _dispatcher_command(integration, tmp_path, ADDITIONAL_CONTEXT_HANDLER, "session_start", target_os="posix") + assert _parse_dispatcher_command( + posix_cmd.replace("python3", "echo", 1), integration, tmp_path, target_os="posix" + ) is None + ps_cmd = _dispatcher_command(integration, tmp_path, ADDITIONAL_CONTEXT_HANDLER, "session_start", target_os="windows") + assert _parse_dispatcher_command( + ps_cmd.replace("'python'", "'echo'", 1), integration, tmp_path, target_os="windows" + ) is None + + gemini = get_integration("gemini") + gemini_cmd = _dispatcher_command(gemini, tmp_path, ADDITIONAL_CONTEXT_HANDLER, "session_start") + assert _parse_dispatcher_command(gemini_cmd, gemini, tmp_path) == ( + ADDITIONAL_CONTEXT_HANDLER, + "session_start", + "hookSpecificOutput", + ) + assert _parse_dispatcher_command( + gemini_cmd.replace("SessionStart", "SessionEnd"), gemini, tmp_path + ) is None + assert _parse_dispatcher_command( + gemini_cmd.removesuffix(" SessionStart"), gemini, tmp_path + ) is None + assert _parse_dispatcher_command( + posix_cmd + " extra", integration, tmp_path, target_os="posix" + ) is None + assert _parse_dispatcher_command( + posix_cmd.replace("python3", "python3", 1), + gemini, + tmp_path, + target_os="posix", + ) is None + + +@pytest.mark.parametrize("timeout", ["²", "9" * 5000]) +def test_parse_dispatcher_rejects_invalid_timeout_without_raising(tmp_path, timeout): + integration = FakeContextIntegration() + command = _dispatcher_command(integration, tmp_path, "handler", "session_start", target_os="posix") + command = command.replace(" 60 ", f" {timeout} ") + assert _parse_dispatcher_command(command, integration, tmp_path, target_os="posix") is None + + +@pytest.mark.parametrize("envelope", [None, "plain", "hookSpecificOutput", "additionalContext", "additional_context", "hook_specific_output"]) +def test_supports_context_delivery_accepts_supported_envelopes(envelope): + class SupportedEnvelope(FakeContextIntegration): + events_context_envelope = {} if envelope is None else {"session_start": envelope} + + assert supports_context_delivery(SupportedEnvelope(), "session_start") + + +@pytest.mark.parametrize("damage", ["wrong_event", "wrong_command", "wrong_envelope", "wrong_interpreter", "malformed", "unowned"]) def test_invalid_installed_native_handler_is_rejected(tmp_path, installed, damage): path = tmp_path / installed.events_config_file native = json.loads(path.read_text(encoding="utf-8")) @@ -343,6 +402,9 @@ def test_invalid_installed_native_handler_is_rejected(tmp_path, installed, damag elif damage == "wrong_envelope": for field in ("bash", "powershell"): entry[field] = entry[field].replace("additionalContext", "plain") + elif damage == "wrong_interpreter": + entry["bash"] = entry["bash"].replace("python3", "echo", 1) + entry["powershell"] = entry["powershell"].replace("'python'", "'echo'", 1) elif damage == "unowned": entry.pop("__speckit_event__") path.write_text("{" if damage == "malformed" else json.dumps(native), encoding="utf-8") @@ -394,6 +456,7 @@ def test_parse_dispatcher_with_project_venv_interpreter(tmp_path): interpreter = tmp_path / ".venv/bin/python" interpreter.parent.mkdir(parents=True) interpreter.write_text("", encoding="utf-8") - command = _dispatcher_command(FakeContextIntegration(), tmp_path, "handler", "session_start") + integration = FakeContextIntegration() + command = _dispatcher_command(integration, tmp_path, "handler", "session_start") assert command.startswith(".venv/bin/python ") - assert _parse_dispatcher_command(command) == ("handler", "session_start", "additionalContext") + assert _parse_dispatcher_command(command, integration, tmp_path) == ("handler", "session_start", "additionalContext") diff --git a/tests/workflows/test_command_additional_context.py b/tests/workflows/test_command_additional_context.py index 94f274c1af..cf6aa978ef 100644 --- a/tests/workflows/test_command_additional_context.py +++ b/tests/workflows/test_command_additional_context.py @@ -317,3 +317,29 @@ def test_additional_context_expression_error_continues_without_disclosure(projec assert state.step_results["after"]["status"] == "completed" assert "NaN" not in state.step_results["ask"]["error"] assert "NaN" not in (state.runs_dir / "log.jsonl").read_text(encoding="utf-8") + + +def test_additional_context_deeply_nested_json_continues_without_disclosure( + project_dir, monkeypatch +): + secret = "secret-nested-marker" + + def raise_recursion(*args, **kwargs): + raise RecursionError(secret) + + monkeypatch.setattr("specify_cli.workflows._json.json.loads", raise_recursion) + definition = WorkflowDefinition.from_string(yaml.safe_dump({ + "schema_version": "1.0", + "workflow": {"id": "context-nested", "name": "Context Nested", "version": "1.0.0"}, + "inputs": {"ctx": {"type": "string", "default": "[[[]]]"}}, + "steps": [ + {**config("{{ inputs.ctx | from_json }}"), "continue_on_error": True}, + {"id": "after", "type": "shell", "run": "echo after"}, + ], + })) + state = WorkflowEngine(project_dir).execute(definition) + assert state.step_results["ask"]["status"] == "failed" + assert state.step_results["ask"]["error"] == "Command step 'ask': additional_context: expression could not be evaluated." + assert state.step_results["after"]["status"] == "completed" + assert secret not in state.step_results["ask"]["error"] + assert secret not in (state.runs_dir / "log.jsonl").read_text(encoding="utf-8") diff --git a/tests/workflows/test_json_helper.py b/tests/workflows/test_json_helper.py new file mode 100644 index 0000000000..3daa1e76c6 --- /dev/null +++ b/tests/workflows/test_json_helper.py @@ -0,0 +1,35 @@ +"""Tests for strict workflow JSON loading helpers.""" + +from __future__ import annotations + +import pytest + +from specify_cli.workflows._json import safe_json_loads + + +def test_safe_json_loads_parses_valid_json(): + assert safe_json_loads('{"a": [1, true, null, "x"]}') == { + "a": [1, True, None, "x"] + } + + +@pytest.mark.parametrize("constant", ["NaN", "Infinity", "-Infinity"]) +def test_safe_json_loads_rejects_non_json_constants_by_default(constant): + with pytest.raises(ValueError, match=f"invalid JSON constant: {constant}"): + safe_json_loads(constant) + + +def test_safe_json_loads_prefixes_errors_with_context(): + with pytest.raises(ValueError, match="^from_json: invalid JSON:"): + safe_json_loads("{bad", context="from_json") + with pytest.raises(ValueError, match="^from_json: invalid JSON constant: NaN$"): + safe_json_loads("NaN", context="from_json") + + +def test_safe_json_loads_normalizes_recursion_error_to_value_error(monkeypatch): + def raise_recursion(*args, **kwargs): + raise RecursionError("stack depth") + + monkeypatch.setattr("specify_cli.workflows._json.json.loads", raise_recursion) + with pytest.raises(ValueError, match="^from_json: invalid JSON: nested too deeply$"): + safe_json_loads("[[[]]]", context="from_json") From 4bfdba116d4ffa424c70379f58068941068c5a46 Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 1 Dec 2026 18:38:45 +0100 Subject: [PATCH 05/20] refactor(workflows): narrow JSON helper contract Describe the helper as JSON text loading for workflow expressions and remove the unused strict_constants option. Existing callers continue to reject non-JSON numeric constants. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- src/specify_cli/workflows/_json.py | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/specify_cli/workflows/_json.py b/src/specify_cli/workflows/_json.py index 0489c05784..72dcf60e2a 100644 --- a/src/specify_cli/workflows/_json.py +++ b/src/specify_cli/workflows/_json.py @@ -1,10 +1,7 @@ -"""Strict JSON loading helpers for workflow code. +"""Strict JSON text loading for workflow expressions. -Centralizes ``json.loads`` / ``json.load`` error normalization so callers -relying on ``ValueError`` (for example step failure handling and -``continue_on_error``) do not crash on ``RecursionError`` from deeply nested -documents or accept Python's non-JSON numeric constants (``NaN``, ``Infinity``, -``-Infinity``). +Normalize excessive nesting to ``ValueError`` and reject Python's non-JSON +numeric constants (``NaN``, ``Infinity``, ``-Infinity``). """ from __future__ import annotations @@ -16,25 +13,21 @@ def safe_json_loads( text: str, *, - strict_constants: bool = True, context: str | None = None, ) -> Any: """Parse JSON *text*, normalizing ``RecursionError`` to ``ValueError``. - When *strict_constants* is ``True`` (the default), non-JSON numeric - constants (``NaN``, ``Infinity``, ``-Infinity``) are rejected as - ``ValueError``. Optional *context* prefixes every raised ``ValueError`` - (e.g. ``"from_json"`` → ``"from_json: invalid JSON: ..."``). + Non-JSON numeric constants (``NaN``, ``Infinity``, ``-Infinity``) are + rejected as ``ValueError``. Optional *context* prefixes every raised + ``ValueError`` (e.g. ``"from_json"`` → ``"from_json: invalid JSON: ..."``). """ prefix = f"{context}: " if context else "" - kwargs: dict[str, Any] = {} - if strict_constants: - def _reject(value: str) -> NoReturn: - raise ValueError(f"{prefix}invalid JSON constant: {value}") - kwargs["parse_constant"] = _reject + def _reject(value: str) -> NoReturn: + raise ValueError(f"{prefix}invalid JSON constant: {value}") + try: - return json.loads(text, **kwargs) + return json.loads(text, parse_constant=_reject) except json.JSONDecodeError as exc: raise ValueError(f"{prefix}invalid JSON: {exc}") from exc except RecursionError: From 615f9078ed1113c0bea2eb049e30d5a73fa66b3e Mon Sep 17 00:00:00 2001 From: Markus Date: Tue, 1 Dec 2026 20:46:20 +0100 Subject: [PATCH 06/20] fix(events): centralize state errors and check session_start matcher Address PR #5616 review round 5: - Centralize IntegrationReadError message, reason, detail, remedy, and summary formatting in integration_state.py so schema_too_new advises upgrading Spec Kit (never deleting .specify/integration.json) across context_delivery_error(), integration status, _helpers, _lifecycle, generic, extensions, and event refresh. - Require at least one unfiltered session_start __speckit_additional_context__ handler (matcher omitted, empty, or '*') in context_delivery_error(), and document the native-filter requirement on installed_event_handlers() in base.py, design/integration.md, docs/integrations/api.md, and docs/workflow-steps/types.md. - Add unit and regression tests for all IntegrationReadError kinds, schema_too_new remedies across callers, restrictive override matchers, and a contract-compliant json-nested native handler reader. Assisted-by: Antigravity (model: Gemini 4 Neon, autonomous) --- design/integration.md | 10 +- docs/integrations/api.md | 6 +- docs/workflow-steps/types.md | 3 +- src/specify_cli/events/__init__.py | 57 +++--- src/specify_cli/extensions/__init__.py | 9 +- src/specify_cli/integration_state.py | 84 ++++++++- src/specify_cli/integration_status.py | 30 +-- src/specify_cli/integrations/_helpers.py | 25 +-- src/specify_cli/integrations/_lifecycle.py | 8 +- src/specify_cli/integrations/base.py | 8 +- .../integrations/generic/__init__.py | 8 +- tests/integrations/test_integration_state.py | 76 ++++++++ .../events/test_context_delivery.py | 176 +++++++++++++++++- .../integrations/test_command_list.py | 4 +- .../integrations/test_command_status.py | 2 + .../integrations/test_lifecycle.py | 33 ++++ 16 files changed, 434 insertions(+), 105 deletions(-) diff --git a/design/integration.md b/design/integration.md index 53df734221..bbb0626656 100644 --- a/design/integration.md +++ b/design/integration.md @@ -122,9 +122,13 @@ mapping, an envelope other than `suppress`, and a `dispatch_command` accepting overriding adapter must honor the promise. Test declaration consistency and provide live evidence for the agent-side behavior. The integration must also report its installed canonical handlers through `installed_event_handlers()`, -either using a reader for its event format or overriding the method. `None` -means the installation cannot be inspected; a missing handler prevents dispatch. -The shared dispatcher must exactly match the current generated template. +either using a reader for its event format or overriding the method. For +formats with native event filters, `installed_event_handlers()` must exclude +handlers whose filter restricts normal fresh-session dispatch (for example, a +`resume`-only `session_start` matcher); only unfiltered or wildcard handlers +(absent, `""`, or `"*"`) qualify. `None` means the installation cannot be +inspected; a missing handler prevents dispatch. The shared dispatcher must +exactly match the current generated template. Spec Kit installs the hook, runs the handler and writes the envelope. Agent-side preconditions such as trust, feature flags and authentication belong in each diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 2da3d04646..80073510b9 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -375,5 +375,9 @@ mapped to a native event with a non-suppressing envelope, and authentication, or feature-flag preconditions and provide live evidence. Implement `installed_event_handlers(project_root)` when the event format has no shared reader; return canonical event names mapped to lists of installed handler names, -or `None` if the installation cannot be inspected. See +or `None` if the installation cannot be inspected. For formats with native event +filters, exclude handlers on filterable events such as `session_start` whose +filter restricts normal fresh-session dispatch (for example, a `resume`-only +matcher), reporting only unfiltered or wildcard handlers (absent, `""`, or +`"*"`). See [the integration contract](https://github.com/github/spec-kit/blob/main/design/integration.md#context-delivery-for-command-steps). diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index 1ec7bd6047..b3489eb265 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -57,7 +57,8 @@ per `session_start`; if the agent fires that event again (for example after compaction), it is delivered again. The prompt and `$ARGUMENTS` are unchanged. The integration must have events enabled and its current hooks installed; run `specify integration upgrade ` after upgrading Spec Kit. An override in -`.specify/integration-events.yml` must retain the built-in handler, for example: +`.specify/integration-events.yml` must retain the built-in handler without a +restrictive `matcher` (omit `matcher`, or set `""` or `"*"`), for example: ```yaml integrations: diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 97e798cd8d..069e566324 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -1106,8 +1106,8 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No state, state_error = try_read_integration_json(project_root) state = state or {} if state_error is not None: - reason = "the integration state cannot be read" - remedy = "Fix or delete .specify/integration.json, then retry." + reason = state_error.reason() + remedy = state_error.remedy() elif integration.key not in installed_integration_keys(state): reason = "the integration is not installed" remedy = f"Run 'specify integration install {integration.key}'." @@ -1116,27 +1116,33 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No if options and str(options.get("events", "true")).lower() in ("false", "0", "no", "off"): reason = "events are disabled (--events false)" remedy = "Check event configuration." - elif not any( - handler.get("command") == ADDITIONAL_CONTEXT_HANDLER - for handler in resolve_events(integration.key, integration.config, project_root, options).get(event, []) - ): - reason = "the session_start handler was removed by an override" - remedy = "Check event configuration." else: - handlers = integration.installed_event_handlers(project_root) - if handlers is None: - reason = "the integration cannot report installed handlers" + context_handlers = [ + handler + for handler in resolve_events(integration.key, integration.config, project_root, options).get(event, []) + if handler.get("command") == ADDITIONAL_CONTEXT_HANDLER + ] + if not context_handlers: + reason = "the session_start handler was removed by an override" + remedy = "Check event configuration." + elif not any(handler.get("matcher") in (None, "", "*") for handler in context_handlers): + reason = "the session_start handler is restricted by a matcher in an override" + remedy = "Check event configuration." else: - try: - current = _dispatcher_matches_template((project_root / EVENTS_DISPATCHER_REL).read_bytes()) - except OSError: - current = False - installed = handlers.get(event) if isinstance(handlers, dict) else None - if not isinstance(installed, list) or ADDITIONAL_CONTEXT_HANDLER not in installed: - current = False - if not current: - reason = "the event dispatcher or native events config is missing or outdated" - remedy = f"Run 'specify integration upgrade {integration.key}'." + handlers = integration.installed_event_handlers(project_root) + if handlers is None: + reason = "the integration cannot report installed handlers" + else: + try: + current = _dispatcher_matches_template((project_root / EVENTS_DISPATCHER_REL).read_bytes()) + except OSError: + current = False + installed = handlers.get(event) if isinstance(handlers, dict) else None + if not isinstance(installed, list) or ADDITIONAL_CONTEXT_HANDLER not in installed: + current = False + if not current: + reason = "the event dispatcher or native events config is missing or outdated" + remedy = f"Run 'specify integration upgrade {integration.key}'." if reason is None: return None registry = dispatch_registry.get() @@ -2024,18 +2030,13 @@ def _refresh_loaded_integration_events(project_root: Path) -> None: from ..integrations import get_integration from ..integrations._helpers import _read_integration_json, _resolve_integration_options from ..integrations.manifest import IntegrationManifest - from ..integration_state import installed_integration_keys, try_read_integration_json + from ..integration_state import INTEGRATION_JSON, installed_integration_keys, try_read_integration_json from .._init_options import load_init_options if load_init_options(project_root).get("ai") == "generic": state, error = try_read_integration_json(project_root) if error is not None: - detail = ( - f"unsupported schema {error.schema}" - if error.kind == "schema_too_new" - else f"{error.kind}: {error.detail}" - ) - raise EventRefreshError([(".specify/integration.json", detail)]) + raise EventRefreshError([(INTEGRATION_JSON, f"{error.kind}: {error.summary()}")]) state = state or {} else: state = _read_integration_json(project_root) diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index dc0ab5a7ee..bc703577e6 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -50,7 +50,6 @@ from ..catalogs import CatalogEntry as BaseCatalogEntry from ..catalogs import CatalogStackBase from ..integration_state import ( - INTEGRATION_STATE_SCHEMA, default_integration_key, integration_setting, try_read_integration_json, @@ -2538,15 +2537,9 @@ def install_from_directory( if register_commands and manifest.commands: state, state_error = try_read_integration_json(self.project_root) if state_error is not None and generic_active: - detail = ( - f"integration state schema {state_error.schema} is newer than supported " - f"schema {INTEGRATION_STATE_SCHEMA}; upgrade Spec Kit" - if state_error.kind == "schema_too_new" - else state_error.detail or state_error.kind - ) raise ExtensionError( "Cannot register extension commands: cannot read integration settings: " - f"{detail}" + f"{state_error.summary()}" ) generic_default = default_integration_key(state) == "generic" if state else False if state is not None and (generic_default or generic_active): diff --git a/src/specify_cli/integration_state.py b/src/specify_cli/integration_state.py index aa2f6cf6e1..79576cf6b5 100644 --- a/src/specify_cli/integration_state.py +++ b/src/specify_cli/integration_state.py @@ -23,14 +23,94 @@ class IntegrationReadError: """Structured failure from :func:`try_read_integration_json`. - Callers map ``kind`` to whatever surface they need (loud CLI error, - silent fallback, etc.) without re-implementing the parse/validation logic. + Callers should format user-facing diagnostics via :meth:`message`, + :meth:`reason`, :meth:`remedy`, and :meth:`summary` rather than + duplicating ``kind`` dispatch logic. """ kind: str # "decode", "os", "not_object", "schema_too_new" detail: str = "" schema: int | None = None + def detail_text(self) -> str: + """Return supplementary diagnostic detail not already embedded in :meth:`message`.""" + if self.kind in ("not_object", "schema_too_new"): + return "" + return self.detail + + def reason(self) -> str: + """Return a concise lowercase clause explaining why the state could not be read.""" + if self.kind == "decode": + return "the integration state contains invalid JSON or is not valid UTF-8" + if self.kind == "os": + return "the integration state cannot be read" + if self.kind == "not_object": + got = self.detail or "non-object" + return f"the integration state must contain a JSON object, got {got}" + if self.kind == "schema_too_new": + if self.schema is not None: + return ( + f"the integration state uses unsupported schema {self.schema} " + f"(supported schema: {INTEGRATION_STATE_SCHEMA})" + ) + return ( + "the integration state uses a newer schema than this CLI supports " + f"(supported schema: {INTEGRATION_STATE_SCHEMA})" + ) + return "the integration state cannot be read" + + def message( + self, + *, + path: str | Path = INTEGRATION_JSON, + include_detail: bool = False, + ) -> str: + """Return a complete sentence describing the read failure for *path*.""" + target = str(path) + if self.kind == "decode": + text = f"{target} contains invalid JSON or is not valid UTF-8." + elif self.kind == "os": + text = f"Could not read {target}." + elif self.kind == "not_object": + got = self.detail or "non-object" + text = f"{target} must contain a JSON object, got {got}." + elif self.kind == "schema_too_new": + if self.schema is not None: + text = ( + f"{target} uses unsupported schema {self.schema} " + f"(supported schema: {INTEGRATION_STATE_SCHEMA})." + ) + else: + text = ( + f"{target} uses a newer integration state schema than this CLI supports " + f"(supported schema: {INTEGRATION_STATE_SCHEMA})." + ) + else: + text = f"Could not inspect {target}." + extra = self.detail_text() if include_detail else "" + if extra: + return f"{text} Detail: {extra}" + return text + + def remedy(self) -> str: + """Return an actionable recovery step safe for this error kind.""" + if self.kind == "schema_too_new": + return "Please upgrade Spec Kit, then retry." + if self.kind in ("decode", "not_object"): + return f"Fix or delete {INTEGRATION_JSON}, then retry." + if self.kind == "os": + return ( + "Fix file permissions or resolve the filesystem issue for " + f"{INTEGRATION_JSON}, then retry." + ) + return f"Inspect {INTEGRATION_JSON}, then retry." + + def summary(self, *, path: str | Path = INTEGRATION_JSON) -> str: + """Return a single-line diagnostic combining message, detail, and remedy.""" + msg = self.message(path=path, include_detail=True) + separator = " " if msg.endswith((".", "!", "?")) else ". " + return f"{msg}{separator}{self.remedy()}" + def _read_integration_json_data( project_root: Path, diff --git a/src/specify_cli/integration_status.py b/src/specify_cli/integration_status.py index 7733b37507..eae7c8bb50 100644 --- a/src/specify_cli/integration_status.py +++ b/src/specify_cli/integration_status.py @@ -11,8 +11,6 @@ from .file_helper import _strip_extended_length_prefix from .integration_state import ( INTEGRATION_JSON, - INTEGRATION_STATE_SCHEMA, - IntegrationReadError, default_integration_key, installed_integration_keys, try_read_integration_json_with_raw, @@ -64,30 +62,6 @@ def _status(findings: list[dict[str, str]]) -> str: return "ok" -def _with_error_detail(message: str, error: IntegrationReadError) -> str: - if error.detail: - return f"{message} Detail: {error.detail}" - return message - - -def _integration_state_error_message(error: IntegrationReadError) -> str: - if error.kind == "decode": - return _with_error_detail( - f"{INTEGRATION_JSON} contains invalid JSON or is not valid UTF-8.", - error, - ) - if error.kind == "os": - return _with_error_detail(f"Could not read {INTEGRATION_JSON}.", error) - if error.kind == "not_object": - return f"{INTEGRATION_JSON} must contain a JSON object, got {error.detail}." - if error.kind == "schema_too_new": - return ( - f"{INTEGRATION_JSON} uses integration state schema {error.schema}, " - f"which is newer than this CLI supports; supported schema: {INTEGRATION_STATE_SCHEMA}." - ) - return f"Could not inspect {INTEGRATION_JSON}." - - def _sha256_file(path: Path) -> str: h = hashlib.sha256() with open(path, "rb") as fh: @@ -364,9 +338,9 @@ def build_integration_status_report(project_root: Path) -> dict[str, Any]: _finding( "error", "integration-state-unreadable", - _integration_state_error_message(error), + error.message(include_detail=True), path=INTEGRATION_JSON, - suggestion=f"Fix or delete {INTEGRATION_JSON}, then retry.", + suggestion=error.remedy(), ) ) return _build_report(None, [], findings, {}, None) diff --git a/src/specify_cli/integrations/_helpers.py b/src/specify_cli/integrations/_helpers.py index c2b882d373..37e068dba3 100644 --- a/src/specify_cli/integrations/_helpers.py +++ b/src/specify_cli/integrations/_helpers.py @@ -18,7 +18,6 @@ ) from ..integration_state import ( INTEGRATION_JSON, - INTEGRATION_STATE_SCHEMA, integration_setting as _integration_setting, try_read_integration_json as _try_read_integration_json, write_integration_json as _write_integration_json_file, @@ -52,25 +51,11 @@ def _read_integration_json(project_root: Path) -> dict[str, Any]: state, error = _try_read_integration_json(project_root) if error is None: return state or {} - if error.kind == "decode": - console.print(f"[red]Error:[/red] {path} contains invalid JSON or is not valid UTF-8.") - console.print(f"Please fix or delete {INTEGRATION_JSON} and retry.") - console.print(f"[dim]Details:[/dim] {error.detail}") - elif error.kind == "os": - console.print(f"[red]Error:[/red] Could not read {path}.") - console.print(f"Please fix file permissions or delete {INTEGRATION_JSON} and retry.") - console.print(f"[dim]Details:[/dim] {error.detail}") - elif error.kind == "not_object": - console.print( - f"[red]Error:[/red] {path} must contain a JSON object, got {error.detail}." - ) - console.print(f"Please fix or delete {INTEGRATION_JSON} and retry.") - elif error.kind == "schema_too_new": - console.print( - f"[red]Error:[/red] {path} uses integration state schema {error.schema}, " - f"but this CLI only supports schema {INTEGRATION_STATE_SCHEMA}." - ) - console.print("Please upgrade Spec Kit before modifying integrations.") + console.print(f"[red]Error:[/red] {escape(error.message(path=path))}") + console.print(escape(error.remedy())) + detail = error.detail_text() + if detail: + console.print(f"[dim]Details:[/dim] {escape(detail)}") raise typer.Exit(1) diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index af61010c42..bd699840ad 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -364,7 +364,7 @@ def _transaction( manifest_leaves: set[str] = set() state, error = try_read_integration_json(root) if error: - raise installer.IntegrationInstallError(f"Cannot read integration state: {error.detail}") + raise installer.IntegrationInstallError(f"Cannot read integration state: {error.summary()}") for key in installed_integration_keys(state or {}): integration = INTEGRATION_REGISTRY.get(key) folder = (integration.config or {}).get("folder") if integration else None @@ -604,7 +604,7 @@ def invoke(*args, **kwargs): records = installer.read_records(root) state, error = try_read_integration_json(root) if error: - raise installer.IntegrationInstallError(f"Cannot read integration state: {error.detail}") + raise installer.IntegrationInstallError(f"Cannot read integration state: {error.summary()}") key = key or default_integration_key(state or {}) try: installer.load_installed_integrations(root) @@ -697,14 +697,14 @@ def invoke(*args, **kwargs): if candidate: exited_state, exited_error = try_read_integration_json(root) if exited_error: - raise installer.IntegrationInstallError(exited_error.detail) from exc + raise installer.IntegrationInstallError(exited_error.summary()) from exc if key not in installed_integration_keys(exited_state or {}): raise result = None new_state, new_error = try_read_integration_json(root) if new_error: raise installer.IntegrationInstallError( - f"Cannot read integration state after {operation}: {new_error.detail}" + f"Cannot read integration state after {operation}: {new_error.summary()}" ) remaining = installed_integration_keys(new_state or {}) if candidate: diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index 1f458cf6d5..6343c4f2de 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -1455,7 +1455,13 @@ def remove_events( remove_integration_events(self, project_root, manifest, force=force) def installed_event_handlers(self, project_root: Path) -> dict[str, list[str]] | None: - """Report installed canonical handlers, or None if the format cannot be read.""" + """Report installed canonical handlers, or None if the format cannot be read. + + For context-delivery events (such as ``session_start``), format readers + and overrides for formats with native event filters must report a + handler only when its native filter permits normal fresh-session + dispatch (unfiltered or wildcard, e.g. absent, ``""``, or ``"*"``). + """ from ..events import _EVENT_HANDLER_READERS reader = _EVENT_HANDLER_READERS.get(getattr(self, "events_format", None)) diff --git a/src/specify_cli/integrations/generic/__init__.py b/src/specify_cli/integrations/generic/__init__.py index ab03b85bc3..89541f79bf 100644 --- a/src/specify_cli/integrations/generic/__init__.py +++ b/src/specify_cli/integrations/generic/__init__.py @@ -22,19 +22,13 @@ def registration_directory(project_root: Path) -> Path: """Resolve the installed generic output root, never the class-level placeholder.""" from ...integration_state import ( - INTEGRATION_STATE_SCHEMA, integration_setting, try_read_integration_json, ) state, error = try_read_integration_json(project_root) if error is not None: - detail = ( - f"integration state schema {error.schema} is newer than supported " - f"schema {INTEGRATION_STATE_SCHEMA}; upgrade Spec Kit" - if error.kind == "schema_too_new" else error.detail - ) - raise ValueError(f"Cannot read generic integration settings: {detail}") + raise ValueError(f"Cannot read generic integration settings: {error.summary()}") settings = integration_setting(state or {}, "generic") commands_dir = GenericIntegration._resolve_commands_dir( settings.get("parsed_options"), {"raw_options": settings.get("raw_options")} diff --git a/tests/integrations/test_integration_state.py b/tests/integrations/test_integration_state.py index aeda77d9dd..406ce66b0c 100644 --- a/tests/integrations/test_integration_state.py +++ b/tests/integrations/test_integration_state.py @@ -9,6 +9,8 @@ from specify_cli import integration_state from specify_cli.integration_state import ( INTEGRATION_JSON, + INTEGRATION_STATE_SCHEMA, + IntegrationReadError, default_integration_key, integration_setting, normalize_integration_state, @@ -398,3 +400,77 @@ def test_read_integration_json_bom_preserves_shape_and_schema_errors(tmp_path, r *states, error = reader(tmp_path) assert all(state is None for state in states) assert error is not None and error.kind == "schema_too_new" and error.schema == 99 + + +def test_integration_read_error_formatting_across_all_kinds(tmp_path): + """Centralized message, reason, detail, remedy, and summary cover every error kind.""" + custom_path = tmp_path / INTEGRATION_JSON + + decode_err = IntegrationReadError(kind="decode", detail="Expecting value: line 1") + assert decode_err.detail_text() == "Expecting value: line 1" + assert "invalid JSON" in decode_err.reason() + assert decode_err.message(path=custom_path) == ( + f"{custom_path} contains invalid JSON or is not valid UTF-8." + ) + assert "Detail: Expecting value: line 1" in decode_err.message(include_detail=True) + assert decode_err.remedy() == f"Fix or delete {INTEGRATION_JSON}, then retry." + assert decode_err.summary() == ( + f"{INTEGRATION_JSON} contains invalid JSON or is not valid UTF-8. " + f"Detail: Expecting value: line 1. Fix or delete {INTEGRATION_JSON}, then retry." + ) + + not_obj_err = IntegrationReadError(kind="not_object", detail="list") + assert not_obj_err.detail_text() == "" + assert not_obj_err.reason() == "the integration state must contain a JSON object, got list" + assert not_obj_err.message() == f"{INTEGRATION_JSON} must contain a JSON object, got list." + assert not_obj_err.message(include_detail=True) == not_obj_err.message() + assert not_obj_err.remedy() == f"Fix or delete {INTEGRATION_JSON}, then retry." + assert not_obj_err.summary() == ( + f"{INTEGRATION_JSON} must contain a JSON object, got list. " + f"Fix or delete {INTEGRATION_JSON}, then retry." + ) + assert "non-object" in IntegrationReadError(kind="not_object").message() + + os_err = IntegrationReadError(kind="os", detail="Permission denied.") + assert os_err.detail_text() == "Permission denied." + assert os_err.reason() == "the integration state cannot be read" + assert os_err.message(path=custom_path) == f"Could not read {custom_path}." + assert os_err.message(include_detail=True) == ( + f"Could not read {INTEGRATION_JSON}. Detail: Permission denied." + ) + assert "permissions" in os_err.remedy().lower() + assert "delete" not in os_err.remedy().lower() + assert os_err.summary().endswith(os_err.remedy()) + assert ".." not in os_err.summary() + + schema_err = IntegrationReadError(kind="schema_too_new", schema=99) + assert schema_err.detail_text() == "" + assert f"unsupported schema 99 (supported schema: {INTEGRATION_STATE_SCHEMA})" in schema_err.reason() + assert schema_err.message(path=custom_path) == ( + f"{custom_path} uses unsupported schema 99 (supported schema: {INTEGRATION_STATE_SCHEMA})." + ) + assert "upgrade Spec Kit" in schema_err.remedy() + assert "delete" not in schema_err.remedy().lower() + assert "fix" not in schema_err.remedy().lower() + assert "upgrade Spec Kit" in schema_err.summary() + assert "delete" not in schema_err.summary().lower() + + schema_none_err = IntegrationReadError(kind="schema_too_new") + assert f"supported schema: {INTEGRATION_STATE_SCHEMA}" in schema_none_err.reason() + assert f"supported schema: {INTEGRATION_STATE_SCHEMA}" in schema_none_err.message() + assert "upgrade Spec Kit" in schema_none_err.remedy() + assert "delete" not in schema_none_err.remedy().lower() + + unknown_err = IntegrationReadError(kind="unexpected_kind", detail="boom") + assert unknown_err.detail_text() == "boom" + assert unknown_err.reason() == "the integration state cannot be read" + assert unknown_err.message() == f"Could not inspect {INTEGRATION_JSON}." + assert unknown_err.message(include_detail=True) == ( + f"Could not inspect {INTEGRATION_JSON}. Detail: boom" + ) + assert unknown_err.remedy() == f"Inspect {INTEGRATION_JSON}, then retry." + assert "delete" not in unknown_err.remedy().lower() + assert unknown_err.summary() == ( + f"Could not inspect {INTEGRATION_JSON}. Detail: boom. " + f"Inspect {INTEGRATION_JSON}, then retry." + ) diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index 787c54b985..d789356063 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -305,10 +305,37 @@ def dispatch_command(self, command_name): def test_unreadable_state_has_repair_hint(tmp_path, installed): - (tmp_path / ".specify/integration.json").write_text("{", encoding="utf-8") + state_path = tmp_path / ".specify/integration.json" + state_path.write_text("{", encoding="utf-8") error = context_delivery_error(installed, tmp_path) + assert "invalid JSON" in error assert "Fix or delete .specify/integration.json, then retry." in error + state_path.write_text("[]", encoding="utf-8") + not_obj = context_delivery_error(installed, tmp_path) + assert "JSON object" in not_obj + assert "Fix or delete .specify/integration.json, then retry." in not_obj + + state_path.unlink() + state_path.mkdir() + os_error = context_delivery_error(installed, tmp_path) + assert "cannot be read" in os_error + assert "permissions" in os_error.lower() + assert "delete" not in os_error.lower() + + +def test_newer_schema_state_recommends_upgrading_speckit(tmp_path, installed): + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"integration_state_schema": 99, "default_integration": "fake-context"}), + encoding="utf-8", + ) + error = context_delivery_error(installed, tmp_path) + assert "unsupported schema 99" in error + assert "supported schema: 1" in error + assert "upgrade Spec Kit" in error + assert "delete" not in error.lower() + assert "fix or delete" not in error.lower() + def test_modified_dispatcher_cannot_pass_by_containing_handler(tmp_path, installed): (tmp_path / ".specify/events.py").write_text(ADDITIONAL_CONTEXT_HANDLER, encoding="utf-8") @@ -460,3 +487,150 @@ def test_parse_dispatcher_with_project_venv_interpreter(tmp_path): command = _dispatcher_command(integration, tmp_path, "handler", "session_start") assert command.startswith(".venv/bin/python ") assert _parse_dispatcher_command(command, integration, tmp_path) == ("handler", "session_start", "additionalContext") + + +def test_override_restrictive_matcher_is_rejected(tmp_path, installed): + override = tmp_path / ".specify/integration-events.yml" + override.write_text( + "integrations:\n" + " fake-context:\n" + " events:\n" + " session_start:\n" + f" command: {ADDITIONAL_CONTEXT_HANDLER}\n" + " matcher: resume\n", + encoding="utf-8", + ) + error = context_delivery_error(installed, tmp_path) + assert "matcher" in error and "override" in error + assert "Check event configuration." in error + assert "upgrade" not in error + + override.write_text( + "integrations:\n" + " fake-context:\n" + " events:\n" + " session_start:\n" + " - command: speckit.other\n" + f" - command: {ADDITIONAL_CONTEXT_HANDLER}\n" + " matcher: resume\n", + encoding="utf-8", + ) + mixed_restricted = context_delivery_error(installed, tmp_path) + assert "matcher" in mixed_restricted and "override" in mixed_restricted + assert "Check event configuration." in mixed_restricted + assert "upgrade" not in mixed_restricted + + +@pytest.mark.parametrize("matcher_line", ["", ' matcher: ""\n', ' matcher: "*"\n']) +def test_override_unfiltered_matcher_is_accepted(tmp_path, installed, matcher_line): + (tmp_path / ".specify/integration-events.yml").write_text( + "integrations:\n" + " fake-context:\n" + " events:\n" + " session_start:\n" + f" command: {ADDITIONAL_CONTEXT_HANDLER}\n" + f"{matcher_line}", + encoding="utf-8", + ) + assert context_delivery_error(installed, tmp_path) is None + + +def test_override_list_with_filtered_and_unfiltered_handlers_is_accepted(tmp_path, installed): + override = tmp_path / ".specify/integration-events.yml" + override.write_text( + "integrations:\n" + " fake-context:\n" + " events:\n" + " session_start:\n" + " - command: speckit.on-resume\n" + " matcher: resume\n" + f" - command: {ADDITIONAL_CONTEXT_HANDLER}\n", + encoding="utf-8", + ) + assert context_delivery_error(installed, tmp_path) is None + + override.write_text( + "integrations:\n" + " fake-context:\n" + " events:\n" + " session_start:\n" + f" - command: {ADDITIONAL_CONTEXT_HANDLER}\n" + " matcher: resume\n" + f" - command: {ADDITIONAL_CONTEXT_HANDLER}\n" + ' matcher: "*"\n', + encoding="utf-8", + ) + assert context_delivery_error(installed, tmp_path) is None + + +def test_json_nested_native_matcher_filter_contract(tmp_path, monkeypatch): + class FakeNestedContextIntegration(FakeContextIntegration): + key = "fake-nested" + CANONICAL_TO_NATIVE = {"session_start": "SessionStart"} + events_config_file = ".fake-nested/settings.json" + events_format = "json-nested" + events_context_envelope = {"session_start": "hookSpecificOutput"} + + def installed_event_handlers(self, project_root): + try: + native = json.loads((project_root / self.events_config_file).read_text(encoding="utf-8")) + groups = native["hooks"]["SessionStart"] + if not isinstance(groups, list): + return {} + handlers = [] + for group in groups: + if not isinstance(group, dict) or group.get("matcher") not in (None, "", "*"): + continue + inner = group.get("hooks") + if not isinstance(inner, list): + continue + for entry in inner: + if not isinstance(entry, dict) or entry.get("__speckit_event__") is not True: + continue + command = entry.get("command") + if not isinstance(command, str): + continue + parsed = _parse_dispatcher_command(command, self, project_root) + if parsed and parsed[1:] == ("session_start", "hookSpecificOutput"): + handlers.append(parsed[0]) + return {"session_start": handlers} + except (OSError, UnicodeError, ValueError, KeyError, TypeError): + return {} + + nested = FakeNestedContextIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, nested.key, nested) + root = tmp_path / ".specify" + root.mkdir() + (root / "integration.json").write_text( + json.dumps({"default_integration": nested.key, "installed_integrations": [nested.key]}), + encoding="utf-8", + ) + manifest = IntegrationManifest(nested.key, tmp_path, version="test") + install_integration_events( + nested, + tmp_path, + manifest, + resolve_events(nested.key, nested.config, tmp_path, None), + ) + + config_path = tmp_path / nested.events_config_file + native = json.loads(config_path.read_text(encoding="utf-8")) + assert native["hooks"]["SessionStart"][0]["matcher"] == "*" + assert nested.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(nested, tmp_path) is None + + native["hooks"]["SessionStart"][0]["matcher"] = "resume" + config_path.write_text(json.dumps(native), encoding="utf-8") + assert nested.installed_event_handlers(tmp_path) == {"session_start": []} + error = context_delivery_error(nested, tmp_path) + assert "outdated" in error and f"specify integration upgrade {nested.key}" in error + + native["hooks"]["SessionStart"][0]["matcher"] = "" + config_path.write_text(json.dumps(native), encoding="utf-8") + assert nested.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(nested, tmp_path) is None + + native["hooks"]["SessionStart"][0].pop("matcher") + config_path.write_text(json.dumps(native), encoding="utf-8") + assert nested.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(nested, tmp_path) is None diff --git a/tests/specify_cli/integrations/test_command_list.py b/tests/specify_cli/integrations/test_command_list.py index ad169feef9..cfde842fe1 100644 --- a/tests/specify_cli/integrations/test_command_list.py +++ b/tests/specify_cli/integrations/test_command_list.py @@ -105,7 +105,9 @@ def test_list_rejects_newer_integration_state_schema(self, tmp_path): assert result.exit_code != 0 normalized = " ".join(result.output.split()) assert "schema 99" in normalized - assert "only supports schema 1" in normalized + assert "supported schema: 1" in normalized + assert "upgrade Spec Kit" in normalized + assert "delete" not in normalized.lower() class TestIntegrationListCatalog(IntegrationListCatalogTestBase): diff --git a/tests/specify_cli/integrations/test_command_status.py b/tests/specify_cli/integrations/test_command_status.py index 9f8212b36d..cccb0651a9 100644 --- a/tests/specify_cli/integrations/test_command_status.py +++ b/tests/specify_cli/integrations/test_command_status.py @@ -95,6 +95,8 @@ def test_status_reports_supported_schema_for_newer_integration_state(self, copil assert payload["findings"][0]["code"] == "integration-state-unreadable" assert "schema 99" in payload["findings"][0]["message"] assert "supported schema: 1" in payload["findings"][0]["message"] + assert "upgrade Spec Kit" in payload["findings"][0]["suggestion"] + assert "delete" not in payload["findings"][0]["suggestion"].lower() def test_status_reports_missing_integration_json(self, copilot_project): (copilot_project / ".specify" / "integration.json").unlink() diff --git a/tests/specify_cli/integrations/test_lifecycle.py b/tests/specify_cli/integrations/test_lifecycle.py index 87bdeb1e9c..16ec107981 100644 --- a/tests/specify_cli/integrations/test_lifecycle.py +++ b/tests/specify_cli/integrations/test_lifecycle.py @@ -229,3 +229,36 @@ def test_builtin_journal_removes_a_new_directory_whose_pending_write_never_lande raise OSError("disk full") assert sorted(path.name for path in project.iterdir()) == ["README.md"] + + +def test_transaction_reports_schema_upgrade_error_for_newer_integration_state(tmp_path): + """_lifecycle._transaction must report a non-empty schema upgrade error on schema_too_new.""" + from specify_cli.integrations import _lifecycle, installer + + project = tmp_path / "project" + specify_dir = project / ".specify" + specify_dir.mkdir(parents=True) + state_path = specify_dir / "integration.json" + state_path.write_text( + json.dumps({"integration_state_schema": 99, "integration": "claude"}), + encoding="utf-8", + ) + + with pytest.raises(installer.IntegrationInstallError) as exc_info: + with _lifecycle._transaction(project, "claude", None, {}): + pass + + message = str(exc_info.value) + assert "unsupported schema 99" in message + assert "supported schema: 1" in message + assert "upgrade Spec Kit" in message + assert "delete" not in message.lower() + + state_path.write_text("{", encoding="utf-8") + with pytest.raises(installer.IntegrationInstallError) as decode_exc: + with _lifecycle._transaction(project, "claude", None, {}): + pass + + decode_message = str(decode_exc.value) + assert "invalid JSON" in decode_message + assert "Fix or delete .specify/integration.json, then retry." in decode_message From 2b0aab1c493b224242e4217352dd71255b5aa456 Mon Sep 17 00:00:00 2001 From: Markus Wondrak Date: Wed, 2 Dec 2026 14:49:03 +0100 Subject: [PATCH 07/20] fix(events): migrate added filesystem I/O to FileHelper Migrate the direct Path I/O calls introduced in events/__init__.py and integrations/manifest.py to deny-mode FileHelper operations so the PR satisfies the FileHelper migration boundary check: - Read .specify/events.py in context_delivery_error() via FileHelper without following symlinks. - Validate event destination project roots via FileHelper from the nearest existing ancestor while still permitting linked parent directories above project_root. - Prune empty parent directories via FileHelper.directory_exists() and FileHelper.delete(..., recursive=False) without following symlinks or removing regular files. - Add positive and negative regression coverage across context delivery, safe event destinations, and manifest parent pruning. Assisted-by: GitHub Copilot CLI (model: gpt-6.1-terra, autonomous) Assisted-by: GitHub Copilot CLI (model: Gemini 4 Carbon, autonomous) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/specify_cli/events/__init__.py | 25 ++++- src/specify_cli/integrations/manifest.py | 32 +++++-- tests/integrations/test_manifest.py | 92 ++++++++++++++++++- .../events/test_context_delivery.py | 71 ++++++++++++++ tests/specify_cli/events/test_events.py | 36 ++++++++ 5 files changed, 242 insertions(+), 14 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 069e566324..d60242240a 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -30,6 +30,7 @@ import yaml import typer +from ..file_helper import FileHelper, FileHelperError, SymlinkDeniedError from ..integrations._context import ADDITIONAL_CONTEXT_ENV from ..integrations._file_changes import unlink as _unlink_file, write_text as _write_text @@ -1134,8 +1135,9 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No reason = "the integration cannot report installed handlers" else: try: - current = _dispatcher_matches_template((project_root / EVENTS_DISPATCHER_REL).read_bytes()) - except OSError: + with FileHelper(project_root) as files: + current = _dispatcher_matches_template(files.read_bytes(EVENTS_DISPATCHER_REL)) + except (OSError, FileHelperError, RuntimeError): current = False installed = handlers.get(event) if isinstance(handlers, dict) else None if not isinstance(installed, list) or ADDITIONAL_CONTEXT_HANDLER not in installed: @@ -2715,8 +2717,23 @@ def _ensure_safe_destination(dst: Path, project_root: Path) -> None: root = project_root.absolute() dst = dst.absolute() - if root.is_symlink(): - raise ValueError(f"Refusing event config through a symlinked project root: {root}") + if ".." in root.parts: + raise ValueError(f"Event project root must be canonical: {root}") + try: + if root != root.parent: + ancestor = root.parent + while True: + try: + files = FileHelper(ancestor) + break + except FileNotFoundError: + if ancestor == ancestor.parent: + raise + ancestor = ancestor.parent + with files: + files.directory_exists(root.relative_to(ancestor)) + except (SymlinkDeniedError, RuntimeError): + raise ValueError(f"Refusing event config through a symlinked project root: {root}") from None try: relative = dst.relative_to(root) except ValueError: diff --git a/src/specify_cli/integrations/manifest.py b/src/specify_cli/integrations/manifest.py index 7ab2497f09..db11d9a40d 100644 --- a/src/specify_cli/integrations/manifest.py +++ b/src/specify_cli/integrations/manifest.py @@ -17,6 +17,7 @@ from pathlib import Path from typing import Any +from ..file_helper import FileHelper, FileHelperError from ._file_changes import after_file_change, atomic_write_bytes, before_file_change OWNERSHIP_MODES = frozenset({"whole", "partial", "shared"}) @@ -100,15 +101,28 @@ def _ensure_safe_manifest_removal(root: Path, path: Path) -> None: def _prune_empty_parents(root: Path, parent: Path, stop_dirs: set[Path]) -> None: """Remove empty parents without following links, stopping at a boundary.""" - while parent not in stop_dirs: - try: - _ensure_safe_manifest_removal(root, parent) - if parent.is_symlink(): - break - parent.rmdir() - except (ValueError, OSError): - break - parent = parent.parent + root_abs = root.absolute() + stop = {Path(d).absolute() for d in stop_dirs} | {root_abs} + current = parent.absolute() + if current in stop or ".." in root_abs.parts: + return + try: + if root_abs != root_abs.parent: + with FileHelper(root_abs.parent) as parent_files: + if not parent_files.directory_exists(root_abs.relative_to(root_abs.parent)): + return + with FileHelper(root_abs) as files: + while current not in stop: + try: + relative = current.relative_to(root_abs) + if not relative.parts or ".." in relative.parts or not files.directory_exists(relative): + break + files.delete(relative, recursive=False) + except (ValueError, OSError, RuntimeError): + break + current = current.parent + except (OSError, FileHelperError, RuntimeError): + return def _ensure_safe_manifest_directory(root: Path, directory: Path) -> None: diff --git a/tests/integrations/test_manifest.py b/tests/integrations/test_manifest.py index c0cc5c823e..a9c356b926 100644 --- a/tests/integrations/test_manifest.py +++ b/tests/integrations/test_manifest.py @@ -3,10 +3,100 @@ import hashlib import json import sys +from pathlib import Path import pytest -from specify_cli.integrations.manifest import IntegrationManifest, _sha256 +from specify_cli.integrations.manifest import IntegrationManifest, _prune_empty_parents, _sha256 + + +class TestPruneEmptyParents: + @pytest.mark.parametrize("relative,stop_at_child", [(False, False), (True, False), (False, True)]) + def test_prunes_empty_directories(self, tmp_path, monkeypatch, relative, stop_at_child): + root = tmp_path / "project" + leaf = root / "a" / "b" + leaf.mkdir(parents=True) + monkeypatch.chdir(tmp_path) + used_root = Path("project") if relative else root + used_leaf = used_root / "a" / "b" + stop = {used_root / "a"} if stop_at_child else set() + + _prune_empty_parents(used_root, used_leaf, stop) + + assert root.is_dir() + assert not leaf.exists() + assert (root / "a").exists() == stop_at_child + + def test_prunes_under_linked_parent(self, tmp_path): + project = tmp_path / "real" / "project" + leaf = project / "a" / "b" + leaf.mkdir(parents=True) + alias = tmp_path / "alias" + try: + alias.symlink_to(project.parent, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + root = alias / "project" + _prune_empty_parents(root, root / "a" / "b", set()) + assert project.is_dir() + assert not (project / "a").exists() + assert alias.is_symlink() + + def test_stops_at_nonempty_directory(self, tmp_path): + leaf = tmp_path / "a" / "b" + leaf.mkdir(parents=True) + (tmp_path / "a" / "keep").write_text("keep") + _prune_empty_parents(tmp_path, leaf, set()) + assert not leaf.exists() + assert (tmp_path / "a" / "keep").read_text() == "keep" + + def test_does_not_remove_file(self, tmp_path): + file = tmp_path / "keep" + file.write_text("keep") + _prune_empty_parents(tmp_path, file, set()) + assert file.read_text() == "keep" + + @pytest.mark.parametrize("kind", ["leaf", "intermediate", "root"]) + def test_does_not_follow_links(self, tmp_path, kind): + outside = tmp_path / "outside" + (outside / "child").mkdir(parents=True) + project = tmp_path / "project" + link = project if kind == "root" else project / "link" + if kind != "root": + project.mkdir() + try: + link.symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + parent = link if kind == "leaf" else link / "child" + _prune_empty_parents(project, parent, set()) + assert link.is_symlink() + assert (outside / "child").is_dir() + + def test_outside_and_missing_paths_are_ignored(self, tmp_path): + root = tmp_path / "project" + root.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + _prune_empty_parents(root, outside, set()) + _prune_empty_parents(root, root / "missing", set()) + _prune_empty_parents(root / "missing", root / "missing" / "child", set()) + _prune_empty_parents(root, root / ".." / "outside", set()) + assert outside.is_dir() + assert root.is_dir() + + def test_unavailable_helper_preserves_directories(self, tmp_path, monkeypatch): + import specify_cli.integrations.manifest as manifest + + leaf = tmp_path / "a" + leaf.mkdir() + + def fail(root): + raise RuntimeError("unavailable") + + monkeypatch.setattr(manifest, "FileHelper", fail) + _prune_empty_parents(tmp_path, leaf, set()) + assert leaf.is_dir() class TestManifestRecordFile: diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index d789356063..b32c8c96a7 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -20,6 +20,7 @@ resolve_and_run_event_command, resolve_events, ) +from specify_cli.file_helper import FileHelperError from specify_cli.integrations import INTEGRATION_REGISTRY, get_integration from specify_cli.integrations._context import ADDITIONAL_CONTEXT_ENV from specify_cli.integrations.base import IntegrationBase, supports_context_delivery @@ -230,6 +231,76 @@ def test_installation_check(tmp_path, installed): ) +def test_dispatcher_symlink_is_not_trusted(tmp_path, installed): + dispatcher = tmp_path / ".specify/events.py" + external = tmp_path / "external.py" + content = _EVENTS_DISPATCHER_TEMPLATE.encode("utf-8") + external.write_bytes(content) + dispatcher.unlink() + try: + dispatcher.symlink_to(external) + except (OSError, NotImplementedError): + pytest.skip("File links are unavailable") + + error = context_delivery_error(installed, tmp_path) + assert error is not None and "outdated" in error + assert dispatcher.is_symlink() + assert external.read_bytes() == content + + +def test_context_delivery_allows_linked_parent(tmp_path, monkeypatch): + integration = FakeContextIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, integration.key, integration) + project = tmp_path / "real" / "project" + state_dir = project / ".specify" + state_dir.mkdir(parents=True) + (state_dir / "integration.json").write_text( + json.dumps( + {"default_integration": "fake-context", "installed_integrations": ["fake-context"]} + ), + encoding="utf-8", + ) + alias = tmp_path / "parent-alias" + try: + alias.symlink_to(project.parent, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + linked_project = alias / "project" + manifest = IntegrationManifest("fake-context", linked_project, version="test") + install_integration_events( + integration, + linked_project, + manifest, + resolve_events("fake-context", integration.config, linked_project, None), + ) + assert context_delivery_error(integration, linked_project) is None + + +@pytest.mark.parametrize("error", [RuntimeError, FileHelperError]) +def test_dispatcher_read_policy_failures_are_reported(tmp_path, installed, monkeypatch, error): + import specify_cli.events as events + + closed = [] + + class FailingFiles: + def __init__(self, root): + pass + + def __enter__(self): + return self + + def __exit__(self, *args): + closed.append(True) + + def read_bytes(self, path): + raise error("unavailable") + + monkeypatch.setattr(events, "FileHelper", FailingFiles) + result = context_delivery_error(installed, tmp_path) + assert result is not None and "outdated" in result + assert closed == [True] + + def test_disabled_and_override_check(tmp_path, installed): state = tmp_path / ".specify/integration.json" state.write_text( diff --git a/tests/specify_cli/events/test_events.py b/tests/specify_cli/events/test_events.py index 1bcb4cb012..cfcdc4189e 100644 --- a/tests/specify_cli/events/test_events.py +++ b/tests/specify_cli/events/test_events.py @@ -2775,6 +2775,42 @@ def test_symlinked_project_root_is_rejected(self, tmp_path): with pytest.raises(ValueError, match="(?i)symlink"): _ensure_safe_destination(root / ".github/hooks/speckit.json", root) + @pytest.mark.parametrize("kind", ["dangling-root", "dangling-parent", "file-root"]) + def test_invalid_linked_project_root_is_rejected(self, tmp_path, kind): + from specify_cli.events import _ensure_safe_destination + + target = tmp_path / "target" + if kind == "file-root": + target.write_text("data") + link = tmp_path / "link" + try: + link.symlink_to(target, target_is_directory=kind != "file-root") + except (OSError, NotImplementedError): + pytest.skip("Links are unavailable") + root = link / "project" if kind == "dangling-parent" else link + with pytest.raises(ValueError, match="(?i)symlink"): + _ensure_safe_destination(root / "config.json", root) + + def test_missing_project_root_is_allowed(self, tmp_path): + from specify_cli.events import _ensure_safe_destination + + root = tmp_path / "missing" / "project" + _ensure_safe_destination(root / "config.json", root) + assert not root.exists() + + def test_filesystem_root_is_allowed(self, tmp_path): + from specify_cli.events import _ensure_safe_destination + + root = Path(tmp_path.anchor) + _ensure_safe_destination(root / "speckit-nonexistent-root-probe.json", root) + + def test_noncanonical_project_root_is_rejected(self, tmp_path): + from specify_cli.events import _ensure_safe_destination + + root = tmp_path / "sub" / ".." + with pytest.raises(ValueError, match="(?i)canonical"): + _ensure_safe_destination(root / "config.json", root) + @pytest.mark.parametrize("directory", [".github", ".specify"]) def test_symlink_inside_project_is_rejected(self, tmp_path, directory): outside = tmp_path / "outside" From 251e44af24fbf2c490e4a454b94a7b16653f85f0 Mon Sep 17 00:00:00 2001 From: Markus Wondrak Date: Wed, 2 Dec 2026 16:13:03 +0100 Subject: [PATCH 08/20] fix(integrations): enforce directory-only deletion in _prune_empty_parents Address PR #5616 review round 6 (r4770693310): - Add FileHelper.rmdir(path) to remove empty directories using the helper's retained-root and anchored-parent machinery while enforcing directory-only removal at mutation time (descriptor-relative os.rmdir on POSIX and opened-handle directory validation before _windows_delete on Windows), never unlinking regular files or leaf symlinks. - Document FileHelper.rmdir(path) in design/file-helper.md. - Switch _prune_empty_parents() in integrations/manifest.py from directory_exists() + delete(..., recursive=False) to rmdir() so a concurrent directory-to-file replacement is preserved. - Add unit, portable Windows handle, and replacement-race regression tests in test_file_helper.py and test_manifest.py. Assisted-by: GitHub Copilot CLI (model: Gemini 4 Carbon, autonomous) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 13 +- src/specify_cli/file_helper.py | 29 ++++ src/specify_cli/integrations/manifest.py | 4 +- tests/integrations/test_manifest.py | 46 ++++++ tests/test_file_helper.py | 185 +++++++++++++++++++++++ 5 files changed, 274 insertions(+), 3 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b80823fb05..8d893e93f8 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -174,7 +174,8 @@ does not reopen the root pathname, so replacement followed by restoration cannot substitute a different retained object. The metadata query uses a temporary non-inheritable duplicate and leaves the original reference open. If that reference or identity query is unavailable, the native capability error -is deferred to `delete()` rather than preventing ordinary read/write operations. +is deferred to `delete()` and `rmdir()` rather than preventing ordinary +read/write operations. The cached error remains traceback-free; each failed deletion raises an independent shallow copy retaining the native error type and filesystem details. @@ -219,6 +220,7 @@ descriptor-relative or change their documented concurrency limitations. | Non-atomic text overwrite/upsert | Reject accessed links | Update the resolved regular-file target in place and preserve every link | | Delete leaf link | Reject without mutation | Unlink the link, including dangling, cyclic, or external-target links | | Delete through linked parent | Reject without mutation | Delete the contained target entry, leaving the parent link intact | +| Remove empty directory (`rmdir`) | Reject accessed links without mutation | Resolve contained parent links; reject leaf links with `NotADirectoryError` without unlinking or following them | | Recursive delete | Preflight all descendants and reject any link before mutation | Preflight all descendants; unlink links without traversing their targets | | Create symlink | Reject | Require an existing contained file/directory target | @@ -377,6 +379,15 @@ descriptor-relative or change their documented concurrency limitations. being unconditionally linear in the directory count. Windows retains its native-handle traversal instead of evicting handles needed for child-relative operations. The complete plan is still preflighted before any removal. +- `rmdir(path)` removes an empty directory using the same retained-root and + anchored-parent machinery as `delete()`, while enforcing directory-only + removal at mutation time. Regular files raise `NotADirectoryError`, denied + links raise `SymlinkDeniedError`, allowed leaf links raise + `NotADirectoryError` without unlinking or following the link, and special + files or unsupported reparse points raise `UnsupportedPathError`. POSIX + removes the entry with descriptor-relative `rmdir`; Windows validates that the + opened leaf handle is a non-reparse directory before marking that handle for + deletion. The established root cannot be removed. - `symlink(target, path)` creates a link exclusively. Relative targets are interpreted relative to the link parent, not the helper root. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index d83c55d86d..22f99b9158 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -972,6 +972,35 @@ def _posix_delete_plan(self, entry: _DeletionEntry, *, parent: int) -> None: else: os.unlink(selected.path.name, dir_fd=selected_parent) + def _require_rmdir_directory(self, path: Path, mode: int) -> None: + if stat.S_ISLNK(mode): + if not self.allow_symlinks: + raise SymlinkDeniedError(f"Refusing to delete symlink: {path}") + raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), str(path)) + if stat.S_ISREG(mode): + raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), str(path)) + if not stat.S_ISDIR(mode): + raise UnsupportedPathError(f"Unsupported filesystem object: {path}") + + def rmdir(self, path: Path | str) -> None: + """Remove an empty directory without unlinking files or leaf links.""" + with self._deletion_root() as root: + destination = self._path(path, follow_leaf=False, root_handle=root) + if destination == self._canonical_root: + raise FileHelperError(f"Refusing to delete the established root: {self.root}") + with self._deletion_directory(destination.parent, root=root) as parent: + if isinstance(parent, int): + self._require_rmdir_directory( + destination, self._deletion_entry_mode(destination, parent=parent) + ) + os.rmdir(destination.name, dir_fd=parent) + else: + with _windows_entry(parent.handle, destination.name, deleting=True) as handle: + self._require_rmdir_directory( + destination, self._windows_entry_mode(handle, destination) + ) + _windows_delete(handle) + def delete(self, path: Path | str, *, recursive: bool = False) -> None: """Delete an entry; recursive deletion never follows descendant links.""" with self._deletion_root() as root: diff --git a/src/specify_cli/integrations/manifest.py b/src/specify_cli/integrations/manifest.py index db11d9a40d..99f93e24b8 100644 --- a/src/specify_cli/integrations/manifest.py +++ b/src/specify_cli/integrations/manifest.py @@ -115,9 +115,9 @@ def _prune_empty_parents(root: Path, parent: Path, stop_dirs: set[Path]) -> None while current not in stop: try: relative = current.relative_to(root_abs) - if not relative.parts or ".." in relative.parts or not files.directory_exists(relative): + if not relative.parts or ".." in relative.parts: break - files.delete(relative, recursive=False) + files.rmdir(relative) except (ValueError, OSError, RuntimeError): break current = current.parent diff --git a/tests/integrations/test_manifest.py b/tests/integrations/test_manifest.py index a9c356b926..997e225684 100644 --- a/tests/integrations/test_manifest.py +++ b/tests/integrations/test_manifest.py @@ -98,6 +98,52 @@ def fail(root): _prune_empty_parents(tmp_path, leaf, set()) assert leaf.is_dir() + @pytest.mark.parametrize("replacement", ["file", "symlink"]) + def test_preserves_directory_replaced_before_removal(self, tmp_path, monkeypatch, replacement): + from specify_cli.file_helper import FileHelper + + root = tmp_path / "project" + outer = root / "outer" + leaf = outer / "leaf" + leaf.mkdir(parents=True) + outside = tmp_path / "outside" + outside.mkdir() + if replacement == "symlink": + probe = tmp_path / "probe-link" + try: + probe.symlink_to(outside, target_is_directory=True) + except (OSError, NotImplementedError): + pytest.skip("Directory links are unavailable") + probe.unlink() + + original_path = FileHelper._path + swapped = False + + def swap_before_mutation(self, path, *args, **kwargs): + nonlocal swapped + resolved = original_path(self, path, *args, **kwargs) + if not swapped and kwargs.get("root_handle") is not None and resolved.name == "leaf": + swapped = True + resolved.rmdir() + if replacement == "file": + resolved.write_text("user content", encoding="utf-8") + else: + resolved.symlink_to(outside, target_is_directory=True) + return resolved + + monkeypatch.setattr(FileHelper, "_path", swap_before_mutation) + + _prune_empty_parents(root, leaf, set()) + + assert swapped + if replacement == "file": + assert leaf.is_file() + assert leaf.read_text(encoding="utf-8") == "user content" + else: + assert leaf.is_symlink() + assert outside.is_dir() + assert outer.is_dir() + class TestManifestRecordFile: def test_record_file_writes_and_hashes(self, tmp_path): diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 06ade38b61..fd97351f98 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -4832,3 +4832,188 @@ def fail_cleanup(*args, **kwargs): with pytest.raises(PermissionError, match="cleanup failed"): with files.temporary_directory("."): monkeypatch.setattr(FileHelper, "delete", fail_cleanup) + + +@pytest.mark.parametrize("allow", [False, True]) +def test_rmdir_removes_only_empty_directories(root, link, allow): + (root / "empty").mkdir() + (root / "nonempty/child").mkdir(parents=True) + (root / "regular").write_text("keep") + (root / "target-dir").mkdir() + leaf_link = link(root / "leaf-link", root / "target-dir") + (root / "real-parent/nested").mkdir(parents=True) + parent_link = link(root / "parent-link", root / "real-parent") + + with FileHelper(root, allow_symlinks=allow) as files: + files.rmdir("empty") + assert not (root / "empty").exists() + + with pytest.raises(FileHelperError, match="established root"): + files.rmdir(".") + + with pytest.raises(FileNotFoundError): + files.rmdir("missing") + + with pytest.raises(OSError): + files.rmdir("nonempty") + assert (root / "nonempty/child").is_dir() + + with pytest.raises(NotADirectoryError): + files.rmdir("regular") + assert (root / "regular").read_text() == "keep" + + expected_leaf_error = NotADirectoryError if allow else SymlinkDeniedError + with pytest.raises(expected_leaf_error): + files.rmdir("leaf-link") + assert leaf_link.is_symlink() + assert (root / "target-dir").is_dir() + + if allow: + files.rmdir("parent-link/nested") + assert parent_link.is_symlink() + assert not (root / "real-parent/nested").exists() + else: + with pytest.raises(SymlinkDeniedError): + files.rmdir("parent-link/nested") + assert (root / "real-parent/nested").is_dir() + + +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("replacement", ["file", "symlink"]) +@pytest.mark.parametrize("stage", ["after_path", "after_mode"]) +def test_rmdir_preserves_replacement_at_mutation_time(root, link, monkeypatch, allow, replacement, stage): + if stage == "after_mode" and os.name == "nt": + pytest.skip("POSIX descriptor-relative rmdir race boundary") + victim = root / "victim" + victim.mkdir() + target_dir = root / "target-dir" + target_dir.mkdir() + if replacement == "symlink": + probe = root / "probe-link" + link(probe, target_dir) + probe.unlink() + + swapped = False + + def swap(): + nonlocal swapped + swapped = True + victim.rmdir() + if replacement == "file": + victim.write_text("keep") + else: + victim.symlink_to(target_dir, target_is_directory=True) + + if stage == "after_path": + original_path = FileHelper._path + + def swap_after_path(self, path, *args, **kwargs): + resolved = original_path(self, path, *args, **kwargs) + if not swapped and kwargs.get("root_handle") is not None and resolved == victim: + swap() + return resolved + + monkeypatch.setattr(FileHelper, "_path", swap_after_path) + expected = ( + NotADirectoryError + if replacement == "file" or allow + else SymlinkDeniedError + ) + else: + original_mode = FileHelper._deletion_entry_mode + + def swap_after_mode(self, path, **kwargs): + mode = original_mode(self, path, **kwargs) + if not swapped and path == victim: + swap() + return mode + + monkeypatch.setattr(FileHelper, "_deletion_entry_mode", swap_after_mode) + expected = NotADirectoryError + + with FileHelper(root, allow_symlinks=allow) as files: + with pytest.raises(expected): + files.rmdir("victim") + + assert swapped + if replacement == "file": + assert victim.is_file() + assert victim.read_text() == "keep" + else: + assert victim.is_symlink() + assert target_dir.is_dir() + + +@pytest.mark.parametrize("allow", [False, True]) +def test_windows_rmdir_validates_opened_leaf_handle_portably( + root, link, monkeypatch, windows_delete_model, allow +): + (root / "empty").mkdir() + (root / "regular").write_text("keep") + (root / "target-dir").mkdir() + leaf_link = link(root / "leaf-link", root / "target-dir") + (root / "swapped").mkdir() + (root / "junction").mkdir() + + @contextmanager + def handle(path, *, directory, pin=True, parent=None): + assert directory + with windows_delete_model.opened(path, parent=parent) as value: + yield value + + deleted_paths = [] + original_remove = windows_delete_model.remove + + def record_remove(value): + deleted_paths.append(windows_delete_model.locations[value]) + original_remove(value) + + original_mode = file_helper._windows_mode + + def mode_with_junction(value): + if windows_delete_model.locations[value] == root / "junction": + raise OSError(errno.ELOOP, "Unsupported Windows reparse point") + return original_mode(value) + + monkeypatch.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt"})) + monkeypatch.setattr(file_helper, "_windows_handle", handle) + monkeypatch.setattr( + file_helper, "_windows_file_id", + lambda *args, **kwargs: _WindowsFileIdentity("fileid128", 1, b"\x01" * 16), + ) + monkeypatch.setattr(file_helper, "_windows_stat", lambda _: root.stat()) + monkeypatch.setattr(file_helper, "_windows_delete", record_remove) + monkeypatch.setattr(file_helper, "_windows_mode", mode_with_junction) + + with FileHelper(root, allow_symlinks=allow) as files: + files.rmdir("empty") + assert deleted_paths == [root / "empty"] + + with pytest.raises(NotADirectoryError): + files.rmdir("regular") + assert (root / "regular").read_text() == "keep" + + expected_leaf_error = NotADirectoryError if allow else SymlinkDeniedError + with pytest.raises(expected_leaf_error): + files.rmdir("leaf-link") + assert leaf_link.is_symlink() + assert (root / "target-dir").is_dir() + + with pytest.raises(UnsupportedPathError): + files.rmdir("junction") + assert (root / "junction").is_dir() + + original_path = FileHelper._path + + def swap_after_path(self, path, *args, **kwargs): + resolved = original_path(self, path, *args, **kwargs) + if kwargs.get("root_handle") is not None and resolved == root / "swapped": + resolved.rmdir() + resolved.write_text("replaced") + return resolved + + monkeypatch.setattr(FileHelper, "_path", swap_after_path) + with pytest.raises(NotADirectoryError): + files.rmdir("swapped") + assert (root / "swapped").read_text() == "replaced" + assert deleted_paths == [root / "empty"] From b5b17b00ade654da4e52becd65e8ee6647cc0363 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 2 Dec 2026 21:55:55 +0100 Subject: [PATCH 09/20] fix(events): give repair advice for unreadable native hook config When a registered reader cannot inspect its declared configuration, name the file and explain how to repair it before upgrading. Keep the existing diagnostic for integrations without a readable format. Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous) --- src/specify_cli/events/__init__.py | 17 ++++++++++++----- .../specify_cli/events/test_context_delivery.py | 10 ++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index d60242240a..bcaac5760e 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -1132,7 +1132,15 @@ def context_delivery_error(integration: IntegrationBase, project_root: Path | No else: handlers = integration.installed_event_handlers(project_root) if handlers is None: - reason = "the integration cannot report installed handlers" + config_file = getattr(integration, "events_config_file", None) + if config_file and getattr(integration, "events_format", None) in _EVENT_HANDLER_READERS: + reason = f"the native events config {config_file!r} could not be read" + remedy = ( + f"Fix {config_file!r} or move it aside, then run " + f"'specify integration upgrade {integration.key}'." + ) + else: + reason = "the integration cannot report installed handlers" else: try: with FileHelper(project_root) as files: @@ -2674,10 +2682,9 @@ def _drop_marked_entries(entries: list) -> list: def _load_user_json(path: Path) -> dict | None: """Load a user-owned JSON file, aborting (None) on read/parse failure (#22/#23). - Returns the parsed dict, or ``None`` when the file is missing or cannot be - read or parsed (e.g. JSONC with comments, a temporarily malformed JSON - document, or an unreadable path). Callers must skip the merge rather than - resetting user content to ``{}``. + Returns the parsed dict, ``{}`` when the file is missing, or ``None`` when + the file cannot be read or parsed as a JSON object. On ``None``, callers + must skip the merge rather than resetting user content to ``{}``. """ if not path.exists(): return {} diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index b32c8c96a7..ea95acc215 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -518,6 +518,16 @@ def test_unreadable_handler_report_and_unknown_format(tmp_path, installed, monke assert "upgrade" not in error +def test_unreadable_registered_native_config_reports_repair(tmp_path, installed, monkeypatch): + monkeypatch.setattr(type(installed), "installed_event_handlers", IntegrationBase.installed_event_handlers) + monkeypatch.setitem(_EVENT_HANDLER_READERS, installed.events_format, lambda *_: None) + + error = context_delivery_error(installed, tmp_path) + + assert "native events config '.fake/hooks.json' could not be read" in error + assert "Fix '.fake/hooks.json' or move it aside, then run 'specify integration upgrade fake-context'." in error + + def test_installed_handlers_must_be_a_list(tmp_path, installed, monkeypatch): monkeypatch.setattr(installed, "installed_event_handlers", lambda root: {"session_start": ADDITIONAL_CONTEXT_HANDLER}) assert "outdated" in context_delivery_error(installed, tmp_path) From ff90039124647b4739fb13196b125064b55d34d4 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 08:28:46 +0100 Subject: [PATCH 10/20] fix(events): preflight lifecycle destinations before writes Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- design/integration.md | 2 +- docs/integrations/cli.md | 5 + src/specify_cli/events/__init__.py | 80 ++++++--- src/specify_cli/integrations/_helpers.py | 6 +- .../integrations/command_install.py | 9 +- .../integrations/command_switch.py | 9 +- .../integrations/command_upgrade.py | 9 +- .../integrations/test_preflight_setup.py | 162 ++++++++++++++++++ 8 files changed, 235 insertions(+), 47 deletions(-) diff --git a/design/integration.md b/design/integration.md index bbb0626656..e9a9f220a9 100644 --- a/design/integration.md +++ b/design/integration.md @@ -511,7 +511,7 @@ them. Keep agent-specific settings and events consistent with that lifecycle. `preflight_setup(project_root, parsed_options, *, script_type)` before they write shared templates, scripts or integration files. Override it to reject a setup that would fail partway, raising `ValueError` or `OSError`; the CLI then -exits with the message and changes nothing. The default accepts every setup. +exits with the message and changes nothing. The default accepts every setup. The lifecycle also runs shared event-destination preflight before writes and passes the resolved event map to setup. Event cleanup releases only the departing integration's dispatcher claim. It deletes `.specify/events.py` only when that integration's current or prior diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index a29056f1e2..955148199f 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -439,6 +439,11 @@ install a built-in `session_start` handler by default. Otherwise enabling events does not create handlers where none are configured. An integration emits only the native events it supports. +`integration install`, `switch`, and `upgrade` preflight event and dispatcher +destinations for symlink and path safety before changing files. Even with +`--events false`, an unsafe existing hook or dispatcher file that requires +cleanup is refused. + To configure project overrides, create `.specify/integration-events.yml`. Replace `` with your integration key and the example command with an installed, script-backed Spec Kit command: diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index bcaac5760e..7d0d0590fc 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -1528,6 +1528,47 @@ def _context_envelope_for(integration: IntegrationBase, canonical_event: str) -> return mapping.get("*") +def _filter_supported_events( + integration: IntegrationBase, events: ResolvedEvents, *, warn: bool = False +) -> ResolvedEvents: + canonical_to_native = getattr(integration, "CANONICAL_TO_NATIVE", {}) or {} + filtered: ResolvedEvents = {} + for ev, handlers in events.items(): + if not isinstance(handlers, list): + continue + if ev in canonical_to_native: + filtered[ev] = handlers + elif warn: + print( + f"\u26a0\ufe0f {integration.key} does not support '{ev}' events; skipping", + file=sys.stderr, + ) + return filtered + + +def preflight_integration_events( + integration: IntegrationBase, + project_root: Path, + parsed_options: dict[str, Any] | None = None, +) -> ResolvedEvents: + """Resolve events once and validate destinations before setup mutates files.""" + events = resolve_events(integration.key, integration.config, project_root, parsed_options) + if not integration.supports_events(): + return events + filtered = _filter_supported_events(integration, events) + if filtered: + _ensure_safe_destination(project_root / EVENTS_DISPATCHER_REL, project_root) + config_file = getattr(integration, "events_config_file", None) + if config_file: + _ensure_safe_destination(project_root / config_file, project_root) + if getattr(integration, "events_format", None) == "ts-plugin": + _ensure_safe_destination(project_root / ".opencode/plugin/speckit-events.ts", project_root) + else: + _remove_native_event_hooks(integration, project_root, None, check_only=True) + _cleanup_shared_dispatcher(integration, project_root, None, check_only=True) + return events + + def install_integration_events( integration: IntegrationBase, project_root: Path, @@ -1546,18 +1587,7 @@ def install_integration_events( if not canonical_to_native: return [] - # Filter to only supported events, preserving all handlers per event. - filtered: ResolvedEvents = {} - for ev, handlers in events.items(): - if not isinstance(handlers, list): - continue - if ev in canonical_to_native: - filtered[ev] = handlers - else: - print( - f"\u26a0\ufe0f {integration.key} does not support '{ev}' events; skipping", - file=sys.stderr, - ) + filtered = _filter_supported_events(integration, events, warn=True) # #3: an empty resolved map (--events false, or override disabling events) # must still strip prior Specify hooks from this integration's native @@ -1810,7 +1840,9 @@ def install_integration_events( def _remove_native_event_hooks( integration: IntegrationBase, project_root: Path, - manifest: IntegrationManifest, + manifest: IntegrationManifest | None, + *, + check_only: bool = False, ) -> None: """Remove Specify-authored hooks from *this* integration's native config. @@ -1826,6 +1858,8 @@ def _remove_native_event_hooks( if not config_path.exists(): return _ensure_safe_destination(config_path, project_root) + if check_only: + return removed = False if fmt == "copilot-json": removed = _remove_copilot_entries(config_path, project_root=project_root) @@ -1894,9 +1928,10 @@ def _dispatcher_matches_template(content: bytes) -> bool: def _cleanup_shared_dispatcher( - integration: IntegrationBase, project_root: Path, manifest: IntegrationManifest, + integration: IntegrationBase, project_root: Path, manifest: IntegrationManifest | None, *, force: bool = False, + check_only: bool = False, ) -> None: """Release this integration's claim; delete only its last managed copy.""" from ..integrations.manifest import IntegrationManifest @@ -1905,24 +1940,27 @@ def _cleanup_shared_dispatcher( owner = manifest # Upgrades emit into a fresh manifest before replacing the installed one. # Only this integration's prior manifest can supply its missing claim. - if dispatcher_rel not in owner.files: + if owner is None or dispatcher_rel not in owner.files: try: owner = IntegrationManifest.load(integration.key, project_root) except FileNotFoundError: owner = manifest except (OSError, ValueError) as exc: - logger.warning( - "Could not read prior dispatcher manifest for '%s'; preserving %s: %s", - integration.key, project_root / dispatcher_rel, exc, - ) + if not check_only: + logger.warning( + "Could not read prior dispatcher manifest for '%s'; preserving %s: %s", + integration.key, project_root / dispatcher_rel, exc, + ) return + if owner is None: + return expected_hash = owner.files.get(dispatcher_rel) recovered = owner.is_recovered(dispatcher_rel) partial = owner.ownership_modes.get(dispatcher_rel) == "partial" # Release even retained claims so manifest-only teardown cannot delete a # user-owned copy or a dispatcher still used by another integration. - if dispatcher_rel in manifest.files: + if not check_only and manifest is not None and dispatcher_rel in manifest.files: manifest.remove(dispatcher_rel) if not expected_hash or recovered or partial: return @@ -1931,6 +1969,8 @@ def _cleanup_shared_dispatcher( dispatcher_path = project_root / dispatcher_rel if dispatcher_path.exists(): _ensure_safe_destination(dispatcher_path, project_root) + if check_only: + return if not force: try: content = dispatcher_path.read_bytes() diff --git a/src/specify_cli/integrations/_helpers.py b/src/specify_cli/integrations/_helpers.py index 37e068dba3..3d49c883dd 100644 --- a/src/specify_cli/integrations/_helpers.py +++ b/src/specify_cli/integrations/_helpers.py @@ -237,12 +237,14 @@ def _preflight_setup_or_exit( parsed_options: dict[str, Any] | None, script_type: str, action: str, -) -> None: - """Run ``integration.preflight_setup()`` and exit before any write on refusal.""" +) -> dict[str, list[dict[str, Any]]]: + """Run adapter and shared event preflight before any write.""" + from ..events import preflight_integration_events try: integration.preflight_setup( project_root, parsed_options, script_type=script_type ) + return preflight_integration_events(integration, project_root, parsed_options) except (ValueError, OSError) as exc: console.print( f"[red]Error:[/red] Cannot {action} integration " diff --git a/src/specify_cli/integrations/command_install.py b/src/specify_cli/integrations/command_install.py index a39eb7cec0..918be000d5 100644 --- a/src/specify_cli/integrations/command_install.py +++ b/src/specify_cli/integrations/command_install.py @@ -99,7 +99,7 @@ def integration_install( raw_options, parsed_options = _resolve_integration_options( integration, current, key, integration_options ) - _preflight_setup_or_exit( + events_map = _preflight_setup_or_exit( integration, project_root, parsed_options, selected_script, "install" ) @@ -135,13 +135,6 @@ def integration_install( integration.key, project_root, version=_get_speckit_version() ) - from ..events import resolve_events - events_map = resolve_events( - integration.key, - integration.config, - project_root, - parsed_options, - ) try: integration.setup( diff --git a/src/specify_cli/integrations/command_switch.py b/src/specify_cli/integrations/command_switch.py index 3e450ab044..e28f8f58d8 100644 --- a/src/specify_cli/integrations/command_switch.py +++ b/src/specify_cli/integrations/command_switch.py @@ -161,7 +161,7 @@ def integration_switch( ) console.print("No files were changed.") raise typer.Exit(1) - _preflight_setup_or_exit( + events_map = _preflight_setup_or_exit( target_integration, project_root, target_parsed_options, @@ -301,13 +301,6 @@ def integration_switch( target_integration.key, project_root, version=_get_speckit_version() ) - from ..events import resolve_events - events_map = resolve_events( - target_integration.key, - target_integration.config, - project_root, - target_parsed_options, - ) try: target_integration.setup( project_root, manifest, diff --git a/src/specify_cli/integrations/command_upgrade.py b/src/specify_cli/integrations/command_upgrade.py index 4eddd0f201..5a087475d6 100644 --- a/src/specify_cli/integrations/command_upgrade.py +++ b/src/specify_cli/integrations/command_upgrade.py @@ -95,7 +95,7 @@ def integration_upgrade( raw_options, parsed_options = _resolve_integration_options( integration, current, key, integration_options ) - _preflight_setup_or_exit( + events_map = _preflight_setup_or_exit( integration, project_root, parsed_options, selected_script, "upgrade" ) @@ -235,13 +235,6 @@ def integration_upgrade( console.print(f"Upgrading integration: [cyan]{key}[/cyan]") new_manifest = IntegrationManifest(key, project_root, version=_get_speckit_version()) - from ..events import resolve_events - events_map = resolve_events( - key, - integration.config, - project_root, - parsed_options, - ) try: integration.setup( project_root, diff --git a/tests/specify_cli/integrations/test_preflight_setup.py b/tests/specify_cli/integrations/test_preflight_setup.py index 1309fec047..9201c78fcb 100644 --- a/tests/specify_cli/integrations/test_preflight_setup.py +++ b/tests/specify_cli/integrations/test_preflight_setup.py @@ -100,3 +100,165 @@ def preflight_setup(self, project_root, parsed_options=None, *, script_type=None ) def test_script_variant_dirs(script_type, expected): assert script_variant_dirs(script_type) == expected + + +@pytest.mark.parametrize("action", ["install", "switch", "upgrade"]) +def test_event_config_symlink_refused_before_any_write(tmp_path, action): + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + key = "claude" if action == "upgrade" else "codex" + project = _init_project(tmp_path, "claude") + override = project / ".specify/integration-events.yml" + override.write_text( + f"integrations:\n {key}:\n events:\n session_start:\n command: speckit.test\n", + encoding="utf-8", + ) + config = project / (".claude/settings.json" if key == "claude" else ".codex/config.toml") + config.parent.mkdir(parents=True, exist_ok=True) + config.unlink(missing_ok=True) + outside = tmp_path / "outside" + outside.mkdir() + target = outside / "config" + target.write_text("original\n", encoding="utf-8") + _symlink_or_skip(config, target) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", action, key, "--script", "sh"] + if action in ("install", "upgrade"): + args.append("--force") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert config.name in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("disabled", ["flag", "override"]) +@pytest.mark.parametrize("present", [False, True]) +def test_disabled_codex_symlinked_parent_cleanup(tmp_path, disabled, present): + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + outside = tmp_path / "outside" + outside.mkdir() + if present: + (outside / "config.toml").write_text("user = true\n", encoding="utf-8") + _symlink_or_skip(project / ".codex", outside, directory=True) + args = ["integration", "switch", "codex", "--script", "sh"] + if disabled == "flag": + args.append("--integration-options=--events false") + else: + (project / ".specify/integration-events.yml").write_text( + "integrations:\n codex:\n events: {}\n", encoding="utf-8" + ) + before, before_outside = _tree(project), _tree(outside) + result = _run_in_project(project, args) + if present: + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert ".codex/config.toml" in output + assert "No files were changed." in output + assert _tree(project) == before + else: + assert result.exit_code == 0, result.output + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("disable", [False, True]) +def test_dispatcher_symlink_upgrade_refused(tmp_path, disable): + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + override = project / ".specify/integration-events.yml" + override.write_text( + "integrations:\n claude:\n events:\n session_start:\n command: speckit.test\n", + encoding="utf-8", + ) + if disable: + result = _run_in_project(project, ["integration", "upgrade", "claude", "--force"]) + assert result.exit_code == 0, result.output + dispatcher = project / ".specify/events.py" + dispatcher.unlink(missing_ok=True) + outside = tmp_path / "outside" + outside.mkdir() + target = outside / "events.py" + target.write_text("original\n", encoding="utf-8") + _symlink_or_skip(dispatcher, target) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", "upgrade", "claude", "--force"] + if disable: + args.append("--integration-options=--events false") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert ".specify/events.py" in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("destination", ["opencode.json", ".opencode/plugin/speckit-events.ts"]) +@pytest.mark.parametrize("configure", [False, True]) +def test_opencode_event_destinations_preflight(tmp_path, destination, configure): + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + (project / ".specify/integration-events.yml").write_text( + "integrations:\n opencode:\n events:\n session_start:\n command: speckit.test\n", + encoding="utf-8", + ) + path = project / destination + path.parent.mkdir(parents=True, exist_ok=True) + outside = tmp_path / "outside" + outside.mkdir() + target = outside / "file" + target.write_text("original\n", encoding="utf-8") + _symlink_or_skip(path, target) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", "switch", "opencode", "--script", "sh"] + if configure: + args.append("--integration-options=--configure-ignore-file") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert destination in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +def test_override_without_super_cannot_bypass_event_preflight(tmp_path, monkeypatch): + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + (project / ".specify/integration-events.yml").write_text( + "integrations:\n codex:\n events:\n session_start:\n command: speckit.test\n", + encoding="utf-8", + ) + config = project / ".codex/config.toml" + config.parent.mkdir() + target = tmp_path / "outside" + target.write_text("original", encoding="utf-8") + _symlink_or_skip(config, target) + calls = [] + monkeypatch.setattr(CodexIntegration, "preflight_setup", lambda *a, **k: calls.append(True)) + before = _tree(project) + result = _run_in_project(project, ["integration", "switch", "codex"]) + output = " ".join(strip_ansi(result.output).split()) + assert calls == [True] + assert result.exit_code == 1, output + assert ".codex/config.toml" in output + assert "No files were changed." in output + assert _tree(project) == before + assert target.read_text(encoding="utf-8") == "original" + + +def test_upgrade_resolves_events_once(tmp_path, caplog): + project = _init_project(tmp_path, "claude") + (project / ".specify/integration-events.yml").write_text("[invalid", encoding="utf-8") + caplog.clear() + result = _run_in_project(project, ["integration", "upgrade", "claude", "--force"]) + assert result.exit_code == 0, result.output + warnings = [r for r in caplog.records if "Could not read or parse" in r.message] + assert len(warnings) == 1 From 049bd4d95e1b8f47258e3dfdf7675c8a7316519e Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 09:48:49 +0100 Subject: [PATCH 11/20] feat(events): add json-named format, injectSteps envelope, and stale-CLI fallback Move shared event framework additions (json-named native config format, events_cwd_is_config_dir relative path rebasing, injectSteps envelope, and EVENT_CONTEXT_ENVELOPES delegation gate) into the context-delivery framework PR with agy-independent tests. Keep delegating to importable confinement-safe specify_cli packages with envelope='plain' and wrap captured stdout in the requested envelope when an older package lacks the envelope, preserving bundled-template resolution. Add a removed-venv regression test for json-named handlers. Assisted-by: Antigravity (model: Gemini 4 Hydrogen, autonomous) --- design/integration.md | 6 + src/specify_cli/events/__init__.py | 130 +++++- src/specify_cli/integrations/base.py | 5 + .../events/test_context_delivery.py | 100 +++++ tests/specify_cli/events/test_json_named.py | 408 ++++++++++++++++++ 5 files changed, 641 insertions(+), 8 deletions(-) create mode 100644 tests/specify_cli/events/test_json_named.py diff --git a/design/integration.md b/design/integration.md index e9a9f220a9..d12e8a23bc 100644 --- a/design/integration.md +++ b/design/integration.md @@ -137,6 +137,12 @@ inherited context from the child environment even when unset. Legacy overrides that do not accept the keyword cannot receive context and must clear inherited context themselves when unset. +Native `json-named` event configs reserve the `__speckit_event__` definition; +its event arrays contain command handlers directly, while other named +entries remain user-owned. Integrations whose native hooks run from the config +file's directory declare `events_cwd_is_config_dir`; dispatcher and +project-relative interpreter paths are rendered relative to that directory. + ## Output flavors Choose the smallest base class that matches the agent's native format. The diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 7d0d0590fc..0066fe0c04 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -18,6 +18,7 @@ import json import logging import os +import posixpath import re import shlex import shutil @@ -57,6 +58,11 @@ # install) would otherwise run unconfined script tokens. EVENT_SCRIPT_PATH_CONFINEMENT = True +EVENT_CONTEXT_ENVELOPES = frozenset({ + "plain", "hookSpecificOutput", "additionalContext", "additional_context", + "hook_specific_output", "injectSteps", "suppress", +}) + EVENTS_DISPATCHER_DIR = Path(".specify") EVENTS_DISPATCHER_FILENAME = "events.py" # POSIX-form (forward-slash) relative path so it matches manifest keys, which @@ -90,6 +96,7 @@ "additionalContext", "additional_context", "hook_specific_output", + "injectSteps", }) # Canonical event names (snake_case) @@ -360,6 +367,7 @@ def _emit(output, envelope, native_event=""): hookSpecificOutput → {"hookSpecificOutput": {"hookEventName": ..., "additionalContext": ...}} additionalContext → {"additionalContext": ...} (top-level, Copilot) additional_context → {"additional_context": ...} (top-level, Cursor) + injectSteps → {"injectSteps": [{"systemMessage": {"systemMessage": ...}}]} hook_specific_output → {"decision": "allow", "hook_specific_output": {"additional_context": ...}} (Vibe: any non-empty stdout must parse as a HookStructuredResponse or @@ -387,6 +395,9 @@ def _emit(output, envelope, native_event=""): if envelope == "additional_context": sys.stdout.write(json.dumps({"additional_context": output}) + "\\n") return + if envelope == "injectSteps": + sys.stdout.write(json.dumps({"injectSteps": [{"systemMessage": {"systemMessage": output}}]}) + "\\n") + return if envelope == "hook_specific_output": sys.stdout.write(json.dumps({"decision": "allow", "hook_specific_output": {"additional_context": output}}) + "\\n") return @@ -409,10 +420,10 @@ def main(): timeout = 120 # Optional 5th arg: context-injection envelope for stdout (C13): plain # (default), hookSpecificOutput, additionalContext, additional_context, - # hook_specific_output, or suppress. Unknown values fall back to plain + # hook_specific_output, injectSteps, or suppress. Unknown values fall back to plain # passthrough. envelope = sys.argv[4] if len(sys.argv) >= 5 else "plain" - if envelope not in ("plain", "hookSpecificOutput", "additionalContext", "additional_context", "hook_specific_output", "suppress"): + if envelope not in ("plain", "hookSpecificOutput", "additionalContext", "additional_context", "hook_specific_output", "injectSteps", "suppress"): envelope = "plain" # Optional 6th arg: native event name for hookSpecificOutput's # hookEventName field (required by Qwen's hooks spec; included by @@ -444,12 +455,21 @@ def main(): # Require EVENT_SCRIPT_PATH_CONFINEMENT so a stale global install cannot # bypass the generated dispatcher's path guard. try: - from specify_cli.events import ( - EVENT_SCRIPT_PATH_CONFINEMENT as _confine_ok, - resolve_and_run_event_command, - ) - if _confine_ok is not True: + import specify_cli.events as _events + from specify_cli.events import resolve_and_run_event_command + if getattr(_events, "EVENT_SCRIPT_PATH_CONFINEMENT", False) is not True: raise ImportError("specify_cli.events lacks script path confinement") + legacy = {"plain", "hookSpecificOutput", "additionalContext", "additional_context", "hook_specific_output", "suppress"} + if envelope not in getattr(_events, "EVENT_CONTEXT_ENVELOPES", legacy): + import contextlib + import io + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = resolve_and_run_event_command( + command_name, _event_name, payload, project_root, timeout=timeout, envelope="plain", native_event=native_event + ) + _emit(buf.getvalue(), envelope, native_event) + sys.exit(rc) sys.exit( resolve_and_run_event_command( command_name, _event_name, payload, project_root, timeout=timeout, envelope=envelope, native_event=native_event @@ -881,6 +901,9 @@ def _emit_event_stdout(output: str, envelope: str, native_event: str = "") -> No if envelope == "additional_context": sys.stdout.write(json.dumps({"additional_context": output}) + "\n") return + if envelope == "injectSteps": + sys.stdout.write(json.dumps({"injectSteps": [{"systemMessage": {"systemMessage": output}}]}) + "\n") + return if envelope == "hook_specific_output": # Vibe parses any non-empty hook stdout as a HookStructuredResponse; # plain text would be reported as a hook failure. Wrap it as an @@ -1419,6 +1442,17 @@ def _dispatcher_command( interpreter = _resolve_interpreter(project_root) else: interpreter = _resolve_interpreter_for_target(target_os) + config_dir = None + if integration.events_cwd_is_config_dir: + config_dir = PurePosixPath(integration.events_config_file).parent.as_posix() + # The resolver's project venv path is project-relative; PATH commands + # and absolute interpreter paths must not be rebased. + if ( + ("/" in interpreter or "\\" in interpreter) + and not PurePosixPath(interpreter).is_absolute() + and not PureWindowsPath(interpreter).is_absolute() + ): + interpreter = posixpath.relpath(interpreter.replace("\\", "/"), config_dir) q_interp = _shell_quote(interpreter, target_os) q_command = _shell_quote(command_name, target_os) q_event = _shell_quote(event_name, target_os) @@ -1428,7 +1462,10 @@ def _dispatcher_command( # containing spaces doesn't word-split. dispatcher = '"${CLAUDE_PROJECT_DIR}/' + EVENTS_DISPATCHER_REL + '"' else: - dispatcher = _shell_quote(EVENTS_DISPATCHER_REL, target_os) + dispatcher_path = EVENTS_DISPATCHER_REL + if config_dir is not None: + dispatcher_path = posixpath.relpath(EVENTS_DISPATCHER_REL, config_dir) + dispatcher = _shell_quote(dispatcher_path, 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 "" @@ -1805,6 +1842,28 @@ def install_integration_events( manifest.record_existing(rel, ownership="partial") created.append(config_path) + elif fmt == "json-named": + named_hooks: dict[str, list[dict[str, Any]]] = {} + for ev, handlers in filtered.items(): + entries = [] + for cfg in handlers: + command = cfg.get("command", "") + timeout = cfg.get("timeout", 60) + entries.append( + { + "type": "command", + "command": _dispatcher_command( + integration, project_root, command, ev, timeout_seconds=timeout + ), + "timeout": _native_timeout(integration, timeout + EVENT_TIMEOUT_BUFFER), + } + ) + named_hooks[canonical_to_native[ev]] = entries + if _merge_json_named(config_path, named_hooks, project_root=project_root): + rel = str(config_path.relative_to(project_root)) + manifest.record_existing(rel, ownership="partial") + created.append(config_path) + elif fmt == "json-root-nested": # Devin hooks.v1.json: a root event map ({"PreToolUse": [...]}) with # no top-level "hooks" wrapper (U2). Same matcher-grouping and single @@ -1877,6 +1936,8 @@ def _remove_native_event_hooks( removed = _remove_json_entries(config_path, project_root=project_root) elif fmt == "json-root-nested": removed = _remove_json_root_entries(config_path, project_root=project_root) + elif fmt == "json-named": + removed = _remove_json_named(config_path, project_root=project_root) elif fmt == "ts-plugin": removed = _remove_opencode_entries(config_path, project_root=project_root) if removed: @@ -2624,6 +2685,59 @@ def _merge_json_fragment( return True +def _read_json_named_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]]: + """Read dispatcher handlers only from the reserved named definition.""" + config_file = getattr(integration, "events_config_file", None) + if not config_file: + return {} + existing = _load_user_json(project_root / config_file) + definition = existing.get(_SPECKIT_MARKER) if existing is not None else None + if not isinstance(definition, dict): + return {} + result: dict[str, list[str]] = {} + for canonical, native in getattr(integration, "CANONICAL_TO_NATIVE", {}).items(): + entries = definition.get(native, []) + if not isinstance(entries, list): + continue + for entry in entries: + if not isinstance(entry, dict) or entry.get("type") != "command": + continue + command = entry.get("command") + if not isinstance(command, str): + continue + parsed = _parse_dispatcher_command(command, integration, project_root) + if parsed and parsed[1:] == (canonical, context_envelope_for(integration, canonical)): + result.setdefault(canonical, []).append(parsed[0]) + return result + + +_EVENT_HANDLER_READERS["json-named"] = _read_json_named_handlers + + +def _merge_json_named(dst: Path, new_hooks: dict, *, project_root: Path) -> bool: + """Replace the reserved named definition without changing user definitions.""" + existing = _load_user_json(dst) + if existing is None: + return False + existing[_SPECKIT_MARKER] = new_hooks + _safe_write_json(dst, existing, project_root=project_root) + return True + + +def _remove_json_named(dst: Path, *, project_root: Path) -> bool: + """Remove the reserved definition, deleting an otherwise empty config.""" + _ensure_safe_destination(dst, project_root) + existing = _load_user_json(dst) + if existing is None or _SPECKIT_MARKER not in existing: + return False + del existing[_SPECKIT_MARKER] + if not existing: + _unlink_file(dst, missing_ok=True) + return True + _safe_write_json(dst, existing, project_root=project_root) + return False + + def _merge_json_root(dst: Path, new_hooks: dict, *, project_root: Path) -> bool: """Merge Specify-authored hooks into a root-nested JSON config (Devin U2). diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index 6343c4f2de..41f5837f2a 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -1471,6 +1471,10 @@ def supports_events(self) -> bool: """Return True if this integration supports agent-native events.""" return bool(getattr(self, "CANONICAL_TO_NATIVE", None) and getattr(self, "events_config_file", None)) + # Native hook commands normally run from the project root. Set this when + # the agent instead runs them from the native config file's directory. + events_cwd_is_config_dir: bool = False + # Context-injection envelope for hook stdout, keyed by canonical event # (with "*" as the fallback). Not every agent injects a hook's plain-text # stdout as model context: Gemini/Tabnine/Qwen/Devin are JSON-only @@ -1479,6 +1483,7 @@ def supports_events(self) -> bool: # "hookSpecificOutput" → {"hookSpecificOutput": {"additionalContext": ...}} # "additionalContext" → {"additionalContext": ...} (top-level, Copilot) # "additional_context" → {"additional_context": ...} (top-level, Cursor) + # "injectSteps" → {"injectSteps": [{"systemMessage": {"systemMessage": ...}}]} # "suppress" → emit nothing (strict-JSON agents on events whose # output can't be used) # Absent (no matching key and no "*") → plain stdout passthrough diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index ea95acc215..f83cfe8954 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -11,6 +11,7 @@ from specify_cli.events import ( ADDITIONAL_CONTEXT_HANDLER, CANONICAL_EVENTS, + EVENT_CONTEXT_ENVELOPES, _EVENTS_DISPATCHER_TEMPLATE, _EVENT_HANDLER_READERS, _dispatcher_command, @@ -57,6 +58,7 @@ def installed(tmp_path, monkeypatch): "additional_context", "hookSpecificOutput", "hook_specific_output", + "injectSteps", "suppress", ], ) @@ -104,6 +106,8 @@ def test_handler_both_paths(tmp_path, monkeypatch, capsys, envelope, value): assert result.stdout == direct if value and envelope != "suppress": assert direct.count("unique-context") == 1 + if envelope == "injectSteps": + assert json.loads(direct) == {"injectSteps": [{"systemMessage": {"systemMessage": value}}]} if envelope != "plain": assert "unique-context-α" in json.dumps( json.loads(direct), ensure_ascii=False @@ -171,6 +175,14 @@ def test_resolution_and_override(tmp_path, monkeypatch): ) +def test_event_context_envelopes_inventory(): + assert EVENT_CONTEXT_ENVELOPES == frozenset({ + "plain", "hookSpecificOutput", "additionalContext", "additional_context", + "hook_specific_output", "injectSteps", "suppress", + }) + assert isinstance(EVENT_CONTEXT_ENVELOPES, frozenset) + + def test_registry_declarations_and_docs(): for integration in INTEGRATION_REGISTRY.values(): declared = integration.context_delivery_events @@ -715,3 +727,91 @@ def installed_event_handlers(self, project_root): config_path.write_text(json.dumps(native), encoding="utf-8") assert nested.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} assert context_delivery_error(nested, tmp_path) is None + + +@pytest.mark.parametrize("package,envelope", [("stale", "injectSteps"), ("stale", "plain"), ("current", "injectSteps")]) +def test_dispatcher_delegates_only_for_supported_envelope(tmp_path, package, envelope): + root = tmp_path / "project" + specify = root / ".specify" + specify.mkdir(parents=True) + dispatcher = specify / "events.py" + dispatcher.write_text(_EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") + marker = tmp_path / "delegated" + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} + args = [str(dispatcher), "speckit.plan", "session_start", "60", envelope] + if package == "stale": + # Stale package passes confinement, lacks EVENT_CONTEXT_ENVELOPES, and + # resolves a bundled command absent from .specify/templates/commands/. + fake = tmp_path / "fake/specify_cli" + fake.mkdir(parents=True) + (fake / "__init__.py").write_text("", encoding="utf-8") + (fake / "events.py").write_text( + "import json\nfrom pathlib import Path\n" + "EVENT_SCRIPT_PATH_CONFINEMENT = True\n" + "def resolve_and_run_event_command(cmd, ev, payload, root, *, timeout=120, envelope='plain', native_event=''):\n" + f" Path({str(marker)!r}).write_text(json.dumps({{'envelope': envelope}}), encoding='utf-8')\n" + " if envelope == 'plain':\n" + " print('unique-context-α', end='')\n" + " return 0\n", + encoding="utf-8", + ) + env["PYTHONPATH"] = str(fake.parent) + command = [sys.executable, *args] + else: + template = specify / "templates/commands/boot.md" + template.parent.mkdir(parents=True) + template.write_text("---\nscripts:\n py: scripts/boot.py\n---\n", encoding="utf-8") + script = specify / "scripts/boot.py" + script.parent.mkdir() + script.write_text("print('unique-context-α', end='')\n", encoding="utf-8") + args = [str(dispatcher), "speckit.boot", "session_start", "60", envelope] + wrapper = ( + "import runpy, sys\nfrom pathlib import Path\nimport specify_cli.events as events\n" + "original = events.resolve_and_run_event_command\n" + "def delegate(*a, **kw):\n" + f" Path({str(marker)!r}).write_text('yes', encoding='utf-8')\n" + " return original(*a, **kw)\n" + "events.resolve_and_run_event_command = delegate\n" + "sys.argv = sys.argv[1:]\nrunpy.run_path(sys.argv[0], run_name='__main__')\n" + ) + command = [sys.executable, "-c", wrapper, *args] + result = subprocess.run(command, input="{}", capture_output=True, encoding="utf-8", env=env, cwd=root) + assert result.returncode == 0, result.stderr + assert marker.exists() + if package == "stale": + assert json.loads(marker.read_text(encoding="utf-8"))["envelope"] == "plain" + if envelope == "injectSteps": + assert json.loads(result.stdout) == {"injectSteps": [{"systemMessage": {"systemMessage": "unique-context-α"}}]} + assert result.stdout.count("unique-context") == 1 + else: + assert result.stdout == "unique-context-α" + + +def test_dispatcher_stale_package_preserves_exit_code_and_empty_stdout(tmp_path): + root = tmp_path / "project" + specify = root / ".specify" + specify.mkdir(parents=True) + dispatcher = specify / "events.py" + dispatcher.write_text(_EVENTS_DISPATCHER_TEMPLATE, encoding="utf-8") + fake = tmp_path / "fake/specify_cli" + fake.mkdir(parents=True) + (fake / "__init__.py").write_text("", encoding="utf-8") + (fake / "events.py").write_text( + "import sys\nEVENT_SCRIPT_PATH_CONFINEMENT = True\n" + "def resolve_and_run_event_command(*a, **kw):\n" + " sys.stderr.write('handler failed\\n')\n" + " return 3\n", + encoding="utf-8", + ) + env = {**os.environ, "PYTHONPATH": str(fake.parent), "PYTHONIOENCODING": "utf-8"} + result = subprocess.run( + [sys.executable, str(dispatcher), "speckit.plan", "session_start", "60", "injectSteps"], + input="{}", + capture_output=True, + encoding="utf-8", + env=env, + cwd=root, + ) + assert result.returncode == 3 + assert result.stdout == "" + assert "handler failed" in result.stderr diff --git a/tests/specify_cli/events/test_json_named.py b/tests/specify_cli/events/test_json_named.py new file mode 100644 index 0000000000..8cf69bbcfc --- /dev/null +++ b/tests/specify_cli/events/test_json_named.py @@ -0,0 +1,408 @@ +"""Named native event definitions, config-dir paths, and injectSteps envelope.""" + +import json +import os +import shlex +import shutil +import subprocess +import sys +from typing import ClassVar + +import pytest + +from specify_cli.events import ( + ADDITIONAL_CONTEXT_HANDLER, + _SPECKIT_MARKER, + _dispatcher_command, + _parse_dispatcher_command, + context_delivery_error, + install_integration_events, + refresh_integration_events, + remove_integration_events, + resolve_events, +) +from specify_cli.integrations import INTEGRATION_REGISTRY +from specify_cli.integrations.base import IntegrationBase +from specify_cli.integrations.manifest import IntegrationManifest + + +class FakeNamedIntegration(IntegrationBase): + key: ClassVar[str] = "fake-named" + CANONICAL_TO_NATIVE = {"session_start": "SessionStart"} + events_config_file = ".agents/hooks.json" + events_format = "json-named" + events_cwd_is_config_dir = True + events_context_envelope = {"session_start": "injectSteps"} + context_delivery_events = frozenset({"session_start"}) + config: ClassVar[dict] = { + "name": "Fake Named", + "folder": ".agents/", + "commands_subdir": "skills", + "install_url": "https://example.com", + "requires_cli": False, + } + registrar_config: ClassVar[dict] = { + "dir": ".agents/skills", + "format": "markdown", + "args": "$ARGUMENTS", + "extension": "/SKILL.md", + } + + def build_exec_args(self, prompt, **kwargs): + return [self.key, "-p", prompt] + + def setup(self, project_root, manifest, parsed_options=None, **opts): + return [] + + def teardown(self, project_root, manifest, *, force=False): + remove_integration_events(self, project_root, manifest, force=force) + return [], [] + + +@pytest.fixture(autouse=True) +def _register_fake_named(monkeypatch): + monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) + + +def test_named_merge_replaces_owned_definition_preserving_user_definitions(tmp_path): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + path = tmp_path / ".agents/hooks.json" + path.parent.mkdir() + user = { + "SessionStart": [{"type": "command", "command": "user", "timeout": 9}], + "enabled": False, + } + path.write_text(json.dumps({"user": user, _SPECKIT_MARKER: {"OldEvent": []}}), encoding="utf-8") + events = { + "session_start": [ + {"command": "speckit.first", "timeout": 13}, + {"command": "speckit.second"}, + ] + } + install_integration_events(integration, tmp_path, manifest, events) + data = json.loads(path.read_text(encoding="utf-8")) + assert data["user"] == user + assert set(data) == {"user", _SPECKIT_MARKER} + handlers = data[_SPECKIT_MARKER]["SessionStart"] + assert len(handlers) == 2 + for handler, command, timeout in zip( + handlers, ("speckit.first", "speckit.second"), (18, 65) + ): + assert set(handler) == {"type", "command", "timeout"} + assert handler["type"] == "command" and handler["timeout"] == timeout + args = shlex.split(handler["command"]) + assert args[1:] == [ + "../.specify/events.py", + command, + "session_start", + str(timeout - 5), + "injectSteps", + ] + install_integration_events( + integration, tmp_path, manifest, {"session_start": [events["session_start"][1]]} + ) + data = json.loads(path.read_text(encoding="utf-8")) + assert len(data[_SPECKIT_MARKER]["SessionStart"]) == 1 + remove_integration_events(integration, tmp_path, manifest, force=True) + assert json.loads(path.read_text(encoding="utf-8")) == {"user": user} + + +@pytest.mark.parametrize("operation", ["remove", "disabled"]) +@pytest.mark.parametrize("user_file", [False, True]) +def test_named_removal_prunes_only_empty_parents(tmp_path, operation, user_file): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events( + integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None) + ) + path = tmp_path / ".agents/hooks.json" + assert path.is_file() + if user_file: + (tmp_path / ".agents/other").write_text("user", encoding="utf-8") + if operation == "remove": + integration.teardown(tmp_path, manifest, force=True) + else: + install_integration_events( + integration, + tmp_path, + manifest, + resolve_events("fake-named", None, tmp_path, {"events": "false"}), + ) + assert not path.exists() + assert (tmp_path / ".agents").exists() is user_file + assert not (tmp_path / ".specify/events.py").exists() + + +def test_unsupported_events_are_not_rendered(tmp_path, capsys): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events( + integration, + tmp_path, + manifest, + { + "session_start": [{"command": "speckit.start"}], + "post_tool_use": [{"command": "speckit.other"}], + }, + ) + data = json.loads((tmp_path / ".agents/hooks.json").read_text(encoding="utf-8")) + assert list(data[_SPECKIT_MARKER]) == ["SessionStart"] + assert "does not support 'post_tool_use'" in capsys.readouterr().err + + +def test_named_malformed_and_unowned_files_are_not_clobbered(tmp_path): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + path = tmp_path / ".agents/hooks.json" + path.parent.mkdir() + for original in ("{ invalid json", '{"user": {}}'): + path.write_text(original, encoding="utf-8") + remove_integration_events(integration, tmp_path, manifest, force=True) + assert path.read_text(encoding="utf-8") == original + path.write_text("{ invalid json", encoding="utf-8") + install_integration_events( + integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None) + ) + assert path.read_text(encoding="utf-8") == "{ invalid json" + integration.teardown(tmp_path, manifest, force=True) + assert path.read_text(encoding="utf-8") == "{ invalid json" + + +def test_named_refresh_and_delivery_check(tmp_path): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events( + integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None) + ) + manifest.save() + state = tmp_path / ".specify/integration.json" + state.write_text( + json.dumps({"default_integration": "fake-named", "installed_integrations": ["fake-named"]}), + encoding="utf-8", + ) + assert context_delivery_error(integration, tmp_path) is None + path = tmp_path / ".agents/hooks.json" + data = json.loads(path.read_text(encoding="utf-8")) + data["user"] = {"SessionStart": [{"command": "keep"}]} + data[_SPECKIT_MARKER]["Stale"] = [] + path.write_text(json.dumps(data), encoding="utf-8") + refresh_integration_events(tmp_path) + data = json.loads(path.read_text(encoding="utf-8")) + assert data["user"] == {"SessionStart": [{"command": "keep"}]} + assert list(data[_SPECKIT_MARKER]) == ["SessionStart"] + assert ( + ADDITIONAL_CONTEXT_HANDLER + in data[_SPECKIT_MARKER]["SessionStart"][0]["command"] + ) + state.write_text( + json.dumps( + { + "default_integration": "fake-named", + "installed_integrations": ["fake-named"], + "integration_settings": { + "fake-named": {"parsed_options": {"events": "false"}} + }, + } + ), + encoding="utf-8", + ) + refresh_integration_events(tmp_path) + assert json.loads(path.read_text(encoding="utf-8")) == { + "user": {"SessionStart": [{"command": "keep"}]} + } + assert "disabled" in context_delivery_error(integration, tmp_path) + + +@pytest.mark.skipif( + os.name == "nt", reason="POSIX shell execution" +) +def test_named_hook_executes_from_config_dir_with_project_venv(tmp_path): + root = tmp_path / "project with spaces" + root.mkdir() + venv_python = root / ".venv/bin/python" + venv_python.parent.mkdir(parents=True) + venv_python.symlink_to(sys.executable) + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", root) + install_integration_events( + integration, root, manifest, resolve_events("fake-named", None, root, None) + ) + handler = json.loads((root / ".agents/hooks.json").read_text(encoding="utf-8"))[_SPECKIT_MARKER][ + "SessionStart" + ][0] + assert shlex.split(handler["command"])[0:2] == [ + "../.venv/bin/python", + "../.specify/events.py", + ] + assert integration.installed_event_handlers(root) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + (root / ".specify/integration.json").write_text( + json.dumps({"default_integration": "fake-named", "installed_integrations": ["fake-named"]}), encoding="utf-8" + ) + assert context_delivery_error(integration, root) is None + result = subprocess.run( + ["/bin/sh", "-c", handler["command"]], + cwd=root / ".agents", + input="{}", + encoding="utf-8", + capture_output=True, + env={**os.environ, "SPECKIT_ADDITIONAL_CONTEXT": "unique value", "PYTHONIOENCODING": "utf-8"}, + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == { + "injectSteps": [{"systemMessage": {"systemMessage": "unique value"}}] + } + assert result.stdout.count("unique value") == 1 + + +def test_named_delivery_rejects_deleted_venv(tmp_path): + venv_rel = ".venv/Scripts/python.exe" if os.name == "nt" else ".venv/bin/python" + venv_python = tmp_path / venv_rel + venv_python.parent.mkdir(parents=True) + venv_python.write_text("", encoding="utf-8") + + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events( + integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None) + ) + manifest.save() + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": "fake-named", "installed_integrations": ["fake-named"]}), + encoding="utf-8", + ) + handler = json.loads((tmp_path / ".agents/hooks.json").read_text(encoding="utf-8"))[_SPECKIT_MARKER][ + "SessionStart" + ][0] + assert shlex.split(handler["command"])[0] == f"../{venv_rel}" + assert integration.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(integration, tmp_path) is None + + shutil.rmtree(tmp_path / ".venv") + assert integration.installed_event_handlers(tmp_path) == {} + assert "outdated" in context_delivery_error(integration, tmp_path) + + +def test_named_removal_rejects_symlinked_config(tmp_path): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events( + integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None) + ) + path = tmp_path / ".agents/hooks.json" + outside = tmp_path / "outside.json" + outside.write_text(path.read_text(encoding="utf-8"), encoding="utf-8") + path.unlink() + try: + path.symlink_to(outside) + except OSError: + pytest.skip("symlinks are unavailable") + original = outside.read_bytes() + with pytest.raises(ValueError, match="(?i)symlink"): + remove_integration_events(integration, tmp_path, manifest, force=True) + assert outside.read_bytes() == original + + +def test_named_cleanup_keeps_other_integration_and_shared_agents_files(tmp_path): + from specify_cli.integrations.codex import CodexIntegration + + named = FakeNamedIntegration() + codex = CodexIntegration() + named_manifest = IntegrationManifest("fake-named", tmp_path) + codex_manifest = IntegrationManifest("codex", tmp_path) + install_integration_events( + named, tmp_path, named_manifest, resolve_events("fake-named", None, tmp_path, None) + ) + install_integration_events( + codex, + tmp_path, + codex_manifest, + {"session_start": [{"command": "speckit.other"}]}, + ) + codex_manifest.save() + state = tmp_path / ".specify/integration.json" + state.write_text( + json.dumps( + {"default_integration": "fake-named", "installed_integrations": ["fake-named", "codex"]} + ), + encoding="utf-8", + ) + other_skill = tmp_path / ".agents/skills/other/SKILL.md" + other_skill.parent.mkdir(parents=True) + other_skill.write_text("user skill", encoding="utf-8") + remove_integration_events(named, tmp_path, named_manifest) + assert other_skill.read_text(encoding="utf-8") == "user skill" + assert not (tmp_path / ".agents/hooks.json").exists() + assert (tmp_path / ".codex/config.toml").is_file() + assert (tmp_path / ".specify/events.py").is_file() + + +def test_config_directory_dispatcher_path_is_generic_and_quoted(tmp_path, monkeypatch): + from specify_cli import events + + class OtherIntegration(FakeNamedIntegration): + key = "other" + events_config_file = "nested hooks/deeper/hooks.json" + + monkeypatch.setattr( + events, "_resolve_interpreter", lambda root: "/python with space/python" + ) + command = _dispatcher_command( + OtherIntegration(), tmp_path, "some command", "session_start" + ) + assert shlex.split(command) == [ + "/python with space/python", + "../../.specify/events.py", + "some command", + "session_start", + "60", + "injectSteps", + ] + + +@pytest.mark.parametrize( + "damage", + ["malformed", "unowned", "wrong_event", "wrong_canonical", "modified", "wrong_envelope", "wrong_type", "stale_dispatcher"], +) +def test_named_delivery_rejects_invalid_installation(tmp_path, damage): + integration = FakeNamedIntegration() + manifest = IntegrationManifest("fake-named", tmp_path) + install_integration_events(integration, tmp_path, manifest, resolve_events("fake-named", None, tmp_path, None)) + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": "fake-named", "installed_integrations": ["fake-named"]}), encoding="utf-8" + ) + path = tmp_path / ".agents/hooks.json" + data = json.loads(path.read_text(encoding="utf-8")) + definition = data[_SPECKIT_MARKER] + handler = definition["SessionStart"][0] + if damage == "unowned": + data["user"] = data.pop(_SPECKIT_MARKER) + elif damage == "wrong_event": + definition["SessionEnd"] = definition.pop("SessionStart") + elif damage == "wrong_canonical": + handler["command"] = handler["command"].replace("session_start", "session_end") + elif damage == "modified": + handler["command"] += " ; echo bad" + elif damage == "wrong_envelope": + handler["command"] = handler["command"].replace("injectSteps", "plain") + elif damage == "wrong_type": + handler["type"] = "other" + elif damage == "stale_dispatcher": + (tmp_path / ".specify/events.py").write_text("# stale", encoding="utf-8") + path.write_text("{" if damage == "malformed" else json.dumps(data), encoding="utf-8") + assert "outdated" in context_delivery_error(integration, tmp_path) + + +@pytest.mark.parametrize("target", ["host", "posix", "windows"]) +def test_named_dispatcher_parser_round_trip(tmp_path, monkeypatch, target): + class OtherIntegration(FakeNamedIntegration): + events_config_file = "nested hooks/deeper/hooks.json" + + monkeypatch.setattr("specify_cli.events._resolve_interpreter", lambda root: ".venv dir/bin/python") + integration = OtherIntegration() + command = _dispatcher_command(integration, tmp_path, "handler name", "session_start", target_os=target) + assert _parse_dispatcher_command(command, integration, tmp_path, target_os=target) == ( + "handler name", "session_start", "injectSteps" + ) + assert _parse_dispatcher_command(command + " ; echo bad", integration, tmp_path, target_os=target) is None + assert _parse_dispatcher_command(command, FakeNamedIntegration(), tmp_path, target_os=target) is None From 6e6337ae40f529ae996604d0b65f67dd74fcfb7d Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 15:10:30 +0100 Subject: [PATCH 12/20] fix(events): reject unsafe and unreadable named hook configs Read installed named hook definitions with FileHelper in deny mode. Reject symlinked files and ancestors, and distinguish malformed or unreadable configs from missing hooks so preflight suggests a repair that can work. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- src/specify_cli/events/__init__.py | 24 +++- tests/specify_cli/events/test_json_named.py | 123 +++++++++++++++++++- 2 files changed, 143 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 0066fe0c04..fa8d048d62 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2685,13 +2685,31 @@ def _merge_json_fragment( return True -def _read_json_named_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]]: +def _read_json_named_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]] | None: """Read dispatcher handlers only from the reserved named definition.""" config_file = getattr(integration, "events_config_file", None) if not config_file: return {} - existing = _load_user_json(project_root / config_file) - definition = existing.get(_SPECKIT_MARKER) if existing is not None else None + try: + with FileHelper(project_root) as files: + existing = json.loads(files.read_text(config_file, encoding="utf-8")) + except FileHelperError: + return None + except FileNotFoundError: + return {} + except (OSError, ValueError) as exc: + logger.warning( + "Could not read or parse %s (it may be unreadable, contain JSONC " + "comments, or be malformed); " + "skipping event-config merge to preserve user content.", + project_root / config_file, + ) + logger.debug("Read/parse error detail: %s", exc) + return None + if not isinstance(existing, dict): + logger.warning("%s is not a JSON object; skipping event-config merge.", project_root / config_file) + return None + definition = existing.get(_SPECKIT_MARKER) if not isinstance(definition, dict): return {} result: dict[str, list[str]] = {} diff --git a/tests/specify_cli/events/test_json_named.py b/tests/specify_cli/events/test_json_named.py index 8cf69bbcfc..f10d7b8c33 100644 --- a/tests/specify_cli/events/test_json_named.py +++ b/tests/specify_cli/events/test_json_named.py @@ -283,6 +283,58 @@ def test_named_delivery_rejects_deleted_venv(tmp_path): assert "outdated" in context_delivery_error(integration, tmp_path) +def test_named_delivery_accepts_linked_project_root(tmp_path): + from tests.specify_cli.integrations._helpers import _symlink_or_skip + + root = tmp_path / "project" + root.mkdir() + integration = FakeNamedIntegration() + manifest = IntegrationManifest(integration.key, root) + install_integration_events(integration, root, manifest, resolve_events(integration.key, None, root, None)) + (root / ".specify/integration.json").write_text( + json.dumps({"default_integration": integration.key, "installed_integrations": [integration.key]}), + encoding="utf-8", + ) + alias = tmp_path / "project-alias" + _symlink_or_skip(alias, root, directory=True) + assert context_delivery_error(integration, alias) is None + + +@pytest.mark.parametrize("link_kind", ["file", "parent"]) +def test_named_delivery_rejects_symlinked_config(tmp_path, link_kind): + from tests.specify_cli.integrations._helpers import _symlink_or_skip + + root = tmp_path / "project" + root.mkdir() + integration = FakeNamedIntegration() + manifest = IntegrationManifest(integration.key, root) + install_integration_events(integration, root, manifest, resolve_events(integration.key, None, root, None)) + (root / ".specify/integration.json").write_text( + json.dumps({"default_integration": integration.key, "installed_integrations": [integration.key]}), + encoding="utf-8", + ) + path = root / integration.events_config_file + assert context_delivery_error(integration, root) is None + outside = tmp_path / "outside" + outside.mkdir() + if link_kind == "file": + target = outside / path.name + shutil.move(path, target) + _symlink_or_skip(path, target) + else: + target = outside / path.parent.name + shutil.move(path.parent, target) + _symlink_or_skip(path.parent, target, directory=True) + target = target / path.name + original = target.read_bytes() + + assert integration.installed_event_handlers(root) is None + error = context_delivery_error(integration, root) + assert "native events config '.agents/hooks.json' could not be read" in error + assert "Fix '.agents/hooks.json' or move it aside" in error + assert target.read_bytes() == original + + def test_named_removal_rejects_symlinked_config(tmp_path): integration = FakeNamedIntegration() manifest = IntegrationManifest("fake-named", tmp_path) @@ -390,7 +442,76 @@ def test_named_delivery_rejects_invalid_installation(tmp_path, damage): elif damage == "stale_dispatcher": (tmp_path / ".specify/events.py").write_text("# stale", encoding="utf-8") path.write_text("{" if damage == "malformed" else json.dumps(data), encoding="utf-8") - assert "outdated" in context_delivery_error(integration, tmp_path) + error = context_delivery_error(integration, tmp_path) + if damage == "malformed": + assert "could not be read" in error + assert "Fix '.agents/hooks.json' or move it aside" in error + else: + assert "outdated" in error + + +@pytest.mark.parametrize( + "content", [b"{", b"[]", b"\xff"], ids=["malformed", "non-object", "invalid-utf8"] +) +def test_named_unreadable_config_requires_repair(tmp_path, content): + integration = FakeNamedIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + events = resolve_events(integration.key, None, tmp_path, None) + install_integration_events(integration, tmp_path, manifest, events) + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": integration.key, "installed_integrations": [integration.key]}), + encoding="utf-8", + ) + path = tmp_path / integration.events_config_file + assert context_delivery_error(integration, tmp_path) is None + path.write_bytes(content) + + assert integration.installed_event_handlers(tmp_path) is None + error = context_delivery_error(integration, tmp_path) + assert "native events config '.agents/hooks.json' could not be read" in error + assert "Fix '.agents/hooks.json' or move it aside, then run 'specify integration upgrade fake-named'." in error + install_integration_events(integration, tmp_path, manifest, events) + assert path.read_bytes() == content + + +def test_named_config_read_error_requires_repair(tmp_path, monkeypatch): + from specify_cli.file_helper import FileHelper + + integration = FakeNamedIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events(integration, tmp_path, manifest, resolve_events(integration.key, None, tmp_path, None)) + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": integration.key, "installed_integrations": [integration.key]}), + encoding="utf-8", + ) + original_read = FileHelper.read_text + + def read_text(files, path, *, encoding="utf-8"): + if str(path) == integration.events_config_file: + raise PermissionError("unreadable") + return original_read(files, path, encoding=encoding) + + monkeypatch.setattr(FileHelper, "read_text", read_text) + assert integration.installed_event_handlers(tmp_path) is None + error = context_delivery_error(integration, tmp_path) + assert "native events config '.agents/hooks.json' could not be read" in error + assert "Fix '.agents/hooks.json' or move it aside" in error + + +def test_named_missing_config_requires_upgrade(tmp_path): + integration = FakeNamedIntegration() + manifest = IntegrationManifest(integration.key, tmp_path) + install_integration_events(integration, tmp_path, manifest, resolve_events(integration.key, None, tmp_path, None)) + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": integration.key, "installed_integrations": [integration.key]}), + encoding="utf-8", + ) + (tmp_path / integration.events_config_file).unlink() + assert integration.installed_event_handlers(tmp_path) == {} + error = context_delivery_error(integration, tmp_path) + assert "missing or outdated" in error + assert "Run 'specify integration upgrade fake-named'." in error + assert "move it aside" not in error @pytest.mark.parametrize("target", ["host", "posix", "windows"]) From 35eb15e8c16452767a20cc89076d15be0c9551ba Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 15:10:30 +0100 Subject: [PATCH 13/20] fix(dispatch): stabilize relative PATH for integration processes Capture the calling directory for workflow dispatch and normalize relative PATH entries in integration child environments without mutating the parent environment. Preserve shell-step and empty-PATH behavior, existing Copilot lookup semantics, and context isolation. Add real-subprocess and portable Windows regressions; native Windows validation remains pending. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous) --- design/integration.md | 34 + docs/integrations/api.md | 18 + docs/integrations/cli.md | 19 + src/specify_cli/_utils.py | 13 +- src/specify_cli/integrations/_context.py | 233 ++++- src/specify_cli/integrations/base.py | 29 +- .../integrations/copilot/__init__.py | 5 +- src/specify_cli/integrations/installer.py | 4 +- src/specify_cli/workflows/_execution.py | 1 + src/specify_cli/workflows/base.py | 5 + src/specify_cli/workflows/engine.py | 8 + .../workflows/step/command/__init__.py | 6 +- .../workflows/step/prompt/__init__.py | 17 +- tests/integrations/test_base.py | 2 + tests/integrations/test_context.py | 5 + tests/integrations/test_dispatch_path.py | 810 ++++++++++++++++++ .../test_dispatch_windows_lookup.py | 458 ++++++++++ tests/integrations/test_integration_agy.py | 2 +- tests/integrations/test_integration_bob.py | 2 + tests/integrations/test_integration_claude.py | 8 +- tests/integrations/test_integration_codex.py | 8 +- .../integrations/test_integration_copilot.py | 13 +- .../test_integration_cursor_agent.py | 16 +- tests/integrations/test_integration_mcode.py | 3 +- tests/test_workflows.py | 120 +-- .../test_command_additional_context.py | 18 +- tests/workflows/test_dispatch_settings.py | 16 +- tests/workflows/test_step_capture.py | 2 +- 28 files changed, 1765 insertions(+), 110 deletions(-) create mode 100644 tests/integrations/test_dispatch_path.py create mode 100644 tests/integrations/test_dispatch_windows_lookup.py diff --git a/design/integration.md b/design/integration.md index d12e8a23bc..a4dbeb5ca5 100644 --- a/design/integration.md +++ b/design/integration.md @@ -587,3 +587,37 @@ they have merged. See the and devcontainer setup if the agent needs additional tooling. Prefer existing bases and shared processing over copied setup loops. + +### Workflow dispatch search environment + +Command and prompt dispatch capture the caller's working directory at workflow +run or resume. Each dispatch copies the current environment and anchors relative +PATH entries to that location for the integration process and its descendants. +This changes the search locations for **all** programs in that child, including +native hooks, not only Python. PATH order and duplicates are retained; an +absent PATH stays absent and an entirely empty PATH remains empty. Direct +integration dispatch preserves its existing empty-PATH subprocess fallback, +which can search the child working directory. Individual empty segments in a +nonempty PATH refer to the caller's directory. If anchoring would insert a PATH +separator into an entry, dispatch fails rather than search unintended paths. +The shell step does not use this PATH transformation. No process-global +environment or working-directory changes are made. + +Base command dispatch, Copilot's override and prompt dispatch use the shared +integration environment. Base and prompt dispatch use the shared executable +lookup; Copilot retains its existing executable probe and subprocess launch. +On Windows that launch does not use the child PATH or cwd to locate the CLI, +so its selection can still differ from workflow preflight. An explicit relative +Copilot executable override remains relative to the child working directory on +POSIX. Prompt dispatch also retains its existing fallback when the integration +key is found but the executable in its argv is not. + +Custom adapter `dispatch_command()` overrides starting subprocesses must use +`integration_dispatch()` as a context manager around the shared +`integration_environment()` and `dispatch_which()` helpers to obtain the same +child environment and preserve context isolation; overrides not using them and +agents started manually are outside this guarantee. Direct base dispatch captures +its own caller location. Hook files remain portable and contain no machine-specific +interpreter paths. Strict native-hook verification can still reject a hook if +the interpreter selected at installation differs from the one selected at +run time; reinstall or upgrade the integration in that environment. diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 80073510b9..0e012c483f 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -381,3 +381,21 @@ filter restricts normal fresh-session dispatch (for example, a `resume`-only matcher), reporting only unfiltered or wildcard handlers (absent, `""`, or `"*"`). See [the integration contract](https://github.com/github/spec-kit/blob/main/design/integration.md#context-delivery-for-command-steps). + +### Subprocess search environment + +Workflow command and prompt dispatch anchor relative PATH entries to the +caller directory captured at run or resume. This applies to every program +searched by the integration child and its hooks. Copilot retains its existing +executable launch: on Windows, the initial CLI lookup does not use this child +PATH; on POSIX, explicit relative executable overrides remain relative to the +child cwd. Prompt dispatch retains its existing executable fallback. An unset or +wholly empty PATH is left unchanged; direct dispatch can still search the child +working directory when PATH is empty. Dispatch fails if anchoring inserts a PATH +separator into an entry. Shell steps retain their existing environment semantics. Adapter +`dispatch_command()` overrides that start their own subprocesses should +use `specify_cli.integrations._context.integration_dispatch()` as a context +manager around `integration_environment()` and `dispatch_which()` for the +child environment and executable selection, and +must continue to isolate additional context. Overrides that do not use these +helpers, and agents started outside Spec Kit, do not receive this guarantee. diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index 955148199f..ed71216c92 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -567,3 +567,22 @@ Use `upgrade` when you've upgraded Spec Kit and want to refresh an installed int ### Do extensions and presets I install apply to every installed integration? No. Extensions (`specify extension add`) and presets (`specify preset add`) register their command overrides for the currently active (default) integration only, even if other integrations are installed. A non-default integration does not receive those artifacts until it becomes the default: `specify integration use ` (or `switch `) rescaffolds every enabled extension and preset for the newly active integration. `specify integration upgrade` follows the same rule — it only re-registers extensions and presets when upgrading the active integration. + +### PATH during workflow dispatch + +When Spec Kit launches an integration for a command or prompt step, relative +PATH entries are anchored to the directory from which the workflow was run or +resumed. This affects lookup of tools in the integration process and its hooks. +Copilot retains its existing CLI launch behavior: on Windows, the initial CLI +lookup does not use this child PATH; on POSIX, explicit relative executable +overrides remain relative to the child working directory. Prompt steps retain +their existing executable fallback. An unset PATH remains unset; an entirely +empty PATH stays empty. With an empty PATH, a shell or a direct integration dispatch may still search its child +working directory, so that case is not stabilized. If anchoring a relative +entry would insert a PATH separator into that entry (for example, `:` in a +POSIX caller directory), dispatch fails rather than search unintended paths; +use absolute entries or start from a directory without that separator. +Shell steps and manually started agents are unchanged. Custom adapters that start +subprocesses without the shared dispatch helpers are not covered. A native +hook whose interpreter selection changed since installation can still fail +strict verification; upgrade the integration in the current environment. diff --git a/src/specify_cli/_utils.py b/src/specify_cli/_utils.py index 300ca4ff58..176ffd7cae 100644 --- a/src/specify_cli/_utils.py +++ b/src/specify_cli/_utils.py @@ -27,17 +27,23 @@ def docker_agent_command(executable: str | None = None) -> list[str] | None: is verified with a bounded, read-only version probe so a plain Docker CLI is not mistaken for an installed Docker Agent. """ + from .integrations._context import dispatch_probe_options, dispatch_which + resolved_from_path = executable is None if executable is None: - if shutil.which("docker-agent"): + if dispatch_which("docker-agent"): return ["docker-agent", "run"] - executable = shutil.which("docker") + executable = dispatch_which("docker") if executable is None: return None executable_name = Path(executable).name.lower() if executable_name in {"docker", "docker.exe"}: - command = [executable, "agent", "version"] + options = dispatch_probe_options() + probe_executable = dispatch_which(executable) if options else executable + if probe_executable is None: + return None + command = [probe_executable, "agent", "version"] run_command = [executable, "agent", "run"] else: # An explicit non-Docker executable is an operator override. Preserve @@ -49,6 +55,7 @@ def docker_agent_command(executable: str | None = None) -> list[str] | None: capture_output=True, check=False, timeout=DOCKER_AGENT_CHECK_TIMEOUT, + **options, ) except (OSError, subprocess.TimeoutExpired): return None diff --git a/src/specify_cli/integrations/_context.py b/src/specify_cli/integrations/_context.py index 83c7e7c99d..2dad0d596b 100644 --- a/src/specify_cli/integrations/_context.py +++ b/src/specify_cli/integrations/_context.py @@ -1,12 +1,63 @@ -"""Child environment for command context delivery.""" +"""Child environments and executable lookup for integration dispatch.""" + +from __future__ import annotations import os +import shutil +import sys +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from functools import wraps +from pathlib import PureWindowsPath +from typing import Iterator ADDITIONAL_CONTEXT_ENV = "SPECKIT_ADDITIONAL_CONTEXT" +class DispatchPathError(ValueError): + """The caller's PATH cannot be represented safely for a child process.""" + + +@dataclass(frozen=True) +class DispatchLocation: + """The caller's working directory, including Windows per-drive directories.""" + + cwd: str + drive_cwds: dict[str, str] + + +def capture_dispatch_location() -> DispatchLocation: + cwd = os.getcwd() + # Windows resolves D:foo against D's current directory, which need not + # be the process's current directory. Capture it before the workflow runs. + drives = ( + {f"{letter}:": os.path.abspath(f"{letter}:.") for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"} + if os.name == "nt" else {} + ) + return DispatchLocation(cwd, drives) + + +def _anchored(path: str, location: DispatchLocation) -> str: + if os.name == "nt": + drive, tail = os.path.splitdrive(path) + if drive and (drive.startswith(("\\\\", "//")) or tail.startswith(("/", "\\"))): + return path + if drive: + drive_cwd = location.drive_cwds.get(drive.upper()) + return os.path.join(drive_cwd, tail) if drive_cwd is not None else path + if tail.startswith(("/", "\\")): + return os.path.join(os.path.splitdrive(location.cwd)[0], tail) + elif os.path.isabs(path): + return path + return os.path.join(location.cwd, path) + + def dispatch_environment(additional_context: str | None) -> dict[str, str]: - """Copy the environment without inheriting another dispatch's context.""" + """Copy the environment without inheriting another dispatch's context. + + This is also used by shell steps, whose PATH must remain unchanged. + """ env = dict(os.environ) for key in list(env): if key == ADDITIONAL_CONTEXT_ENV or ( @@ -16,3 +67,181 @@ def dispatch_environment(additional_context: str | None) -> dict[str, str]: if additional_context: env[ADDITIONAL_CONTEXT_ENV] = additional_context return env + + +@dataclass(frozen=True) +class _Dispatch: + location: DispatchLocation + environment: dict[str, str] + windows_prepend_cwd: bool = False + + +_dispatch: ContextVar[_Dispatch | None] = ContextVar("integration_dispatch", default=None) + + +@contextmanager +def integration_dispatch( + location: DispatchLocation | None = None, *, fresh: bool = False +) -> Iterator[None]: + """Pin one environment and caller location for preflight and subprocesses.""" + if not fresh and _dispatch.get() is not None: + yield + return + location = location or capture_dispatch_location() + env = dispatch_environment(None) + path_key = next((key for key in env if key.upper() == "PATH"), None) if os.name == "nt" else "PATH" + original_path = env.get(path_key) if path_key else None + windows_prepend_cwd = False + if os.name == "nt" and original_path != "": + search_path = original_path if original_path is not None else os.defpath + if sys.version_info < (3, 12): + windows_prepend_cwd = os.curdir not in search_path.split(os.pathsep) + else: + import _winapi + + # For bare names the native policy is independent of the name. + # Capture it now instead of consulting a later process environment. + windows_prepend_cwd = _winapi.NeedCurrentDirectoryForExePath("speckit") + if path_key in env and original_path: + anchored = [_anchored(part, location) for part in original_path.split(os.pathsep)] + if any(os.pathsep in part for part in anchored): + raise DispatchPathError( + f"Cannot stabilize PATH: a caller-anchored entry contains the PATH separator " + f"{os.pathsep!r}. Use absolute PATH entries or start from a directory without it." + ) + env[path_key] = os.pathsep.join(anchored) + token = _dispatch.set(_Dispatch(location, env, windows_prepend_cwd)) + try: + yield + finally: + _dispatch.reset(token) + + +def scoped_dispatch(method): + """Keep direct dispatch calls compatible while pinning their environment.""" + @wraps(method) + def invoke(*args, **kwargs): + with integration_dispatch(): + return method(*args, **kwargs) + return invoke + + +def integration_environment(additional_context: str | None) -> dict[str, str]: + """Return the scoped integration child environment with isolated context.""" + dispatch = _dispatch.get() + if dispatch is None: + with integration_dispatch(): + return integration_environment(additional_context) + env = dict(dispatch.environment) + if additional_context: + env[ADDITIONAL_CONTEXT_ENV] = additional_context + return env + + +def dispatch_probe_options() -> dict[str, object]: + """Use the dispatch environment and caller directory for CLI probes.""" + dispatch = _dispatch.get() + if dispatch is None: + return {} + return {"cwd": dispatch.location.cwd, "env": dict(dispatch.environment)} + + +def empty_path_bare_command(command: str) -> bool: + """Preserve the historical direct subprocess fallback for an empty PATH.""" + dispatch = _dispatch.get() + if dispatch is None or os.path.dirname(command): + return False + if os.name == "nt" and os.path.splitdrive(command)[0]: + return False + key = next((key for key in dispatch.environment if key.upper() == "PATH"), None) if os.name == "nt" else "PATH" + return key in dispatch.environment and dispatch.environment[key] == "" + + +def fully_qualified_windows_executable(command: str) -> bool: + """Whether *command* is independent of every Windows working directory.""" + if os.name != "nt": + return False + path = PureWindowsPath(command) + drive = path.drive + return bool( + path.root + and path.is_absolute() + and ( + drive.startswith("\\\\") + or (len(drive) == 2 and drive[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" and drive[1] == ":") + ) + ) + + +def _windows_names(command: str, env: dict[str, str]) -> list[str]: + key = next((key for key in env if key.upper() == "PATHEXT"), None) + extensions = (env.get(key) if key else None) or ".COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC" + extensions = [ext for ext in extensions.split(os.pathsep) if ext] + if sys.version_info >= (3, 12): + extensions = [ext.rstrip(".") for ext in extensions] + matches_extension = any(command.upper().endswith(ext.upper()) for ext in extensions) + if sys.version_info < (3, 12) and matches_extension: + return [command] + names = [command + ext for ext in extensions] + return [command, *names] if matches_extension else names + + +def _windows_exact_executable(candidate: str) -> str | None: + # Windows os.access treats F_OK and X_OK alike. F_OK makes Python 3.12+ + # which() check the exact name before consulting live PATHEXT; discard any + # suffix match so only the captured PATHEXT drives our candidate ordering. + found = shutil.which(candidate, mode=os.F_OK) + # Python 3.12+ splits and rejoins qualified names, which can remove + # separators at that boundary. Do not normalize '..': it may cross links. + expected = os.path.join(*os.path.split(candidate)) if sys.version_info >= (3, 12) else candidate + if found is not None and os.path.normcase(found) == os.path.normcase(expected): + return found + return None + + +def dispatch_which(command: str) -> str | None: + """Find exactly the executable the integration dispatch will start.""" + dispatch = _dispatch.get() + if dispatch is None: + return shutil.which(command) + location, env = dispatch.location, dispatch.environment + dirname = os.path.dirname(command) + if dirname or (os.name == "nt" and os.path.splitdrive(command)[0]): + executable = _anchored(command, location) + if os.name != "nt": + return shutil.which(executable) + # Python 3.11 checks a qualified name directly; modern which() + # applies PATHEXT even when the name has a directory component. + if sys.version_info < (3, 12): + return _windows_exact_executable(executable) + for name in _windows_names(executable, env): + found = _windows_exact_executable(name) + if found is not None: + return found + return None + path_key = next((key for key in env if key.upper() == "PATH"), None) if os.name == "nt" else "PATH" + path = env.get(path_key) if path_key else None + if os.name != "nt": + if path is None: + try: + path = os.confstr("CS_PATH") + except (AttributeError, ValueError): + path = os.defpath + found = shutil.which(command, path=path) + return _anchored(found, location) if found else None + if path is None: + path = os.defpath + if not path: + return None + # Reproduce shutil.which's candidate ordering using the captured PATH, + # PATHEXT and native current-directory policy, not the live environment. + directories = ([location.cwd] if dispatch.windows_prepend_cwd else []) + path.split(os.pathsep) + names = _windows_names(command, env) + for directory in directories: + directory = _anchored(directory, location) + for name in names: + candidate = os.path.join(directory, name) + found = _windows_exact_executable(candidate) + if found is not None: + return found + return None diff --git a/src/specify_cli/integrations/base.py b/src/specify_cli/integrations/base.py index 41f5837f2a..77f827bf84 100644 --- a/src/specify_cli/integrations/base.py +++ b/src/specify_cli/integrations/base.py @@ -33,7 +33,14 @@ from .._toml_string import has_illegal_toml_control as _has_illegal_toml_control from ..events import install_integration_events, remove_integration_events from ._capture import run_captured -from ._context import dispatch_environment +from ._context import ( + dispatch_probe_options, + dispatch_which, + empty_path_bare_command, + fully_qualified_windows_executable, + integration_environment, + scoped_dispatch, +) if TYPE_CHECKING: from .manifest import IntegrationManifest @@ -708,6 +715,7 @@ def _build_dispatch_prompt( """ return self.build_command_invocation(command_name, args) + @scoped_dispatch def dispatch_command( self, command_name: str, @@ -761,7 +769,7 @@ def dispatch_command( ``build_exec_args()``, so builders that predate them keep working. *additional_context* uses child-only environment transport via - ``dispatch_environment()``; an inherited value is removed when unset. + ``integration_environment()``; an inherited value is removed when unset. Delivery requires a declaration and an installed hook. Overrides must preserve this isolation. See ``design/integration.md``, "Context delivery for command steps". @@ -806,15 +814,19 @@ def dispatch_command( # Windows: ``subprocess.run`` calls ``CreateProcess`` which does not # consult ``PATHEXT``, so a bare command name like ``cursor-agent`` # that resolves to ``cursor-agent.cmd`` fails with ``WinError 2``. - # Resolve via ``shutil.which`` (which does honor ``PATHEXT``) so - # ``.cmd``/``.bat`` shims work transparently. On POSIX this is a - # no-op for absolute paths and a harmless lookup otherwise. - resolved = shutil.which(exec_args[0]) + # Resolve against the same search environment passed to the child, + # including PATHEXT on Windows and caller-relative executable paths. + resolved = dispatch_which(exec_args[0]) if resolved: exec_args = [resolved, *exec_args[1:]] + elif not ( + empty_path_bare_command(exec_args[0]) + or fully_qualified_windows_executable(exec_args[0]) + ): + raise FileNotFoundError(f"Integration executable not found: {exec_args[0]}") cwd = str(project_root) if project_root else None - env = dispatch_environment(additional_context) + env = integration_environment(additional_context) if stream: # No timeout when streaming — the user sees live output and @@ -1154,7 +1166,7 @@ def resolve_python_interpreter(project_root: Path | None = None) -> str: if candidate.exists(): return relative for name in ("python3", "python"): - found = shutil.which(name) + found = dispatch_which(name) if not found: continue # On Windows, python3/python on PATH may be the Microsoft @@ -1224,6 +1236,7 @@ def _interpreter_runs(path: str) -> bool: stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15, + **dispatch_probe_options(), ).returncode == 0 ) diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 7dcbaf642f..69fee33147 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -30,7 +30,7 @@ import typer from .._capture import run_captured -from .._context import dispatch_environment +from .._context import integration_environment, scoped_dispatch from ..base import ( IntegrationBase, IntegrationOption, @@ -449,6 +449,7 @@ def build_command_invocation(self, command_name: str, args: str = "") -> str: return invocation return args or "" + @scoped_dispatch def dispatch_command( self, command_name: str, @@ -524,7 +525,7 @@ def dispatch_command( cli_args.extend(["--output-format", "json"]) cwd = str(project_root) if project_root else None - env = dispatch_environment(additional_context) + env = integration_environment(additional_context) if stream: try: diff --git a/src/specify_cli/integrations/installer.py b/src/specify_cli/integrations/installer.py index 10bf6f9213..cb155e0909 100644 --- a/src/specify_cli/integrations/installer.py +++ b/src/specify_cli/integrations/installer.py @@ -140,8 +140,10 @@ def project_dispatch(handler): @wraps(handler) def invoke(*args, **kwargs): context = signature.bind(*args, **kwargs).arguments["context"] + from ._context import integration_dispatch + root = Path(context.project_root) if context.project_root else Path.cwd() - with project_integrations(root): + with integration_dispatch(context.dispatch_location, fresh=True), project_integrations(root): return handler(*args, **kwargs) return invoke diff --git a/src/specify_cli/workflows/_execution.py b/src/specify_cli/workflows/_execution.py index 7cd2c1b51d..16383dd147 100644 --- a/src/specify_cli/workflows/_execution.py +++ b/src/specify_cli/workflows/_execution.py @@ -375,6 +375,7 @@ def child_context_for_call(parent, binding, definition): return StepContext( inputs=binding["inputs"], project_root=parent.project_root, + dispatch_location=parent.dispatch_location, run_id=parent.run_id, is_resume=parent.is_resume, inside_fan_out=parent.inside_fan_out, diff --git a/src/specify_cli/workflows/base.py b/src/specify_cli/workflows/base.py index dcf4dcf8a4..1a9e5e952c 100644 --- a/src/specify_cli/workflows/base.py +++ b/src/specify_cli/workflows/base.py @@ -13,6 +13,8 @@ from enum import Enum from typing import Any +from specify_cli.integrations._context import DispatchLocation + class StepStatus(str, Enum): """Status of a step execution.""" @@ -89,6 +91,9 @@ class StepContext: #: Workflow-level default context size. default_context_size: str | None = None + #: Caller location captured when run or resume began. + dispatch_location: DispatchLocation | None = None + @dataclass class StepResult: diff --git a/src/specify_cli/workflows/engine.py b/src/specify_cli/workflows/engine.py index 2aca2c1a9f..7307363e5e 100644 --- a/src/specify_cli/workflows/engine.py +++ b/src/specify_cli/workflows/engine.py @@ -1163,6 +1163,9 @@ def execute( ------- The final ``RunState`` after execution completes (or pauses). """ + from specify_cli.integrations._context import capture_dispatch_location + + dispatch_location = capture_dispatch_location() self._execution_state.set(None) self._load_integrations() dispatch_default_errors = _dispatch_default_errors(definition) @@ -1212,6 +1215,7 @@ def execute( default_model=definition.default_model, default_options=definition.default_options, project_root=str(self.project_root), + dispatch_location=dispatch_location, run_id=state.run_id, workflow_dir=workflow_dir, default_reasoning_effort=definition.default_reasoning_effort, @@ -1255,6 +1259,9 @@ def resume( workflow inputs. Keys not supplied keep their persisted values; an empty/``None`` ``inputs`` leaves the run's inputs unchanged. """ + from specify_cli.integrations._context import capture_dispatch_location + + dispatch_location = capture_dispatch_location() self._execution_state.set(None) self._load_integrations() state = RunState.load(run_id, self.project_root) @@ -1312,6 +1319,7 @@ def resume( default_model=definition.default_model, default_options=definition.default_options, project_root=str(self.project_root), + dispatch_location=dispatch_location, run_id=state.run_id, is_resume=True, workflow_dir=state.workflow_dir, diff --git a/src/specify_cli/workflows/step/command/__init__.py b/src/specify_cli/workflows/step/command/__init__.py index 57cd2d8a78..1d5295da5f 100644 --- a/src/specify_cli/workflows/step/command/__init__.py +++ b/src/specify_cli/workflows/step/command/__init__.py @@ -3,10 +3,10 @@ from __future__ import annotations import inspect -import shutil from pathlib import Path from typing import Any +from specify_cli.integrations._context import dispatch_which from specify_cli.integrations.base import ( DispatchSettingsError, check_dispatch_settings, @@ -392,8 +392,8 @@ def _try_dispatch( # Check if the CLI tool is actually installed. # Try the integration key first (covers most agents), then fall back # to exec_args[0] for agents whose executable differs. - cli_path = shutil.which(impl.key) - fallback_cli_path = shutil.which(exec_args[0]) if exec_args else None + cli_path = dispatch_which(impl.key) + fallback_cli_path = dispatch_which(exec_args[0]) if exec_args else None if cli_path is None and fallback_cli_path is None: return None diff --git a/src/specify_cli/workflows/step/prompt/__init__.py b/src/specify_cli/workflows/step/prompt/__init__.py index 9817147c0f..84ce284281 100644 --- a/src/specify_cli/workflows/step/prompt/__init__.py +++ b/src/specify_cli/workflows/step/prompt/__init__.py @@ -3,12 +3,11 @@ from __future__ import annotations import math -import shutil from pathlib import Path from typing import Any from specify_cli.integrations._capture import run_captured -from specify_cli.integrations._context import dispatch_environment +from specify_cli.integrations._context import DispatchPathError, dispatch_which, integration_environment from specify_cli.integrations.base import ( DispatchSettingsError, check_dispatch_settings, @@ -161,6 +160,14 @@ def execute(self, config: dict[str, Any], context: StepContext) -> StepResult: "Prompt", config, exc, dispatch.sources ), ) + except DispatchPathError as exc: + output["exit_code"] = 1 + output["dispatched"] = False + return StepResult( + status=StepStatus.FAILED, + output=output, + error=f"Prompt step {config.get('id', '?')!r}: {exc}", + ) if dispatch_result is not None: output["exit_code"] = dispatch_result["exit_code"] @@ -299,8 +306,8 @@ def _try_dispatch( # Check if the CLI tool is actually installed. # Try the integration key first (covers most agents), then fall back # to exec_args[0] for agents whose executable differs. - cli_path = shutil.which(impl.key) - fallback_cli_path = shutil.which(exec_args[0]) if exec_args else None + cli_path = dispatch_which(impl.key) + fallback_cli_path = dispatch_which(exec_args[0]) if exec_args else None if cli_path is None and fallback_cli_path is None: return None @@ -321,7 +328,7 @@ def _try_dispatch( import subprocess - env = dispatch_environment(None) + env = integration_environment(None) if capture_max_bytes is not None: try: return run_captured( diff --git a/tests/integrations/test_base.py b/tests/integrations/test_base.py index f901536248..d2fc2670d0 100644 --- a/tests/integrations/test_base.py +++ b/tests/integrations/test_base.py @@ -1349,6 +1349,7 @@ def test_unset_settings_reach_legacy_builders_unchanged( ): calls = [] monkeypatch.setattr("subprocess.run", _fake_run(calls)) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) integration = _LegacyStrictBuilder() result = integration.dispatch_command( @@ -1370,6 +1371,7 @@ def test_unset_settings_reach_legacy_builders_unchanged( def test_only_requested_settings_are_forwarded(self, monkeypatch, tmp_path): calls = [] monkeypatch.setattr("subprocess.run", _fake_run(calls)) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) _TranslatingIntegration().dispatch_command( "speckit.plan", project_root=tmp_path, reasoning_effort="high" diff --git a/tests/integrations/test_context.py b/tests/integrations/test_context.py index 1f7a5bb273..5961edcef6 100644 --- a/tests/integrations/test_context.py +++ b/tests/integrations/test_context.py @@ -20,6 +20,7 @@ @pytest.mark.parametrize("value", [None, "", "private-context"]) def test_dispatch_environment_all_paths(monkeypatch, integration, path, value): monkeypatch.setenv(ADDITIONAL_CONTEXT_ENV, "inherited") + monkeypatch.setenv("PATH", "./tools") seen = [] def run(args, **kwargs): @@ -43,6 +44,8 @@ def capture(args, **kwargs): impl = CopilotIntegration() monkeypatch.setattr(module, "run_captured", capture) + if integration == "base": + monkeypatch.setattr(module, "dispatch_which", lambda name: name) kwargs = {"stream": path == "stream"} if path == "bounded": kwargs["capture_max_bytes"] = 100 @@ -51,6 +54,8 @@ def capture(args, **kwargs): ) assert len(seen) == 1 assert seen[0][1].get(ADDITIONAL_CONTEXT_ENV) == (value or None) + assert seen[0][1]["PATH"] == os.path.join(os.getcwd(), "./tools") + assert os.environ["PATH"] == "./tools" assert os.environ[ADDITIONAL_CONTEXT_ENV] == "inherited" diff --git a/tests/integrations/test_dispatch_path.py b/tests/integrations/test_dispatch_path.py new file mode 100644 index 0000000000..e4bb584bc6 --- /dev/null +++ b/tests/integrations/test_dispatch_path.py @@ -0,0 +1,810 @@ +"""Regression tests for integration subprocess executable and hook lookup.""" + +import json +import os +import sys + +import pytest + +from specify_cli.events import install_integration_events, resolve_events +from specify_cli.integrations import INTEGRATION_REGISTRY +from specify_cli.integrations.manifest import IntegrationManifest +from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX shell and executable scripts") +def test_relative_path_survives_agent_and_generated_hook_cwd(tmp_path, monkeypatch): + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + (tools / "python3").symlink_to(sys.executable) + agent = tools / "fake-named" + agent.write_text( + f"#!{sys.executable}\n" + "import json, subprocess\n" + "from pathlib import Path\n" + "config = json.loads(Path('.agents/hooks.json').read_text())\n" + "hook = config['__speckit_event__']['SessionStart'][0]['command']\n" + "result = subprocess.run(['/bin/sh', '-c', hook], cwd='.agents', " + "input='{}', text=True, capture_output=True)\n" + "print(result.stdout, end='')\n" + "print(result.stderr, end='', file=__import__('sys').stderr)\n" + "raise SystemExit(result.returncode)\n", + encoding="utf-8", + ) + agent.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./tools") + install_integration_events( + impl, root, IntegrationManifest(impl.key, root), + resolve_events(impl.key, impl.config, root, None), + ) + result = impl.dispatch_command( + "speckit.plan", project_root=root, stream=False, + additional_context="caller context", + ) + assert result["exit_code"] == 0, result["stderr"] + assert json.loads(result["stdout"]) == { + "injectSteps": [{"systemMessage": {"systemMessage": "caller context"}}] + } + assert os.environ["PATH"] == "./tools" + + +def test_path_normalization_preserves_order_duplicates_and_dotdot(tmp_path, monkeypatch): + from specify_cli.integrations._context import integration_dispatch, integration_environment + + monkeypatch.chdir(tmp_path) + value = os.pathsep.join(["tools with spaces", "", "link/../bin", "tools with spaces", str(tmp_path)]) + monkeypatch.setenv("PATH", value) + with integration_dispatch(): + env = integration_environment("secret") + assert env["PATH"].split(os.pathsep) == [ + str(tmp_path / "tools with spaces"), str(tmp_path) + os.sep, + os.path.join(str(tmp_path), "link/../bin"), str(tmp_path / "tools with spaces"), str(tmp_path), + ] + assert env["SPECKIT_ADDITIONAL_CONTEXT"] == "secret" + assert os.environ["PATH"] == value + + +@pytest.mark.parametrize("value", [None, ""]) +def test_absent_and_empty_path_are_unchanged(monkeypatch, value): + from specify_cli.integrations._context import integration_dispatch, integration_environment + + if value is None: + monkeypatch.delenv("PATH", raising=False) + else: + monkeypatch.setenv("PATH", value) + with integration_dispatch(): + env = integration_environment(None) + assert env.get("PATH") == value + assert ("PATH" in env) == (value is not None) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +@pytest.mark.parametrize("kind", ["base", "prompt"]) +def test_relative_executable_override_selects_caller_not_project(tmp_path, monkeypatch, kind): + from specify_cli.integrations import INTEGRATION_REGISTRY + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.step.prompt import PromptStep + + root = tmp_path / "project" + caller = root / "caller" + caller.mkdir(parents=True) + for directory, text in [(root, "wrong"), (caller, "right")]: + executable = directory / "agent" + executable.write_text(f"#!/bin/sh\nprintf {text}", encoding="utf-8") + executable.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "/bin") + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: ["./agent"]) + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + if kind == "prompt": + result = PromptStep._try_dispatch( + "prompt", impl.key, None, StepContext(project_root=str(root)), capture_max_bytes=100 + ) + else: + result = impl.dispatch_command("plan", project_root=root, stream=False) + assert result["exit_code"] == 0 + assert result["stdout"] == "right" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_missing_cli_never_falls_through_to_project_directory(tmp_path, monkeypatch): + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.step.prompt import PromptStep + from specify_cli.integrations import INTEGRATION_REGISTRY + + root = tmp_path / "project" + caller = root / "caller" + caller.mkdir(parents=True) + executable = root / "fake-named" + executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + executable.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./missing") + with pytest.raises(FileNotFoundError): + impl.dispatch_command("plan", project_root=root) + assert PromptStep._try_dispatch("x", impl.key, None, StepContext(project_root=str(root))) is None + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows PATH and PATHEXT semantics") +def test_windows_native_path_and_executable_search(tmp_path, monkeypatch): + import shutil + import subprocess + from specify_cli.integrations._context import integration_dispatch, integration_environment, dispatch_which + + caller = tmp_path / "caller" + project = tmp_path / "project" + tools = caller / "tools" + tools.mkdir(parents=True) + project.mkdir() + # cmd.exe is self-contained with respect to the system DLL search path. + shutil.copyfile(os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe"), tools / "agent.exe") + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", ".\\tools") + (tools / "agent.cmd").write_text("@echo cmd\n", encoding="ascii") + monkeypatch.setenv("NoDefaultCurrentDirectoryInExePath", "1") + monkeypatch.setenv("PATHEXT", ".CMD;.EXE") + with integration_dispatch(): + found = dispatch_which("agent") + assert found and os.path.samefile(found, tools / "agent.cmd") + monkeypatch.setenv("PATHEXT", ".EXE;.CMD") + with integration_dispatch(): + env = integration_environment(None) + found = dispatch_which("agent") + assert found and os.path.samefile(found, tools / "agent.exe") + result = subprocess.run([found, "/c", "echo", "right"], cwd=project, env=env, capture_output=True, text=True) + assert result.returncode == 0 and result.stdout.strip() == "right" + assert os.environ["PATH"] == ".\\tools" + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows drive-relative paths") +def test_windows_native_drive_relative_and_rooted_path(tmp_path, monkeypatch): + from specify_cli.integrations._context import capture_dispatch_location, integration_dispatch, integration_environment + + monkeypatch.chdir(tmp_path) + drive = os.path.splitdrive(str(tmp_path))[0] + other = "D:" if drive.upper() != "D:" else "C:" + expected_other = os.path.abspath(other + ".") + location = capture_dispatch_location() + monkeypatch.setenv("PATH", os.pathsep.join([drive + "tools", other + "tools", "\\tools"])) + with integration_dispatch(location): + parts = integration_environment(None)["PATH"].split(os.pathsep) + assert parts == [ + os.path.join(str(tmp_path), "tools"), os.path.join(expected_other, "tools"), drive + "\\tools" + ] + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX shell syntax") +@pytest.mark.parametrize("override, expected", [(None, "./caller-tools"), ("./explicit", "./explicit")]) +def test_shell_path_is_not_normalized(tmp_path, monkeypatch, override, expected): + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.step.shell import ShellStep + + monkeypatch.setenv("PATH", "./caller-tools") + config = {"id": "shell", "run": 'printf %s "$PATH"'} + if override is not None: + config["env"] = {"PATH": override} + result = ShellStep().execute(config, StepContext(project_root=str(tmp_path))) + assert result.output["stdout"] == expected + assert os.environ["PATH"] == "./caller-tools" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX symlink and interpreter names") +def test_changed_interpreter_does_not_weaken_hook_verification(tmp_path, monkeypatch): + from specify_cli.events import context_delivery_error + from specify_cli.integrations._context import integration_dispatch + + root = tmp_path / "project" + caller = root / "caller" + first = caller / "first" + second = caller / "second" + first.mkdir(parents=True) + second.mkdir() + (first / "python3").symlink_to(sys.executable) + (second / "python").symlink_to(sys.executable) + impl = FakeNamedIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./first") + install_integration_events( + impl, root, IntegrationManifest(impl.key, root), + resolve_events(impl.key, impl.config, root, None), + ) + (root / ".specify/integration.json").write_text( + json.dumps({"default_integration": impl.key, "installed_integrations": [impl.key]}), encoding="utf-8" + ) + with integration_dispatch(): + assert context_delivery_error(impl, root) is None + monkeypatch.setenv("PATH", "./second") + with integration_dispatch(): + assert "missing or outdated" in context_delivery_error(impl, root) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX shell and executable scripts") +def test_ordinary_generated_hook_and_its_tool_use_caller_path(tmp_path, monkeypatch): + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + (tools / "python3").symlink_to(sys.executable) + tool = tools / "ordinary-tool" + tool.write_text("#!/bin/sh\nprintf ordinary", encoding="utf-8") + tool.chmod(0o755) + agent = tools / "fake-named" + agent.write_text( + f"#!{sys.executable}\n" + "import json, subprocess\nfrom pathlib import Path\n" + "config=json.loads(Path('.agents/hooks.json').read_text())\n" + "hook=config['__speckit_event__']['SessionStart'][0]['command']\n" + "r=subprocess.run(['/bin/sh','-c',hook],cwd='.agents',input='{}',text=True,capture_output=True)\n" + "print(r.stdout,end='');print(r.stderr,end='',file=__import__('sys').stderr)\n" + "raise SystemExit(r.returncode)\n", encoding="utf-8" + ) + agent.chmod(0o755) + template = root / ".specify/templates/commands/probe.md" + template.parent.mkdir(parents=True) + template.write_text("---\nscripts:\n sh: scripts/probe.sh\n---\n", encoding="utf-8") + script = root / ".specify/scripts/probe.sh" + script.parent.mkdir(parents=True) + script.write_text("#!/bin/sh\nordinary-tool\n", encoding="utf-8") + script.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./tools") + install_integration_events( + impl, root, IntegrationManifest(impl.key, root), + {"session_start": [{"command": "speckit.probe"}]}, + ) + result = impl.dispatch_command("plan", project_root=root, stream=False) + assert result["exit_code"] == 0, result["stderr"] + assert json.loads(result["stdout"]) == { + "injectSteps": [{"systemMessage": {"systemMessage": "ordinary"}}] + } + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_workflow_run_and_resume_capture_their_own_caller(tmp_path, monkeypatch): + from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine + + root = tmp_path / "project" + first = root / "first" + second = root / "second" + for directory in (first, second): + tools = directory / "tools" + tools.mkdir(parents=True) + executable = tools / "fake-named" + executable.write_text( + "#!/bin/sh\nif [ ! -e .specify/once ]; then : > .specify/once; exit 1; fi\nprintf %s \"$PATH\"\n", + encoding="utf-8", + ) + executable.chmod(0o755) + (root / ".specify").mkdir() + impl = FakeNamedIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.setenv("PATH", "./tools") + definition = WorkflowDefinition({ + "schema_version": "1.0", + "workflow": {"id": "path-resume", "name": "Path", "version": "1.0.0", "integration": impl.key}, + "steps": [{"id": "ask", "command": "plan", "capture": True}], + }) + engine = WorkflowEngine(root) + monkeypatch.setattr(engine, "_load_integrations", lambda: os.chdir(root)) + monkeypatch.chdir(first) + state = engine.execute(definition) + assert state.status.value == "failed" + monkeypatch.chdir(second) + state = engine.resume(state.run_id) + assert state.status.value == "completed" + assert state.step_results["ask"]["output"]["stdout"] == os.path.join(str(second), "./tools") + assert os.environ["PATH"] == "./tools" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_fan_out_and_child_workflow_keep_run_caller(tmp_path, monkeypatch): + from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine + from tests.workflows.test_composition_execution import install + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + agent = tools / "fake-named" + agent.write_text('#!/bin/sh\nprintf %s "$PATH"\n', encoding="utf-8") + agent.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.setenv("PATH", "./tools") + child = WorkflowDefinition({ + "workflow": {"id": "child", "name": "Child", "integration": impl.key}, + "steps": [{"id": "child-step", "command": "plan", "capture": True}], + "outputs": {"path": {"value": "{{ steps.child-step.output.stdout }}"}}, + }) + install(root, child) + definition = WorkflowDefinition({ + "workflow": {"id": "parent", "name": "Parent", "integration": impl.key}, + "steps": [ + {"id": "fan", "type": "fan-out", "items": ["a", "b"], "max_concurrency": 2, + "step": {"id": "ask", "command": "plan", "capture": True}}, + {"id": "call", "type": "workflow", "workflow": "child"}, + ], + }) + engine = WorkflowEngine(root) + monkeypatch.setattr(engine, "_load_integrations", lambda: os.chdir(root)) + monkeypatch.chdir(caller) + state = engine.execute(definition) + assert state.status.value == "completed" + expected = os.path.join(str(caller), "./tools") + assert state.step_results["call"]["output"]["path"] == expected + assert [item["stdout"] for item in state.step_results["fan"]["output"]["results"]] == [expected, expected] + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX symlink traversal") +def test_path_symlink_dotdot_keeps_kernel_traversal(tmp_path, monkeypatch): + root = tmp_path / "project" + caller = root / "caller" + nested = tmp_path / "external/nested" + real_bin = tmp_path / "external/bin" + wrong_bin = caller / "bin" + for directory in (caller, nested, real_bin, wrong_bin): + directory.mkdir(parents=True, exist_ok=True) + (caller / "link").symlink_to(nested, target_is_directory=True) + for directory, text in ((real_bin, "right"), (wrong_bin, "wrong")): + exe = directory / "fake-named" + exe.write_text(f"#!/bin/sh\nprintf {text}", encoding="utf-8") + exe.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "link/../bin") + result = FakeNamedIntegration().dispatch_command("plan", project_root=root, stream=False) + assert result["stdout"] == "right" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_docker_plugin_probe_and_dispatch_share_search_environment(tmp_path, monkeypatch): + from specify_cli.integrations.docker_agent import DockerAgentIntegration + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + docker = tools / "docker" + docker.write_text( + '#!/bin/sh\nif [ "$2" = version ]; then printf %s "$PATH" > probe-path; exit 0; fi\n' + 'printf "run:%s" "$PATH"\n', encoding="utf-8" + ) + docker.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./tools") + result = DockerAgentIntegration().dispatch_command( + "plan", project_root=root, stream=False, integration_args=["agent.yaml"] + ) + expected = os.path.join(str(caller), "./tools") + assert (caller / "probe-path").read_text(encoding="utf-8") == expected + assert result["exit_code"] == 0 + assert result["stdout"] == "run:" + expected + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH separator in directory name") +def test_path_separator_in_caller_never_selects_decoy(tmp_path, monkeypatch): + parent = tmp_path / "work" + caller = tmp_path / "work:space" + (caller / "tools").mkdir(parents=True) + parent.mkdir() + for directory, output in ((parent, "decoy"), (caller / "tools", "correct")): + executable = directory / "fake-named" + executable.write_text(f'#!/bin/sh\nprintf {output} > "$PWD/agent-ran"', encoding="utf-8") + executable.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "tools") + with pytest.raises(ValueError, match="PATH.*separator"): + FakeNamedIntegration().dispatch_command("plan", project_root=caller, stream=False) + assert not (caller / "agent-ran").exists() + assert os.environ["PATH"] == "tools" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX execvpe with an empty PATH") +def test_direct_dispatch_with_empty_path_keeps_project_cwd_lookup(tmp_path, monkeypatch): + project = tmp_path / "project" + caller = tmp_path / "caller" + project.mkdir() + caller.mkdir() + executable = project / "fake-named" + executable.write_text("#!/bin/sh\nprintf project", encoding="utf-8") + executable.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "") + result = FakeNamedIntegration().dispatch_command("plan", project_root=project, stream=False) + assert result["exit_code"] == 0 + assert result["stdout"] == "project" + assert os.environ["PATH"] == "" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH separator in directory name") +@pytest.mark.parametrize("kind", ["command", "prompt"]) +def test_workflow_reports_unrepresentable_path(tmp_path, monkeypatch, kind): + from specify_cli.workflows.base import StepContext, StepStatus + from specify_cli.workflows.step.command import CommandStep + from specify_cli.workflows.step.prompt import PromptStep + + caller = tmp_path / "work:space" + caller.mkdir() + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "tools") + monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) + context = StepContext(project_root=str(caller), default_integration="fake-named") + result = ( + CommandStep().execute({"id": "ask", "command": "plan"}, context) + if kind == "command" + else PromptStep().execute({"id": "ask", "prompt": "hello"}, context) + ) + assert result.status == StepStatus.FAILED + assert "PATH" in result.error and "separator" in result.error + assert result.output["dispatched"] is False + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX execvpe with an empty PATH") +def test_empty_path_does_not_redirect_missing_explicit_override(tmp_path, monkeypatch): + project = tmp_path / "project" + caller = tmp_path / "caller" + project.mkdir() + caller.mkdir() + executable = project / "agent" + executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + executable.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: ["./agent"]) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "") + with pytest.raises(FileNotFoundError): + impl.dispatch_command("plan", project_root=project, stream=False) + + +@pytest.mark.skipif(os.name != "nt" or sys.version_info >= (3, 12), reason="native Windows Python 3.11") +def test_windows_311_literal_dot_keeps_path_order(tmp_path, monkeypatch): + import shutil + from specify_cli.integrations._context import dispatch_which, integration_dispatch + + caller = tmp_path / "caller" + trusted = tmp_path / "trusted" + caller.mkdir() + trusted.mkdir() + cmd = os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe") + for directory in (caller, trusted): + shutil.copyfile(cmd, directory / "agent.exe") + monkeypatch.chdir(caller) + monkeypatch.setenv("Path", str(trusted) + ";.") + monkeypatch.setenv("PATHEXT", ".EXE") + with integration_dispatch(): + found = dispatch_which("agent") + assert found and os.path.samefile(found, trusted / "agent.exe") + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows executable and environment semantics") +def test_windows_snapshot_explicit_override_and_invalid_path_entry(tmp_path, monkeypatch): + import shutil + import subprocess + from specify_cli.integrations._context import dispatch_which, integration_dispatch + + caller = tmp_path / "caller" + trusted = tmp_path / "trusted" + caller.mkdir() + trusted.mkdir() + cmd = os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe") + for directory in (caller, trusted): + shutil.copyfile(cmd, directory / "agent.exe") + (trusted / "agent.cmd").write_text("@echo cmd\r\n", encoding="ascii") + (trusted / "agent.exe.cmd").write_text("@echo wrong\r\n", encoding="ascii") + monkeypatch.chdir(caller) + monkeypatch.setenv("Path", "1:bad;" + str(trusted)) + monkeypatch.setenv("NoDefaultCurrentDirectoryInExePath", "1") + monkeypatch.setenv("PATHEXT", ".CMD;.EXE") + with integration_dispatch(): + monkeypatch.setenv("PATHEXT", ".EXE;.CMD") + monkeypatch.delenv("NoDefaultCurrentDirectoryInExePath") + found = dispatch_which("agent") + if sys.version_info >= (3, 12): + assert found and os.path.samefile(found, trusted / "agent.cmd") + run = subprocess.run([found], capture_output=True, text=True, cwd=trusted) + assert run.returncode == 0 and run.stdout.strip() == "cmd" + monkeypatch.setenv("PATHEXT", ".CMD") + with integration_dispatch(): + found = dispatch_which(str(trusted / "agent.exe")) + expected = trusted / ("agent.exe" if sys.version_info < (3, 12) else "agent.exe.cmd") + assert found and os.path.samefile(found, expected) + (caller / "agent.exe").unlink() + with integration_dispatch(): + found = dispatch_which("agent.exe") + assert found and os.path.samefile(found, trusted / "agent.exe.cmd") + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows quoted PATH behavior") +def test_windows_quoted_path_does_not_hide_later_valid_entry(tmp_path, monkeypatch): + import shutil + from specify_cli.integrations._context import dispatch_which, integration_dispatch + + caller = tmp_path / "caller" + trusted = tmp_path / "trusted" + caller.mkdir() + trusted.mkdir() + shutil.copyfile(os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe"), trusted / "agent.exe") + monkeypatch.chdir(caller) + monkeypatch.setenv("Path", f'"{caller}";{trusted}') + monkeypatch.setenv("PATHEXT", ".EXE") + monkeypatch.setenv("NoDefaultCurrentDirectoryInExePath", "1") + with integration_dispatch(): + found = dispatch_which("agent") + assert found and os.path.samefile(found, trusted / "agent.exe") + + +@pytest.mark.skipif(os.name != "nt", reason="Windows PowerShell 5.1 generated hook") +def test_windows_powershell_51_generated_hook_uses_dispatch_path(tmp_path, monkeypatch): + import subprocess + from specify_cli.integrations._context import integration_dispatch, integration_environment + from tests.fixtures.context_delivery import FakeContextIntegration + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + (tools / "python.cmd").write_text(f'@echo off\r\n"{sys.executable}" %*\r\n', encoding="utf-8") + impl = FakeContextIntegration() + impl.events_cwd_is_config_dir = True + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", ".\\tools") + install_integration_events( + impl, root, IntegrationManifest(impl.key, root), + resolve_events(impl.key, impl.config, root, None), + ) + hooks = json.loads((root / ".fake/hooks.json").read_text(encoding="utf-8")) + hook = hooks["hooks"]["sessionStart"][0]["powershell"] + powershell = os.path.join(os.environ["SystemRoot"], "System32", "WindowsPowerShell", "v1.0", "powershell.exe") + version = subprocess.run( + [powershell, "-NoProfile", "-NonInteractive", "-Command", "$PSVersionTable.PSVersion.Major"], + capture_output=True, text=True, check=True, + ) + assert version.stdout.strip() == "5" + with integration_dispatch(): + env = integration_environment("windows context") + result = subprocess.run( + [powershell, "-NoProfile", "-NonInteractive", "-Command", hook], + cwd=root / ".fake", env=env, input="{}", capture_output=True, text=True, + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == {"additionalContext": "windows context"} + assert os.environ["PATH"] == ".\\tools" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX execvpe with an empty PATH") +def test_direct_copilot_with_empty_path_keeps_project_cwd_lookup(tmp_path, monkeypatch): + from specify_cli.integrations.copilot import CopilotIntegration + + project = tmp_path / "project" + caller = tmp_path / "caller" + project.mkdir() + caller.mkdir() + executable = project / "copilot" + executable.write_text("#!/bin/sh\nprintf project", encoding="utf-8") + executable.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.delenv("SPECKIT_INTEGRATION_COPILOT_EXECUTABLE", raising=False) + monkeypatch.setenv("PATH", "") + result = CopilotIntegration().dispatch_command("plan", project_root=project, stream=False) + assert result["exit_code"] == 0 + assert result["stdout"] == "project" + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows exact executable lookup") +def test_windows_qualified_executable_returns_checked_spelling(tmp_path, monkeypatch): + import shutil + from specify_cli.integrations._context import dispatch_which, integration_dispatch + + trusted = tmp_path / "trusted" + trusted.mkdir() + shutil.copyfile(os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe"), trusted / "agent.exe") + monkeypatch.setenv("PATH", str(trusted)) + monkeypatch.setenv("PATHEXT", ".EXE;.CMD") + candidate = str(trusted) + "\\\\agent.exe" + with integration_dispatch(): + selected = dispatch_which(candidate) + checked = os.path.join(*os.path.split(candidate)) if sys.version_info >= (3, 12) else candidate + assert selected == checked + assert os.path.samefile(selected, trusted / "agent.exe") + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows PATHEXT semantics") +def test_windows_qualified_extensionless_executable_version_precedence(tmp_path, monkeypatch): + from specify_cli.integrations._context import dispatch_which, integration_dispatch + + trusted = tmp_path / "trusted" + trusted.mkdir() + (trusted / "agent").write_text("not a Windows executable", encoding="utf-8") + (trusted / "agent.cmd").write_text("@echo selected\r\n", encoding="ascii") + monkeypatch.setenv("PATH", str(trusted)) + monkeypatch.setenv("PATHEXT", ".CMD;.EXE") + candidate = str(trusted / "agent") + with integration_dispatch(): + selected = dispatch_which(candidate) + expected = trusted / ("agent" if sys.version_info < (3, 12) else "agent.cmd") + assert selected and os.path.samefile(selected, expected) + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows Copilot argv baseline") +def test_windows_copilot_keeps_main_bare_argv_and_stabilizes_child_path(tmp_path, monkeypatch): + from types import SimpleNamespace + from specify_cli.integrations.copilot import CopilotIntegration + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + (tools / "copilot.cmd.exe").write_text("decoy", encoding="ascii") + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", ".\\tools") + monkeypatch.setenv("PATHEXT", ".CMD;.EXE") + monkeypatch.delenv("SPECKIT_INTEGRATION_COPILOT_EXECUTABLE", raising=False) + monkeypatch.setenv("SPECKIT_ADDITIONAL_CONTEXT", "parent") + calls = [] + + def run(args, **kwargs): + calls.append((list(args), kwargs)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + result = CopilotIntegration().dispatch_command("plan", project_root=root, stream=False) + assert result["exit_code"] == 0 + assert calls[0][0][0] == "copilot.cmd" + assert calls[0][1]["env"]["PATH"] == os.path.join(str(caller), ".\\tools") + assert "SPECKIT_ADDITIONAL_CONTEXT" not in calls[0][1]["env"] + + +@pytest.mark.skipif( + os.name != "nt" or sys.version_info < (3, 12), + reason="native Windows extended path lookup on Python 3.12+", +) +def test_windows_extended_executable_starts_checked_spelling(tmp_path, monkeypatch): + import shutil + import subprocess + from specify_cli.integrations._context import dispatch_which, integration_dispatch, integration_environment + + trusted = tmp_path / "trusted" + trusted.mkdir() + shutil.copyfile(os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe"), trusted / "agent.exe") + path = str(trusted) + extended = "\\\\?\\UNC\\" + path[2:] if path.startswith("\\\\") else "\\\\?\\" + path + candidate = extended + "\\\\agent.exe" + checked = os.path.join(*os.path.split(candidate)) + monkeypatch.setenv("PATH", str(trusted)) + monkeypatch.setenv("PATHEXT", ".EXE;.CMD") + with integration_dispatch(): + selected = dispatch_which(candidate) + assert selected == checked + result = subprocess.run( + [selected, "/c", "echo", "checked"], env=integration_environment(None), + capture_output=True, text=True, + ) + assert result.returncode == 0 + assert result.stdout.strip() == "checked" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_copilot_keeps_bare_argv_and_stabilizes_child_path(tmp_path, monkeypatch): + from specify_cli.integrations.copilot import CopilotIntegration + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + agent = tools / "copilot" + agent.write_text('#!/bin/sh\nprintf "%s|" "$SPECKIT_ADDITIONAL_CONTEXT"\nhelper\n', encoding="utf-8") + agent.chmod(0o755) + helper = tools / "helper" + helper.write_text("#!/bin/sh\nprintf helper\n", encoding="utf-8") + helper.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./tools") + monkeypatch.setenv("SPECKIT_ADDITIONAL_CONTEXT", "parent") + monkeypatch.delenv("SPECKIT_INTEGRATION_COPILOT_EXECUTABLE", raising=False) + result = CopilotIntegration().dispatch_command( + "plan", project_root=root, stream=False, additional_context="private" + ) + assert result["exit_code"] == 0, result["stderr"] + assert result["stdout"] == "private|helper" + assert os.environ["PATH"] == "./tools" + assert os.environ["SPECKIT_ADDITIONAL_CONTEXT"] == "parent" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_copilot_relative_path_missing_does_not_find_project_executable(tmp_path, monkeypatch): + from specify_cli.integrations.copilot import CopilotIntegration + + root = tmp_path / "project" + caller = root / "caller" + caller.mkdir(parents=True) + decoy = root / "copilot" + decoy.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + decoy.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./missing") + monkeypatch.delenv("SPECKIT_INTEGRATION_COPILOT_EXECUTABLE", raising=False) + with pytest.raises(FileNotFoundError): + CopilotIntegration().dispatch_command("plan", project_root=root, stream=False) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_copilot_relative_override_keeps_main_child_cwd_behavior(tmp_path, monkeypatch): + from specify_cli.integrations.copilot import CopilotIntegration + + root = tmp_path / "project" + caller = root / "caller" + caller.mkdir(parents=True) + for directory, output in ((caller, "caller"), (root, "project")): + exe = directory / "agent" + exe.write_text(f"#!/bin/sh\nprintf {output}", encoding="utf-8") + exe.chmod(0o755) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "/bin") + monkeypatch.setenv("SPECKIT_INTEGRATION_COPILOT_EXECUTABLE", "./agent") + result = CopilotIntegration().dispatch_command("plan", project_root=root, stream=False) + assert result["exit_code"] == 0 + assert result["stdout"] == "project" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") +def test_prompt_missing_fallback_keeps_main_integration_key_behavior(tmp_path, monkeypatch): + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.step.prompt import PromptStep + + root = tmp_path / "project" + caller = root / "caller" + tools = caller / "tools" + tools.mkdir(parents=True) + cli = tools / "fake-named" + cli.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + cli.chmod(0o755) + fallback = root / "agent" + fallback.write_text("#!/bin/sh\nprintf project", encoding="utf-8") + fallback.chmod(0o755) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: ["./agent"]) + monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + monkeypatch.chdir(caller) + monkeypatch.setenv("PATH", "./tools") + result = PromptStep._try_dispatch( + "prompt", impl.key, None, StepContext(project_root=str(root)), capture_max_bytes=100 + ) + assert result["exit_code"] == 0 + assert result["stdout"] == "project" + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows fully qualified executable dispatch") +def test_windows_base_fully_qualified_executable_falls_back_to_os(tmp_path, monkeypatch): + import shutil + + agent = tmp_path / "agent.exe" + shutil.copyfile(os.path.join(os.environ["SystemRoot"], "System32", "cmd.exe"), agent) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: [str(agent), "/d", "/c", "echo", "absolute"]) + monkeypatch.setenv("PATH", str(tmp_path)) + monkeypatch.setenv("PATHEXT", ".CMD") + result = impl.dispatch_command("plan", project_root=tmp_path, stream=False) + assert result["exit_code"] == 0 + assert result["stdout"].strip() == "absolute" + + +@pytest.mark.skipif(os.name != "nt", reason="native Windows missing executable error") +def test_windows_base_missing_fully_qualified_executable_reports_os_error(tmp_path, monkeypatch): + agent = tmp_path / "missing.exe" + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: [str(agent)]) + monkeypatch.setenv("PATH", str(tmp_path)) + monkeypatch.setenv("PATHEXT", ".CMD") + with pytest.raises(FileNotFoundError) as error: + impl.dispatch_command("plan", project_root=tmp_path, stream=False) + assert error.value.winerror == 2 diff --git a/tests/integrations/test_dispatch_windows_lookup.py b/tests/integrations/test_dispatch_windows_lookup.py new file mode 100644 index 0000000000..ee186b19c2 --- /dev/null +++ b/tests/integrations/test_dispatch_windows_lookup.py @@ -0,0 +1,458 @@ +"""Portable simulations of documented Windows executable lookup semantics.""" + +import ntpath +import os +import sys +from types import SimpleNamespace + +import pytest + +from specify_cli.integrations import _context as dispatch + + +@pytest.fixture +def windows_lookup(monkeypatch): + env = {"Path": r"C:\trusted", "PATHEXT": ".CMD;.EXE"} + files = set() + fake_sys = SimpleNamespace(version_info=(3, 14)) + fake_os = SimpleNamespace( + name="nt", path=ntpath, pathsep=";", curdir=".", defpath=r".;C:\bin", + environ=env, F_OK=os.F_OK, X_OK=os.X_OK, + ) + location = dispatch.DispatchLocation(r"C:\caller", {"C:": r"C:\caller"}) + + def access(path, mode): + return ntpath.normcase(path) in files + + def which(candidate, **kwargs): + if fake_sys.version_info < (3, 12): + return candidate if access(candidate, 0) else None + extensions = [ext.rstrip(".") for ext in env.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") if ext] + names = [candidate + ext for ext in extensions] + if not (kwargs.get("mode", os.F_OK | os.X_OK) & os.X_OK) or any( + candidate.upper().endswith(ext.upper()) for ext in extensions + ): + names.insert(0, candidate) + return next((name for name in names if access(name, 0)), None) + + def needs_cwd(command): + return "NoDefaultCurrentDirectoryInExePath" not in env + + monkeypatch.setattr(dispatch, "os", fake_os) + monkeypatch.setattr(dispatch, "sys", fake_sys) + monkeypatch.setattr(dispatch.shutil, "which", which) + monkeypatch.setitem(sys.modules, "_winapi", SimpleNamespace(NeedCurrentDirectoryForExePath=needs_cwd)) + return env, files, fake_sys, location + + +def test_windows_311_literal_dot_keeps_its_path_position(windows_lookup): + env, files, fake_sys, location = windows_lookup + fake_sys.version_info = (3, 11) + env["Path"] = r"C:\trusted;." + env["PATHEXT"] = ".EXE" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.EXE", r"C:\caller\agent.EXE"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which("agent") == r"C:\trusted\agent.EXE" + + +def test_windows_pathext_uses_dispatch_snapshot(windows_lookup): + env, files, _, location = windows_lookup + env["NoDefaultCurrentDirectoryInExePath"] = "1" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.CMD", r"C:\trusted\agent.EXE"])) + with dispatch.integration_dispatch(location): + env["PATHEXT"] = ".EXE;.CMD" + assert dispatch.dispatch_which("agent") == r"C:\trusted\agent.CMD" + + +def test_windows_current_directory_policy_uses_dispatch_snapshot(windows_lookup): + env, files, _, location = windows_lookup + env["NoDefaultCurrentDirectoryInExePath"] = "1" + env["PATHEXT"] = ".EXE" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.EXE", r"C:\caller\agent.EXE"])) + with dispatch.integration_dispatch(location): + del env["NoDefaultCurrentDirectoryInExePath"] + assert dispatch.dispatch_which("agent") == r"C:\trusted\agent.EXE" + + +def test_windows_qualified_suffixed_name_follows_main_pathext(windows_lookup): + env, files, fake_sys, location = windows_lookup + env["PATHEXT"] = ".CMD" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.exe", r"C:\trusted\agent.exe.CMD"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent.exe") == r"C:\trusted\agent.exe.CMD" + fake_sys.version_info = (3, 11) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent.exe") == r"C:\trusted\agent.exe" + + +def test_windows_unrecognized_drive_prefix_does_not_raise(windows_lookup, monkeypatch): + _, _, _, location = windows_lookup + splitdrive = ntpath.splitdrive + monkeypatch.setattr(ntpath, "splitdrive", lambda value: ("1:", "bad") if value == "1:bad" else splitdrive(value)) + assert dispatch._anchored("1:bad", location) == "1:bad" + + +def test_windows_311_prepends_caller_if_dot_absent(windows_lookup): + env, files, fake_sys, location = windows_lookup + fake_sys.version_info = (3, 11) + env["NoDefaultCurrentDirectoryInExePath"] = "1" + env["PATHEXT"] = ".EXE" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.EXE", r"C:\caller\agent.EXE"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which("agent") == r"C:\caller\agent.EXE" + + +def test_windows_prepend_policy_is_not_changed_after_snapshot(windows_lookup): + env, files, _, location = windows_lookup + env["PATHEXT"] = ".EXE" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.EXE", r"C:\caller\agent.EXE"])) + with dispatch.integration_dispatch(location): + env["NoDefaultCurrentDirectoryInExePath"] = "1" + assert dispatch.dispatch_which("agent") == r"C:\caller\agent.EXE" + + +def test_windows_missing_qualified_exe_uses_main_pathext_fallback(windows_lookup): + env, files, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + files.add(ntpath.normcase(r"C:\trusted\agent.exe.CMD")) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent.exe") == r"C:\trusted\agent.exe.CMD" + + +def test_windows_extensionless_override_uses_captured_pathext(windows_lookup): + env, files, _, location = windows_lookup + files.update(map(ntpath.normcase, [r"C:\trusted\agent.CMD", r"C:\trusted\agent.EXE"])) + with dispatch.integration_dispatch(location): + env["PATHEXT"] = ".EXE;.CMD" + assert dispatch.dispatch_which(r"C:\trusted\agent") == r"C:\trusted\agent.CMD" + + +def test_windows_invalid_drive_entry_does_not_hide_valid_directory(windows_lookup): + env, files, _, location = windows_lookup + env["Path"] = r"1:bad;C:\trusted" + env["PATHEXT"] = ".EXE" + env["NoDefaultCurrentDirectoryInExePath"] = "1" + files.add(ntpath.normcase(r"C:\trusted\agent.EXE")) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which("agent") == r"C:\trusted\agent.EXE" + + +def test_windows_bare_suffixed_name_uses_main_pathext_fallback(windows_lookup): + env, files, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + env["NoDefaultCurrentDirectoryInExePath"] = "1" + files.update(map(ntpath.normcase, [r"C:\trusted\agent.exe", r"C:\trusted\agent.exe.CMD"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which("agent.exe") == r"C:\trusted\agent.exe.CMD" + + +def test_windows_unrepresentable_caller_path_fails_without_emitting_child_environment(windows_lookup): + env, _, _, _ = windows_lookup + env["Path"] = "tools" + location = dispatch.DispatchLocation(r"C:\semi;colon", {"C:": r"C:\semi;colon"}) + with pytest.raises(dispatch.DispatchPathError, match="PATH.*separator"): + with dispatch.integration_dispatch(location): + pytest.fail("must reject before yielding a child environment") + + +def test_windows_qualified_exact_executable_returns_checked_spelling(windows_lookup, monkeypatch): + env, files, _, location = windows_lookup + env["PATHEXT"] = ".EXE;.CMD" + files.add(ntpath.normcase(r"C:\trusted\agent.exe")) + + def which_roundtrip(candidate, **kwargs): + candidate = ntpath.join(*ntpath.split(candidate)) + return candidate if ntpath.normcase(candidate) in files else None + + monkeypatch.setattr(dispatch.shutil, "which", which_roundtrip) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\\agent.exe") == r"C:\trusted\agent.exe" + + +def test_windows_modern_qualified_extensionless_prefers_pathext(windows_lookup): + _, files, _, location = windows_lookup + files.update(map(ntpath.normcase, [r"C:\trusted\agent", r"C:\trusted\agent.CMD"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent") == r"C:\trusted\agent.CMD" + + +def test_windows_311_qualified_extensionless_keeps_exact_first(windows_lookup): + _, files, fake_sys, location = windows_lookup + fake_sys.version_info = (3, 11) + files.update(map(ntpath.normcase, [r"C:\trusted\agent", r"C:\trusted\agent.CMD"])) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent") == r"C:\trusted\agent" + + +def test_windows_modern_qualified_extensionless_does_not_use_only_unsuffixed(windows_lookup): + _, files, _, location = windows_lookup + files.add(ntpath.normcase(r"C:\trusted\agent")) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent") is None + + +def test_windows_path_lookup_returns_checked_spelling_in_path_entry(windows_lookup, monkeypatch): + env, files, _, location = windows_lookup + env["Path"] = "C:\\trusted\\\\" + env["NoDefaultCurrentDirectoryInExePath"] = "1" + files.add(ntpath.normcase(r"C:\trusted\agent.exe")) + + def which_roundtrip(candidate, **kwargs): + candidate = ntpath.join(*ntpath.split(candidate)) + return candidate if ntpath.normcase(candidate) in files else None + + monkeypatch.setattr(dispatch.shutil, "which", which_roundtrip) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which("agent.exe") == r"C:\trusted\agent.exe" + + +def test_windows_exact_comparison_does_not_collapse_dotdot(windows_lookup, monkeypatch): + _, _, _, location = windows_lookup + candidate = r"C:\link\..\bin\\agent.exe" + monkeypatch.setattr(dispatch.shutil, "which", lambda candidate, **kwargs: r"C:\bin\agent.exe") + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(candidate) is None + + +def test_windows_311_qualified_extensionless_miss_follows_main(windows_lookup): + _, files, fake_sys, location = windows_lookup + fake_sys.version_info = (3, 11) + files.add(ntpath.normcase(r"C:\trusted\agent.CMD")) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(r"C:\trusted\agent") is None + + +@pytest.mark.parametrize("route", ["qualified", "path", "qualified-pathext"]) +def test_windows_extended_path_returns_the_checked_executable(windows_lookup, monkeypatch, route): + env, files, _, location = windows_lookup + env["Path"] = "\\\\?\\C:\\trusted\\\\" + env["PATHEXT"] = ".CMD;.EXE" + env["NoDefaultCurrentDirectoryInExePath"] = "1" + expected = r"\\?\C:\trusted\agent.CMD" if route == "qualified-pathext" else r"\\?\C:\trusted\agent.exe" + files.add(ntpath.normcase(expected)) + + def which_roundtrip(candidate, **kwargs): + candidate = ntpath.join(*ntpath.split(candidate)) + return candidate if ntpath.normcase(candidate) in files else None + + monkeypatch.setattr(dispatch.shutil, "which", which_roundtrip) + with dispatch.integration_dispatch(location): + if route == "qualified": + selected = dispatch.dispatch_which(r"\\?\C:\trusted\\agent.exe") + elif route == "path": + selected = dispatch.dispatch_which("agent.exe") + else: + selected = dispatch.dispatch_which(r"\\?\C:\trusted\\agent") + assert selected == expected + + +def test_windows_311_exact_executable_preserves_checked_spelling(windows_lookup, monkeypatch): + _, _, fake_sys, location = windows_lookup + fake_sys.version_info = (3, 11) + candidate = r"\\?\C:\trusted\\agent.exe" + monkeypatch.setattr(dispatch.shutil, "which", lambda candidate, **kwargs: candidate) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(candidate) == candidate + + +def test_windows_checked_extended_path_does_not_collapse_dotdot(windows_lookup, monkeypatch): + _, _, _, location = windows_lookup + candidate = r"\\?\C:\link\..\bin\\agent.exe" + checked = r"\\?\C:\link\..\bin\agent.exe" + monkeypatch.setattr(dispatch.shutil, "which", lambda candidate, **kwargs: ntpath.join(*ntpath.split(candidate))) + with dispatch.integration_dispatch(location): + assert dispatch.dispatch_which(candidate) == checked + + +@pytest.mark.parametrize( + ("decoy", "probe_name", "baseline_argv0"), + [ + (r"C:\trusted\copilot.exe.CMD", "copilot.exe", "copilot.exe"), + (r"C:\trusted\copilot.cmd.EXE", "copilot.cmd", "copilot.cmd"), + ], +) +def test_windows_copilot_command_keeps_main_bare_argv(windows_lookup, monkeypatch, decoy, probe_name, baseline_argv0): + """Main probes via which but passes the selected bare name to the launcher.""" + from specify_cli.integrations import copilot + + env, files, _, location = windows_lookup + env.update({"Path": r"C:\trusted", "PATHEXT": ".CMD;.EXE", "NoDefaultCurrentDirectoryInExePath": "1"}) + files.add(ntpath.normcase(decoy)) + monkeypatch.setattr(copilot, "os", SimpleNamespace(name="nt", environ=env)) + monkeypatch.setattr(copilot, "shutil", SimpleNamespace(which=lambda name: decoy if name == probe_name else None)) + calls = [] + + def run(args, **kwargs): + calls.append((list(args), kwargs)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location): + result = copilot.CopilotIntegration().dispatch_command("plan", stream=False) + assert result["exit_code"] == 0 + assert calls[0][0][0] == baseline_argv0 + assert calls[0][1]["env"]["Path"] == r"C:\trusted" + + +def test_windows_copilot_prompt_keeps_main_pathext_fallback(windows_lookup, monkeypatch, tmp_path): + """Main's prompt path resolves the builder's bare name through which.""" + from specify_cli.integrations import copilot + from specify_cli.workflows.base import StepContext + from specify_cli.workflows.step.prompt import PromptStep + + env, files, _, location = windows_lookup + env.update({"Path": r"C:\trusted", "PATHEXT": ".CMD;.EXE", "NoDefaultCurrentDirectoryInExePath": "1"}) + decoy = r"C:\trusted\copilot.cmd.EXE" + files.add(ntpath.normcase(decoy)) + monkeypatch.setattr(copilot, "os", SimpleNamespace(name="nt", environ=env)) + monkeypatch.setattr(copilot, "shutil", SimpleNamespace(which=lambda name: decoy if name == "copilot.cmd" else None)) + impl = copilot.CopilotIntegration() + monkeypatch.setattr("specify_cli.integrations.get_integration", lambda name: impl) + calls = [] + + def run(args, **kwargs): + calls.append((list(args), kwargs)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location): + result = PromptStep._try_dispatch.__wrapped__("hello", "copilot", None, StepContext(project_root=str(tmp_path))) + assert result["exit_code"] == 0 + assert calls[0][0][0] == decoy + + +@pytest.mark.parametrize("mode", ["stream", "bounded", "unbounded"]) +def test_base_windows_fully_qualified_executable_falls_back_after_lookup_miss(windows_lookup, monkeypatch, mode): + from specify_cli.integrations._capture import CapturedProcess + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + env, files, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + executable = r"C:\trusted\agent.exe" + files.add(ntpath.normcase(executable)) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + calls = [] + + def run(args, **kwargs): + calls.append((list(args), kwargs)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + def capture(args, **kwargs): + calls.append((list(args), kwargs)) + return CapturedProcess(exit_code=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + monkeypatch.setattr("specify_cli.integrations.base.run_captured", capture) + kwargs = {"stream": mode == "stream"} + if mode == "bounded": + kwargs["capture_max_bytes"] = 100 + with dispatch.integration_dispatch(location): + result = impl.dispatch_command("plan", **kwargs) + assert result["exit_code"] == 0 + assert calls[0][0][0] == executable + assert calls[0][1]["env"]["PATHEXT"] == ".CMD" + + +def test_base_windows_qualified_lookup_miss_does_not_substitute_sibling(windows_lookup, monkeypatch): + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + env, files, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + executable = r"C:\trusted\agent.exe" + files.update(map(ntpath.normcase, [executable, executable + ".CMD"])) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: None) + calls = [] + + def run(args, **kwargs): + calls.append(list(args)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location): + result = impl.dispatch_command("plan", stream=False) + assert result["exit_code"] == 0 + assert calls[0][0] == executable + + +def test_base_windows_missing_absolute_executable_reports_os_error(windows_lookup, monkeypatch): + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + env, _, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + executable = r"C:\trusted\missing.exe" + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + calls = [] + + def run(args, **kwargs): + calls.append(list(args)) + raise FileNotFoundError(2, "OS lookup failed", args[0]) + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location), pytest.raises(FileNotFoundError) as error: + impl.dispatch_command("plan", stream=False) + assert calls == [[executable]] + assert error.value.filename == executable + assert error.value.strerror == "OS lookup failed" + + +@pytest.mark.parametrize("executable", [r"agent.exe", r".\agent.exe", r"C:agent.exe", r"\agent.exe", r"1:\agent.exe"]) +def test_base_windows_relative_or_invalid_executable_does_not_fall_back(windows_lookup, monkeypatch, executable): + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + _, _, _, location = windows_lookup + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: None) + calls = [] + monkeypatch.setattr("subprocess.run", lambda *args, **kwargs: calls.append(args)) + with dispatch.integration_dispatch(location), pytest.raises(FileNotFoundError, match="Integration executable not found"): + impl.dispatch_command("plan", stream=False) + assert not calls + + +@pytest.mark.parametrize("executable", [r"C:\trusted\..\agent.exe", r"\\server\share\agent.exe", r"\\?\C:\trusted\agent.exe", r"\\?\UNC\server\share\agent.exe"]) +def test_base_windows_absolute_fallback_keeps_original_spelling(windows_lookup, monkeypatch, executable): + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + _, _, _, location = windows_lookup + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: None) + calls = [] + + def run(args, **kwargs): + calls.append(list(args)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location): + result = impl.dispatch_command("plan", stream=False) + assert result["exit_code"] == 0 + assert calls == [[executable]] + + +def test_base_windows_successful_lookup_keeps_main_suffix_order(windows_lookup, monkeypatch): + from tests.specify_cli.events.test_json_named import FakeNamedIntegration + + env, files, _, location = windows_lookup + env["PATHEXT"] = ".CMD" + executable = r"C:\trusted\agent.exe" + sibling = executable + ".CMD" + files.update(map(ntpath.normcase, [executable, sibling])) + impl = FakeNamedIntegration() + monkeypatch.setattr(impl, "build_exec_args", lambda *args, **kwargs: [executable]) + calls = [] + + def run(args, **kwargs): + calls.append(list(args)) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("subprocess.run", run) + with dispatch.integration_dispatch(location): + result = impl.dispatch_command("plan", stream=False) + assert result["exit_code"] == 0 + assert calls == [[sibling]] diff --git a/tests/integrations/test_integration_agy.py b/tests/integrations/test_integration_agy.py index b3681ee8fc..630eae52fb 100644 --- a/tests/integrations/test_integration_agy.py +++ b/tests/integrations/test_integration_agy.py @@ -309,7 +309,7 @@ def test_dispatch_command_forwards_project_root_as_add_dir(self, tmp_path): mock_result.stderr = "" with ( - patch("specify_cli.integrations.base.shutil.which", return_value="agy"), + patch("specify_cli.integrations.base.dispatch_which", return_value="agy"), patch("subprocess.run", return_value=mock_result) as mock_run, ): result = i.dispatch_command( diff --git a/tests/integrations/test_integration_bob.py b/tests/integrations/test_integration_bob.py index 8e85c66559..410bab962b 100644 --- a/tests/integrations/test_integration_bob.py +++ b/tests/integrations/test_integration_bob.py @@ -1085,6 +1085,7 @@ def fake_run(cmd, **kwargs): return subprocess.CompletedProcess(cmd, 0, "", "") monkeypatch.setattr(subprocess, "run", fake_run) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) monkeypatch.chdir(self._legacy_project(tmp_path)) get_integration("bob").dispatch_command("speckit.git.commit") @@ -1106,6 +1107,7 @@ def fake_run(cmd, **kwargs): return subprocess.CompletedProcess(cmd, 0, "", "") monkeypatch.setattr(subprocess, "run", fake_run) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) bob = get_integration("bob") bob.dispatch_command( diff --git a/tests/integrations/test_integration_claude.py b/tests/integrations/test_integration_claude.py index 953f8960b5..3a247c84ae 100644 --- a/tests/integrations/test_integration_claude.py +++ b/tests/integrations/test_integration_claude.py @@ -2,7 +2,6 @@ import json import os -import shutil import subprocess from pathlib import Path from unittest.mock import patch @@ -1284,6 +1283,7 @@ def fake_run(args, **kwargs): return subprocess.CompletedProcess(args, 0, stdout="", stderr="") monkeypatch.setattr(subprocess, "run", fake_run) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) return calls @pytest.mark.parametrize("via", ["dispatch_command", "build_exec_args"]) @@ -1440,7 +1440,11 @@ def test_effort_follows_extra_args(self, monkeypatch, runs): @staticmethod def _execute(monkeypatch, tmp_path, step, config, *, steps=None, **settings): - monkeypatch.setattr(shutil, "which", lambda name, *a, **k: f"/bin/{name}") + for module in ( + "specify_cli.workflows.step.command", + "specify_cli.workflows.step.prompt", + ): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) return step().execute( {"id": "ask", **config, **settings}, StepContext( diff --git a/tests/integrations/test_integration_codex.py b/tests/integrations/test_integration_codex.py index 698456942b..c051fc489d 100644 --- a/tests/integrations/test_integration_codex.py +++ b/tests/integrations/test_integration_codex.py @@ -1,6 +1,5 @@ """Tests for CodexIntegration.""" -import shutil import subprocess import tomllib @@ -227,6 +226,7 @@ def fake_run(args, **kwargs): return subprocess.CompletedProcess(args, 0, stdout="", stderr="") monkeypatch.setattr(subprocess, "run", fake_run) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) return calls @pytest.mark.parametrize("via", ["dispatch_command", "build_exec_args"]) @@ -354,7 +354,11 @@ def test_dispatch_command_rejects_before_the_cli_starts(self, runs): @staticmethod def _execute(monkeypatch, tmp_path, step, config, *, steps=None, **settings): - monkeypatch.setattr(shutil, "which", lambda name, *a, **k: f"/bin/{name}") + for module in ( + "specify_cli.workflows.step.command", + "specify_cli.workflows.step.prompt", + ): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) return step().execute( {"id": "ask", **config, **settings}, StepContext( diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 033406db42..e720a6e3c1 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -2,7 +2,6 @@ import json import os -import shutil import subprocess from pathlib import Path from unittest.mock import patch @@ -1592,7 +1591,11 @@ def test_legacy_builder_subclass_rejects_the_prompt_path(self): def test_workflow_steps_dispatch_settings( self, monkeypatch, tmp_path, runs, step, config, prompt ): - monkeypatch.setattr(shutil, "which", lambda name, *a, **k: f"/bin/{name}") + for module in ( + "specify_cli.workflows.step.command", + "specify_cli.workflows.step.prompt", + ): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) result = step().execute( { "id": "ask", @@ -1631,7 +1634,11 @@ def run(args, **kwargs): streamed.append(list(args)) return subprocess.CompletedProcess(args, 1, stdout="", stderr="") - monkeypatch.setattr(shutil, "which", lambda name, *a, **k: f"/bin/{name}") + for module in ( + "specify_cli.workflows.step.command", + "specify_cli.workflows.step.prompt", + ): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr( "specify_cli.workflows.step.prompt.run_captured", run_captured ) diff --git a/tests/integrations/test_integration_cursor_agent.py b/tests/integrations/test_integration_cursor_agent.py index 010d739b8a..c83b2df320 100644 --- a/tests/integrations/test_integration_cursor_agent.py +++ b/tests/integrations/test_integration_cursor_agent.py @@ -2,6 +2,8 @@ from urllib.parse import urlparse +import pytest + from specify_cli.integrations import get_integration from .test_integration_base_skills import SkillsIntegrationTests @@ -202,7 +204,7 @@ def test_dispatch_command_resolves_cmd_shim_for_subprocess(self): fake_path = r"C:\Users\foo\AppData\Local\cursor-agent\cursor-agent.CMD" with patch( - "specify_cli.integrations.base.shutil.which", return_value=fake_path + "specify_cli.integrations.base.dispatch_which", return_value=fake_path ), patch("subprocess.run", return_value=mock_result) as mock_run: result = i.dispatch_command( "speckit.plan", args="feature-x", stream=False, timeout=5 @@ -214,8 +216,7 @@ def test_dispatch_command_resolves_cmd_shim_for_subprocess(self): assert argv[1:6] == ["-p", "--trust", "--approve-mcps", "--force", "/speckit-plan feature-x"] def test_dispatch_command_passthrough_when_shutil_which_finds_nothing(self): - """If ``shutil.which`` returns ``None``, leave argv unchanged so the - existing ``FileNotFoundError`` path remains observable to callers.""" + """A missing executable must not fall through to the child's cwd.""" from unittest.mock import patch, MagicMock i = get_integration("cursor-agent") @@ -225,9 +226,8 @@ def test_dispatch_command_passthrough_when_shutil_which_finds_nothing(self): mock_result.stderr = "" with patch( - "specify_cli.integrations.base.shutil.which", return_value=None + "specify_cli.integrations.base.dispatch_which", return_value=None ), patch("subprocess.run", return_value=mock_result) as mock_run: - i.dispatch_command("speckit.plan", stream=False, timeout=5) - - argv = mock_run.call_args[0][0] - assert argv[0] == "cursor-agent" + with pytest.raises(FileNotFoundError): + i.dispatch_command("speckit.plan", stream=False, timeout=5) + mock_run.assert_not_called() diff --git a/tests/integrations/test_integration_mcode.py b/tests/integrations/test_integration_mcode.py index 644e62342f..89356ce74a 100644 --- a/tests/integrations/test_integration_mcode.py +++ b/tests/integrations/test_integration_mcode.py @@ -76,7 +76,6 @@ def test_build_exec_args_allows_permission_override(self, monkeypatch): def test_dispatch_command_uses_full_permission(self, monkeypatch, tmp_path): """The real dispatch path must pass the non-interactive permission mode.""" import subprocess - import shutil from types import SimpleNamespace from specify_cli.integrations import get_integration @@ -88,7 +87,7 @@ def run(args, **kwargs): return SimpleNamespace(returncode=0, stdout="ok", stderr="") monkeypatch.setattr(subprocess, "run", run) - monkeypatch.setattr(shutil, "which", lambda _: None) + monkeypatch.setattr("specify_cli.integrations.base.dispatch_which", lambda name: name) result = get_integration("mcode").dispatch_command( "specify", "Add a health check", project_root=tmp_path, stream=False ) diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 56baaa7b16..4a947883ef 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -2118,7 +2118,7 @@ def test_execute_basic(self): "command": "speckit.specify", "input": {"args": "{{ inputs.name }}"}, } - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.status == StepStatus.FAILED assert result.output["command"] == "speckit.specify" @@ -2140,14 +2140,15 @@ def fake_run(args, **kwargs): monkeypatch.delenv( "SPECKIT_INTEGRATION_DOCKER_AGENT_EXTRA_ARGS", raising=False ) - monkeypatch.setattr( - "shutil.which", - lambda name: ( - "/usr/bin/docker-agent" - if name in {"docker-agent", "/usr/bin/docker-agent"} - else None - ), - ) + def find_docker(name): + return "/usr/bin/docker-agent" if name in {"docker-agent", "/usr/bin/docker-agent"} else None + + for module in ( + "specify_cli.integrations._context", + "specify_cli.integrations.base", + "specify_cli.workflows.step.command", + ): + monkeypatch.setattr(f"{module}.dispatch_which", find_docker) monkeypatch.setattr("subprocess.run", fake_run) step = CommandStep() @@ -2238,14 +2239,15 @@ def fake_run(args, **kwargs): monkeypatch.delenv( "SPECKIT_INTEGRATION_DOCKER_AGENT_EXTRA_ARGS", raising=False ) - monkeypatch.setattr( - "shutil.which", - lambda name: ( - "/usr/bin/docker-agent" - if name in {"docker-agent", "/usr/bin/docker-agent"} - else None - ), - ) + def find_docker(name): + return "/usr/bin/docker-agent" if name in {"docker-agent", "/usr/bin/docker-agent"} else None + + for module in ( + "specify_cli.integrations._context", + "specify_cli.integrations.base", + "specify_cli.workflows.step.command", + ): + monkeypatch.setattr(f"{module}.dispatch_which", find_docker) monkeypatch.setattr("subprocess.run", fake_run) config = { @@ -2341,8 +2343,9 @@ def test_try_dispatch_resolves_rovodev_via_acli(self, tmp_path): mock_result.stdout = "" mock_result.stderr = "" - with patch("specify_cli.workflows.step.command.shutil.which", + with patch("specify_cli.workflows.step.command.dispatch_which", lambda name: "/usr/bin/acli" if name == "acli" else None), \ + patch("specify_cli.integrations.base.dispatch_which", return_value="/usr/bin/acli"), \ patch("subprocess.run", return_value=mock_result): result = step.execute(config, ctx) @@ -2445,7 +2448,7 @@ def test_execute_non_string_command_fails_cleanly(self): # resolvable integration + installed CLI so, absent the guard, dispatch # would actually be attempted and the crash would fire. ctx = StepContext(default_integration="claude") - with patch("specify_cli.workflows.step.command.shutil.which", + with patch("specify_cli.workflows.step.command.dispatch_which", return_value="/usr/bin/claude"): for bad in (None, ["a", "b"], 5, {"x": 1}): result = step.execute( @@ -2516,7 +2519,7 @@ def test_step_override_integration(self): "integration": "gemini", "input": {}, } - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.output["integration"] == "gemini" @@ -2548,7 +2551,7 @@ def test_step_override_model(self): "model": "opus-4", "input": {}, } - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.output["model"] == "opus-4" @@ -2565,7 +2568,7 @@ def test_options_merge(self): "options": {"thinking-budget": 32768}, "input": {}, } - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.output["options"]["max-tokens"] == 8000 assert result.output["options"]["thinking-budget"] == 32768 @@ -2587,7 +2590,7 @@ def test_dispatch_not_attempted_without_cli(self): "command": "speckit.specify", "input": {"args": "{{ inputs.name }}"}, } - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.status == StepStatus.FAILED assert result.output["dispatched"] is False @@ -2616,8 +2619,8 @@ def test_dispatch_with_mock_cli(self, tmp_path, monkeypatch): mock_result.stdout = '{"result": "done"}' mock_result.stderr = "" - with patch("specify_cli.workflows.step.command.shutil.which", return_value="/usr/local/bin/claude"), \ - patch("specify_cli.integrations.base.shutil.which", return_value="/usr/local/bin/claude"), \ + with patch("specify_cli.workflows.step.command.dispatch_which", return_value="/usr/local/bin/claude"), \ + patch("specify_cli.integrations.base.dispatch_which", return_value="/usr/local/bin/claude"), \ patch("subprocess.run", return_value=mock_result) as mock_run: result = step.execute(config, ctx) @@ -2668,8 +2671,8 @@ def test_dispatch_args_resolving_to_null_send_no_arguments( mock_result.stdout = "" mock_result.stderr = "" - with patch("specify_cli.workflows.step.command.shutil.which", return_value="/usr/local/bin/claude"), \ - patch("specify_cli.integrations.base.shutil.which", return_value="/usr/local/bin/claude"), \ + with patch("specify_cli.workflows.step.command.dispatch_which", return_value="/usr/local/bin/claude"), \ + patch("specify_cli.integrations.base.dispatch_which", return_value="/usr/local/bin/claude"), \ patch("subprocess.run", return_value=mock_result) as mock_run: result = CommandStep().execute(config, ctx) @@ -2706,7 +2709,8 @@ def fake_which(name: str) -> str | None: mock_result.stdout = '{"result": "done"}' mock_result.stderr = "" - with patch("specify_cli.workflows.step.command.shutil.which", side_effect=fake_which), \ + with patch("specify_cli.workflows.step.command.dispatch_which", side_effect=fake_which), \ + patch("specify_cli.integrations.base.dispatch_which", return_value="/opt/claude"), \ patch("subprocess.run", return_value=mock_result) as mock_run: result = step.execute(config, ctx) @@ -2740,8 +2744,8 @@ def test_dispatch_failure_returns_failed_status(self, tmp_path): mock_result.stdout = "" mock_result.stderr = "API error" - with patch("specify_cli.workflows.step.command.shutil.which", return_value="/usr/local/bin/claude"), \ - patch("specify_cli.integrations.base.shutil.which", return_value="/usr/local/bin/claude"), \ + with patch("specify_cli.workflows.step.command.dispatch_which", return_value="/usr/local/bin/claude"), \ + patch("specify_cli.integrations.base.dispatch_which", return_value="/usr/local/bin/claude"), \ patch("subprocess.run", return_value=mock_result): result = step.execute(config, ctx) @@ -2768,7 +2772,7 @@ def test_execute_basic(self): "type": "prompt", "prompt": "Review {{ inputs.file }} for security issues", } - with patch("specify_cli.workflows.step.prompt.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.prompt.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.status == StepStatus.FAILED assert result.output["prompt"] == "Review auth.py for security issues" @@ -2802,7 +2806,7 @@ def test_execute_with_step_integration(self): "prompt": "Summarize the codebase", "integration": "gemini", } - with patch("specify_cli.workflows.step.prompt.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.prompt.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.output["integration"] == "gemini" @@ -2819,7 +2823,7 @@ def test_execute_with_model(self): "prompt": "hello", "model": "opus-4", } - with patch("specify_cli.workflows.step.prompt.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.prompt.dispatch_which", return_value=None): result = step.execute(config, ctx) assert result.output["model"] == "opus-4" @@ -2845,7 +2849,7 @@ def test_try_dispatch_resolves_rovodev_via_acli(self, tmp_path): mock_result.stdout = "" mock_result.stderr = "" - with patch("specify_cli.workflows.step.prompt.shutil.which", + with patch("specify_cli.workflows.step.prompt.dispatch_which", lambda name: "/usr/bin/acli" if name == "acli" else None), \ patch("subprocess.run", return_value=mock_result): result = step.execute(config, ctx) @@ -2879,7 +2883,7 @@ def test_try_dispatch_executes_the_resolved_executable(self, tmp_path): mock_result.stderr = "" with patch( - "specify_cli.workflows.step.prompt.shutil.which", + "specify_cli.workflows.step.prompt.dispatch_which", lambda name: resolved, ), patch("subprocess.run", return_value=mock_result) as run: result = step.execute(config, ctx) @@ -2910,7 +2914,7 @@ def test_dispatch_with_mock_cli(self, tmp_path): mock_result.stdout = "Here is the explanation" mock_result.stderr = "" - with patch("specify_cli.workflows.step.prompt.shutil.which", return_value="/usr/local/bin/claude"), \ + with patch("specify_cli.workflows.step.prompt.dispatch_which", return_value="/usr/local/bin/claude"), \ patch("subprocess.run", return_value=mock_result): result = step.execute(config, ctx) @@ -2947,7 +2951,7 @@ def fake_which(name: str) -> str | None: mock_result.stdout = "Here is the explanation" mock_result.stderr = "" - with patch("specify_cli.workflows.step.prompt.shutil.which", side_effect=fake_which), \ + with patch("specify_cli.workflows.step.prompt.dispatch_which", side_effect=fake_which), \ patch("subprocess.run", return_value=mock_result) as mock_run: result = step.execute(config, ctx) @@ -3141,7 +3145,7 @@ def fail_if_called(*args, **kwargs): # too large to convert to float raises OverflowError. for bad in ("30", True, float("nan"), 0, -5, ["30"], 10**400): with patch( - "specify_cli.workflows.step.prompt.shutil.which", + "specify_cli.workflows.step.prompt.dispatch_which", return_value="/opt/claude", ): result = step.execute( @@ -3179,7 +3183,7 @@ def test_try_dispatch_threads_project_root(self): mock_result.stderr = "" with patch("specify_cli.integrations.get_integration", mock_get_integration), \ - patch("specify_cli.workflows.step.prompt.shutil.which", return_value="/opt/dummy"), \ + patch("specify_cli.workflows.step.prompt.dispatch_which", return_value="/opt/dummy"), \ patch("subprocess.run", return_value=mock_result): step.execute( {"id": "p", "type": "prompt", "prompt": "hi", "integration": "dummy"}, @@ -7203,7 +7207,7 @@ def test_execute_simple_workflow(self, project_dir): """ definition = WorkflowDefinition.from_string(yaml_str) engine = WorkflowEngine(project_dir) - with patch("specify_cli.workflows.step.command.shutil.which", return_value=None): + with patch("specify_cli.workflows.step.command.dispatch_which", return_value=None): state = engine.execute(definition, {"name": "login"}) assert state.status == RunStatus.FAILED @@ -8307,7 +8311,7 @@ def test_command_input_args_resolves_run_id(self, project_dir): """) engine = WorkflowEngine(project_dir) with patch( - "specify_cli.workflows.step.command.shutil.which", + "specify_cli.workflows.step.command.dispatch_which", return_value=None, ): state = engine.execute(definition, run_id="cafef00d") @@ -12282,14 +12286,15 @@ def fake_run(args, **kwargs): monkeypatch.delenv( "SPECKIT_INTEGRATION_DOCKER_AGENT_EXTRA_ARGS", raising=False ) - monkeypatch.setattr( - "shutil.which", - lambda name: ( - "/usr/bin/docker-agent" - if name in {"docker-agent", "/usr/bin/docker-agent"} - else None - ), - ) + def find_docker(name): + return "/usr/bin/docker-agent" if name in {"docker-agent", "/usr/bin/docker-agent"} else None + + for module in ( + "specify_cli.integrations._context", + "specify_cli.integrations.base", + "specify_cli.workflows.step.command", + ): + monkeypatch.setattr(f"{module}.dispatch_which", find_docker) monkeypatch.setattr("subprocess.run", fake_run) definition = WorkflowDefinition.from_string(self._WF_RUNTIME_CONFIG) @@ -12332,14 +12337,15 @@ def test_resume_does_not_mix_new_integration_with_old_runtime_config( monkeypatch.delenv( "SPECKIT_INTEGRATION_DOCKER_AGENT_EXTRA_ARGS", raising=False ) - monkeypatch.setattr( - "shutil.which", - lambda name: ( - "/usr/bin/docker-agent" - if name in {"docker-agent", "/usr/bin/docker-agent"} - else None - ), - ) + def find_docker(name): + return "/usr/bin/docker-agent" if name in {"docker-agent", "/usr/bin/docker-agent"} else None + + for module in ( + "specify_cli.integrations._context", + "specify_cli.integrations.base", + "specify_cli.workflows.step.command", + ): + monkeypatch.setattr(f"{module}.dispatch_which", find_docker) monkeypatch.setattr( "subprocess.run", lambda *args, **kwargs: type("Result", (), {"returncode": 1})(), diff --git a/tests/workflows/test_command_additional_context.py b/tests/workflows/test_command_additional_context.py index cf6aa978ef..ab1791d2bb 100644 --- a/tests/workflows/test_command_additional_context.py +++ b/tests/workflows/test_command_additional_context.py @@ -114,7 +114,8 @@ def fake_run(args, **kwargs): calls.append((args, kwargs["env"])) return Result() - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", fake_run) step = CommandStep() context = StepContext( @@ -153,7 +154,8 @@ def old( return {"exit_code": 0, "stdout": "", "stderr": ""} monkeypatch.setattr(cls, "dispatch_command", old) - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) context = StepContext(default_integration="fake-context", project_root=str(project_dir)) bad = CommandStep().execute(config("SECRET"), context) assert bad.status == StepStatus.FAILED and "does not accept" in bad.error @@ -169,7 +171,8 @@ def fake_run(args, **kwargs): seen.append((args[2], kwargs["env"].get(ADDITIONAL_CONTEXT_ENV))) return type("Result", (), {"returncode": 0})() - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", fake_run) def run(value): @@ -193,7 +196,8 @@ def fake_run(args, **kwargs): calls.append(kwargs["env"][ADDITIONAL_CONTEXT_ENV]) return type("Result", (), {"returncode": 1 if len(calls) == 1 else 0})() - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", fake_run) definition = WorkflowDefinition.from_string( yaml.safe_dump( @@ -230,7 +234,8 @@ def fake_run(args, **kwargs): seen.append((args[2], kwargs["env"][ADDITIONAL_CONTEXT_ENV])) return type("Result", (), {"returncode": 0})() - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", fake_run) definition = WorkflowDefinition.from_string( yaml.safe_dump( @@ -269,7 +274,8 @@ def fake_run(args, **kwargs): calls.append(kwargs["env"][ADDITIONAL_CONTEXT_ENV]) return type("Result", (), {"returncode": 1 if len(calls) == 2 else 0})() - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ("specify_cli.integrations.base", "specify_cli.workflows.step.command"): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", fake_run) definition = WorkflowDefinition.from_string( yaml.safe_dump( diff --git a/tests/workflows/test_dispatch_settings.py b/tests/workflows/test_dispatch_settings.py index 272bc51e44..f78118e6a4 100644 --- a/tests/workflows/test_dispatch_settings.py +++ b/tests/workflows/test_dispatch_settings.py @@ -9,6 +9,7 @@ import dataclasses import json +from pathlib import Path from types import SimpleNamespace import pytest @@ -266,7 +267,12 @@ def run_captured(args, **kwargs): exit_code=state.returncode, stdout=state.stdout, stderr=state.stderr ) - monkeypatch.setattr("shutil.which", lambda name: name) + for module in ( + "specify_cli.integrations.base", + "specify_cli.workflows.step.command", + "specify_cli.workflows.step.prompt", + ): + monkeypatch.setattr(f"{module}.dispatch_which", lambda name: name) monkeypatch.setattr("subprocess.run", run) for module in ( "specify_cli.integrations.base", @@ -279,7 +285,7 @@ def run_captured(args, **kwargs): @pytest.fixture def no_cli(monkeypatch): """Find no CLI, so reaching executable detection means 'not installed'.""" - monkeypatch.setattr("shutil.which", lambda name: None) + monkeypatch.setattr("shutil.which", lambda name, **kwargs: None) @pytest.fixture @@ -836,7 +842,9 @@ def test_receives_exactly_the_set_keywords( flags += ["--effort", settings["reasoning_effort"]] if "context_size" in settings: flags += ["--context", settings["context_size"]] - assert cli.runs == [[fake.key, "-p", PROMPTS[kind], *flags]] + assert len(cli.runs) == 1 + assert Path(cli.runs[0][0]).name == fake.key + assert cli.runs[0][1:] == ["-p", PROMPTS[kind], *flags] @pytest.mark.parametrize("capture", [False, True], ids=["streamed", "captured"]) def test_settings_compose_with_capture( @@ -1407,4 +1415,4 @@ def test_step_context_positional_construction_is_unchanged(): assert context.default_context_size is None names = [field.name for field in dataclasses.fields(StepContext)] assert names[8] == "project_root" - assert names[-2:] == ["default_reasoning_effort", "default_context_size"] + assert names[-3:] == ["default_reasoning_effort", "default_context_size", "dispatch_location"] diff --git a/tests/workflows/test_step_capture.py b/tests/workflows/test_step_capture.py index e4cff661a9..3e6899131f 100644 --- a/tests/workflows/test_step_capture.py +++ b/tests/workflows/test_step_capture.py @@ -664,7 +664,7 @@ def run(args, **kwargs): def bounded(args, **kwargs): seen.append(kwargs['env']) return CapturedProcess(exit_code=0, stdout='', stderr='') - monkeypatch.setattr('shutil.which', lambda name: name) + monkeypatch.setattr('specify_cli.workflows.step.prompt.dispatch_which', lambda name: name) monkeypatch.setattr('subprocess.run', run) monkeypatch.setattr('specify_cli.workflows.step.prompt.run_captured', bounded) result = _execute('prompt', project_dir, capture=capture) From d3f26104b8dc00a34bc5a50b5714b3855cb134c2 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 15:15:13 +0100 Subject: [PATCH 14/20] test(events): isolate fake integration state Remove test-only integrations before refreshing derived agent caches so event and dispatch tests do not leak fake agents into later tests. The previously failing test-order regressions now pass. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- tests/integrations/test_dispatch_path.py | 46 +++++++++++++-------- tests/specify_cli/events/test_json_named.py | 9 +++- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/tests/integrations/test_dispatch_path.py b/tests/integrations/test_dispatch_path.py index e4bb584bc6..878ece7a8f 100644 --- a/tests/integrations/test_dispatch_path.py +++ b/tests/integrations/test_dispatch_path.py @@ -12,8 +12,18 @@ from tests.specify_cli.events.test_json_named import FakeNamedIntegration +@pytest.fixture +def isolated_registry(): + """Restore derived agent caches after removing test-only integrations.""" + from specify_cli.integrations.installer import _refresh_configs + + with pytest.MonkeyPatch.context() as registry: + yield registry + _refresh_configs() + + @pytest.mark.skipif(os.name == "nt", reason="POSIX shell and executable scripts") -def test_relative_path_survives_agent_and_generated_hook_cwd(tmp_path, monkeypatch): +def test_relative_path_survives_agent_and_generated_hook_cwd(tmp_path, monkeypatch, isolated_registry): root = tmp_path / "project" caller = root / "caller" tools = caller / "tools" @@ -35,7 +45,7 @@ def test_relative_path_survives_agent_and_generated_hook_cwd(tmp_path, monkeypat ) agent.chmod(0o755) impl = FakeNamedIntegration() - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.chdir(caller) monkeypatch.setenv("PATH", "./tools") install_integration_events( @@ -85,7 +95,7 @@ def test_absent_and_empty_path_are_unchanged(monkeypatch, value): @pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") @pytest.mark.parametrize("kind", ["base", "prompt"]) -def test_relative_executable_override_selects_caller_not_project(tmp_path, monkeypatch, kind): +def test_relative_executable_override_selects_caller_not_project(tmp_path, monkeypatch, isolated_registry, kind): from specify_cli.integrations import INTEGRATION_REGISTRY from specify_cli.workflows.base import StepContext from specify_cli.workflows.step.prompt import PromptStep @@ -101,7 +111,7 @@ def test_relative_executable_override_selects_caller_not_project(tmp_path, monke monkeypatch.setenv("PATH", "/bin") impl = FakeNamedIntegration() monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: ["./agent"]) - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) if kind == "prompt": result = PromptStep._try_dispatch( "prompt", impl.key, None, StepContext(project_root=str(root)), capture_max_bytes=100 @@ -113,7 +123,7 @@ def test_relative_executable_override_selects_caller_not_project(tmp_path, monke @pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") -def test_missing_cli_never_falls_through_to_project_directory(tmp_path, monkeypatch): +def test_missing_cli_never_falls_through_to_project_directory(tmp_path, monkeypatch, isolated_registry): from specify_cli.workflows.base import StepContext from specify_cli.workflows.step.prompt import PromptStep from specify_cli.integrations import INTEGRATION_REGISTRY @@ -125,7 +135,7 @@ def test_missing_cli_never_falls_through_to_project_directory(tmp_path, monkeypa executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") executable.chmod(0o755) impl = FakeNamedIntegration() - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.chdir(caller) monkeypatch.setenv("PATH", "./missing") with pytest.raises(FileNotFoundError): @@ -197,7 +207,7 @@ def test_shell_path_is_not_normalized(tmp_path, monkeypatch, override, expected) @pytest.mark.skipif(os.name == "nt", reason="POSIX symlink and interpreter names") -def test_changed_interpreter_does_not_weaken_hook_verification(tmp_path, monkeypatch): +def test_changed_interpreter_does_not_weaken_hook_verification(tmp_path, monkeypatch, isolated_registry): from specify_cli.events import context_delivery_error from specify_cli.integrations._context import integration_dispatch @@ -210,7 +220,7 @@ def test_changed_interpreter_does_not_weaken_hook_verification(tmp_path, monkeyp (first / "python3").symlink_to(sys.executable) (second / "python").symlink_to(sys.executable) impl = FakeNamedIntegration() - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.chdir(caller) monkeypatch.setenv("PATH", "./first") install_integration_events( @@ -270,7 +280,7 @@ def test_ordinary_generated_hook_and_its_tool_use_caller_path(tmp_path, monkeypa @pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") -def test_workflow_run_and_resume_capture_their_own_caller(tmp_path, monkeypatch): +def test_workflow_run_and_resume_capture_their_own_caller(tmp_path, monkeypatch, isolated_registry): from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine root = tmp_path / "project" @@ -287,7 +297,7 @@ def test_workflow_run_and_resume_capture_their_own_caller(tmp_path, monkeypatch) executable.chmod(0o755) (root / ".specify").mkdir() impl = FakeNamedIntegration() - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.setenv("PATH", "./tools") definition = WorkflowDefinition({ "schema_version": "1.0", @@ -307,7 +317,7 @@ def test_workflow_run_and_resume_capture_their_own_caller(tmp_path, monkeypatch) @pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") -def test_fan_out_and_child_workflow_keep_run_caller(tmp_path, monkeypatch): +def test_fan_out_and_child_workflow_keep_run_caller(tmp_path, monkeypatch, isolated_registry): from specify_cli.workflows.engine import WorkflowDefinition, WorkflowEngine from tests.workflows.test_composition_execution import install @@ -319,7 +329,7 @@ def test_fan_out_and_child_workflow_keep_run_caller(tmp_path, monkeypatch): agent.write_text('#!/bin/sh\nprintf %s "$PATH"\n', encoding="utf-8") agent.chmod(0o755) impl = FakeNamedIntegration() - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.setenv("PATH", "./tools") child = WorkflowDefinition({ "workflow": {"id": "child", "name": "Child", "integration": impl.key}, @@ -427,7 +437,7 @@ def test_direct_dispatch_with_empty_path_keeps_project_cwd_lookup(tmp_path, monk @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH separator in directory name") @pytest.mark.parametrize("kind", ["command", "prompt"]) -def test_workflow_reports_unrepresentable_path(tmp_path, monkeypatch, kind): +def test_workflow_reports_unrepresentable_path(tmp_path, monkeypatch, isolated_registry, kind): from specify_cli.workflows.base import StepContext, StepStatus from specify_cli.workflows.step.command import CommandStep from specify_cli.workflows.step.prompt import PromptStep @@ -436,7 +446,7 @@ def test_workflow_reports_unrepresentable_path(tmp_path, monkeypatch, kind): caller.mkdir() monkeypatch.chdir(caller) monkeypatch.setenv("PATH", "tools") - monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) + isolated_registry.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) context = StepContext(project_root=str(caller), default_integration="fake-named") result = ( CommandStep().execute({"id": "ask", "command": "plan"}, context) @@ -543,7 +553,7 @@ def test_windows_quoted_path_does_not_hide_later_valid_entry(tmp_path, monkeypat @pytest.mark.skipif(os.name != "nt", reason="Windows PowerShell 5.1 generated hook") -def test_windows_powershell_51_generated_hook_uses_dispatch_path(tmp_path, monkeypatch): +def test_windows_powershell_51_generated_hook_uses_dispatch_path(tmp_path, monkeypatch, isolated_registry): import subprocess from specify_cli.integrations._context import integration_dispatch, integration_environment from tests.fixtures.context_delivery import FakeContextIntegration @@ -555,7 +565,7 @@ def test_windows_powershell_51_generated_hook_uses_dispatch_path(tmp_path, monke (tools / "python.cmd").write_text(f'@echo off\r\n"{sys.executable}" %*\r\n', encoding="utf-8") impl = FakeContextIntegration() impl.events_cwd_is_config_dir = True - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.chdir(caller) monkeypatch.setenv("PATH", ".\\tools") install_integration_events( @@ -757,7 +767,7 @@ def test_copilot_relative_override_keeps_main_child_cwd_behavior(tmp_path, monke @pytest.mark.skipif(os.name == "nt", reason="POSIX executable scripts") -def test_prompt_missing_fallback_keeps_main_integration_key_behavior(tmp_path, monkeypatch): +def test_prompt_missing_fallback_keeps_main_integration_key_behavior(tmp_path, monkeypatch, isolated_registry): from specify_cli.workflows.base import StepContext from specify_cli.workflows.step.prompt import PromptStep @@ -773,7 +783,7 @@ def test_prompt_missing_fallback_keeps_main_integration_key_behavior(tmp_path, m fallback.chmod(0o755) impl = FakeNamedIntegration() monkeypatch.setattr(impl, "build_exec_args", lambda *a, **k: ["./agent"]) - monkeypatch.setitem(INTEGRATION_REGISTRY, impl.key, impl) + isolated_registry.setitem(INTEGRATION_REGISTRY, impl.key, impl) monkeypatch.chdir(caller) monkeypatch.setenv("PATH", "./tools") result = PromptStep._try_dispatch( diff --git a/tests/specify_cli/events/test_json_named.py b/tests/specify_cli/events/test_json_named.py index f10d7b8c33..061f1d1e44 100644 --- a/tests/specify_cli/events/test_json_named.py +++ b/tests/specify_cli/events/test_json_named.py @@ -60,8 +60,13 @@ def teardown(self, project_root, manifest, *, force=False): @pytest.fixture(autouse=True) -def _register_fake_named(monkeypatch): - monkeypatch.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) +def _register_fake_named(): + from specify_cli.integrations.installer import _refresh_configs + + with pytest.MonkeyPatch.context() as registry: + registry.setitem(INTEGRATION_REGISTRY, "fake-named", FakeNamedIntegration()) + yield + _refresh_configs() def test_named_merge_replaces_owned_definition_preserving_user_definitions(tmp_path): From c9164ce2568192274dd0e4bebecf948ba586b3c6 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 19:19:52 +0100 Subject: [PATCH 15/20] feat(copilot): declare additional_context delivery Declare session_start context delivery for GitHub Copilot, so workflow command steps with additional_context work with Copilot (#5533, stacked on #5616). - CopilotIntegration.context_delivery_events = {session_start}. With events enabled, Copilot projects now get .specify/events.py and .github/hooks/speckit.json with the built-in session_start handler by default. - New copilot-json installed-handler reader: only Spec Kit-marked entries, mapped through CANONICAL_TO_NATIVE, using the current platform's command field (bash or powershell), and only when the parsed event and envelope match what Spec Kit renders. - Docs: Copilot folder-trust precondition (hooks load in -p mode only in a trusted folder; untrusted runs drop the context and still exit 0; Spec Kit adds no trust flags), default event files, and the support table entry. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous) Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous) --- docs/integrations/copilot.md | 19 ++- docs/workflow-steps/types.md | 4 +- src/specify_cli/events/__init__.py | 31 +++++ .../integrations/copilot/__init__.py | 1 + .../integrations/test_integration_copilot.py | 122 ++++++++++++++++++ .../events/test_context_delivery.py | 11 +- tests/specify_cli/test_command_init.py | 24 +++- 7 files changed, 205 insertions(+), 7 deletions(-) diff --git a/docs/integrations/copilot.md b/docs/integrations/copilot.md index 4b917c8985..252b608505 100644 --- a/docs/integrations/copilot.md +++ b/docs/integrations/copilot.md @@ -17,6 +17,21 @@ specify init my-project --integration copilot For an existing Spec Kit project, use `specify integration install copilot`. See [integration management](cli.md) for activation, upgrades, and removal. +## Additional Context and Folder Trust + +Copilot CLI loads repository hooks in `-p` mode only in a trusted folder. +Trust the folder through Copilot's trust prompt or `trustedFolders` in +`~/.copilot/config.json`, or use `--trust-folder` for a single run. +`COPILOT_ALLOW_ALL=true` also trusts the folder but approves all tools. In an +untrusted folder Copilot skips hooks, drops additional context, and still exits +successfully. Spec Kit does not add trust flags automatically. + +Spec Kit does not write hooks through a symlinked `.github/hooks` directory, so +`init`, `integration install`, and `integration upgrade` fail there with events +enabled. Use `--integration-options="--events false"` to +opt out of events, disabling `additional_context` delivery and extension event +hooks for Copilot. + ## Default Skills Layout Skills are installed as `.github/skills/speckit-/SKILL.md`. @@ -102,7 +117,9 @@ a newly created settings file is manifest-tracked. ## Runtime Events and Workflow Permissions -Native events use `.github/hooks/speckit.json`. +With events enabled, Copilot projects get `.specify/events.py` and +`.github/hooks/speckit.json` by default, including a built-in `session_start` +handler for additional context. `--integration-options="--events false"` disables Spec Kit event handlers. See [runtime events](cli.md#runtime-events). diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index b3489eb265..cb6319b6ce 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -71,7 +71,9 @@ integrations: An override replaces the integration's entire event map, so include any other handlers you want to keep. -No built-in integration declares support yet. +| Integration | Guide and agent-side preconditions | +| ----------- | ---------------------------------- | +| `copilot` | [Copilot](../integrations/copilot.md#additional-context-and-folder-trust) | An integration's agent-side trust, authentication, and feature gates are outside Spec Kit's control. Older external adapters that override diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index fa8d048d62..9f31140870 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2555,6 +2555,37 @@ def _remove_toml_entries(dst: Path, *, project_root: Path) -> bool: return False +def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]]: + """Read owned, correctly routed dispatcher handlers from Copilot hooks.""" + config_file = getattr(integration, "events_config_file", None) + if not config_file: + return {} + existing = _load_user_json(project_root / config_file) + hooks = existing.get("hooks", {}) if existing is not None else {} + if not isinstance(hooks, dict): + return {} + target = "windows" if os.name == "nt" else "posix" + field = "powershell" if target == "windows" else "bash" + result: dict[str, list[str]] = {} + for canonical, native in getattr(integration, "CANONICAL_TO_NATIVE", {}).items(): + entries = hooks.get(native, []) + if not isinstance(entries, list): + continue + for entry in entries: + if not isinstance(entry, dict) or entry.get(_SPECKIT_MARKER) is not True: + continue + command = entry.get(field) + if not isinstance(command, str): + continue + parsed = _parse_dispatcher_command(command, integration, project_root, target_os=target) + if parsed and parsed[1:] == (canonical, context_envelope_for(integration, canonical)): + result.setdefault(canonical, []).append(parsed[0]) + return result + + +_EVENT_HANDLER_READERS["copilot-json"] = _read_copilot_json_handlers + + def _merge_copilot_json(dst: Path, new_hooks: dict[str, list], *, project_root: Path) -> bool: """Merge Specify-owned hooks into Copilot's dedicated hooks JSON (#8). diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 69fee33147..8403a27328 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -184,6 +184,7 @@ class CopilotIntegration(IntegrationBase): } events_config_file = ".github/hooks/speckit.json" events_format = "copilot-json" + context_delivery_events = frozenset({"session_start"}) # Copilot consumes additionalContext from sessionStart and drops command # hook output from userPromptSubmitted. events_context_envelope = { diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index e720a6e3c1..86797694f5 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -328,6 +328,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", + ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -338,6 +339,7 @@ def test_complete_file_inventory_sh(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", + ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -392,6 +394,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/agents/speckit.plan.agent.md", ".github/agents/speckit.specify.agent.md", ".github/agents/speckit.tasks.agent.md", + ".github/hooks/speckit.json", ".github/prompts/speckit.analyze.prompt.md", ".github/prompts/speckit.checklist.prompt.md", ".github/prompts/speckit.clarify.prompt.md", @@ -402,6 +405,7 @@ def test_complete_file_inventory_ps(self, tmp_path): ".github/prompts/speckit.specify.prompt.md", ".github/prompts/speckit.tasks.prompt.md", ".vscode/settings.json", + ".specify/events.py", ".specify/integration.json", ".specify/init-options.json", ".specify/integrations/copilot.manifest.json", @@ -912,6 +916,8 @@ def test_complete_file_inventory_skills_sh(self, tmp_path): assert result.exit_code == 0, f"init failed: {result.output}" actual = sorted(p.relative_to(project).as_posix() for p in project.rglob("*") if p.is_file() and ".git" not in p.parts) expected = sorted([ + ".github/hooks/speckit.json", + ".specify/events.py", # Skill files (core commands) *[f".github/skills/speckit-{cmd}/SKILL.md" for cmd in self._SKILL_COMMANDS], # Integration metadata @@ -1681,3 +1687,119 @@ def run(args, **kwargs): tmp_path / ".specify" / "workflows" / "runs" / state.run_id / "log.jsonl" ).read_text(encoding="utf-8") assert _SECRET_OUTPUT not in log + + +@pytest.fixture +def context_delivery_install(tmp_path): + from specify_cli.events import install_integration_events, resolve_events + + copilot = get_integration("copilot") + state = tmp_path / ".specify/integration.json" + state.parent.mkdir() + state.write_text(json.dumps({ + "default_integration": "copilot", "installed_integrations": ["copilot"] + }), encoding="utf-8") + manifest = IntegrationManifest("copilot", tmp_path, version="test") + install_integration_events(copilot, tmp_path, manifest, resolve_events("copilot", copilot.config, tmp_path, None)) + return copilot + + +def test_copilot_context_delivery_install(tmp_path, context_delivery_install): + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, context_delivery_error + + copilot = context_delivery_install + native = json.loads((tmp_path / copilot.events_config_file).read_text(encoding="utf-8")) + entry = native["hooks"]["sessionStart"][0] + assert entry["__speckit_event__"] is True + assert all(ADDITIONAL_CONTEXT_HANDLER in entry[field] for field in ("bash", "powershell")) + assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(copilot, tmp_path) is None + + +@pytest.mark.parametrize("damage", [ + "malformed", "jsonc", "wrong_native_event", "wrong_command", "wrong_canonical_event", + "wrong_envelope", "unmarked", "marker_not_true", "stale_dispatcher", "modified_dispatcher", +]) +def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_delivery_install, damage): + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, context_delivery_error + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + native = json.loads(path.read_text(encoding="utf-8")) + entry = native["hooks"]["sessionStart"][0] + if damage == "wrong_native_event": + native["hooks"]["sessionEnd"] = native["hooks"].pop("sessionStart") + elif damage in ("wrong_command", "wrong_canonical_event", "wrong_envelope"): + original, replacement = { + "wrong_command": (ADDITIONAL_CONTEXT_HANDLER, "other-handler"), + "wrong_canonical_event": ("session_start", "session_end"), + "wrong_envelope": ("additionalContext", "plain"), + }[damage] + for field in ("bash", "powershell"): + entry[field] = entry[field].replace(original, replacement) + elif damage == "unmarked": + entry.pop("__speckit_event__") + elif damage == "marker_not_true": + entry["__speckit_event__"] = 1 + elif damage in ("stale_dispatcher", "modified_dispatcher"): + dispatcher = tmp_path / ".specify/events.py" + dispatcher.write_text("# stale\n" if damage == "stale_dispatcher" else + dispatcher.read_text(encoding="utf-8") + "# modified\n", encoding="utf-8") + content = {"malformed": "{", "jsonc": '{// comment\n"hooks": {}}'}.get(damage, json.dumps(native)) + path.write_text(content, encoding="utf-8") + error = context_delivery_error(copilot, tmp_path) + assert "missing or outdated" in error + assert "specify integration upgrade copilot" in error + + +@pytest.mark.parametrize("target,selected,other", [("posix", "bash", "powershell"), ("nt", "powershell", "bash")]) +def test_copilot_context_delivery_selects_current_platform_command( + tmp_path, context_delivery_install, monkeypatch, target, selected, other +): + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + native = json.loads(path.read_text(encoding="utf-8")) + entry = native["hooks"]["sessionStart"][0] + valid = entry[other] + entry[other] = "broken" + path.write_text(json.dumps(native), encoding="utf-8") + with monkeypatch.context() as patcher: + patcher.setattr("specify_cli.events.os.name", target) + assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + entry[other], entry[selected] = valid, "broken" + path.write_text(json.dumps(native), encoding="utf-8") + assert copilot.installed_event_handlers(tmp_path) == {} + + +def test_copilot_context_delivery_reader_maps_owned_handlers(tmp_path, context_delivery_install): + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, _dispatcher_command + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + native = json.loads(path.read_text(encoding="utf-8")) + start = native["hooks"]["sessionStart"][0] + command = _dispatcher_command(copilot, tmp_path, "end-handler", "session_end", target_os="posix") + ps_command = _dispatcher_command(copilot, tmp_path, "end-handler", "session_end", target_os="windows") + end = {"__speckit_event__": True, "bash": command, "powershell": ps_command} + native["hooks"]["sessionStart"].extend([None, {}, {**start, "__speckit_event__": False}, start]) + native["hooks"]["sessionEnd"] = [end] + native["hooks"]["unknown"] = [start] + path.write_text(json.dumps(native), encoding="utf-8") + assert copilot.installed_event_handlers(tmp_path) == { + "session_start": [ADDITIONAL_CONTEXT_HANDLER, ADDITIONAL_CONTEXT_HANDLER], + "session_end": ["end-handler"], + } + + +@pytest.mark.parametrize("content", ['[]', '{"hooks": []}', '{"hooks": {"sessionStart": {}}}']) +def test_copilot_context_delivery_reader_rejects_non_object_or_invalid_hooks( + tmp_path, context_delivery_install, content +): + from specify_cli.events import context_delivery_error + + copilot = context_delivery_install + (tmp_path / copilot.events_config_file).write_text(content, encoding="utf-8") + assert copilot.installed_event_handlers(tmp_path) == {} + assert "missing or outdated" in context_delivery_error(copilot, tmp_path) diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index f83cfe8954..0645f9b46d 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -523,6 +523,7 @@ def test_invalid_installed_native_handler_is_rejected(tmp_path, installed, damag def test_unreadable_handler_report_and_unknown_format(tmp_path, installed, monkeypatch): + monkeypatch.setattr(installed, "events_format", "unknown-format") assert IntegrationBase.installed_event_handlers(installed, tmp_path) is None monkeypatch.setattr(installed, "installed_event_handlers", lambda root: None) error = context_delivery_error(installed, tmp_path) @@ -564,12 +565,14 @@ def reader(adapter, root): assert seen == [(integration, tmp_path)] -def test_copilot_is_not_a_context_delivery_declarer(tmp_path): +def test_copilot_is_a_context_delivery_declarer(tmp_path): copilot = get_integration("copilot") - assert resolve_events("copilot", copilot.config, tmp_path, None) == {} + assert resolve_events("copilot", copilot.config, tmp_path, None) == { + "session_start": [{"command": ADDITIONAL_CONTEXT_HANDLER}] + } error = context_delivery_error(copilot, tmp_path) - assert "not declared" in error - assert "Supporting integrations: none" in error + assert "not installed" in error + assert "Supporting integrations: copilot" in error def test_parse_dispatcher_with_project_venv_interpreter(tmp_path): diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 4b24a86ec6..0e5cda0f28 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -142,7 +142,7 @@ def test_reinit_preserves_feature_numbering(tmp_path: Path, monkeypatch, numberi assert updated["here"] is True -def test_init_copilot_with_missing_config_in_symlinked_hooks_dir(tmp_path, monkeypatch): +def test_init_copilot_refuses_symlinked_hooks_dir(tmp_path, monkeypatch): project = tmp_path / "project" outside = tmp_path / "outside" (project / ".github").mkdir(parents=True) @@ -156,8 +156,30 @@ def test_init_copilot_with_missing_config_in_symlinked_hooks_dir(tmp_path, monke "--ignore-agent-tools", "--force", ]) + assert result.exit_code != 0, result.output + assert "Refusing to record symlinked manifest path:" in result.output + assert ".github/hooks/speckit.json (symlinked at .github/hooks)" in result.output + assert hooks.is_symlink() + assert not list(outside.iterdir()) + + +def test_init_copilot_with_events_disabled_allows_symlinked_hooks_dir(tmp_path, monkeypatch): + project = tmp_path / "project" + outside = tmp_path / "outside" + (project / ".github").mkdir(parents=True) + outside.mkdir() + hooks = project / ".github/hooks" + _symlink_or_skip(hooks, outside, directory=True) + monkeypatch.chdir(project) + + result = CliRunner().invoke(app, [ + "init", ".", "--integration", "copilot", "--script", "sh", + "--ignore-agent-tools", "--force", "--integration-options=--events false", + ]) + assert result.exit_code == 0, result.output assert hooks.is_symlink() + assert not (hooks / "speckit.json").exists() assert not list(outside.iterdir()) From 498ca2ed5e9aaa9394fcbffb7b03510312cd2ea9 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 2 Dec 2026 21:55:56 +0100 Subject: [PATCH 16/20] fix(copilot): validate event setup and installed hooks Reject symlinked event destinations before lifecycle writes, preserving no-op disabled setups. Distinguish unreadable hook configuration from absent hooks and reject explicit non-command types while honoring the native default for omitted type. Normalize platform separators in symlink assertions. Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous) Assisted-by: pi coding agent (model: mai-code-2, autonomous) --- docs/integrations/copilot.md | 15 ++- src/specify_cli/events/__init__.py | 10 +- .../integrations/copilot/__init__.py | 19 +++ .../integrations/test_integration_copilot.py | 110 +++++++++++++++++- tests/specify_cli/test_command_init.py | 5 +- 5 files changed, 144 insertions(+), 15 deletions(-) diff --git a/docs/integrations/copilot.md b/docs/integrations/copilot.md index 252b608505..e16597200b 100644 --- a/docs/integrations/copilot.md +++ b/docs/integrations/copilot.md @@ -26,11 +26,16 @@ Trust the folder through Copilot's trust prompt or `trustedFolders` in untrusted folder Copilot skips hooks, drops additional context, and still exits successfully. Spec Kit does not add trust flags automatically. -Spec Kit does not write hooks through a symlinked `.github/hooks` directory, so -`init`, `integration install`, and `integration upgrade` fail there with events -enabled. Use `--integration-options="--events false"` to -opt out of events, disabling `additional_context` delivery and extension event -hooks for Copilot. +Spec Kit does not write hooks through a symlinked `.github/hooks` directory. +When Copilot hooks are configured, `init` fails there, and `integration install`, +`switch`, and `upgrade` refuse before changing project files. Use +`--integration-options="--events false"` to opt out of `additional_context` +delivery and extension event hooks. This allows a symlinked hook directory +only when it has no `speckit.json` to clean up. + +If `.github/hooks/speckit.json` cannot be read as a JSON object, upgrade +preserves it rather than overwriting it. Fix the file or move it aside, then +run `specify integration upgrade copilot` to restore context delivery. ## Default Skills Layout diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 9f31140870..4d2175396c 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2555,13 +2555,15 @@ def _remove_toml_entries(dst: Path, *, project_root: Path) -> bool: return False -def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]]: - """Read owned, correctly routed dispatcher handlers from Copilot hooks.""" +def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]] | None: + """Read owned, correctly routed handlers, or None for unreadable config.""" config_file = getattr(integration, "events_config_file", None) if not config_file: return {} existing = _load_user_json(project_root / config_file) - hooks = existing.get("hooks", {}) if existing is not None else {} + if existing is None: + return None + hooks = existing.get("hooks", {}) if not isinstance(hooks, dict): return {} target = "windows" if os.name == "nt" else "posix" @@ -2574,6 +2576,8 @@ def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path for entry in entries: if not isinstance(entry, dict) or entry.get(_SPECKIT_MARKER) is not True: continue + if entry.get("type", "command") != "command": + continue command = entry.get(field) if not isinstance(command, str): continue diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 8403a27328..a7a655d5f7 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -663,6 +663,25 @@ def post_process_skill_content(self, content: str) -> str: ) return updated + def preflight_setup( + self, + project_root: Path, + parsed_options: dict[str, Any] | None = None, + *, + script_type: str | None = None, + ) -> None: + """Reject unsafe event destinations before the CLI writes files.""" + from ...events import EVENTS_DISPATCHER_REL, _ensure_safe_destination, resolve_events + + events = resolve_events(self.key, self.config, project_root, parsed_options) + writes_hooks = any(event in self.CANONICAL_TO_NATIVE for event in events) + config_path = project_root / self.events_config_file + if writes_hooks: + _ensure_safe_destination(project_root / EVENTS_DISPATCHER_REL, project_root) + # An empty event map still removes old hooks if the config exists. + if writes_hooks or config_path.exists(): + _ensure_safe_destination(config_path, project_root) + def setup( self, project_root: Path, diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 86797694f5..10464d7ccf 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -1689,6 +1689,77 @@ def run(args, **kwargs): assert _SECRET_OUTPUT not in log +@pytest.mark.parametrize("action", ["install", "upgrade"]) +@pytest.mark.parametrize("case", ["default", "disabled-present", "disabled-absent", "disabled-dangling", "empty-override"]) +def test_copilot_hook_preflight_with_symlinked_directory(tmp_path, action, case): + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + if action == "install": + project = _init_project(tmp_path, "claude") + # Install would recreate missing shared infrastructure before setup. + (project / ".specify/templates/plan-template.md").unlink() + else: + project = _init_project(tmp_path, "copilot", "--events false") + # A forced upgrade would overwrite this template and skill before hooks. + (project / ".specify/templates/plan-template.md").write_text("local template\n", encoding="utf-8") + (project / ".github/skills/speckit-plan/SKILL.md").write_text("local skill\n", encoding="utf-8") + + outside = tmp_path / "outside" + outside.mkdir() + (outside / "sentinel").write_text("outside file\n", encoding="utf-8") + config = outside / "speckit.json" + if case == "disabled-present": + config.write_text('{"hooks":{"sessionStart":[{"__speckit_event__":true}]}}\n', encoding="utf-8") + elif case == "disabled-dangling": + _symlink_or_skip(config, outside / "missing.json") + hooks = project / ".github/hooks" + hooks.parent.mkdir(exist_ok=True) + _symlink_or_skip(hooks, outside, directory=True) + + args = ["integration", action, "copilot", "--force"] + if case.startswith("disabled-") and action == "install": + args.append("--integration-options=--events false") + elif not case.startswith("disabled-") and action == "upgrade": + args.append("--integration-options=") # Clear the persisted --events false. + if case == "empty-override": + (project / ".specify/integration-events.yml").write_text( + "integrations:\n copilot:\n events: {}\n", encoding="utf-8", + ) + + before_project, before_outside = _tree(project), _tree(outside) + result = _run_in_project(project, args) + if case in ("default", "disabled-present"): + assert result.exit_code == 1, result.output + assert _tree(project) == before_project + output = " ".join(result.output.replace("\\", "/").split()) + assert ".github/hooks/speckit.json (symlinked at .github/hooks)" in output + assert "No files were changed." in output + else: + assert result.exit_code == 0, result.output + assert (project / ".github/skills/speckit-plan/SKILL.md").is_file() + assert not (project / ".specify/events.py").exists() + assert hooks.is_symlink() + assert _tree(outside) == before_outside + + +def test_copilot_hook_preflight_rejects_symlinked_dispatcher(tmp_path): + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "copilot", "--events false") + outside = tmp_path / "outside.py" + outside.write_bytes(b"# outside\n") + _symlink_or_skip(project / ".specify/events.py", outside) + (project / ".specify/templates/plan-template.md").write_text("local template\n", encoding="utf-8") + before = _tree(project) + + result = _run_in_project(project, ["integration", "upgrade", "copilot", "--force", "--integration-options="]) + + assert result.exit_code == 1, result.output + assert _tree(project) == before + assert outside.read_bytes() == b"# outside\n" + assert "No files were changed." in result.output + + @pytest.fixture def context_delivery_install(tmp_path): from specify_cli.events import install_integration_events, resolve_events @@ -1710,6 +1781,7 @@ def test_copilot_context_delivery_install(tmp_path, context_delivery_install): copilot = context_delivery_install native = json.loads((tmp_path / copilot.events_config_file).read_text(encoding="utf-8")) entry = native["hooks"]["sessionStart"][0] + assert entry["type"] == "command" assert entry["__speckit_event__"] is True assert all(ADDITIONAL_CONTEXT_HANDLER in entry[field] for field in ("bash", "powershell")) assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} @@ -1717,7 +1789,7 @@ def test_copilot_context_delivery_install(tmp_path, context_delivery_install): @pytest.mark.parametrize("damage", [ - "malformed", "jsonc", "wrong_native_event", "wrong_command", "wrong_canonical_event", + "wrong_native_event", "wrong_type", "null_type", "wrong_command", "wrong_canonical_event", "wrong_envelope", "unmarked", "marker_not_true", "stale_dispatcher", "modified_dispatcher", ]) def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_delivery_install, damage): @@ -1729,6 +1801,10 @@ def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_deli entry = native["hooks"]["sessionStart"][0] if damage == "wrong_native_event": native["hooks"]["sessionEnd"] = native["hooks"].pop("sessionStart") + elif damage == "wrong_type": + entry["type"] = "prompt" + elif damage == "null_type": + entry["type"] = None elif damage in ("wrong_command", "wrong_canonical_event", "wrong_envelope"): original, replacement = { "wrong_command": (ADDITIONAL_CONTEXT_HANDLER, "other-handler"), @@ -1745,8 +1821,7 @@ def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_deli dispatcher = tmp_path / ".specify/events.py" dispatcher.write_text("# stale\n" if damage == "stale_dispatcher" else dispatcher.read_text(encoding="utf-8") + "# modified\n", encoding="utf-8") - content = {"malformed": "{", "jsonc": '{// comment\n"hooks": {}}'}.get(damage, json.dumps(native)) - path.write_text(content, encoding="utf-8") + path.write_text(json.dumps(native), encoding="utf-8") error = context_delivery_error(copilot, tmp_path) assert "missing or outdated" in error assert "specify integration upgrade copilot" in error @@ -1793,8 +1868,33 @@ def test_copilot_context_delivery_reader_maps_owned_handlers(tmp_path, context_d } -@pytest.mark.parametrize("content", ['[]', '{"hooks": []}', '{"hooks": {"sessionStart": {}}}']) -def test_copilot_context_delivery_reader_rejects_non_object_or_invalid_hooks( +@pytest.mark.parametrize("content", ["{", '{// comment\n"hooks": {}}', "[]"], ids=["malformed", "jsonc", "non-object"]) +def test_copilot_context_delivery_unreadable_config_requires_repair(tmp_path, context_delivery_install, content): + from specify_cli.events import context_delivery_error + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + path.write_text(content, encoding="utf-8") + error = context_delivery_error(copilot, tmp_path) + assert "native events config '.github/hooks/speckit.json' could not be read" in error + assert "Fix '.github/hooks/speckit.json' or move it aside, then run 'specify integration upgrade copilot'." in error + assert copilot.installed_event_handlers(tmp_path) is None + assert path.read_text(encoding="utf-8") == content + + +def test_copilot_context_delivery_missing_config_only_requires_upgrade(tmp_path, context_delivery_install): + from specify_cli.events import context_delivery_error + + copilot = context_delivery_install + (tmp_path / copilot.events_config_file).unlink() + error = context_delivery_error(copilot, tmp_path) + assert "missing or outdated" in error + assert "Run 'specify integration upgrade copilot'." in error + assert copilot.installed_event_handlers(tmp_path) == {} + + +@pytest.mark.parametrize("content", ['{"hooks": []}', '{"hooks": {"sessionStart": {}}}']) +def test_copilot_context_delivery_reader_rejects_invalid_hooks( tmp_path, context_delivery_install, content ): from specify_cli.events import context_delivery_error diff --git a/tests/specify_cli/test_command_init.py b/tests/specify_cli/test_command_init.py index 0e5cda0f28..ef870c625b 100644 --- a/tests/specify_cli/test_command_init.py +++ b/tests/specify_cli/test_command_init.py @@ -157,8 +157,9 @@ def test_init_copilot_refuses_symlinked_hooks_dir(tmp_path, monkeypatch): ]) assert result.exit_code != 0, result.output - assert "Refusing to record symlinked manifest path:" in result.output - assert ".github/hooks/speckit.json (symlinked at .github/hooks)" in result.output + output = " ".join(result.output.replace("\\", "/").split()) + assert "Refusing to record symlinked manifest path:" in output + assert ".github/hooks/speckit.json (symlinked at .github/hooks)" in output assert hooks.is_symlink() assert not list(outside.iterdir()) From 266b04f59545c7a89c516d01c8f064296b3b5b1c Mon Sep 17 00:00:00 2001 From: Markus Date: Thu, 3 Dec 2026 18:58:24 +0100 Subject: [PATCH 17/20] fix(copilot): validate hook working directory and cleanup preflight Reject context hooks whose working directory is not the project root. Check dispatcher cleanup before an events-disabled setup can write files, and exercise symlink refusal and opt-out during switch. Assisted-by: pi coding agent (model: gemini-4-hydrogen, autonomous) Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous) --- docs/integrations/copilot.md | 15 +- src/specify_cli/events/__init__.py | 12 ++ .../integrations/copilot/__init__.py | 22 ++- .../integrations/test_integration_copilot.py | 145 +++++++++++++++++- 4 files changed, 176 insertions(+), 18 deletions(-) diff --git a/docs/integrations/copilot.md b/docs/integrations/copilot.md index e16597200b..6799c4bfd2 100644 --- a/docs/integrations/copilot.md +++ b/docs/integrations/copilot.md @@ -26,12 +26,15 @@ Trust the folder through Copilot's trust prompt or `trustedFolders` in untrusted folder Copilot skips hooks, drops additional context, and still exits successfully. Spec Kit does not add trust flags automatically. -Spec Kit does not write hooks through a symlinked `.github/hooks` directory. -When Copilot hooks are configured, `init` fails there, and `integration install`, -`switch`, and `upgrade` refuse before changing project files. Use -`--integration-options="--events false"` to opt out of `additional_context` -delivery and extension event hooks. This allows a symlinked hook directory -only when it has no `speckit.json` to clean up. +Spec Kit does not write hooks through a symlinked `.github/hooks` directory or +a symlinked `.specify/events.py` dispatcher. When Copilot hooks are configured, +`init` fails there, and `integration install`, `switch`, and `upgrade` refuse +before changing project files. Use `--integration-options="--events false"` to +opt out of `additional_context` delivery and extension event hooks. This allows +a symlinked `.github/hooks` directory only when no existing `speckit.json` +target exists there to inspect (regardless of ownership), and allows a +symlinked `.specify/events.py` only when cleanup would skip it (for example, +when it is unowned or another installed integration still references it). If `.github/hooks/speckit.json` cannot be read as a JSON object, upgrade preserves it rather than overwriting it. Fix the file or move it aside, then diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 4d2175396c..7703b5c19d 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2555,6 +2555,16 @@ def _remove_toml_entries(dst: Path, *, project_root: Path) -> bool: return False +def _copilot_cwd_is_root(cwd: Any, project_root: Path) -> bool: + """Return True iff *cwd* lexically names the project root without walking paths.""" + if not isinstance(cwd, str) or not cwd or "\x00" in cwd: + return False + cwd_path = Path(cwd) + if not cwd_path.is_absolute(): + return not cwd_path.drive and not cwd_path.root and cwd_path.parts == () + return cwd_path == project_root.absolute() + + def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]] | None: """Read owned, correctly routed handlers, or None for unreadable config.""" config_file = getattr(integration, "events_config_file", None) @@ -2578,6 +2588,8 @@ def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path continue if entry.get("type", "command") != "command": continue + if "cwd" in entry and not _copilot_cwd_is_root(entry["cwd"], project_root): + continue command = entry.get(field) if not isinstance(command, str): continue diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index a7a655d5f7..8d98f27fad 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -671,16 +671,26 @@ def preflight_setup( script_type: str | None = None, ) -> None: """Reject unsafe event destinations before the CLI writes files.""" - from ...events import EVENTS_DISPATCHER_REL, _ensure_safe_destination, resolve_events + from ...events import ( + EVENTS_DISPATCHER_REL, + _cleanup_shared_dispatcher, + _ensure_safe_destination, + _remove_native_event_hooks, + resolve_events, + ) events = resolve_events(self.key, self.config, project_root, parsed_options) - writes_hooks = any(event in self.CANONICAL_TO_NATIVE for event in events) - config_path = project_root / self.events_config_file + writes_hooks = any( + isinstance(handlers, list) and event in self.CANONICAL_TO_NATIVE + for event, handlers in events.items() + ) if writes_hooks: _ensure_safe_destination(project_root / EVENTS_DISPATCHER_REL, project_root) - # An empty event map still removes old hooks if the config exists. - if writes_hooks or config_path.exists(): - _ensure_safe_destination(config_path, project_root) + _ensure_safe_destination(project_root / self.events_config_file, project_root) + else: + # Empty event maps still remove old native hooks and owned dispatchers. + _remove_native_event_hooks(self, project_root, None, check_only=True) + _cleanup_shared_dispatcher(self, project_root, None, check_only=True) def setup( self, diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 10464d7ccf..3014a04bc4 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -1689,15 +1689,16 @@ def run(args, **kwargs): assert _SECRET_OUTPUT not in log -@pytest.mark.parametrize("action", ["install", "upgrade"]) +@pytest.mark.parametrize("action", ["install", "switch", "upgrade"]) @pytest.mark.parametrize("case", ["default", "disabled-present", "disabled-absent", "disabled-dangling", "empty-override"]) def test_copilot_hook_preflight_with_symlinked_directory(tmp_path, action, case): from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree - if action == "install": + if action in ("install", "switch"): project = _init_project(tmp_path, "claude") - # Install would recreate missing shared infrastructure before setup. - (project / ".specify/templates/plan-template.md").unlink() + if action == "install": + # Install would recreate missing shared infrastructure before setup. + (project / ".specify/templates/plan-template.md").unlink() else: project = _init_project(tmp_path, "copilot", "--events false") # A forced upgrade would overwrite this template and skill before hooks. @@ -1716,8 +1717,10 @@ def test_copilot_hook_preflight_with_symlinked_directory(tmp_path, action, case) hooks.parent.mkdir(exist_ok=True) _symlink_or_skip(hooks, outside, directory=True) - args = ["integration", action, "copilot", "--force"] - if case.startswith("disabled-") and action == "install": + args = ["integration", action, "copilot"] + if action != "switch": + args.append("--force") + if case.startswith("disabled-") and action in ("install", "switch"): args.append("--integration-options=--events false") elif not case.startswith("disabled-") and action == "upgrade": args.append("--integration-options=") # Clear the persisted --events false. @@ -1738,6 +1741,12 @@ def test_copilot_hook_preflight_with_symlinked_directory(tmp_path, action, case) assert result.exit_code == 0, result.output assert (project / ".github/skills/speckit-plan/SKILL.md").is_file() assert not (project / ".specify/events.py").exists() + if action == "switch": + assert not (project / ".claude/commands/speckit.plan.md").exists() + assert not (project / ".specify/integrations/claude.manifest.json").exists() + state = json.loads((project / ".specify/integration.json").read_text(encoding="utf-8")) + assert state["default_integration"] == "copilot" + assert state["installed_integrations"] == ["copilot"] assert hooks.is_symlink() assert _tree(outside) == before_outside @@ -1760,6 +1769,80 @@ def test_copilot_hook_preflight_rejects_symlinked_dispatcher(tmp_path): assert "No files were changed." in result.output +def test_copilot_hook_preflight_rejects_owned_symlinked_dispatcher_on_disable(tmp_path): + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "copilot") + sibling = tmp_path / "sibling.py" + sibling.write_bytes(b"# benign sibling\n") + dispatcher = project / ".specify/events.py" + dispatcher.unlink() + _symlink_or_skip(dispatcher, sibling) + (project / ".github/skills/speckit-plan/SKILL.md").write_text("local skill\n", encoding="utf-8") + before = _tree(project) + + result = _run_in_project( + project, + ["integration", "upgrade", "copilot", "--force", "--integration-options=--events false"], + ) + + assert result.exit_code == 1, result.output + assert _tree(project) == before + assert sibling.read_bytes() == b"# benign sibling\n" + assert (project / ".github/hooks/speckit.json").is_file() + output = " ".join(result.output.replace("\\", "/").split()) + assert ".specify/events.py" in output + assert "No files were changed." in output + + +@pytest.mark.parametrize("case", ["unowned", "referenced"]) +def test_copilot_hook_preflight_allows_preserved_symlinked_dispatcher_on_disable(tmp_path, case): + from specify_cli.events import EVENTS_DISPATCHER_REL, install_integration_events + from specify_cli.integrations.claude import ClaudeIntegration + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip + + if case == "unowned": + project = _init_project(tmp_path, "copilot", "--events false") + # Recreate a non-empty native config so disable still cleans hooks while skipping unowned dispatcher. + hooks_path = project / ".github/hooks/speckit.json" + hooks_path.parent.mkdir(parents=True, exist_ok=True) + hooks_path.write_text('{"hooks":{"sessionStart":[{"__speckit_event__":true}]}}\n', encoding="utf-8") + else: + project = _init_project(tmp_path, "copilot") + install_res = _run_in_project( + project, + ["integration", "install", "claude", "--force", "--script", "sh"], + ) + assert install_res.exit_code == 0, install_res.output + claude = ClaudeIntegration() + claude_manifest = IntegrationManifest("claude", project) + install_integration_events( + claude, + project, + claude_manifest, + {"pre_tool_use": [{"command": "speckit.check"}]}, + ) + claude_manifest.save() + assert EVENTS_DISPATCHER_REL in IntegrationManifest.load("claude", project).files + + sibling = tmp_path / "sibling.py" + sibling.write_bytes(b"# preserved sibling\n") + dispatcher = project / ".specify/events.py" + if dispatcher.exists() or dispatcher.is_symlink(): + dispatcher.unlink() + _symlink_or_skip(dispatcher, sibling) + + result = _run_in_project( + project, + ["integration", "upgrade", "copilot", "--force", "--integration-options=--events false"], + ) + + assert result.exit_code == 0, result.output + assert dispatcher.is_symlink() + assert sibling.read_bytes() == b"# preserved sibling\n" + assert not (project / ".github/hooks/speckit.json").exists() + + @pytest.fixture def context_delivery_install(tmp_path): from specify_cli.events import install_integration_events, resolve_events @@ -1903,3 +1986,53 @@ def test_copilot_context_delivery_reader_rejects_invalid_hooks( (tmp_path / copilot.events_config_file).write_text(content, encoding="utf-8") assert copilot.installed_event_handlers(tmp_path) == {} assert "missing or outdated" in context_delivery_error(copilot, tmp_path) + + +def test_copilot_context_delivery_accepts_root_cwd_variants(tmp_path, context_delivery_install): + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, context_delivery_error + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + for cwd in (".", "./", "./.", str(tmp_path), str(tmp_path.absolute())): + native = json.loads(path.read_text(encoding="utf-8")) + native["hooks"]["sessionStart"][0]["cwd"] = cwd + path.write_text(json.dumps(native), encoding="utf-8") + assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]}, cwd + assert context_delivery_error(copilot, tmp_path) is None, cwd + + +@pytest.mark.parametrize( + "cwd", + [ + "docs", + "../outside", + "docs/..", + "cycle", + "", + " ", + None, + 123, + ["."], + False, + ], + ids=["subdir", "parent", "traversal", "symlink_cycle", "empty", "whitespace", "null", "int", "list", "bool"], +) +def test_copilot_context_delivery_rejects_non_root_or_invalid_cwd( + tmp_path, context_delivery_install, cwd +): + from specify_cli.events import context_delivery_error + from tests.specify_cli.integrations._helpers import _symlink_or_skip + + copilot = context_delivery_install + (tmp_path / "docs").mkdir(exist_ok=True) + if cwd == "cycle": + _symlink_or_skip(tmp_path / "cycle", tmp_path / "cycle") + path = tmp_path / copilot.events_config_file + native = json.loads(path.read_text(encoding="utf-8")) + native["hooks"]["sessionStart"][0]["cwd"] = cwd + path.write_text(json.dumps(native), encoding="utf-8") + + assert copilot.installed_event_handlers(tmp_path) == {} + error = context_delivery_error(copilot, tmp_path) + assert "missing or outdated" in error + assert "specify integration upgrade copilot" in error From 067b9e5fb6508731651e42f09bec5db1d770c26f Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 08:29:22 +0100 Subject: [PATCH 18/20] refactor(copilot): rely on lifecycle event preflight Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- .../integrations/copilot/__init__.py | 29 ------------------- 1 file changed, 29 deletions(-) diff --git a/src/specify_cli/integrations/copilot/__init__.py b/src/specify_cli/integrations/copilot/__init__.py index 8d98f27fad..8403a27328 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -663,35 +663,6 @@ def post_process_skill_content(self, content: str) -> str: ) return updated - def preflight_setup( - self, - project_root: Path, - parsed_options: dict[str, Any] | None = None, - *, - script_type: str | None = None, - ) -> None: - """Reject unsafe event destinations before the CLI writes files.""" - from ...events import ( - EVENTS_DISPATCHER_REL, - _cleanup_shared_dispatcher, - _ensure_safe_destination, - _remove_native_event_hooks, - resolve_events, - ) - - events = resolve_events(self.key, self.config, project_root, parsed_options) - writes_hooks = any( - isinstance(handlers, list) and event in self.CANONICAL_TO_NATIVE - for event, handlers in events.items() - ) - if writes_hooks: - _ensure_safe_destination(project_root / EVENTS_DISPATCHER_REL, project_root) - _ensure_safe_destination(project_root / self.events_config_file, project_root) - else: - # Empty event maps still remove old native hooks and owned dispatchers. - _remove_native_event_hooks(self, project_root, None, check_only=True) - _cleanup_shared_dispatcher(self, project_root, None, check_only=True) - def setup( self, project_root: Path, From 4e6c73f2c8c7eabc3416fb06f45498a595cd604c Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 15:10:54 +0100 Subject: [PATCH 19/20] fix(copilot): reject symlinked installed hook configs Read the native hook file through deny-mode FileHelper during context-delivery preflight, preserving missing and malformed configuration diagnostics. Cover linked files and linked parents without changing their targets. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) --- src/specify_cli/events/__init__.py | 20 +++++++++-- .../integrations/test_integration_copilot.py | 34 ++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/events/__init__.py b/src/specify_cli/events/__init__.py index 7703b5c19d..0c2939eb17 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2570,8 +2570,24 @@ def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path config_file = getattr(integration, "events_config_file", None) if not config_file: return {} - existing = _load_user_json(project_root / config_file) - if existing is None: + try: + with FileHelper(project_root) as files: + existing = json.loads(files.read_text(config_file, encoding="utf-8")) + except FileNotFoundError: + return {} + except (FileHelperError, RuntimeError): + return None + except (OSError, ValueError) as exc: + logger.warning( + "Could not read or parse %s (it may be unreadable, contain JSONC " + "comments, or be malformed); " + "skipping event-config merge to preserve user content.", + project_root / config_file, + ) + logger.debug("Read/parse error detail: %s", exc) + return None + if not isinstance(existing, dict): + logger.warning("%s is not a JSON object; skipping event-config merge.", project_root / config_file) return None hooks = existing.get("hooks", {}) if not isinstance(hooks, dict): diff --git a/tests/integrations/test_integration_copilot.py b/tests/integrations/test_integration_copilot.py index 3014a04bc4..ed9c4a214c 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -1914,6 +1914,8 @@ def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_deli def test_copilot_context_delivery_selects_current_platform_command( tmp_path, context_delivery_install, monkeypatch, target, selected, other ): + from types import SimpleNamespace + from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER copilot = context_delivery_install @@ -1924,7 +1926,7 @@ def test_copilot_context_delivery_selects_current_platform_command( entry[other] = "broken" path.write_text(json.dumps(native), encoding="utf-8") with monkeypatch.context() as patcher: - patcher.setattr("specify_cli.events.os.name", target) + patcher.setattr("specify_cli.events.os", SimpleNamespace(name=target)) assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} entry[other], entry[selected] = valid, "broken" path.write_text(json.dumps(native), encoding="utf-8") @@ -1951,6 +1953,36 @@ def test_copilot_context_delivery_reader_maps_owned_handlers(tmp_path, context_d } +@pytest.mark.parametrize("link_kind", ["file", "parent"]) +def test_copilot_context_delivery_rejects_symlinked_config(tmp_path, context_delivery_install, link_kind): + import shutil + + from specify_cli.events import context_delivery_error + from tests.specify_cli.integrations._helpers import _symlink_or_skip + + copilot = context_delivery_install + path = tmp_path / copilot.events_config_file + assert context_delivery_error(copilot, tmp_path) is None + outside = tmp_path.parent / f"{tmp_path.name}-outside" + outside.mkdir() + if link_kind == "file": + target = outside / path.name + shutil.move(path, target) + _symlink_or_skip(path, target) + else: + target = outside / path.parent.name + shutil.move(path.parent, target) + _symlink_or_skip(path.parent, target, directory=True) + target = target / path.name + original = target.read_bytes() + + assert copilot.installed_event_handlers(tmp_path) is None + error = context_delivery_error(copilot, tmp_path) + assert "native events config '.github/hooks/speckit.json' could not be read" in error + assert "Fix '.github/hooks/speckit.json' or move it aside" in error + assert target.read_bytes() == original + + @pytest.mark.parametrize("content", ["{", '{// comment\n"hooks": {}}', "[]"], ids=["malformed", "jsonc", "non-object"]) def test_copilot_context_delivery_unreadable_config_requires_repair(tmp_path, context_delivery_install, content): from specify_cli.events import context_delivery_error From fb72c77e449349c08c6fb430d6a9feea085a3a44 Mon Sep 17 00:00:00 2001 From: Markus Date: Sat, 5 Dec 2026 09:50:25 +0100 Subject: [PATCH 20/20] feat(agy): declare session_start context delivery through Antigravity hooks Keep only agy integration declaration, documentation, and agy-specific tests in this PR after moving shared event framework changes into #5616. Add agy removed-venv context delivery regression test. Assisted-by: Antigravity (model: Gemini 4 Hydrogen, autonomous) --- docs/integrations/agy.md | 22 ++ docs/integrations/cli.md | 4 +- docs/workflow-steps/types.md | 1 + src/specify_cli/integrations/agy/__init__.py | 7 + tests/integrations/test_integration_agy.py | 194 ++++++++++++++++++ .../events/test_context_delivery.py | 2 +- 6 files changed, 228 insertions(+), 2 deletions(-) diff --git a/docs/integrations/agy.md b/docs/integrations/agy.md index 8fb913c3b6..ed0d382010 100644 --- a/docs/integrations/agy.md +++ b/docs/integrations/agy.md @@ -26,6 +26,28 @@ Invoke them in the agent's chat, for example `/speckit-specify` or This directory is shared with other integrations, so do not assume their generated skills can coexist without overlap. +## Runtime Events and Additional Context + +Antigravity supports the `session_start` runtime event. Spec Kit installs its +handler in the reserved `__speckit_event__` definition in `.agents/hooks.json`; +other named definitions remain user-owned. Its dispatcher is `.specify/events.py`. +See [runtime events](cli.md#runtime-events) for overrides and disabling events. + +Command steps can use [additional context](../workflow-steps/types.md#additional-context-for-command-steps) +when events are enabled and current hooks are installed. Antigravity must be +installed and authenticated, and it must load the workspace hook and fire +`SessionStart`. In a Linux probe of agy 1.5.20's default configuration, no +trust approval was observed and the dangerous permissions flag was not needed. +Other trust or managed settings were not tested. Hook errors and timeouts in +that probe failed open silently: the CLI exited 0 with no terminal error, and +diagnostics appeared only in agy's CLI log. A successful exit therefore does +not prove context was delivered. Windows hook execution and shell quoting are +unverified. + +Spec Kit does not read or write `.agents/hooks.json` through a symlink, so +`init`, `integration install`, `integration switch`, and `integration upgrade` fail when that file is +a symlink. + ## Headless Permissions Automatic tool approval is disabled by default. In headless non-interactive diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index ed71216c92..09a322a0f9 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -482,7 +482,9 @@ Supplying `--integration-options` replaces stored setup options, so repeat other options you want to keep. A disabled event set removes previously installed Spec Kit hooks rather than merely stopping new hook generation. Agent-specific guides identify native event configuration paths and -limitations. These runtime events are distinct from extension command hooks. +limitations. For example, [Antigravity](agy.md#runtime-events-and-additional-context) +supports only `session_start`. These runtime events are distinct from extension +command hooks. ## Workflow CLI Dispatch diff --git a/docs/workflow-steps/types.md b/docs/workflow-steps/types.md index cb6319b6ce..7597080a3a 100644 --- a/docs/workflow-steps/types.md +++ b/docs/workflow-steps/types.md @@ -73,6 +73,7 @@ handlers you want to keep. | Integration | Guide and agent-side preconditions | | ----------- | ---------------------------------- | +| `agy` | [Antigravity](../integrations/agy.md#runtime-events-and-additional-context) | | `copilot` | [Copilot](../integrations/copilot.md#additional-context-and-folder-trust) | An integration's agent-side trust, authentication, and feature gates are diff --git a/src/specify_cli/integrations/agy/__init__.py b/src/specify_cli/integrations/agy/__init__.py index f9b10f43a2..e5066cedb1 100644 --- a/src/specify_cli/integrations/agy/__init__.py +++ b/src/specify_cli/integrations/agy/__init__.py @@ -42,6 +42,13 @@ class AgyIntegration(SkillsIntegration): """ key: ClassVar[str] = "agy" + CANONICAL_TO_NATIVE = {"session_start": "SessionStart"} + events_config_file = ".agents/hooks.json" + events_format = "json-named" + events_cwd_is_config_dir = True + events_context_envelope = {"session_start": "injectSteps"} + context_delivery_events = frozenset({"session_start"}) + config: ClassVar[dict[str, Any]] = { "name": "Antigravity", "folder": ".agents/", diff --git a/tests/integrations/test_integration_agy.py b/tests/integrations/test_integration_agy.py index 630eae52fb..8f6e4e1971 100644 --- a/tests/integrations/test_integration_agy.py +++ b/tests/integrations/test_integration_agy.py @@ -16,6 +16,12 @@ class TestAgyIntegration(SkillsIntegrationTests): COMMANDS_SUBDIR = "skills" REGISTRAR_DIR = ".agents/skills" + def _expected_files(self, script_variant: str) -> list[str]: + return sorted( + super()._expected_files(script_variant) + + [".agents/hooks.json", ".specify/events.py"] + ) + def test_options_include_skills_flag(self): """Override inherited test: AgyIntegration should not expose a --skills flag because .agents/ is its only layout.""" i = get_integration(self.KEY) @@ -60,6 +66,39 @@ def test_integration_agy_creates_skills(self, tmp_path): assert result.exit_code == 0, f"init --integration agy failed: {result.output}" assert (target / ".agents" / "skills" / "speckit-plan" / "SKILL.md").exists() + def test_init_with_events_disabled(self, tmp_path): + from tests.specify_cli.integrations._helpers import _init_project + + project = _init_project(tmp_path, "agy", "--events false") + assert (project / ".agents/skills/speckit-plan/SKILL.md").is_file() + assert not (project / ".agents/hooks.json").exists() + assert not (project / ".specify/events.py").exists() + + def test_upgrade_disabled_and_uninstall_preserve_user_hooks(self, tmp_path): + import json + + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project + + project = _init_project(tmp_path, "agy") + hooks = project / ".agents/hooks.json" + data = json.loads(hooks.read_text()) + data["user"] = {"SessionStart": [{"type": "command", "command": "user", "timeout": 10}]} + hooks.write_text(json.dumps(data)) + result = _run_in_project( + project, ["integration", "upgrade", "agy", "--force", "--integration-options", "--events false"] + ) + assert result.exit_code == 0, result.output + assert json.loads(hooks.read_text()) == {"user": data["user"]} + assert not (project / ".specify/events.py").exists() + result = _run_in_project( + project, ["integration", "upgrade", "agy", "--force", "--integration-options", "--events true"] + ) + assert result.exit_code == 0, result.output + assert "__speckit_event__" in json.loads(hooks.read_text()) + result = _run_in_project(project, ["integration", "uninstall", "agy", "--force"]) + assert result.exit_code == 0, result.output + assert json.loads(hooks.read_text()) == {"user": data["user"]} + def test_agy_setup_warning(self, tmp_path): """Agy integration should print a warning about CLI v1.0.0+ / IDE v2.0.0+ requirement during setup.""" from typer.testing import CliRunner @@ -385,3 +424,158 @@ def test_hook_note_preserves_indentation(self): note_line = next((ln for ln in lines if "replace dots" in ln), None) assert note_line is not None, "Hook note line should be present" assert note_line.startswith(" "), "Note should preserve indentation" + + +@pytest.mark.parametrize("action", ["install", "switch", "upgrade"]) +def test_agy_hook_symlink_preflight_before_writes(tmp_path, action): + from tests.conftest import strip_ansi + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "agy" if action == "upgrade" else "claude") + hooks = project / ".agents/hooks.json" + hooks.parent.mkdir(parents=True, exist_ok=True) + hooks.unlink(missing_ok=True) + outside = tmp_path / "outside" + outside.mkdir() + target = outside / "hooks.json" + target.write_text("{}\n", encoding="utf-8") + _symlink_or_skip(hooks, target) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", action, "agy", "--script", "sh"] + if action in ("install", "upgrade"): + args.append("--force") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert ".agents/hooks.json" in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("disabled", [False, True]) +def test_agy_symlinked_parent_preflight_refuses(tmp_path, disabled): + from tests.conftest import strip_ansi + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + outside = tmp_path / "outside" + outside.mkdir() + if disabled: + (outside / "hooks.json").write_text("{}\n", encoding="utf-8") + _symlink_or_skip(project / ".agents", outside, directory=True) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", "switch", "agy"] + if disabled: + args.append("--integration-options=--events false") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert ".agents/hooks.json" in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("case", ["disabled-dangling", "empty-override"]) +def test_agy_disabled_absent_hook_succeeds(tmp_path, case): + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "claude") + hooks = project / ".agents/hooks.json" + hooks.parent.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + args = ["integration", "switch", "agy"] + if case == "disabled-dangling": + _symlink_or_skip(hooks, outside / "missing") + args.append("--integration-options=--events false") + else: + (project / ".specify/integration-events.yml").write_text( + "integrations:\n agy:\n events: {}\n", encoding="utf-8" + ) + before_outside = _tree(outside) + result = _run_in_project(project, args) + assert result.exit_code == 0, result.output + assert not hooks.exists() + assert _tree(outside) == before_outside + + +def test_agy_disabled_preflight_accepts_absent_hook_behind_symlink(tmp_path): + from specify_cli.events import preflight_integration_events + from tests.specify_cli.integrations._helpers import _symlink_or_skip, _tree + + project = tmp_path / "project" + project.mkdir() + outside = tmp_path / "outside" + outside.mkdir() + _symlink_or_skip(project / ".agents", outside, directory=True) + before, before_outside = _tree(project), _tree(outside) + assert preflight_integration_events(get_integration("agy"), project, {"events": "false"}) == {} + assert _tree(project) == before + assert _tree(outside) == before_outside + + +@pytest.mark.parametrize("disable", [False, True]) +def test_agy_dispatcher_symlink_upgrade_preflight(tmp_path, disable): + from tests.conftest import strip_ansi + from tests.specify_cli.integrations._helpers import _init_project, _run_in_project, _symlink_or_skip, _tree + + project = _init_project(tmp_path, "agy") + dispatcher = project / ".specify/events.py" + dispatcher.unlink() + outside = tmp_path / "outside" + outside.mkdir() + target = outside / "events.py" + target.write_text("original\n", encoding="utf-8") + _symlink_or_skip(dispatcher, target) + before, before_outside = _tree(project), _tree(outside) + args = ["integration", "upgrade", "agy", "--force"] + if disable: + args.append("--integration-options=--events false") + result = _run_in_project(project, args) + output = " ".join(strip_ansi(result.output).split()) + assert result.exit_code == 1, output + assert ".specify/events.py" in output + assert "No files were changed." in output + assert _tree(project) == before + assert _tree(outside) == before_outside + + +def test_agy_deleted_venv_rejects_context_delivery(tmp_path): + import json + import os + import shlex + import shutil + + from specify_cli.events import ( + ADDITIONAL_CONTEXT_HANDLER, + _SPECKIT_MARKER, + context_delivery_error, + install_integration_events, + resolve_events, + ) + from specify_cli.integrations.manifest import IntegrationManifest + + venv_rel = ".venv/Scripts/python.exe" if os.name == "nt" else ".venv/bin/python" + venv_python = tmp_path / venv_rel + venv_python.parent.mkdir(parents=True) + venv_python.write_text("", encoding="utf-8") + + agy = get_integration("agy") + manifest = IntegrationManifest("agy", tmp_path) + install_integration_events(agy, tmp_path, manifest, resolve_events("agy", None, tmp_path, None)) + (tmp_path / ".specify/integration.json").write_text( + json.dumps({"default_integration": "agy", "installed_integrations": ["agy"]}), + encoding="utf-8", + ) + handler = json.loads((tmp_path / ".agents/hooks.json").read_text(encoding="utf-8"))[_SPECKIT_MARKER][ + "SessionStart" + ][0] + assert shlex.split(handler["command"])[0] == f"../{venv_rel}" + assert agy.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]} + assert context_delivery_error(agy, tmp_path) is None + + shutil.rmtree(tmp_path / ".venv") + assert agy.installed_event_handlers(tmp_path) == {} + assert "outdated" in context_delivery_error(agy, tmp_path) diff --git a/tests/specify_cli/events/test_context_delivery.py b/tests/specify_cli/events/test_context_delivery.py index 0645f9b46d..483b8793b9 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -572,7 +572,7 @@ def test_copilot_is_a_context_delivery_declarer(tmp_path): } error = context_delivery_error(copilot, tmp_path) assert "not installed" in error - assert "Supporting integrations: copilot" in error + assert "Supporting integrations: agy, copilot" in error def test_parse_dispatcher_with_project_venv_interpreter(tmp_path):