From 4822dd6d32ec96097566bb700de4c0e95bd337c1 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 17:10:49 +0100 Subject: [PATCH 01/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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/12] 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 c822a5106013c0f341390b3ef7326b9de325d274 Mon Sep 17 00:00:00 2001 From: Markus Date: Sun, 29 Nov 2026 19:19:52 +0100 Subject: [PATCH 10/12] 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 bcaac5760e..1fbe7aa051 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2454,6 +2454,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 7dcbaf642f..8128d3eb7b 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 033406db42..75e1b8c1e9 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 @@ -1674,3 +1680,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 ea95acc215..e90941f248 100644 --- a/tests/specify_cli/events/test_context_delivery.py +++ b/tests/specify_cli/events/test_context_delivery.py @@ -511,6 +511,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) @@ -552,12 +553,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 7047b21a9bbfe52a2690de23658fde58953a38a1 Mon Sep 17 00:00:00 2001 From: Markus Date: Wed, 2 Dec 2026 21:55:56 +0100 Subject: [PATCH 11/12] 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 1fbe7aa051..6a4654dc17 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -2454,13 +2454,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" @@ -2473,6 +2475,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 8128d3eb7b..c2207a2683 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -662,6 +662,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 75e1b8c1e9..246224b75f 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -1682,6 +1682,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 @@ -1703,6 +1774,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]} @@ -1710,7 +1782,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): @@ -1722,6 +1794,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"), @@ -1738,8 +1814,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 @@ -1786,8 +1861,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 1fda723b22fa215ec4b15cc90b86001a3331481b Mon Sep 17 00:00:00 2001 From: Markus Date: Thu, 3 Dec 2026 18:58:24 +0100 Subject: [PATCH 12/12] 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 | 38 ++++- .../integrations/copilot/__init__.py | 22 ++- .../integrations/test_integration_copilot.py | 145 +++++++++++++++++- 4 files changed, 194 insertions(+), 26 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 6a4654dc17..953024395e 100644 --- a/src/specify_cli/events/__init__.py +++ b/src/specify_cli/events/__init__.py @@ -1810,7 +1810,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 +1828,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 +1898,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 +1910,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 +1939,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() @@ -2454,6 +2464,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) @@ -2477,6 +2497,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 c2207a2683..48f89d51a9 100644 --- a/src/specify_cli/integrations/copilot/__init__.py +++ b/src/specify_cli/integrations/copilot/__init__.py @@ -670,16 +670,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 246224b75f..47450503c0 100644 --- a/tests/integrations/test_integration_copilot.py +++ b/tests/integrations/test_integration_copilot.py @@ -1682,15 +1682,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. @@ -1709,8 +1710,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. @@ -1731,6 +1734,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 @@ -1753,6 +1762,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 @@ -1896,3 +1979,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