Skip to content

Commit 200565e

Browse files
mnriemCopilot
andcommitted
Fix legacy hook enable and projection refresh edge cases
Match legacy enable fallback to registration's last-write-wins semantics. Retire orphaned projections during shared infrastructure refresh and rebuild unchanged native registrations without rewriting YAML. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <[email protected]>
1 parent 60b2456 commit 200565e

5 files changed

Lines changed: 173 additions & 11 deletions

File tree

‎docs/reference/extensions.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -319,8 +319,9 @@ or perform an extension configuration update. Only the literal JSON boolean
319319
markdown/YAML hook behavior unchanged, without producing a projection.
320320
Other values for this key are rejected. Turning the option off retires an
321321
existing projection on the next configuration save or shared-infrastructure
322-
refresh. Run only one Specify CLI mutation against a project at a time;
323-
simultaneous CLI changes to the same project are unsupported.
322+
refresh, even if `extensions.yml` has been removed. Run only one Specify CLI
323+
mutation against a project at a time; simultaneous CLI changes to the same
324+
project are unsupported.
324325
325326
When opted in, extension configuration saves publish a validated projection in
326327
`.specify/hook-dispatch/`: one `<event>.json` response and SHA-256 digest per
@@ -331,7 +332,9 @@ Only enabled hooks with no condition appear in the projection,
331332
in their YAML declaration order (regardless of priority). Each response
332333
includes `extension`, `command`, `optional`, `description`, `prompt`, and
333334
`priority`. Existing projects receive a projection when their shared
334-
infrastructure is refreshed; configuration writes regenerate it. Invalid
335+
infrastructure is refreshed; configuration writes regenerate it. Re-registering
336+
an unchanged extension also refreshes the projection without rewriting the
337+
configuration's comments or line endings. Invalid
335338
hook entries and unsafe projection paths prevent publication when opted in. Current installed
336339
commands continue using their existing hook resolution; the projection does
337340
not change execution behavior. For projection portability, missing or invalid

‎src/specify_cli/__init__.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,13 @@ def _install_shared_infra(
191191
refresh_managed=refresh_managed,
192192
refresh_hint=refresh_hint,
193193
)
194-
if config_file.exists() or config_file.is_symlink():
194+
projection_dir = config_file.parent / "hook-dispatch"
195+
if (
196+
config_file.exists() or config_file.is_symlink()
197+
or projection_dir.exists() or projection_dir.is_symlink()
198+
):
199+
from .extensions import HookExecutor
200+
195201
HookExecutor(project_path).migrate_project_config()
196202
return result
197203

‎src/specify_cli/extensions/__init__.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3748,12 +3748,21 @@ def enable(self, extension_id: str) -> bool:
37483748
manifest = self.get_extension(extension_id)
37493749
if manifest is None:
37503750
raise ExtensionError(f"Cannot read manifest for '{extension_id}'")
3751-
previous = [
3752-
{"event": event, "command": entry["command"], "enabled": entry.get("enabled", True)}
3753-
for event, entries in manifest.hooks.items()
3754-
for entry in coerce_hook_entries(entries)
3755-
if isinstance(entry, dict) and entry.get("command")
3756-
]
3751+
previous = []
3752+
for event, entries in manifest.hooks.items():
3753+
# Match registration's last-write-wins values and order.
3754+
states = {}
3755+
for entry in coerce_hook_entries(entries):
3756+
if not isinstance(entry, dict) or not entry.get("command"):
3757+
continue
3758+
command = entry["command"]
3759+
if command in states:
3760+
del states[command]
3761+
states[command] = {
3762+
"event": event, "command": command,
3763+
"enabled": entry.get("enabled", True),
3764+
}
3765+
previous.extend(states.values())
37573766
owned = [
37583767
(event, hook)
37593768
for event, hooks in config.get("hooks", {}).items()
@@ -6262,6 +6271,8 @@ def register_hooks(self, manifest: ExtensionManifest):
62626271

62636272
if changed:
62646273
self.save_project_config(config)
6274+
elif native_hooks:
6275+
self.migrate_project_config()
62656276

62666277
def unregister_hooks(self, extension_id: str):
62676278
"""Remove extension hooks from project config.

‎tests/specify_cli/extensions/test_command_enable.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,47 @@ def test_enable_older_disabled_extension_uses_manifest_declared_states(
191191
config = yaml.safe_load((project_dir / ".specify/extensions.yml").read_text())
192192
assert [hook["enabled"] for hook in config["hooks"]["before_plan"]] == [False, True]
193193

194+
@pytest.mark.parametrize("last_enabled", [False, True])
195+
def test_enable_older_disabled_extension_deduplicates_manifest_last_write_wins(
196+
self, project_dir, extension_dir, last_enabled
197+
):
198+
enable_native_hooks(project_dir)
199+
manifest_path = extension_dir / "extension.yml"
200+
manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
201+
manifest["hooks"] = {
202+
"before_plan": [
203+
{"command": "speckit.test-ext.hello", "enabled": not last_enabled},
204+
{"command": "speckit.test-ext.other", "enabled": True},
205+
{"command": "speckit.test-ext.hello", "enabled": last_enabled},
206+
],
207+
"after_plan": {"command": "speckit.test-ext.hello", "enabled": True},
208+
}
209+
manifest_path.write_text(yaml.safe_dump(manifest, sort_keys=False), encoding="utf-8")
210+
manager = ExtensionManager(project_dir)
211+
manager.install_from_directory(extension_dir, "0.1.0", register_commands=False)
212+
executor = HookExecutor(project_dir)
213+
original_hooks = executor.load_project_config_for_update()["hooks"]
214+
assert [
215+
hook["command"] for hook in original_hooks["before_plan"]
216+
] == ["speckit.test-ext.other", "speckit.test-ext.hello"]
217+
assert manager.disable("test-ext")
218+
metadata = manager.registry.get("test-ext")
219+
metadata.pop("disabled_hook_states")
220+
manager.registry.restore("test-ext", metadata)
221+
222+
assert manager.enable("test-ext")
223+
assert executor.load_project_config_for_update()["hooks"] == original_hooks
224+
assert manager.registry.get("test-ext")["enabled"] is True
225+
cache = project_dir / ".specify/hook-dispatch"
226+
assert [
227+
hook["command"] for hook in json.loads((cache / "before_plan.json").read_text())["hooks"]
228+
] == ["speckit.test-ext.other"] + (
229+
["speckit.test-ext.hello"] if last_enabled else []
230+
)
231+
assert [
232+
hook["command"] for hook in json.loads((cache / "after_plan.json").read_text())["hooks"]
233+
] == ["speckit.test-ext.hello"]
234+
194235
def test_cli_enable_keeps_manifest_disabled_hook_out_of_projection(
195236
self, project_dir, extension_dir
196237
):

‎tests/specify_cli/extensions/test_hook_projection.py‎

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import yaml
99

1010
from specify_cli import save_init_options
11-
from specify_cli.extensions import HookExecutor
11+
from specify_cli.extensions import ExtensionManifest, HookExecutor
1212
from specify_cli.extensions._hook_projection import project_hooks
1313

1414

@@ -352,6 +352,107 @@ def test_shared_infrastructure_refresh_projects_existing_config(tmp_path, monkey
352352
_assert_snapshot(tmp_path)
353353

354354

355+
@pytest.mark.parametrize("opt_in", [False, True])
356+
def test_shared_infrastructure_refresh_retires_projection_without_config(
357+
tmp_path, monkeypatch, opt_in
358+
):
359+
import specify_cli
360+
361+
executor = _enabled_executor(tmp_path)
362+
executor.save_project_config(_config())
363+
executor.config_file.unlink()
364+
save_init_options(tmp_path, {"native_extension_hooks": opt_in})
365+
monkeypatch.setattr(specify_cli, "_install_shared_infra_impl", lambda *args, **kwargs: True)
366+
367+
assert specify_cli._install_shared_infra(tmp_path, "sh", refresh_managed=True)
368+
assert not (tmp_path / ".specify/hook-dispatch").exists()
369+
assert not executor.config_file.exists()
370+
371+
372+
def test_shared_infrastructure_refresh_rejects_symlinked_projection_without_config(
373+
tmp_path, monkeypatch
374+
):
375+
import specify_cli
376+
377+
root = tmp_path / ".specify"
378+
root.mkdir()
379+
target = tmp_path / "external"
380+
target.mkdir()
381+
marker = target / "before_plan.json"
382+
marker.write_bytes(b"untouched")
383+
cache = root / "hook-dispatch"
384+
cache.symlink_to(target, target_is_directory=True)
385+
monkeypatch.setattr(specify_cli, "_install_shared_infra_impl", lambda *args, **kwargs: True)
386+
387+
with pytest.raises(ValueError, match="symlinked hook projection"):
388+
specify_cli._install_shared_infra(tmp_path, "sh", refresh_managed=True)
389+
assert cache.is_symlink()
390+
assert marker.read_bytes() == b"untouched"
391+
assert not (root / "extensions.yml").exists()
392+
393+
394+
@pytest.mark.parametrize("cache_state", ["missing", "stale"])
395+
@pytest.mark.parametrize("has_hooks", [False, True])
396+
def test_unchanged_native_registration_refreshes_projection_without_rewriting_yaml(
397+
tmp_path, extension_dir, cache_state, has_hooks
398+
):
399+
if not has_hooks:
400+
manifest_path = extension_dir / "extension.yml"
401+
data = yaml.safe_load(manifest_path.read_text(encoding="utf-8"))
402+
data["hooks"] = {}
403+
manifest_path.write_text(yaml.safe_dump(data), encoding="utf-8")
404+
manifest = ExtensionManifest(extension_dir / "extension.yml")
405+
executor = _enabled_executor(tmp_path)
406+
executor.register_hooks(manifest)
407+
original = b"# Preserve this comment\r\n" + executor.config_file.read_bytes().replace(
408+
b"\n", b"\r\n"
409+
)
410+
executor.config_file.write_bytes(original)
411+
cache = tmp_path / ".specify/hook-dispatch"
412+
if cache_state == "missing":
413+
for child in cache.iterdir():
414+
child.unlink()
415+
cache.rmdir()
416+
else:
417+
(cache / "events.txt").write_bytes(b"before_plan\n")
418+
(cache / "before_plan.json").write_bytes(b"stale")
419+
420+
executor.register_hooks(manifest)
421+
422+
assert executor.config_file.read_bytes() == original
423+
assert (cache / "source.yml").read_bytes() == original
424+
expected = project_hooks(yaml.safe_load(original))
425+
index = "".join(f"{event}\n" for event in expected).encode("utf-8")
426+
assert (cache / "events.txt").read_bytes() == index
427+
assert (cache / "events.txt.sha256").read_text().strip() == hashlib.sha256(index).hexdigest()
428+
for event, payload in expected.items():
429+
assert (cache / f"{event}.json").read_bytes() == payload
430+
assert (cache / f"{event}.json.sha256").read_text().strip() == hashlib.sha256(payload).hexdigest()
431+
assert not (cache / "before_plan.json").exists()
432+
433+
434+
def test_unchanged_native_registration_reports_projection_failure(
435+
tmp_path, extension_dir, monkeypatch
436+
):
437+
import specify_cli.extensions._hook_projection as projection
438+
439+
manifest = ExtensionManifest(extension_dir / "extension.yml")
440+
executor = _enabled_executor(tmp_path)
441+
executor.register_hooks(manifest)
442+
original = executor.config_file.read_bytes()
443+
real_write = projection.write_bytes
444+
445+
def fail_index(path, content):
446+
if path.name == "events.txt":
447+
raise OSError("disk full")
448+
return real_write(path, content)
449+
450+
monkeypatch.setattr(projection, "write_bytes", fail_index)
451+
with pytest.raises(OSError, match="disk full.*refresh-shared-infra"):
452+
executor.register_hooks(manifest)
453+
assert executor.config_file.read_bytes() == original
454+
455+
355456
def test_project_hooks_is_pure():
356457
config = _config()
357458
original = yaml.safe_dump(config)

0 commit comments

Comments
 (0)