r/ClaudeCode • u/Most_Remote_4613 • 3h ago
Tips & Workflows Small PreCompact hook that stops an accidental bare /compact
I generally use Vscode Claude Code extension and "compact misclick" annoys me so i asked Claude Code to find a solution and it has handled it. Until so far, there are no side-effects.
I'am sharing its report so you can ask your ai and use it if you want:
A PreCompact hook. It refuses a manual compact that has no instructions. /compact <your instructions> still works, and auto-compact isn't touched.
~/.claude/settings.json:
{
"hooks": {
"PreCompact": [
{
"matcher": "manual",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["/path/to/.claude/hooks/precompact-require-instructions.mjs"]
}
]
}
]
}
}precompact-require-instructions.mjs:
#!/usr/bin/env node
// Blocks a manual compact with no instructions. Exit 2 = block.
// Any error lets the compact through.
import process from 'node:process';
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
return Buffer.concat(chunks).toString('utf8');
}
try {
if (process.env.CLAUDE_ALLOW_BARE_COMPACT === '1') process.exit(0);
const input = JSON.parse(await readStdin());
if (input.hook_event_name !== 'PreCompact' || input.trigger !== 'manual') process.exit(0);
const instructions = typeof input.custom_instructions === 'string'
? input.custom_instructions.trim()
: '';
if (instructions.length > 0) process.exit(0);
process.stderr.write(
'Bare compact blocked. Save your notes first, then run /compact <instructions>.\n'
);
process.exit(2);
} catch {
process.exit(0);
}Some details:
- It prints nothing when it lets the compact through. On PreCompact, stdout gets added to the compact instructions, so the script keeps it empty.
- If you really want a bare compact, set
CLAUDE_ALLOW_BARE_COMPACT=1. - Tested on Claude Code 2.1.337. A bare
/compactgot "Compaction blocked by PreCompact hook", and/compact <text>went through. - I haven't tested what happens when you're right at the hard context limit.
My routine now: write a short handoff file first with a handoff skill which i have prepared, then /compact with a line that points to it as an optional custom summarization instructions.

