Files
planning-with-files/tests/test_codex_hooks.py
T
OthmanAdi 2d089130a9 release: v2.38.0 (Claude Code turn-loop integration + OpenCode SQLite fix)
PreCompact hook fires on /compact and autoCompact. When task_plan.md is
present, surfaces a reminder to flush in-context progress to progress.md
before compaction completes and prints the active Plan-SHA256 if attested.
Stays silent without a plan. Exit 0 always; never blocks compaction.

/plan-goal composes with Claude Code's /goal (v2.1.139, May 12 2026).
Derives a termination condition from the active plan so /goal stops the
agent when the plan-file is genuinely complete, not just when the
conversation looks done.

/plan-loop composes with /loop (v2.1.72+). Default 10-minute tick re-reads
planning files, runs check-complete, nudges a progress.md entry if the
last tick produced no change. templates/loop.md ships a planning-aware
default for ~/.claude/loop.md so bare /loop works grounded in the plan.

OpenCode session-catchup rewritten for the SQLite migration (sst/opencode
dev @ 2026-05-14). Reads ${XDG_DATA_HOME:-~/.local/share}/opencode/opencode.db
read-only via URI, scopes by session.directory, surfaces unsynced planning
edits. Verified against a real 162 MB OpenCode database (94 sessions, 56
unsynced parts correctly extracted from the lovable-at-home directory).

Codex gains a PermissionRequest adapter that surfaces a one-line plan
reminder when an active plan exists. Read-only; never blocks.

Tests: +19 covering PreCompact behavior, slash command file structure,
OpenCode SQLite catchup with a synthetic schema-matching DB, and Codex
PermissionRequest emit/silent behavior. 98 tests passing.

Deliberately not changed: paths glob (auto-invocation behavior risk),
wholesale !command swap (would freeze attestation hash and defeat v2.37
tamper gate), native Plan Mode panel integration (no plugin API
documented), language variant consolidation (separate breaking-change
track). PreCompact lives in the canonical SKILL.md + 5 language variants
+ clawhub-upload; other IDE mirrors keep their existing compaction
hooks until per-IDE PreCompact adapters land in a future release.
2026-05-14 19:26:17 +02:00

190 lines
6.4 KiB
Python

import json
import os
import subprocess
import sys
import tempfile
import textwrap
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
CODEX_ROOT = REPO_ROOT / ".codex"
HOOKS_JSON = CODEX_ROOT / "hooks.json"
HOOKS_DIR = CODEX_ROOT / "hooks"
class CodexHooksTests(unittest.TestCase):
def run_python_hook(self, script_name: str, payload: dict, cwd: Path) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[sys.executable, str(HOOKS_DIR / script_name)],
input=json.dumps(payload),
text=True,
capture_output=True,
cwd=str(cwd),
check=False,
)
def run_shell_hook(self, script_name: str, cwd: Path, env: dict | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["sh", str(HOOKS_DIR / script_name)],
text=True,
capture_output=True,
cwd=str(cwd),
env=env,
check=False,
)
def test_hooks_json_declares_all_expected_codex_events(self) -> None:
self.assertTrue(HOOKS_JSON.exists(), ".codex/hooks.json is missing")
payload = json.loads(HOOKS_JSON.read_text(encoding="utf-8"))
self.assertEqual(
{
"SessionStart",
"UserPromptSubmit",
"PreToolUse",
"PermissionRequest",
"PostToolUse",
"Stop",
},
set(payload["hooks"]),
)
def test_permission_request_adapter_emits_plan_reminder(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
root.joinpath("task_plan.md").write_text(
"# Task Plan\n### Phase 1\n- **Status:** in_progress\n",
encoding="utf-8",
)
result = self.run_python_hook(
"permission_request.py",
{"cwd": str(root), "tool_name": "Bash"},
root,
)
self.assertEqual(0, result.returncode, result.stderr)
payload = json.loads(result.stdout)
self.assertIn("systemMessage", payload)
self.assertIn("Active plan", payload["systemMessage"])
def test_permission_request_silent_without_plan(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
result = self.run_python_hook(
"permission_request.py",
{"cwd": str(root), "tool_name": "Bash"},
root,
)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("", result.stdout.strip())
def test_session_start_reuses_plan_context(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir, tempfile.TemporaryDirectory() as home:
root = Path(tmpdir)
root.joinpath("task_plan.md").write_text(
"# Task Plan\n\n## Goal\nShip Codex hooks\n",
encoding="utf-8",
)
root.joinpath("progress.md").write_text(
"# Progress\n\nFinished adapter draft.\n",
encoding="utf-8",
)
root.joinpath("findings.md").write_text(
"# Findings\n\n- reuse cursor hooks\n",
encoding="utf-8",
)
env = os.environ.copy()
env["HOME"] = home
result = self.run_shell_hook("session-start.sh", root, env=env)
self.assertEqual(0, result.returncode, result.stderr)
self.assertIn("ACTIVE PLAN", result.stdout)
self.assertIn("Ship Codex hooks", result.stdout)
self.assertIn("Finished adapter draft", result.stdout)
def test_pre_tool_use_adapter_emits_system_message(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
root.joinpath("task_plan.md").write_text(
textwrap.dedent(
"""\
# Task Plan
### Phase 1: Discovery
- **Status:** complete
"""
),
encoding="utf-8",
)
result = self.run_python_hook(
"pre_tool_use.py",
{"cwd": str(root), "tool_input": {"command": "pwd"}},
root,
)
self.assertEqual(0, result.returncode, result.stderr)
payload = json.loads(result.stdout)
self.assertIn("systemMessage", payload)
self.assertIn("# Task Plan", payload["systemMessage"])
def test_post_tool_use_adapter_emits_progress_reminder(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
root.joinpath("task_plan.md").write_text("# Task Plan\n", encoding="utf-8")
result = self.run_python_hook(
"post_tool_use.py",
{"cwd": str(root), "tool_response": "ok"},
root,
)
self.assertEqual(0, result.returncode, result.stderr)
payload = json.loads(result.stdout)
self.assertIn("progress.md", payload["systemMessage"])
def test_stop_adapter_blocks_once_then_allows_reentry(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
root.joinpath("task_plan.md").write_text(
textwrap.dedent(
"""\
### Phase 1: Discovery
- **Status:** complete
### Phase 2: Implementation
- **Status:** pending
"""
),
encoding="utf-8",
)
first = self.run_python_hook(
"stop.py",
{"cwd": str(root), "stop_hook_active": False},
root,
)
second = self.run_python_hook(
"stop.py",
{"cwd": str(root), "stop_hook_active": True},
root,
)
self.assertEqual(0, first.returncode, first.stderr)
self.assertEqual(0, second.returncode, second.stderr)
first_payload = json.loads(first.stdout)
second_payload = json.loads(second.stdout)
self.assertEqual("block", first_payload["decision"])
self.assertIn("Task incomplete", first_payload["reason"])
self.assertIn("Task incomplete", second_payload["systemMessage"])
if __name__ == "__main__":
unittest.main()