Skip to content

Commit 55d2b52

Browse files
feat(hooks): the openspec early-warning hook — one body, three harness wrappers (Q5 step 3)
EARLY WARNING, NOT ENFORCEMENT, and labelled so in every file: the hard gate stays `just release-check` + CI. The hook exists so a release action is questioned at the keyboard instead of failing twenty minutes later — and per the arbitration's own caution, a hook that cannot be shown to block is never described as enforcement. Verification state is recorded per harness in the script header: Kiro's PreToolUse exit-2 block is verified against the harness's own hook documentation; Claude Code's is vendor-documented, unattested here; Codex's events were verified against the vendor page in the 2026-09-04 review. One body (scripts/openspec-gate.py, tool call as JSON on stdin), the same hub pattern as the xTiles skill; the wrappers are committed (force-added past the harness-dir gitignore rules, the same convention as openspec/) at .kiro/hooks/openspec-gate.json, .claude/settings.json and .codex/hooks.json so contributors inherit them. The gate IMPORTS the real release guard from check-release-consistency.py rather than re-implementing it — two implementations of "what counts as shipped" is how a hook and a release gate come to disagree. Behaviour: `git tag` / `prepare-release` are blocked (exit 2) when an openspec change with commits since the last tag is neither archived nor deferred; `git commit` gets a one-line warning and is NEVER blocked — open changes are legal during a cycle; anything else exits 0 with no subprocess spawned. UserPromptSubmit gets a terse reminder only when the guard would fail. The hook fails OPEN on its own errors: a broken early warning must never block work the hard gate would allow. Tests drive the script in a subprocess against fixture repos carrying the REAL consistency script: block-on-tag, warn-on-commit, deferred unblocks, garbage stdin fails open, and a wrapper-drift pin that all three wrappers call the one body. Full preflight green: 4790 passed, 4 skipped.
1 parent 2b2f26f commit 55d2b52

5 files changed

Lines changed: 339 additions & 0 deletions

File tree

‎.claude/settings.json‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"hooks": {
3+
"PreToolUse": [
4+
{
5+
"matcher": "Bash",
6+
"hooks": [
7+
{
8+
"type": "command",
9+
"command": "uv run python scripts/openspec-gate.py pre-tool-use",
10+
"timeout": 30
11+
}
12+
]
13+
}
14+
],
15+
"UserPromptSubmit": [
16+
{
17+
"hooks": [
18+
{
19+
"type": "command",
20+
"command": "uv run python scripts/openspec-gate.py remind",
21+
"timeout": 30
22+
}
23+
]
24+
}
25+
]
26+
}
27+
}

‎.codex/hooks.json‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"hooks": {
3+
"PreToolUse": [
4+
{
5+
"hooks": [
6+
{
7+
"type": "command",
8+
"command": "uv run python scripts/openspec-gate.py pre-tool-use",
9+
"timeout": 30
10+
}
11+
]
12+
}
13+
],
14+
"UserPromptSubmit": [
15+
{
16+
"hooks": [
17+
{
18+
"type": "command",
19+
"command": "uv run python scripts/openspec-gate.py remind",
20+
"timeout": 30
21+
}
22+
]
23+
}
24+
]
25+
}
26+
}

‎.kiro/hooks/openspec-gate.json‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"version": "v1",
3+
"hooks": [
4+
{
5+
"name": "openspec-gate (early warning, not enforcement)",
6+
"trigger": "PreToolUse",
7+
"matcher": "execute_bash",
8+
"action": {
9+
"type": "command",
10+
"command": "uv run python scripts/openspec-gate.py pre-tool-use"
11+
}
12+
},
13+
{
14+
"name": "openspec-remind",
15+
"trigger": "UserPromptSubmit",
16+
"action": {
17+
"type": "command",
18+
"command": "uv run python scripts/openspec-gate.py remind"
19+
}
20+
}
21+
]
22+
}
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
"""The openspec early-warning hook: block release actions, warn on commits.
2+
3+
Drives ``scripts/openspec-gate.py`` in a subprocess with the same stdin JSON
4+
shape every harness sends (``tool_input.command``), against fixture git repos
5+
where the release guard genuinely fails and genuinely passes — so both the
6+
exit-2 branch and the fail-open contract are proven, not assumed.
7+
"""
8+
9+
from __future__ import annotations
10+
11+
import json
12+
import subprocess
13+
import sys
14+
from pathlib import Path
15+
16+
import pytest
17+
18+
GATE = Path(__file__).resolve().parents[3] / "scripts" / "openspec-gate.py"
19+
CONSISTENCY = GATE.parent / "check-release-consistency.py"
20+
21+
22+
def _git(cwd: Path, *args: str) -> None:
23+
subprocess.run(
24+
["git", *args],
25+
cwd=cwd,
26+
check=True,
27+
capture_output=True,
28+
env={
29+
"PATH": "/usr/bin:/bin",
30+
"GIT_AUTHOR_NAME": "t",
31+
"GIT_AUTHOR_EMAIL": "t@t",
32+
"GIT_COMMITTER_NAME": "t",
33+
"GIT_COMMITTER_EMAIL": "t@t",
34+
"HOME": str(cwd),
35+
},
36+
timeout=60,
37+
)
38+
39+
40+
@pytest.fixture()
41+
def repo(tmp_path: Path) -> Path:
42+
"""A repo with an UNARCHIVED, UNDEFERRED change committed after the tag —
43+
the exact state the 0.2.0 cut shipped in."""
44+
root = tmp_path / "repo"
45+
(root / "scripts").mkdir(parents=True)
46+
# The gate imports the guard from the repo under test, so the fixture
47+
# carries the REAL script — a stub here would test the stub.
48+
(root / "scripts" / "check-release-consistency.py").write_text(
49+
CONSISTENCY.read_text(encoding="utf-8"), encoding="utf-8"
50+
)
51+
(root / "seed.txt").write_text("seed")
52+
_git(root, "init", "-q")
53+
_git(root, "add", ".")
54+
_git(root, "commit", "-qm", "seed")
55+
_git(root, "tag", "v0.0.1")
56+
change = root / "openspec" / "changes" / "unshipped-thing"
57+
change.mkdir(parents=True)
58+
(change / "proposal.md").write_text("## Why\n")
59+
_git(root, "add", "openspec")
60+
_git(root, "commit", "-qm", "work on unshipped-thing")
61+
return root
62+
63+
64+
def _run_gate(repo_root: Path, command: str, mode: str = "pre-tool-use"):
65+
payload = json.dumps({"tool_name": "Bash", "tool_input": {"command": command}})
66+
return subprocess.run(
67+
[sys.executable, str(GATE), mode, "--repo-root", str(repo_root)],
68+
input=payload,
69+
capture_output=True,
70+
text=True,
71+
timeout=60,
72+
)
73+
74+
75+
def test_release_actions_are_blocked_when_the_guard_fails(repo: Path) -> None:
76+
for command in ("git tag v0.0.2", "uv run python scripts/prepare-release.py 0.0.2"):
77+
result = _run_gate(repo, command)
78+
assert result.returncode == 2, f"{command!r} was not blocked: {result.stdout}"
79+
assert "unshipped-thing" in result.stderr
80+
assert "release-check" in result.stderr, "the block must name the hard gate"
81+
82+
83+
def test_commits_are_warned_never_blocked(repo: Path) -> None:
84+
result = _run_gate(repo, "git commit -m 'normal cycle work'")
85+
assert result.returncode == 0, "a commit was blocked — open changes are legal in a cycle"
86+
assert "unshipped-thing" in result.stdout
87+
88+
89+
def test_unrelated_commands_pass_silently(repo: Path) -> None:
90+
result = _run_gate(repo, "ls -la && pytest -q")
91+
assert result.returncode == 0
92+
assert result.stdout == ""
93+
94+
95+
def test_deferred_change_unblocks_the_release_action(repo: Path) -> None:
96+
meta = repo / "openspec" / "changes" / "unshipped-thing" / ".openspec.yaml"
97+
meta.write_text("deferred: waiting on the transport decision\n")
98+
_git(repo, "add", str(meta.relative_to(repo)))
99+
_git(repo, "commit", "-qm", "defer it")
100+
101+
result = _run_gate(repo, "git tag v0.0.2")
102+
assert result.returncode == 0, result.stderr
103+
104+
105+
def test_remind_mode_is_terse_and_never_blocks(repo: Path) -> None:
106+
result = _run_gate(repo, "", mode="remind")
107+
assert result.returncode == 0
108+
assert "unshipped-thing" in result.stdout
109+
assert len(result.stdout.splitlines()) == 1
110+
111+
112+
def test_garbage_stdin_fails_open(repo: Path) -> None:
113+
"""A broken early warning must never block work the hard gate allows."""
114+
result = subprocess.run(
115+
[sys.executable, str(GATE), "pre-tool-use", "--repo-root", str(repo)],
116+
input="not json at all {",
117+
capture_output=True,
118+
text=True,
119+
timeout=60,
120+
)
121+
assert result.returncode == 0
122+
123+
124+
def test_the_wrappers_call_the_same_one_body() -> None:
125+
"""Three harness wrappers, one script — the xTiles skill's hub pattern.
126+
A wrapper drifting to its own logic is exactly what this pins against."""
127+
repo_root = GATE.parents[1]
128+
wrappers = [
129+
repo_root / ".kiro" / "hooks" / "openspec-gate.json",
130+
repo_root / ".claude" / "settings.json",
131+
repo_root / ".codex" / "hooks.json",
132+
]
133+
for wrapper in wrappers:
134+
assert wrapper.is_file(), f"missing hook wrapper: {wrapper}"
135+
text = wrapper.read_text(encoding="utf-8")
136+
assert "scripts/openspec-gate.py" in text, f"{wrapper} does not call the one body"
137+
# And the one body says what it is: early warning, with per-harness
138+
# verification state — never "enforcement".
139+
body = GATE.read_text(encoding="utf-8")
140+
assert "NOT ENFORCEMENT" in body
141+
assert "release-check" in body

‎scripts/openspec-gate.py‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
#!/usr/bin/env python3
2+
"""OpenSpec early-warning hook — one body, three harness wrappers.
3+
4+
EARLY WARNING, NOT ENFORCEMENT. The hard gate is `just release-check`
5+
(scripts/check-release-consistency.py --release) plus CI; this hook exists so
6+
a release action is questioned at the keyboard instead of failing twenty
7+
minutes later. Per the 2026-09-04 arbitration (Q5 step 3), and per its own
8+
caution: a hook that cannot be shown to block must not be described as
9+
enforcement. Verification state of the block mechanism, per harness:
10+
11+
* Kiro CLI — VERIFIED against the harness's own hook documentation
12+
(PreToolUse, exit 2 blocks; stderr forwarded).
13+
* Claude Code — DOCUMENTED by the vendor (PreToolUse, exit 2 blocks);
14+
not attested by a recorded run in this repository.
15+
* Codex — events VERIFIED against the vendor hooks page in the
16+
2026-09-04 review; the exit-2 block is documented there.
17+
18+
Behaviour (stdin carries the tool-call JSON; all three harnesses use the
19+
``tool_input.command`` shape for their shell tool):
20+
21+
* ``git tag …`` or ``prepare-release`` → run the REAL release guard
22+
(imported from check-release-consistency.py, never a re-implementation);
23+
exit 2 with the guard's message when an openspec change with commits since
24+
the last tag is neither archived nor deferred.
25+
* ``git commit …`` → same check, but WARN on stdout and exit 0: open changes
26+
are legal during a cycle, so a commit is never blocked.
27+
* anything else → exit 0 immediately, no subprocess spawned.
28+
* ``remind`` mode (UserPromptSubmit) → one terse line when the guard would
29+
fail, silence otherwise; always exit 0.
30+
31+
Fails OPEN on its own errors (exit 0): a broken early warning must never
32+
block work the hard gate would allow.
33+
"""
34+
35+
from __future__ import annotations
36+
37+
import argparse
38+
import importlib.util
39+
import json
40+
import re
41+
import sys
42+
from pathlib import Path
43+
44+
_RELEASE_RE = re.compile(r"\bgit\s+tag\b|\bprepare-release\b")
45+
_COMMIT_RE = re.compile(r"\bgit\s+commit\b")
46+
47+
48+
def _load_release_guard(repo_root: Path):
49+
"""Import validate_openspec_changes_shipped from the real gate script.
50+
51+
Imported, never copied: two implementations of "what counts as shipped"
52+
is how a hook and a release gate come to disagree.
53+
"""
54+
path = repo_root / "scripts" / "check-release-consistency.py"
55+
spec = importlib.util.spec_from_file_location("_release_consistency", path)
56+
assert spec is not None and spec.loader is not None
57+
module = importlib.util.module_from_spec(spec)
58+
spec.loader.exec_module(module)
59+
return module.validate_openspec_changes_shipped
60+
61+
62+
def _guard_failure(repo_root: Path) -> str | None:
63+
"""The release guard's message when it would fail, else None."""
64+
try:
65+
_load_release_guard(repo_root)(repo_root)
66+
except ValueError as exc:
67+
return str(exc)
68+
return None
69+
70+
71+
def _command_from_stdin() -> str:
72+
try:
73+
payload = json.load(sys.stdin)
74+
except Exception:
75+
return ""
76+
tool_input = payload.get("tool_input") or payload.get("toolInput") or {}
77+
if isinstance(tool_input, dict):
78+
return str(tool_input.get("command", ""))
79+
return ""
80+
81+
82+
def main() -> int:
83+
parser = argparse.ArgumentParser(description=__doc__)
84+
parser.add_argument(
85+
"mode", nargs="?", default="pre-tool-use", choices=["pre-tool-use", "remind"]
86+
)
87+
parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1])
88+
args = parser.parse_args()
89+
repo_root = args.repo_root.resolve()
90+
91+
try:
92+
if args.mode == "remind":
93+
failure = _guard_failure(repo_root)
94+
if failure:
95+
print(f"openspec early warning: {failure}")
96+
return 0
97+
98+
command = _command_from_stdin()
99+
if _RELEASE_RE.search(command):
100+
failure = _guard_failure(repo_root)
101+
if failure:
102+
print(
103+
f"openspec gate: {failure}\n"
104+
"(early warning; the hard gate is `just release-check`)",
105+
file=sys.stderr,
106+
)
107+
return 2
108+
return 0
109+
if _COMMIT_RE.search(command):
110+
failure = _guard_failure(repo_root)
111+
if failure:
112+
# Warn only: open changes are LEGAL during a cycle. Blocking
113+
# commits would gate normal work on a release-time rule.
114+
print(f"openspec reminder (not blocking): {failure}")
115+
return 0
116+
return 0
117+
except Exception as exc: # fail OPEN — see module docstring
118+
print(f"openspec gate skipped (internal error: {exc})", file=sys.stderr)
119+
return 0
120+
121+
122+
if __name__ == "__main__":
123+
sys.exit(main())

0 commit comments

Comments
 (0)