Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .claude/hooks/generate_session_manifest_from_hook.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ function ensureArtifactsDir() {
* Key format: {hookEventName}:{toolName}:{phase}
* Encoded as URL-safe base64 for use in filename.
*/
function buildStableKey(hookEventName, toolName, ledgerPhase) {
const rawKey = `${hookEventName}:${toolName || ''}:${ledgerPhase}`
function buildStableKey(hookEventName, sessionId, toolName, ledgerPhase) {
const rawKey = `${hookEventName}:${sessionId || 'nosession'}:${toolName || ''}:${ledgerPhase}`
return Buffer.from(rawKey).toString('base64url').slice(0, 32)
}

Expand Down Expand Up @@ -169,7 +169,7 @@ async function main() {
const phaseInfo = EVENT_PHASE_MAP[hookEventName] ?? EVENT_PHASE_MAP['Stop']

// Build stable duplicate key (not timestamp-dependent)
const stableKeySegment = buildStableKey(hookEventName, toolName, phaseInfo.ledgerPhase)
const stableKeySegment = buildStableKey(hookEventName, sessionId, toolName, phaseInfo.ledgerPhase)

// Check for duplicate before doing any work
if (hasDuplicateArtifact(stableKeySegment)) {
Expand Down
94 changes: 94 additions & 0 deletions .claude/hooks/session_manifest_coordinator.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
# session_manifest_coordinator.sh
#
# Coordinator hook for Stop / SubagentStop events.
# Runs guard → producer in strict sequence; on guard failure, suppresses
# standard agent_session_manifest generation and exits 0 (fail-open).
#
# This is the SINGLE hook entry-point for Stop / SubagentStop.
# guard (session_recording_policy_guard.sh) and producer
# (generate_session_manifest_from_hook.mjs) MUST NOT be wired directly
# in settings.json alongside this coordinator.
#
# Design:
# 1. Read stdin once and save to a temp file.
# 2. Check stop_hook_active → short-circuit exit 0 (producer not called).
# 3. Run guard with the saved stdin.
# - guard exit 0 → proceed to producer
# - guard non-0 → skip producer, log reason to stderr, exit 0
# 4. Run producer with the saved stdin.
# - producer failure → log to stderr, exit 0 (best-effort telemetry)
#
# stdin : JSON hook context from Claude Code hook system
# stdout : empty (silent)
# stderr : diagnostic messages only
# exit : always 0 (coordinator is best-effort telemetry; never blocks AI agent)
#
set -euo pipefail

# ---------------------------------------------------------------------------
# Resolve script directory (coordinator script location = hooks dir)
# ---------------------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

GUARD_SCRIPT="${SESSION_MANIFEST_GUARD:-${SCRIPT_DIR}/session_recording_policy_guard.sh}"
PRODUCER_SCRIPT="${SESSION_MANIFEST_PRODUCER:-${SCRIPT_DIR}/generate_session_manifest_from_hook.mjs}"
NODE_BIN="${SESSION_MANIFEST_NODE:-node}"

# ---------------------------------------------------------------------------
# Temporary workspace — cleaned up on exit
# ---------------------------------------------------------------------------
_TMPDIR="$(mktemp -d)"
trap 'rm -rf "$_TMPDIR"' EXIT

_STDIN_FILE="${_TMPDIR}/stdin.json"

# AC7: save stdin exactly once; both guard and producer receive the same payload
cat > "$_STDIN_FILE"

# ---------------------------------------------------------------------------
# AC6: stop_hook_active short-circuit
# If stop_hook_active is true, skip producer and exit 0 immediately.
# ---------------------------------------------------------------------------
_STOP_HOOK_ACTIVE=$(python3 -c "
import json, sys
try:
data = json.load(open('$_STDIN_FILE'))
print('true' if data.get('stop_hook_active') is True else 'false')
except Exception:
print('false')
" 2>/dev/null || echo "false")

if [[ "$_STOP_HOOK_ACTIVE" == "true" ]]; then
echo "[session_manifest_coordinator] info: stop_hook_active=true, short-circuit exit 0" >&2
exit 0
fi

# ---------------------------------------------------------------------------
# AC2 / AC3 / AC4: run guard first
# ---------------------------------------------------------------------------
_GUARD_EXIT=0
# Feed the saved stdin to the guard script
"${GUARD_SCRIPT}" < "$_STDIN_FILE" >"$_TMPDIR/guard.stdout" 2>"$_TMPDIR/guard.stderr" || _GUARD_EXIT=$?
cat "$_TMPDIR/guard.stderr" >&2 2>/dev/null || true

if [[ "$_GUARD_EXIT" -ne 0 ]]; then
# AC4: guard failure → skip producer, exit 0 (do not block Stop/SubagentStop)
echo "[session_manifest_coordinator] info: guard exited $_GUARD_EXIT — skipping producer (best-effort, not blocking)" >&2
exit 0
fi

# ---------------------------------------------------------------------------
# AC3 / AC5: guard passed → run producer
# ---------------------------------------------------------------------------
_PRODUCER_EXIT=0
"$NODE_BIN" "${PRODUCER_SCRIPT}" < "$_STDIN_FILE" >"$_TMPDIR/producer.stdout" 2>"$_TMPDIR/producer.stderr" || _PRODUCER_EXIT=$?
cat "$_TMPDIR/producer.stderr" >&2 2>/dev/null || true

if [[ "$_PRODUCER_EXIT" -ne 0 ]]; then
# AC5: producer failure → exit 0 (do not block Stop/SubagentStop)
echo "[session_manifest_coordinator] info: producer exited $_PRODUCER_EXIT — best-effort, not blocking" >&2
exit 0
fi

exit 0
62 changes: 40 additions & 22 deletions .claude/hooks/tests/test_generate_session_manifest_from_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,13 @@ def _get_hook_commands(data: dict, event: str) -> list[str]:


def test_hook_config_policy_guard_before_producer_in_stop():
"""GIVEN Stop hooks are configured (AC5),
WHEN checking hook ordering,
THEN session_recording_policy_guard.sh must appear before generate_session_manifest_from_hook."""
"""GIVEN Stop hooks are configured,
WHEN checking hook ordering (single coordinator wiring since #651),
THEN session_manifest_coordinator.sh must be the sole hook entry for Stop,
and guard/producer must NOT appear as direct siblings (AC1/AC8).
Guard → producer ordering is enforced internally by the coordinator script."""
data = json.loads(SETTINGS_JSON_PATH.read_text(encoding="utf-8"))

# In exec-form, command is "node" and args[0] is the script path.
# Search both command and args for identifying strings.
hooks_section = data.get("hooks", {})
event_entries = hooks_section.get("Stop", [])
hook_entries = []
Expand All @@ -203,22 +203,32 @@ def test_hook_config_policy_guard_before_producer_in_stop():
combined = cmd + " " + " ".join(args)
hook_entries.append(combined)

# AC1: coordinator must be present
coordinator_indices = [i for i, s in enumerate(hook_entries) if "session_manifest_coordinator" in s]
assert coordinator_indices, (
"session_manifest_coordinator.sh not found in Stop hooks "
"(single coordinator only since #651)"
)

# AC8: guard and producer must NOT be wired as direct siblings
guard_indices = [i for i, s in enumerate(hook_entries) if "session_recording_policy_guard" in s]
producer_indices = [i for i, s in enumerate(hook_entries) if "generate_session_manifest_from_hook" in s]

assert guard_indices, "session_recording_policy_guard.sh not found in Stop hooks"
assert producer_indices, "generate_session_manifest_from_hook not found in Stop hooks"

assert min(guard_indices) < min(producer_indices), (
f"session_recording_policy_guard.sh (index {min(guard_indices)}) must appear "
f"before generate_session_manifest_from_hook (index {min(producer_indices)}) in Stop hooks"
assert not guard_indices, (
"session_recording_policy_guard.sh must NOT be wired directly in Stop hooks "
"(single coordinator only since #651)"
)
assert not producer_indices, (
"generate_session_manifest_from_hook must NOT be wired directly in Stop hooks "
"(single coordinator only since #651)"
)


def test_hook_config_policy_guard_before_producer_in_subagent_stop():
"""GIVEN SubagentStop hooks are configured (AC5),
WHEN checking hook ordering,
THEN session_recording_policy_guard.sh must appear before generate_session_manifest_from_hook."""
"""GIVEN SubagentStop hooks are configured,
WHEN checking hook ordering (single coordinator wiring since #651),
THEN session_manifest_coordinator.sh must be the sole hook entry for SubagentStop,
and guard/producer must NOT appear as direct siblings (AC1/AC8).
Guard → producer ordering is enforced internally by the coordinator script."""
data = json.loads(SETTINGS_JSON_PATH.read_text(encoding="utf-8"))

hooks_section = data.get("hooks", {})
Expand All @@ -231,15 +241,23 @@ def test_hook_config_policy_guard_before_producer_in_subagent_stop():
combined = cmd + " " + " ".join(args)
hook_entries.append(combined)

# AC1: coordinator must be present
coordinator_indices = [i for i, s in enumerate(hook_entries) if "session_manifest_coordinator" in s]
assert coordinator_indices, (
"session_manifest_coordinator.sh not found in SubagentStop hooks "
"(single coordinator only since #651)"
)

# AC8: guard and producer must NOT be wired as direct siblings
guard_indices = [i for i, s in enumerate(hook_entries) if "session_recording_policy_guard" in s]
producer_indices = [i for i, s in enumerate(hook_entries) if "generate_session_manifest_from_hook" in s]

assert guard_indices, "session_recording_policy_guard.sh not found in SubagentStop hooks"
assert producer_indices, "generate_session_manifest_from_hook not found in SubagentStop hooks"

assert min(guard_indices) < min(producer_indices), (
f"session_recording_policy_guard.sh (index {min(guard_indices)}) must appear "
f"before generate_session_manifest_from_hook (index {min(producer_indices)}) in SubagentStop hooks"
assert not guard_indices, (
"session_recording_policy_guard.sh must NOT be wired directly in SubagentStop hooks "
"(single coordinator only since #651)"
)
assert not producer_indices, (
"generate_session_manifest_from_hook must NOT be wired directly in SubagentStop hooks "
"(single coordinator only since #651)"
)


Expand Down
Loading
Loading