Stop hook can add ~15s latency per response: DocCrossRefIntegrity runs unconditional LLM inference
Summary
DocCrossRefIntegrity.ts makes an unconditional Sonnet API call on every Stop event where a system file was touched. This adds ~15s of latency after every response and consumes subscription quota, typically returning zero useful edits.
The Problem
The handler has two layers:
- Layer 1 (deterministic): Grep-based checks for broken refs, counts, timestamps — runs in <100ms
- Layer 2 (inference): Spawns
claude --print --model sonnetwith ~32KB of context to detect semantic drift — takes ~15s
Layer 2 runs unconditionally regardless of whether Layer 1 found any issues. It fires whenever any system file (including settings.json) was edited in the session.
Critically, the Stop hook fires after every response, and the transcript is cumulative. So if the first exchange in a session edits a system file, every subsequent stop re-triggers the inference call. A 20-exchange session can burn ~5 minutes of API time on repeated inference calls that typically time out or return nothing.
From a real debug log:
[DocAutoUpdate] [INFERENCE] Context size: 32188 chars
[DocAutoUpdate] [INFERENCE] Completed in 15017ms (success: false)
[DocAutoUpdate] [INFERENCE] Failed: Timeout after 15000ms
[DocAutoUpdate] Wall time: 15042ms
Investigation Needed
- What percentage of inference calls actually produce applied edits vs timing out or returning empty?
- Is the 15s timeout adequate for Sonnet with 32KB context, or does it need tuning?
- Should
settings.jsonedits trigger the handler at all, given they're config changes not doc-relevant code changes?
Suggested Fixes (pick one)
-
Gate Layer 2 behind Layer 1 results — only run inference if
allDrift.length > 0. Deterministic checks already found broken refs; inference then diagnoses how to fix them. Zero drift = no inference call. -
Deduplicate within session — hash the modified file set and skip re-analysis if the same set was already checked in this session. Eliminates the N× multiplier.
-
Remove Layer 2 entirely — the deterministic checks catch concrete issues (broken refs, wrong counts). Semantic drift detection via LLM is expensive, slow, and in practice rarely produces actionable edits. The review queue already captures drift items for manual attention.
Environment
- PAI v3.0
- macOS, Claude Code with OAuth subscription
StopOrchestrator.hook.tsclaims <100ms typical execution
Fixed in v4.0.2 — added allDrift.length > 0 guard before inference call. When no drift is detected, inference is now skipped entirely, saving ~15s per response. Thanks for the report!