Skip to content
Merged
3 changes: 1 addition & 2 deletions src/autoskillit/cli/_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

def _write_settings_data(settings_path: Path, data: dict) -> None:
"""Write settings data back atomically, creating parent dirs if needed."""
data.pop("_autoskillit_registry_hash", None)
settings_path.parent.mkdir(parents=True, exist_ok=True)
atomic_write(settings_path, json.dumps(data, indent=2))

Expand Down Expand Up @@ -120,7 +121,6 @@ def sync_hooks_to_settings(settings_path: Path, *, force: bool = False) -> None:
correctly checks plugin status before writing.
"""
from autoskillit.cli._init_helpers import _is_plugin_installed
from autoskillit.hook_registry import HOOK_REGISTRY_HASH

root = pkg_root()
if is_git_worktree(root):
Expand Down Expand Up @@ -159,7 +159,6 @@ def sync_hooks_to_settings(settings_path: Path, *, force: bool = False) -> None:
for (event_type, _), entry in groups.items():
event_list: list[dict] = data.setdefault("hooks", {}).setdefault(event_type, [])
event_list.append(entry)
data["_autoskillit_registry_hash"] = HOOK_REGISTRY_HASH
_write_settings_data(settings_path, data)


Expand Down
2 changes: 2 additions & 0 deletions src/autoskillit/hook_registry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
render_hook_scope_table,
render_hooks_json_text,
render_relocatable_hook_command,
serialize_hooks_json,
)
from ._risky_operations import (
_contract_session_scopes,
Expand Down Expand Up @@ -133,6 +134,7 @@
"quarantine_hook_payload",
"render_hook_scope_table",
"render_hooks_json_text",
"serialize_hooks_json",
"render_relocatable_hook_command",
"validate_lifecycle_contracts",
"validate_protection_coverage",
Expand Down
27 changes: 17 additions & 10 deletions src/autoskillit/hook_registry/_rendering.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from collections.abc import Sequence
from pathlib import Path

from ._hashing import compute_registry_hash
from ._hooks_defs import (
_LOGICAL_HOOK_COMPONENT,
HookDef,
Expand All @@ -23,7 +22,6 @@
LIFECYCLE_CONTRACTS,
PLUGIN_ROOT_TOKEN,
PROTECTION_WAIVERS,
RETIRED_SCRIPT_BASENAMES,
)


Expand Down Expand Up @@ -102,7 +100,22 @@ def render_hooks_json_text(
digests them; keeping the serialization in one place prevents the three
from drifting apart.
"""
return json.dumps(generate_hooks_json(registry, lifecycle_contracts), indent=2) + "\n"
return serialize_hooks_json(generate_hooks_json(registry, lifecycle_contracts))


def serialize_hooks_json(payload: dict) -> str:
"""Serialize a hook document without AutoSkillit's retired private key.

Repair uses the installed incarnation's payload rather than the running
registry, preserving its hooks and consumer-owned document metadata.
"""
return (
json.dumps(
{key: value for key, value in payload.items() if key != "_autoskillit_registry_hash"},
indent=2,
)
+ "\n"
)


def render_hook_scope_table(
Expand Down Expand Up @@ -174,10 +187,4 @@ def generate_hooks_json(
by_event: dict[str, list] = {}
for (event_type, _), entry in groups.items():
by_event.setdefault(event_type, []).append(entry)
registry_hash = compute_registry_hash(
registry,
RETIRED_SCRIPT_BASENAMES,
lifecycle_contracts,
PROTECTION_WAIVERS,
)
return {"hooks": by_event, "_autoskillit_registry_hash": registry_hash}
return {"hooks": by_event}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
is_hook_payload_quarantined,
quarantine_hook_payload,
render_relocatable_hook_command,
serialize_hooks_json,
)
from autoskillit.workspace._installed._artifact import (
write_installed_plugin_artifact_manifest_locked,
Expand Down Expand Up @@ -358,7 +359,7 @@ def _repair_hook_payload_under_lease(
try:
atomic_write(
hooks_json_path,
json.dumps(fresh, indent=2) + "\n",
serialize_hooks_json(fresh),
strict_durability=True,
)
write_manifest_refresh(manifest_refresh)
Expand Down
26 changes: 13 additions & 13 deletions tests/_retention_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1382,50 +1382,50 @@ def assert_second_pass_is_quiet(
"A shared lease is currently contended, so the legacy candidate waits for its holder."
),
# -- workspace._projected_artifact._hook_repair::repair_broken_plugin_cache_hooks --
f"{_HC}::L480": _self_limiting(
f"{_HC}::L481": _self_limiting(
"The plugin cache root is absent, leaving no hook incarnation to repair."
),
# -- workspace._projected_artifact._hook_repair::repair_broken_projection_hooks --
f"{_HP}::L550": _self_limiting(
f"{_HP}::L551": _self_limiting(
"The projections root is absent, leaving no projection hook payload to repair."
),
# -- workspace._projected_artifact._hook_repair::_hook_repair_needed --
f"{_HRP}::L307": _self_limiting(
f"{_HRP}::L308": _self_limiting(
"An incarnation without hooks.json has no hook payload this repairer can own."
),
f"{_HRP}::L310": _self_limiting(
f"{_HRP}::L311": _self_limiting(
"The content-fingerprinted quarantine marker already records this hooks payload's "
"terminal result."
),
f"{_HRP}::L314": _self_limiting(
f"{_HRP}::L315": _self_limiting(
"A malformed preflight payload is routed into the held-lease repair path before any "
"durable quarantine decision is made."
),
# -- workspace._projected_artifact._hook_repair::_repair_hook_incarnation --
f"{_HR}::L406": _self_limiting(
f"{_HR}::L407": _self_limiting(
"The unleased preflight found no relocatable or dispatcher repair work for this payload."
),
f"{_HR}::L408": _self_limiting(
f"{_HR}::L409": _self_limiting(
"The lease-held transaction owns the final repaired, quarantined, or quiet outcome."
),
f"{_HR}::L418": _resolves_with_contention(
f"{_HR}::L419": _resolves_with_contention(
"An exclusive hook lease is held by another live repairer and will release."
),
f"{_HR}::L424": _retries_after_input_changes(
f"{_HR}::L425": _retries_after_input_changes(
"A transient hook read, write, or rollback failure leaves the candidate retryable."
),
# -- workspace._projected_artifact._hook_repair::_repair_hook_payload_under_lease --
f"{_HRL}::L331": _self_limiting(
f"{_HRL}::L332": _self_limiting(
"The payload changed to a marked incarnation before the lease, completing its disposition."
),
f"{_HRL}::L336": _self_limiting(
f"{_HRL}::L337": _self_limiting(
"A durable quarantine marker and QUARANTINED outcome complete this invalid payload's "
"lifecycle."
),
f"{_HRL}::L342": _self_limiting(
f"{_HRL}::L343": _self_limiting(
"The hook payload became valid under the lease and no repair remains necessary."
),
f"{_HRL}::L348": _self_limiting(
f"{_HRL}::L349": _self_limiting(
"Identity validation writes a durable quarantine marker before reporting the terminal "
"outcome."
),
Expand Down
1 change: 0 additions & 1 deletion tests/_test_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1583,7 +1583,6 @@ class SourceMapRejection(enum.StrEnum):
"server/test_preflight_explicit_backend.py",
"server/test_managed_join_prelaunch.py",
"server/test_tools_fleet_dispatch_preflight.py",
"server/test_lifespan.py",
# file-level: live output-budget E2E imports the hook registry directly
"server/test_output_budget_e2e.py",
"execution/backends/test_claude_join_recovery_live_gate.py",
Expand Down
4 changes: 1 addition & 3 deletions tests/arch/test_durable_artifact_writers_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,7 @@
("workspace/_projected_artifact/_publication.py", "materialize_sanitized_plugin_root"),
# Verbatim byte-for-byte asset copy — no path is baked into the copy.
("workspace/_projected_artifact/_publication.py", "_copy_non_skill_plugin_assets"),
# Drift-check re-renders hooks.json from the registry hash; same content
# unless the registry changes, so this is the canonical hook-config writer,
# not a hook-artifact writer.
# Drift-check re-renders hooks.json when its bytes differ from render_hooks_json_text().
("server/lifecycle/_lifespan/_startup_checks.py", "run_startup_drift_check"),
}
)
Expand Down
35 changes: 35 additions & 0 deletions tests/cli/test_cli_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,41 @@ def test_evict_stale_hooks_removes_legacy_formats(tmp_path):
assert len(quota_commands) == 1


def test_evict_removes_orphaned_registry_hash_key(tmp_path: Path) -> None:
from autoskillit.cli._hooks import _evict_stale_autoskillit_hooks

settings = tmp_path / "settings.json"
user_group = {"matcher": "Bash", "hooks": [{"type": "command", "command": "echo hi"}]}
seed = {
"permissions": {"allow": ["Bash(git status)"]},
"env": {"PROJECT_MODE": "test"},
"_autoskillit_registry_hash": "legacy",
"hooks": {
"PreToolUse": [
{
"matcher": "Read",
"hooks": [
{
"type": "command",
"command": "python3 /old/hooks/_dispatch.py guards/tool_guard",
}
],
},
user_group,
]
},
}
settings.write_text(json.dumps(seed))

_evict_stale_autoskillit_hooks(settings)

data = json.loads(settings.read_text())
assert "_autoskillit_registry_hash" not in data
assert data["permissions"] == seed["permissions"]
assert data["env"] == seed["env"]
assert data["hooks"]["PreToolUse"] == [user_group]


# T-REG-1
def test_install_production_order_includes_quota_check(tmp_path, monkeypatch):
"""install() must register quota_guard.py in hooks.json (plugin authority path)."""
Expand Down
86 changes: 86 additions & 0 deletions tests/contracts/test_claude_code_interface_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import annotations

import json
from pathlib import Path

import pytest
Expand All @@ -21,6 +22,10 @@
import autoskillit.cli.session._session_reload as _patch_session__session_reload
import autoskillit.cli.ui._timed_input as _patch_ui__timed_input

# Populate HOOK_REGISTRY before rendering; hook_registry defers this to avoid an import cycle.
import autoskillit.hooks # noqa: F401
from autoskillit.hook_registry import generate_hooks_json, render_hooks_json_text

pytestmark = [pytest.mark.layer("contracts"), pytest.mark.medium]


Expand Down Expand Up @@ -402,6 +407,87 @@ def test_mcp_json_autoskillit_has_command_key(self) -> None:
)


# ---------------------------------------------------------------------------
# CC-HOOKS: Claude Code hooks.json key contract
# ---------------------------------------------------------------------------


# Supported keys of a Claude Code plugin hooks/hooks.json. Sources (retrieved 2026-10-25):
# https://code.claude.com/docs/en/hooks.md — top level description, hooks; matcher group
# matcher, hooks; handler fields type, if, timeout, statusMessage, and command
# fields command, args, async, asyncRewake, shell
# https://code.claude.com/docs/en/plugins/mods/reference.md — top level modules
# Claude Code CHANGELOG 2.1.274 — top level $schema; 2.1.295 — handler onFailure
_CLAUDE_HOOKS_FILE_KEYS = frozenset({"$schema", "description", "hooks", "modules"})
_CLAUDE_MATCHER_GROUP_KEYS = frozenset({"matcher", "hooks"})
# once is honored only in skill frontmatter.
_CLAUDE_COMMAND_HANDLER_KEYS = frozenset(
{
"type",
"command",
"args",
"async",
"asyncRewake",
"shell",
"onFailure",
"timeout",
"if",
"statusMessage",
}
)


def _unknown_claude_hook_keys(doc: dict) -> dict[str, set[str]]:
"""Report unsupported keys in a document with a required hooks mapping."""
unknown = {}
if extra := set(doc) - _CLAUDE_HOOKS_FILE_KEYS:
unknown["$"] = extra
for event, groups in doc["hooks"].items():
for group_index, group in enumerate(groups):
group_path = f"$.hooks.{event}[{group_index}]"
if extra := set(group) - _CLAUDE_MATCHER_GROUP_KEYS:
unknown[group_path] = extra
for handler_index, handler in enumerate(group["hooks"]):
if extra := set(handler) - _CLAUDE_COMMAND_HANDLER_KEYS:
unknown[f"{group_path}.hooks[{handler_index}]"] = extra
return unknown


class TestClaudeHooksJsonContract:
"""Strict key hygiene for generated command hooks, not full schema validation.

Recheck the upstream hooks reference and CHANGELOG when revising these key sets.
"""

def test_generated_hooks_json_contains_only_hooks(self) -> None:
assert set(generate_hooks_json()) == {"hooks"}

def test_rendered_hooks_json_uses_only_claude_accepted_keys(self) -> None:
doc = json.loads(render_hooks_json_text())
assert "hooks" in doc
unknown = _unknown_claude_hook_keys(doc)
assert not unknown, {path: sorted(keys) for path, keys in unknown.items()}

@pytest.mark.parametrize(
"path",
[None, "$", "$.hooks.PreToolUse[0]", "$.hooks.PreToolUse[0].hooks[0]"],
ids=["valid", "root", "matcher-group", "handler"],
)
def test_hooks_key_checker_reports_unknown_keys_by_path(self, path: str | None) -> None:
handler = {"type": "command", "command": "echo ok"}
group = {"matcher": "Bash", "hooks": [handler]}
doc = {"hooks": {"PreToolUse": [group]}}
if path is not None:
target = {
"$": doc,
"$.hooks.PreToolUse[0]": group,
"$.hooks.PreToolUse[0].hooks[0]": handler,
}[path]
target["_unexpected"] = True
expected = {} if path is None else {path: {"_unexpected"}}
assert _unknown_claude_hook_keys(doc) == expected


# ---------------------------------------------------------------------------
# CC-007: plugin.json structure contract
# ---------------------------------------------------------------------------
Expand Down
10 changes: 9 additions & 1 deletion tests/contracts/test_durable_artifact_relocatability.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ def test_plugin_cache_repair_output_is_relocatable(self, tmp_path: Path) -> None
(hooks_dir / "hooks.json").write_text(
json.dumps(
{
"_autoskillit_registry_hash": "legacy",
"description": "Installed incarnation hooks",
"hooks": {
"PreToolUse": [
{
Expand All @@ -399,7 +401,7 @@ def test_plugin_cache_repair_output_is_relocatable(self, tmp_path: Path) -> None
],
}
]
}
},
}
)
)
Expand All @@ -412,6 +414,12 @@ def test_plugin_cache_repair_output_is_relocatable(self, tmp_path: Path) -> None
outcomes = repair_broken_plugin_cache_hooks(cache_dir, home=managed_home_for(tmp_path))

assert outcomes[0].status is PluginHookRepairStatus.REPAIRED
payload = json.loads((hooks_dir / "hooks.json").read_text())
assert set(payload) == {"hooks", "description"}
assert payload["description"] == "Installed incarnation hooks"
assert payload["hooks"]["PreToolUse"][0]["hooks"][0]["command"].endswith(
" guards/tool_guard"
)
_assert_relocatable((hooks_dir / "hooks.json").read_text())

def test_projection_repair_outputs_are_relocatable(self, tmp_path: Path) -> None:
Expand Down
Loading
Loading