Repository navigation
feat(pi): deliver session_start context through a pi extension - #5623
markuswondrak wants to merge 27 commits into
Conversation
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 (github#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)
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)
There was a problem hiding this comment.
🟡 Changes recommended
Refresh and uninstall can erase local edits without force, violating file-ownership protections, while Windows encoding and manifest-path issues cause test failures.
8 open issues
Preserve unowned or modified Pi extensions during refresh · New Uninstall deletes modified Pi extensions without checking ownership · New Normalize test paths to POSIX manifest keys · New Encode Unicode test fixtures as UTF-8 · New Fall back to runnable venv when PATH Python is unavailable · New Memoize interpreter probes across event handlers · New Test OpenCode cleanup when installing with no events · New Keep Pi runtime and shared lifecycle changes within scope · New
What changed in this PR
Adds Pi context delivery on top of the stacked workflow framework, allowing command steps to supply additional_context without changing command arguments or templates.
Changes:
- Declares Pi support and generates an extension that caches session-start context and projects it into the system prompt.
- Adds installed-handler verification and format-based TypeScript cleanup.
- Expands lifecycle tests and documents integration prerequisites.
Validation was limited to source inspection; tests and before-and-after comparisons were not run.
AI-generated review for the requester by GitHub Copilot (model/settings unavailable; automated).
| File | Description |
|---|---|
tests/workflows/test_step_capture.py |
Checks prompt dispatch environment isolation. |
tests/workflows/test_shell_step.py |
Checks shell context isolation and explicit bindings. |
tests/workflows/test_command_additional_context.py |
Covers validation, dispatch, concurrency, and resume. |
tests/specify_cli/events/test_ts_extension.py |
Covers Pi extension generation, delivery, and cleanup. |
tests/specify_cli/events/test_json_named.py |
Covers Antigravity hook generation and lifecycle. |
tests/specify_cli/events/test_events.py |
Extends destination-safety and directory-cleanup coverage. |
tests/specify_cli/events/test_context_delivery.py |
Tests capability, dispatcher, and installation contracts. |
tests/integrations/test_integration_pi.py |
Adds Pi event files to installation expectations. |
tests/integrations/test_integration_copilot.py |
Covers Copilot event installation and verification. |
tests/integrations/test_integration_agy.py |
Covers Antigravity event inventory and cleanup. |
tests/integrations/test_context.py |
Checks child-only environment transport across dispatch paths. |
tests/integrations/test_capture.py |
Updates the capture fixture for environment forwarding. |
tests/fixtures/context_delivery.py |
Provides a test-only context-delivery adapter. |
src/specify_cli/workflows/step/shell/__init__.py |
Clears inherited context before applying shell bindings. |
src/specify_cli/workflows/step/prompt/__init__.py |
Isolates prompt subprocess environments. |
src/specify_cli/workflows/step/command/__init__.py |
Validates and forwards additional context. |
src/specify_cli/workflows/step/_env_values.py |
Shares process-environment value validation. |
src/specify_cli/integrations/pi/__init__.py |
Declares Pi event mapping and context delivery. |
src/specify_cli/integrations/manifest.py |
Extracts safe empty-parent pruning. |
src/specify_cli/integrations/copilot/__init__.py |
Declares delivery and forwards scoped context. |
src/specify_cli/integrations/base.py |
Adds delivery capabilities and reader interfaces. |
src/specify_cli/integrations/agy/__init__.py |
Declares Antigravity hook format and delivery. |
src/specify_cli/integrations/_context.py |
Builds isolated child environments. |
src/specify_cli/integrations/_capture.py |
Forwards explicit environments to captured processes. |
src/specify_cli/events/__init__.py |
Implements generation, readers, preflight checks, and cleanup. |
docs/workflow-steps/types.md |
Documents additional context and supported integrations. |
docs/integrations/pi.md |
Explains Pi caching, delivery, and trust requirements. |
docs/integrations/copilot.md |
Documents default hooks and folder trust. |
docs/integrations/cli.md |
Updates shared runtime-event guidance. |
docs/integrations/api.md |
Documents adapter delivery declarations and readers. |
docs/integrations/agy.md |
Explains Antigravity hooks and delivery limitations. |
design/integration.md |
Defines context-delivery and event-format contracts. |
Review effort: Max (adaptive)
| _write_text(config_path, _build_ts_extension(filtered), encoding="utf-8") | ||
| manifest.record_file(config_file, config_path.read_bytes()) |
| if event_path.exists(): | ||
| _unlink_file(event_path, missing_ok=True) | ||
| _prune_empty_parents(project_root, event_path.parent, {project_root}) | ||
| manifest.remove(rel) |
| assert str(path.relative_to(tmp_path)) in manifest.files | ||
| assert manifest.ownership_modes.get('.pi/extensions/speckit-events.ts') != 'partial' |
| sys.exit(7) | ||
| if not os.environ.get("EMPTY"): | ||
| print(sys.argv[1] + "-α", end="") | ||
| ''') |
| (fs.existsSync(venvPy) && canImportSpecifyCli(venvPy) && venvPy) || | ||
| (fs.existsSync(venvWin) && canImportSpecifyCli(venvWin) && venvWin) || | ||
| (process.platform === 'win32' ? 'python' : 'python3') |
| function runEvent(command, eventName, event, ctx, timeoutSec) { | ||
| const directory = ctx.cwd; | ||
| const DISPATCHER = path.join(directory, '.specify', 'events.py'); | ||
| const venvPy = path.join(directory, '.venv', 'bin', 'python'); | ||
| const venvWin = path.join(directory, '.venv', 'Scripts', 'python.exe'); | ||
| const INTERPRETER = ( | ||
| (fs.existsSync(venvPy) && canImportSpecifyCli(venvPy) && venvPy) || | ||
| (fs.existsSync(venvWin) && canImportSpecifyCli(venvWin) && venvWin) || | ||
| (process.platform === 'win32' ? 'python' : 'python3') | ||
| ); |
| if fmt in ("ts-plugin", "ts-extension"): | ||
| _remove_owned_ts_event_file(integration, project_root, manifest) |
| }); | ||
| } | ||
| export default function (pi) { |
- 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)
aa4e5a7 to
a378862
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Pi extension installation and cleanup bypass ownership and hash checks, allowing existing files or user edits to be overwritten or deleted without explicit force authorization.
9 open issues
Encode Unicode test fixtures as UTF-8 Normalize test paths to POSIX manifest keys Uninstall deletes modified Pi extensions without checking ownership Preserve unowned or modified Pi extensions during refresh Validate OpenCode config before deleting its plugin · New Memoize interpreter probes across event handlers Fall back to runnable venv when PATH Python is unavailable Keep Pi runtime and shared lifecycle changes within scope Test OpenCode cleanup when installing with no events
Review effort: Max (adaptive)
| if fmt in ("ts-plugin", "ts-extension"): | ||
| _remove_owned_ts_event_file(integration, project_root, manifest) |
|
Please address Copilot feedback |
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)
Resolve the shell-step conflict by preserving both context environment isolation and the opt-in output_encoding behavior. Add regression coverage for their interaction. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
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)
Address PR github#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)
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>
…rents Address PR github#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>
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)
Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
a378862 to
686ad24
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Pi installation and refresh overwrite unowned or locally edited extensions, while cleanup deletes edited extensions without --force, risking loss of user changes.
15 open issues
Protect unowned or modified extensions before writing · New Preserve edited extensions during uninstall and switch · New Encode Unicode test fixtures as UTF-8 Normalize test paths to POSIX manifest keys Uninstall deletes modified Pi extensions without checking ownership Preserve unowned or modified Pi extensions during refresh Avoid logging captured stdout on handler errors · New Fall back to a runnable venv interpreter · New Validate OpenCode config before deleting its plugin Memoize interpreter probes across event handlers Fall back to runnable venv when PATH Python is unavailable Separate shared TS changes into a prerequisite PR · New Test setup with symlinked extensions directories · New Keep Pi runtime and shared lifecycle changes within scope Test OpenCode cleanup when installing with no events
Review effort: Max (adaptive)
| _write_text(config_path, _build_ts_extension(filtered), encoding="utf-8") | ||
| manifest.record_file(config_file, config_path.read_bytes()) |
| _ensure_safe_destination(event_path, project_root) | ||
| if check_only: | ||
| return | ||
| _unlink_file(event_path, missing_ok=True) |
| events = {"session_start": handlers} | ||
| calls = [ | ||
| f' try {{ const text = runEvent({json.dumps(cfg["command"])}, "session_start", payload, ctx, {cfg["timeout"]}); ' | ||
| "if (text) contexts.push(text); } catch (e) { console.error(e); }" |
| function runEvent(command, eventName, event, ctx, timeoutSec) { | ||
| const directory = ctx.cwd; | ||
| const DISPATCHER = path.join(directory, '.specify', 'events.py'); | ||
| const venvPy = path.join(directory, '.venv', 'bin', 'python'); | ||
| const venvWin = path.join(directory, '.venv', 'Scripts', 'python.exe'); | ||
| const INTERPRETER = ( | ||
| (fs.existsSync(venvPy) && canImportSpecifyCli(venvPy) && venvPy) || | ||
| (fs.existsSync(venvWin) && canImportSpecifyCli(venvWin) && venvWin) || | ||
| (process.platform === 'win32' ? 'python' : 'python3') | ||
| ); |
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" | ||
| events_format = "ts-extension" |
| outside.mkdir() | ||
| target = outside / 'events.ts' | ||
| target.write_text('// original', encoding='utf-8') | ||
| _symlink_or_skip(path, target) |
…CLI fallback Move shared event framework additions (json-named native config format, events_cwd_is_config_dir relative path rebasing, injectSteps envelope, and EVENT_CONTEXT_ENVELOPES delegation gate) into the context-delivery framework PR with agy-independent tests. Keep delegating to importable confinement-safe specify_cli packages with envelope='plain' and wrap captured stdout in the requested envelope when an older package lacks the envelope, preserving bundled-template resolution. Add a removed-venv regression test for json-named handlers. Assisted-by: Antigravity (model: Gemini 4 Hydrogen, autonomous)
686ad24 to
b83ae16
Compare
|
Rebased onto updated #5617 ( Verification on AI disclosure: Posted on behalf of @markuswondrak by Antigravity (model: |
There was a problem hiding this comment.
🟡 Changes recommended
Cleanup and refresh can delete or overwrite locally edited TypeScript extensions without honoring recorded hashes or explicit overwrite consent.
21 open issues
Preserve locally edited managed extensions during refresh · New Preserve modified Pi extension files during non-forced cleanup · New Write the harness using UTF-8 · New Preserve edited extensions during uninstall and switch Protect unowned or modified extensions before writing Encode Unicode test fixtures as UTF-8 Normalize test paths to POSIX manifest keys Uninstall deletes modified Pi extensions without checking ownership Preserve unowned or modified Pi extensions during refresh Fall back to a runnable project interpreter for context delivery · New Honor or reject restrictive event matchers · New Fall back to a runnable venv interpreter Avoid logging captured stdout on handler errors Validate OpenCode config before deleting its plugin Memoize interpreter probes across event handlers Fall back to runnable venv when PATH Python is unavailable Keep Pi-specific event handling out of shared runtime code · New Test setup with symlinked extensions directories Separate shared TS changes into a prerequisite PR Keep Pi runtime and shared lifecycle changes within scope
And 1 more that still need to be addressed.
Review effort: Max (adaptive)
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" | ||
| events_format = "ts-extension" |
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" | ||
| events_format = "ts-extension" |
| assert.equal(run().systemPrompt, expected); | ||
| id = 'a'; | ||
| assert.equal(run().systemPrompt, expected); | ||
| ''') |
| function runEvent(command, eventName, event, ctx, timeoutSec) { | ||
| const directory = ctx.cwd; | ||
| const DISPATCHER = path.join(directory, '.specify', 'events.py'); | ||
| const venvPy = path.join(directory, '.venv', 'bin', 'python'); | ||
| const venvWin = path.join(directory, '.venv', 'Scripts', 'python.exe'); | ||
| const INTERPRETER = ( | ||
| (fs.existsSync(venvPy) && canImportSpecifyCli(venvPy) && venvPy) || | ||
| (fs.existsSync(venvWin) && canImportSpecifyCli(venvWin) && venvWin) || | ||
| (process.platform === 'win32' ? 'python' : 'python3') | ||
| ); |
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" | ||
| events_format = "ts-extension" |
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" | ||
| events_format = "ts-extension" |
Read installed named hook definitions with FileHelper in deny mode. Reject symlinked files and ancestors, and distinguish malformed or unreadable configs from missing hooks so preflight suggests a repair that can work. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
Capture the calling directory for workflow dispatch and normalize relative PATH entries in integration child environments without mutating the parent environment. Preserve shell-step and empty-PATH behavior, existing Copilot lookup semantics, and context isolation. Add real-subprocess and portable Windows regressions; native Windows validation remains pending. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: gpt-6.2-sol, autonomous)
Remove test-only integrations before refreshing derived agent caches so event and dispatch tests do not leak fake agents into later tests. The previously failing test-order regressions now pass. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
Declare session_start context delivery for GitHub Copilot, so workflow command steps with additional_context work with Copilot (github#5533, stacked on github#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)
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)
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)
Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
Read the native hook file through deny-mode FileHelper during context-delivery preflight, preserving missing and malformed configuration diagnostics. Cover linked files and linked parents without changing their targets. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
… hooks Keep only agy integration declaration, documentation, and agy-specific tests in this PR after moving shared event framework changes into github#5616. Add agy removed-venv context delivery regression test. Assisted-by: Antigravity (model: Gemini 4 Hydrogen, autonomous)
Add session_start runtime event support to the pi integration and declare context delivery, so workflow command steps with additional_context work with pi (github#5533, stacked on github#5617). Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous)
- Add the ts-extension installed-handler reader. The generated extension carries a "// speckit-events:" inventory header, and the reader returns handlers only when the file is byte-identical to a re-render from that inventory (LF or CRLF). - Send the dispatcher a small session payload (session_id, cwd, hook_event_name) instead of the full before_agent_start event, which contains the whole system prompt and could exceed the dispatcher's 1 MiB stdin limit. - Start the dispatcher with PYTHONIOENCODING=utf-8 so non-ASCII context survives on Windows. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous) Assisted-by: pi coding agent (model: claude-opus-5.5, autonomous)
Check that the owned TS event file exists before validating its destination, matching opencode's plugin removal on main. An absent or dangling file behind a symlinked parent is a no-op again; a present file behind a symlink is still refused. 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: claude-opus-5.5, autonomous)
Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
Use deny-mode FileHelper when inspecting the generated TypeScript extension for context-delivery preflight. Cover linked files and linked parents without changing their targets. Assisted-by: pi coding agent (model: gpt-6.1-terra, autonomous)
b83ae16 to
373753b
Compare
|
Reader and stack update at
Validation: 825 passed, 12 skipped on Linux/Python 3.14; Ruff passed. The linked-file and linked-parent regressions failed before and pass after. Native Windows and Windows PowerShell 5.1 tests have not run. AI disclosure: Written and posted for @markuswondrak by the pi coding agent ( |
There was a problem hiding this comment.
🟡 Changes recommended
Pi’s TS cleanup deletes user-modified files without --force, bypassing manifest hash checks and violating the modified-file preservation contract.
24 open issues
Reject unowned Pi extension file collisions · New Write the harness using UTF-8 Preserve modified Pi extension files during non-forced cleanup Preserve locally edited managed extensions during refresh Preserve edited extensions during uninstall and switch Protect unowned or modified extensions before writing Encode Unicode test fixtures as UTF-8 Normalize test paths to POSIX manifest keys Uninstall deletes modified Pi extensions without checking ownership Preserve unowned or modified Pi extensions during refresh Fall back to python when resolving the dispatcher interpreter · New Honor or reject restrictive event matchers Fall back to a runnable project interpreter for context delivery Fall back to a runnable venv interpreter Avoid logging captured stdout on handler errors Validate OpenCode config before deleting its plugin Memoize interpreter probes across event handlers Fall back to runnable venv when PATH Python is unavailable Clarify symlink cleanup requirements for disabling events · New Keep Pi-specific event handling out of shared runtime code
And 4 more that still need to be addressed.
Review effort: Max (adaptive)
| } | ||
| multi_install_safe = True | ||
| CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"} | ||
| events_config_file = ".pi/extensions/speckit-events.ts" |
| events_format = "ts-extension" | ||
| context_delivery_events = frozenset({"session_start"}) |
| there with events enabled. Use `--integration-options="--events false"` to opt | ||
| out of events, disabling `additional_context` delivery and extension event | ||
| hooks for Pi. |



Description
Part of #5533. Stacked: #5616 (framework) ← #5621 (Copilot) ← #5617 (agy) ← this PR.
This PR adds
session_startruntime event support to thepiintegration and declares context delivery, so workflowcommandsteps withadditional_contextwork with pi.CANONICAL_TO_NATIVE = {"session_start": "before_agent_start"},events_config_file = ".pi/extensions/speckit-events.ts",events_format = "ts-extension", andcontext_delivery_events = frozenset({"session_start"}). The plain envelope is used. pi inherits the basedispatch_command, which already acceptsadditional_context.before_agent_startsession_starthandler cannot return anything (SessionStartEvent).before_agent_startcan return asystemPrompt, which pi projects as the system prompt without writing it to the transcript, so nothing accumulates. A returnedmessagewould be persisted in the history. This follows the opencode precedent, wheresession_startmaps toexperimental.chat.system.transform..pi/extensions/speckit-events.ts, with a cache perctx.sessionManager.getSessionId(). The nativesession_startinvalidates the cache andsession_shutdownevicts it. On the firstbefore_agent_startof a session, the extension runs every resolvedsession_starthandler through.specify/events.py:execFileSyncwith argv, no shell, an absolute path fromctx.cwd, a timeout,PYTHONIOENCODING=utf-8, and a small payload (session_id,cwd,hook_event_name) instead of the full event, which contains the whole system prompt. Output is cached even when empty, so handlers run once per session. Every run then projectsevent.systemPrompt + "\n\n" + cached, which also keeps the context after compaction. Handler errors go to stderr, and the extension never throws._read_ts_extension_handlers, registered forts-extensionand used by #5616'sinstalled_event_handlers(). The file starts with a// speckit-events: {...}inventory line. The reader re-renders the file from that inventory and returns handlers only when the file is byte-identical (LF or CRLF)._owned_ts_event_file,_remove_owned_ts_event_file) instead ofintegration.key. Owned files are removed and empty parents pruned; neighbouring user extensions are untouched. The generated opencode plugin is byte-identical (rendered before and after, same SHA-256).types.md, the runtime-events reference, and the design contract.Why this is one PR: As in #5617, the
ts-extensiongenerator and the format-keyed TS cleanup live in the shared events module next to every other native format. They exist for pi's extension contract and have no use without it.Agent-side precondition (pi)
pi loads project extensions (
.pi/extensions) and project prompt templates (.pi/prompts, which hold the Spec Kit commands) only for a trusted project: a saved trust,defaultProjectTrust, or--approvefor a single run. Untrusted print-mode runs skip both silently and exit 0. Spec Kit does not add--approveautomatically. Extension errors are reported on stderr, but the run still exits 0.Reader and stack update at
373753bbThe installed TypeScript-extension reader now uses deny-mode
FileHelper, rejecting linked extension files and parent directories during context-delivery preflight. The linked-file/parent regressions failed before the change and pass afterward. This update does not address the other open pi review threads.On this rebased head: 825 passed, 12 skipped on Linux/Python 3.14; Ruff passed. The test run includes the agy integration class with a simulated CLI, not a new live agy run. Native Windows and Windows PowerShell 5.1 validation remain pending.
Testing
Earlier tests were run by the agent in this checkout's
.venv:.venv/bin/python -m pytest -q -n 4: 17,516 passed, 676 skipped.uvx ruff@0.15.0 check src tests: passed.markdownlint-cli2on the touched docs: passed.tests/specify_cli/events/test_ts_extension.pycovers:PYTHONIOENCODING, and the minimal payload--events false, uninstall, and switch, including pruning and preservation of user filesevents.pyfail.pi/extensions/speckit-events.tsand.specify/events.py.Probe of pi 1.3.0 on Linux, before implementation (manual extension, 8 runs):
-prun fires onesession_start(startup) and onebefore_agent_start.systemPromptreaches the model.--mode jsonis unaffected.Live evidence with this implementation (pi 1.3.0, model
opencode-go/deepseek-v4.1-flash). Setup: a sample project fromspecify init --integration pi, a local probe extension command that replies with aPROBE-CTX-…token from its context orNONE, and a workflowcommandstep withintegration: piandadditional_context: "{{ inputs.ctx }}". The runs used an environment without the supervising pi session'sPI_*variables.SPECKIT_INTEGRATION_PI_EXTRA_ARGS=--approve,-i ctx=PROBE-CTX-7a96df24PROBE-CTX-7a96df24.NONE.--approve, no saved trust)Not verified:
AI Disclosure
AI disclosure: Opened on behalf of @markuswondrak by the pi coding agent.
Planning, review, live runs, and this PR text: pi with model
claude-opus-5.5(github-copilot, reasoning effortxhigh), interactive and human-supervised. @markuswondrak made each design decision.Probe, code, tests, and docs: written autonomously by pi subagents with model
gpt-6.1-terra(github-copilot, reasoning efforthigh), then reviewed by the supervising agent.Reader and stack update (
373753bb): pi coding agent (gpt-6.1-terravia GitHub Copilot; reasoning effort not supplied; interactive, human-directed) implemented the reader change and tests, rebased the stack, ran validation, and updated the PR.The change was not reviewed line by line by a human. With this PR, the filing account has five open PRs, which @markuswondrak accepted.