Skip to content

Commit b718563

Browse files
author
Markus
committed
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)
1 parent 251e44a commit b718563

7 files changed

Lines changed: 205 additions & 7 deletions

File tree

‎docs/integrations/copilot.md‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,21 @@ specify init my-project --integration copilot
1717
For an existing Spec Kit project, use `specify integration install copilot`.
1818
See [integration management](cli.md) for activation, upgrades, and removal.
1919

20+
## Additional Context and Folder Trust
21+
22+
Copilot CLI loads repository hooks in `-p` mode only in a trusted folder.
23+
Trust the folder through Copilot's trust prompt or `trustedFolders` in
24+
`~/.copilot/config.json`, or use `--trust-folder` for a single run.
25+
`COPILOT_ALLOW_ALL=true` also trusts the folder but approves all tools. In an
26+
untrusted folder Copilot skips hooks, drops additional context, and still exits
27+
successfully. Spec Kit does not add trust flags automatically.
28+
29+
Spec Kit does not write hooks through a symlinked `.github/hooks` directory, so
30+
`init`, `integration install`, and `integration upgrade` fail there with events
31+
enabled. Use `--integration-options="--events false"` to
32+
opt out of events, disabling `additional_context` delivery and extension event
33+
hooks for Copilot.
34+
2035
## Default Skills Layout
2136

2237
Skills are installed as `.github/skills/speckit-<command>/SKILL.md`.
@@ -102,7 +117,9 @@ a newly created settings file is manifest-tracked.
102117

103118
## Runtime Events and Workflow Permissions
104119

105-
Native events use `.github/hooks/speckit.json`.
120+
With events enabled, Copilot projects get `.specify/events.py` and
121+
`.github/hooks/speckit.json` by default, including a built-in `session_start`
122+
handler for additional context.
106123
`--integration-options="--events false"` disables Spec Kit event handlers.
107124
See [runtime events](cli.md#runtime-events).
108125

‎docs/workflow-steps/types.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,9 @@ integrations:
7171
An override replaces the integration's entire event map, so include any other
7272
handlers you want to keep.
7373

74-
No built-in integration declares support yet.
74+
| Integration | Guide and agent-side preconditions |
75+
| ----------- | ---------------------------------- |
76+
| `copilot` | [Copilot](../integrations/copilot.md#additional-context-and-folder-trust) |
7577

7678
An integration's agent-side trust, authentication, and feature gates are
7779
outside Spec Kit's control. Older external adapters that override

‎src/specify_cli/events/__init__.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2446,6 +2446,37 @@ def _remove_toml_entries(dst: Path, *, project_root: Path) -> bool:
24462446
return False
24472447

24482448

2449+
def _read_copilot_json_handlers(integration: IntegrationBase, project_root: Path) -> dict[str, list[str]]:
2450+
"""Read owned, correctly routed dispatcher handlers from Copilot hooks."""
2451+
config_file = getattr(integration, "events_config_file", None)
2452+
if not config_file:
2453+
return {}
2454+
existing = _load_user_json(project_root / config_file)
2455+
hooks = existing.get("hooks", {}) if existing is not None else {}
2456+
if not isinstance(hooks, dict):
2457+
return {}
2458+
target = "windows" if os.name == "nt" else "posix"
2459+
field = "powershell" if target == "windows" else "bash"
2460+
result: dict[str, list[str]] = {}
2461+
for canonical, native in getattr(integration, "CANONICAL_TO_NATIVE", {}).items():
2462+
entries = hooks.get(native, [])
2463+
if not isinstance(entries, list):
2464+
continue
2465+
for entry in entries:
2466+
if not isinstance(entry, dict) or entry.get(_SPECKIT_MARKER) is not True:
2467+
continue
2468+
command = entry.get(field)
2469+
if not isinstance(command, str):
2470+
continue
2471+
parsed = _parse_dispatcher_command(command, integration, project_root, target_os=target)
2472+
if parsed and parsed[1:] == (canonical, context_envelope_for(integration, canonical)):
2473+
result.setdefault(canonical, []).append(parsed[0])
2474+
return result
2475+
2476+
2477+
_EVENT_HANDLER_READERS["copilot-json"] = _read_copilot_json_handlers
2478+
2479+
24492480
def _merge_copilot_json(dst: Path, new_hooks: dict[str, list], *, project_root: Path) -> bool:
24502481
"""Merge Specify-owned hooks into Copilot's dedicated hooks JSON (#8).
24512482

‎src/specify_cli/integrations/copilot/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ class CopilotIntegration(IntegrationBase):
184184
}
185185
events_config_file = ".github/hooks/speckit.json"
186186
events_format = "copilot-json"
187+
context_delivery_events = frozenset({"session_start"})
187188
# Copilot consumes additionalContext from sessionStart and drops command
188189
# hook output from userPromptSubmitted.
189190
events_context_envelope = {

‎tests/integrations/test_integration_copilot.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,7 @@ def test_complete_file_inventory_sh(self, tmp_path):
329329
".github/agents/speckit.plan.agent.md",
330330
".github/agents/speckit.specify.agent.md",
331331
".github/agents/speckit.tasks.agent.md",
332+
".github/hooks/speckit.json",
332333
".github/prompts/speckit.analyze.prompt.md",
333334
".github/prompts/speckit.checklist.prompt.md",
334335
".github/prompts/speckit.clarify.prompt.md",
@@ -339,6 +340,7 @@ def test_complete_file_inventory_sh(self, tmp_path):
339340
".github/prompts/speckit.specify.prompt.md",
340341
".github/prompts/speckit.tasks.prompt.md",
341342
".vscode/settings.json",
343+
".specify/events.py",
342344
".specify/integration.json",
343345
".specify/init-options.json",
344346
".specify/integrations/copilot.manifest.json",
@@ -393,6 +395,7 @@ def test_complete_file_inventory_ps(self, tmp_path):
393395
".github/agents/speckit.plan.agent.md",
394396
".github/agents/speckit.specify.agent.md",
395397
".github/agents/speckit.tasks.agent.md",
398+
".github/hooks/speckit.json",
396399
".github/prompts/speckit.analyze.prompt.md",
397400
".github/prompts/speckit.checklist.prompt.md",
398401
".github/prompts/speckit.clarify.prompt.md",
@@ -403,6 +406,7 @@ def test_complete_file_inventory_ps(self, tmp_path):
403406
".github/prompts/speckit.specify.prompt.md",
404407
".github/prompts/speckit.tasks.prompt.md",
405408
".vscode/settings.json",
409+
".specify/events.py",
406410
".specify/integration.json",
407411
".specify/init-options.json",
408412
".specify/integrations/copilot.manifest.json",
@@ -913,6 +917,8 @@ def test_complete_file_inventory_skills_sh(self, tmp_path):
913917
assert result.exit_code == 0, f"init failed: {result.output}"
914918
actual = sorted(p.relative_to(project).as_posix() for p in project.rglob("*") if p.is_file() and ".git" not in p.parts)
915919
expected = sorted([
920+
".github/hooks/speckit.json",
921+
".specify/events.py",
916922
# Skill files (core commands)
917923
*[f".github/skills/speckit-{cmd}/SKILL.md" for cmd in self._SKILL_COMMANDS],
918924
# Integration metadata
@@ -1674,3 +1680,119 @@ def run(args, **kwargs):
16741680
tmp_path / ".specify" / "workflows" / "runs" / state.run_id / "log.jsonl"
16751681
).read_text(encoding="utf-8")
16761682
assert _SECRET_OUTPUT not in log
1683+
1684+
1685+
@pytest.fixture
1686+
def context_delivery_install(tmp_path):
1687+
from specify_cli.events import install_integration_events, resolve_events
1688+
1689+
copilot = get_integration("copilot")
1690+
state = tmp_path / ".specify/integration.json"
1691+
state.parent.mkdir()
1692+
state.write_text(json.dumps({
1693+
"default_integration": "copilot", "installed_integrations": ["copilot"]
1694+
}), encoding="utf-8")
1695+
manifest = IntegrationManifest("copilot", tmp_path, version="test")
1696+
install_integration_events(copilot, tmp_path, manifest, resolve_events("copilot", copilot.config, tmp_path, None))
1697+
return copilot
1698+
1699+
1700+
def test_copilot_context_delivery_install(tmp_path, context_delivery_install):
1701+
from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, context_delivery_error
1702+
1703+
copilot = context_delivery_install
1704+
native = json.loads((tmp_path / copilot.events_config_file).read_text(encoding="utf-8"))
1705+
entry = native["hooks"]["sessionStart"][0]
1706+
assert entry["__speckit_event__"] is True
1707+
assert all(ADDITIONAL_CONTEXT_HANDLER in entry[field] for field in ("bash", "powershell"))
1708+
assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]}
1709+
assert context_delivery_error(copilot, tmp_path) is None
1710+
1711+
1712+
@pytest.mark.parametrize("damage", [
1713+
"malformed", "jsonc", "wrong_native_event", "wrong_command", "wrong_canonical_event",
1714+
"wrong_envelope", "unmarked", "marker_not_true", "stale_dispatcher", "modified_dispatcher",
1715+
])
1716+
def test_copilot_context_delivery_rejects_damaged_install(tmp_path, context_delivery_install, damage):
1717+
from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, context_delivery_error
1718+
1719+
copilot = context_delivery_install
1720+
path = tmp_path / copilot.events_config_file
1721+
native = json.loads(path.read_text(encoding="utf-8"))
1722+
entry = native["hooks"]["sessionStart"][0]
1723+
if damage == "wrong_native_event":
1724+
native["hooks"]["sessionEnd"] = native["hooks"].pop("sessionStart")
1725+
elif damage in ("wrong_command", "wrong_canonical_event", "wrong_envelope"):
1726+
original, replacement = {
1727+
"wrong_command": (ADDITIONAL_CONTEXT_HANDLER, "other-handler"),
1728+
"wrong_canonical_event": ("session_start", "session_end"),
1729+
"wrong_envelope": ("additionalContext", "plain"),
1730+
}[damage]
1731+
for field in ("bash", "powershell"):
1732+
entry[field] = entry[field].replace(original, replacement)
1733+
elif damage == "unmarked":
1734+
entry.pop("__speckit_event__")
1735+
elif damage == "marker_not_true":
1736+
entry["__speckit_event__"] = 1
1737+
elif damage in ("stale_dispatcher", "modified_dispatcher"):
1738+
dispatcher = tmp_path / ".specify/events.py"
1739+
dispatcher.write_text("# stale\n" if damage == "stale_dispatcher" else
1740+
dispatcher.read_text(encoding="utf-8") + "# modified\n", encoding="utf-8")
1741+
content = {"malformed": "{", "jsonc": '{// comment\n"hooks": {}}'}.get(damage, json.dumps(native))
1742+
path.write_text(content, encoding="utf-8")
1743+
error = context_delivery_error(copilot, tmp_path)
1744+
assert "missing or outdated" in error
1745+
assert "specify integration upgrade copilot" in error
1746+
1747+
1748+
@pytest.mark.parametrize("target,selected,other", [("posix", "bash", "powershell"), ("nt", "powershell", "bash")])
1749+
def test_copilot_context_delivery_selects_current_platform_command(
1750+
tmp_path, context_delivery_install, monkeypatch, target, selected, other
1751+
):
1752+
from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER
1753+
1754+
copilot = context_delivery_install
1755+
path = tmp_path / copilot.events_config_file
1756+
native = json.loads(path.read_text(encoding="utf-8"))
1757+
entry = native["hooks"]["sessionStart"][0]
1758+
valid = entry[other]
1759+
entry[other] = "broken"
1760+
path.write_text(json.dumps(native), encoding="utf-8")
1761+
with monkeypatch.context() as patcher:
1762+
patcher.setattr("specify_cli.events.os.name", target)
1763+
assert copilot.installed_event_handlers(tmp_path) == {"session_start": [ADDITIONAL_CONTEXT_HANDLER]}
1764+
entry[other], entry[selected] = valid, "broken"
1765+
path.write_text(json.dumps(native), encoding="utf-8")
1766+
assert copilot.installed_event_handlers(tmp_path) == {}
1767+
1768+
1769+
def test_copilot_context_delivery_reader_maps_owned_handlers(tmp_path, context_delivery_install):
1770+
from specify_cli.events import ADDITIONAL_CONTEXT_HANDLER, _dispatcher_command
1771+
1772+
copilot = context_delivery_install
1773+
path = tmp_path / copilot.events_config_file
1774+
native = json.loads(path.read_text(encoding="utf-8"))
1775+
start = native["hooks"]["sessionStart"][0]
1776+
command = _dispatcher_command(copilot, tmp_path, "end-handler", "session_end", target_os="posix")
1777+
ps_command = _dispatcher_command(copilot, tmp_path, "end-handler", "session_end", target_os="windows")
1778+
end = {"__speckit_event__": True, "bash": command, "powershell": ps_command}
1779+
native["hooks"]["sessionStart"].extend([None, {}, {**start, "__speckit_event__": False}, start])
1780+
native["hooks"]["sessionEnd"] = [end]
1781+
native["hooks"]["unknown"] = [start]
1782+
path.write_text(json.dumps(native), encoding="utf-8")
1783+
assert copilot.installed_event_handlers(tmp_path) == {
1784+
"session_start": [ADDITIONAL_CONTEXT_HANDLER, ADDITIONAL_CONTEXT_HANDLER],
1785+
"session_end": ["end-handler"],
1786+
}
1787+
1788+
1789+
@pytest.mark.parametrize("content", ['[]', '{"hooks": []}', '{"hooks": {"sessionStart": {}}}'])
1790+
def test_copilot_context_delivery_reader_rejects_non_object_or_invalid_hooks(
1791+
tmp_path, context_delivery_install, content
1792+
):
1793+
from specify_cli.events import context_delivery_error
1794+
1795+
copilot = context_delivery_install
1796+
(tmp_path / copilot.events_config_file).write_text(content, encoding="utf-8")
1797+
assert copilot.installed_event_handlers(tmp_path) == {}
1798+
assert "missing or outdated" in context_delivery_error(copilot, tmp_path)

‎tests/specify_cli/events/test_context_delivery.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,7 @@ def test_invalid_installed_native_handler_is_rejected(tmp_path, installed, damag
511511

512512

513513
def test_unreadable_handler_report_and_unknown_format(tmp_path, installed, monkeypatch):
514+
monkeypatch.setattr(installed, "events_format", "unknown-format")
514515
assert IntegrationBase.installed_event_handlers(installed, tmp_path) is None
515516
monkeypatch.setattr(installed, "installed_event_handlers", lambda root: None)
516517
error = context_delivery_error(installed, tmp_path)
@@ -542,12 +543,14 @@ def reader(adapter, root):
542543
assert seen == [(integration, tmp_path)]
543544

544545

545-
def test_copilot_is_not_a_context_delivery_declarer(tmp_path):
546+
def test_copilot_is_a_context_delivery_declarer(tmp_path):
546547
copilot = get_integration("copilot")
547-
assert resolve_events("copilot", copilot.config, tmp_path, None) == {}
548+
assert resolve_events("copilot", copilot.config, tmp_path, None) == {
549+
"session_start": [{"command": ADDITIONAL_CONTEXT_HANDLER}]
550+
}
548551
error = context_delivery_error(copilot, tmp_path)
549-
assert "not declared" in error
550-
assert "Supporting integrations: none" in error
552+
assert "not installed" in error
553+
assert "Supporting integrations: copilot" in error
551554

552555

553556
def test_parse_dispatcher_with_project_venv_interpreter(tmp_path):

‎tests/specify_cli/test_command_init.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ def test_reinit_preserves_feature_numbering(tmp_path: Path, monkeypatch, numberi
142142
assert updated["here"] is True
143143

144144

145-
def test_init_copilot_with_missing_config_in_symlinked_hooks_dir(tmp_path, monkeypatch):
145+
def test_init_copilot_refuses_symlinked_hooks_dir(tmp_path, monkeypatch):
146146
project = tmp_path / "project"
147147
outside = tmp_path / "outside"
148148
(project / ".github").mkdir(parents=True)
@@ -156,8 +156,30 @@ def test_init_copilot_with_missing_config_in_symlinked_hooks_dir(tmp_path, monke
156156
"--ignore-agent-tools", "--force",
157157
])
158158

159+
assert result.exit_code != 0, result.output
160+
assert "Refusing to record symlinked manifest path:" in result.output
161+
assert ".github/hooks/speckit.json (symlinked at .github/hooks)" in result.output
162+
assert hooks.is_symlink()
163+
assert not list(outside.iterdir())
164+
165+
166+
def test_init_copilot_with_events_disabled_allows_symlinked_hooks_dir(tmp_path, monkeypatch):
167+
project = tmp_path / "project"
168+
outside = tmp_path / "outside"
169+
(project / ".github").mkdir(parents=True)
170+
outside.mkdir()
171+
hooks = project / ".github/hooks"
172+
_symlink_or_skip(hooks, outside, directory=True)
173+
monkeypatch.chdir(project)
174+
175+
result = CliRunner().invoke(app, [
176+
"init", ".", "--integration", "copilot", "--script", "sh",
177+
"--ignore-agent-tools", "--force", "--integration-options=--events false",
178+
])
179+
159180
assert result.exit_code == 0, result.output
160181
assert hooks.is_symlink()
182+
assert not (hooks / "speckit.json").exists()
161183
assert not list(outside.iterdir())
162184

163185

0 commit comments

Comments
 (0)