Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion design/file-helper.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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 |

Expand Down Expand Up @@ -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.

Expand Down
68 changes: 67 additions & 1 deletion design/integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,38 @@ 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. 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. 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
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.

Native `json-named` event configs reserve the `__speckit_event__` definition;
its event arrays contain command handlers directly, while other named
entries remain user-owned. Integrations whose native hooks run from the config
file's directory declare `events_cwd_is_config_dir`; dispatcher and
project-relative interpreter paths are rendered relative to that directory.

## Output flavors

Choose the smallest base class that matches the agent's native format. The
Expand Down Expand Up @@ -485,7 +517,7 @@ them. Keep agent-specific settings and events consistent with that lifecycle.
`preflight_setup(project_root, parsed_options, *, script_type)` before they
write shared templates, scripts or integration files. Override it to reject a
setup that would fail partway, raising `ValueError` or `OSError`; the CLI then
exits with the message and changes nothing. The default accepts every setup.
exits with the message and changes nothing. The default accepts every setup. The lifecycle also runs shared event-destination preflight before writes and passes the resolved event map to setup.

Event cleanup releases only the departing integration's dispatcher claim.
It deletes `.specify/events.py` only when that integration's current or prior
Expand Down Expand Up @@ -555,3 +587,37 @@ they have merged. See the
and devcontainer setup if the agent needs additional tooling.

Prefer existing bases and shared processing over copied setup loops.

### Workflow dispatch search environment

Command and prompt dispatch capture the caller's working directory at workflow
run or resume. Each dispatch copies the current environment and anchors relative
PATH entries to that location for the integration process and its descendants.
This changes the search locations for **all** programs in that child, including
native hooks, not only Python. PATH order and duplicates are retained; an
absent PATH stays absent and an entirely empty PATH remains empty. Direct
integration dispatch preserves its existing empty-PATH subprocess fallback,
which can search the child working directory. Individual empty segments in a
nonempty PATH refer to the caller's directory. If anchoring would insert a PATH
separator into an entry, dispatch fails rather than search unintended paths.
The shell step does not use this PATH transformation. No process-global
environment or working-directory changes are made.

Base command dispatch, Copilot's override and prompt dispatch use the shared
integration environment. Base and prompt dispatch use the shared executable
lookup; Copilot retains its existing executable probe and subprocess launch.
On Windows that launch does not use the child PATH or cwd to locate the CLI,
so its selection can still differ from workflow preflight. An explicit relative
Copilot executable override remains relative to the child working directory on
POSIX. Prompt dispatch also retains its existing fallback when the integration
key is found but the executable in its argv is not.

Custom adapter `dispatch_command()` overrides starting subprocesses must use
`integration_dispatch()` as a context manager around the shared
`integration_environment()` and `dispatch_which()` helpers to obtain the same
child environment and preserve context isolation; overrides not using them and
agents started manually are outside this guarantee. Direct base dispatch captures
its own caller location. Hook files remain portable and contain no machine-specific
interpreter paths. Strict native-hook verification can still reject a hook if
the interpreter selected at installation differs from the one selected at
run time; reinstall or upgrade the integration in that environment.
2 changes: 2 additions & 0 deletions design/workflow-step.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
35 changes: 35 additions & 0 deletions docs/integrations/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -364,3 +364,38 @@ 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. 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. 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).

### Subprocess search environment

Workflow command and prompt dispatch anchor relative PATH entries to the
caller directory captured at run or resume. This applies to every program
searched by the integration child and its hooks. Copilot retains its existing
executable launch: on Windows, the initial CLI lookup does not use this child
PATH; on POSIX, explicit relative executable overrides remain relative to the
child cwd. Prompt dispatch retains its existing executable fallback. An unset or
wholly empty PATH is left unchanged; direct dispatch can still search the child
working directory when PATH is empty. Dispatch fails if anchoring inserts a PATH
separator into an entry. Shell steps retain their existing environment semantics. Adapter
`dispatch_command()` overrides that start their own subprocesses should
use `specify_cli.integrations._context.integration_dispatch()` as a context
manager around `integration_environment()` and `dispatch_which()` for the
child environment and executable selection, and
must continue to isolate additional context. Overrides that do not use these
helpers, and agents started outside Spec Kit, do not receive this guarantee.
31 changes: 28 additions & 3 deletions docs/integrations/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,9 +434,15 @@ 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.

`integration install`, `switch`, and `upgrade` preflight event and dispatcher
destinations for symlink and path safety before changing files. Even with
`--events false`, an unsafe existing hook or dispatcher file that requires
cleanup is refused.

To configure project overrides, create `.specify/integration-events.yml`.
Replace `<key>` with your integration key and the example command with an
Expand Down Expand Up @@ -561,3 +567,22 @@ Use `upgrade` when you've upgraded Spec Kit and want to refresh an installed int
### Do extensions and presets I install apply to every installed integration?

No. Extensions (`specify extension add`) and presets (`specify preset add`) register their command overrides for the currently active (default) integration only, even if other integrations are installed. A non-default integration does not receive those artifacts until it becomes the default: `specify integration use <key>` (or `switch <key>`) rescaffolds every enabled extension and preset for the newly active integration. `specify integration upgrade` follows the same rule — it only re-registers extensions and presets when upgrading the active integration.

### PATH during workflow dispatch

When Spec Kit launches an integration for a command or prompt step, relative
PATH entries are anchored to the directory from which the workflow was run or
resumed. This affects lookup of tools in the integration process and its hooks.
Copilot retains its existing CLI launch behavior: on Windows, the initial CLI
lookup does not use this child PATH; on POSIX, explicit relative executable
overrides remain relative to the child working directory. Prompt steps retain
their existing executable fallback. An unset PATH remains unset; an entirely
empty PATH stays empty. With an empty PATH, a shell or a direct integration dispatch may still search its child
working directory, so that case is not stabilized. If anchoring a relative
entry would insert a PATH separator into that entry (for example, `:` in a
POSIX caller directory), dispatch fails rather than search unintended paths;
use absolute entries or start from a directory without that separator.
Shell steps and manually started agents are unchanged. Custom adapters that start
subprocesses without the shared dispatch helpers are not covered. A native
hook whose interpreter selection changed since installation can still fail
strict verification; upgrade the integration in the current environment.
49 changes: 47 additions & 2 deletions docs/workflow-steps/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,49 @@ 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 <key>` after upgrading Spec Kit. An override in
`.specify/integration-events.yml` must retain the built-in handler without a
restrictive `matcher` (omit `matcher`, or set `""` or `"*"`), for example:

```yaml
integrations:
example-agent:
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.

No built-in integration declares support yet.
Comment thread
markuswondrak marked this conversation as resolved.
Resolved

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.<id>.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):
Expand Down Expand Up @@ -361,7 +404,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.
Expand All @@ -382,7 +427,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.
Expand Down
13 changes: 10 additions & 3 deletions src/specify_cli/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,23 @@ def docker_agent_command(executable: str | None = None) -> list[str] | None:
is verified with a bounded, read-only version probe so a plain Docker CLI
is not mistaken for an installed Docker Agent.
"""
from .integrations._context import dispatch_probe_options, dispatch_which

resolved_from_path = executable is None
if executable is None:
if shutil.which("docker-agent"):
if dispatch_which("docker-agent"):
return ["docker-agent", "run"]
executable = shutil.which("docker")
executable = dispatch_which("docker")
if executable is None:
return None

executable_name = Path(executable).name.lower()
if executable_name in {"docker", "docker.exe"}:
command = [executable, "agent", "version"]
options = dispatch_probe_options()
probe_executable = dispatch_which(executable) if options else executable
if probe_executable is None:
return None
command = [probe_executable, "agent", "version"]
run_command = [executable, "agent", "run"]
else:
# An explicit non-Docker executable is an operator override. Preserve
Expand All @@ -49,6 +55,7 @@ def docker_agent_command(executable: str | None = None) -> list[str] | None:
capture_output=True,
check=False,
timeout=DOCKER_AGENT_CHECK_TIMEOUT,
**options,
)
except (OSError, subprocess.TimeoutExpired):
return None
Expand Down
Loading