tractatus/.claude/hooks/check-token-checkpoint.js
TheFlow 436ca56cb0 feat(governance): implement comprehensive enforcement architecture
Completes enforcement implementation from ENFORCEMENT_AUDIT.md analysis:

 Implemented (6 enforcement mechanisms):
1. Token checkpoint monitoring (inst_075)
   - .claude/hooks/check-token-checkpoint.js
   - PostToolUse hook integration

2. Trigger word detection (inst_078, inst_082)
   - .claude/hooks/trigger-word-checker.js (already completed)
   - "ff" and "ffs" triggers architecturally enforced

3. Framework activity verification (inst_064)
   - Enhanced scripts/session-init.js with fade detection
   - Alerts when components stale >20 messages

4. Test requirement enforcement (inst_068)
   - Enhanced .git/hooks/pre-commit
   - Runs tests if test files exist for modified code
   - Blocks commits on test failures

5. Background process tracking (inst_023)
   - scripts/track-background-process.js
   - Integrated into session-init.js and session-closedown.js
   - Tracks persistent vs temporary processes

6. Security logging verification (inst_046)
   - scripts/verify-security-logging.js
   - Can be integrated into deployment workflow

7. Meta-enforcement monitoring system
   - scripts/audit-enforcement.js
   - Scans HIGH persistence instructions for imperatives
   - Reports enforcement gaps (currently 28/39 gaps)

🔒 Protection Added:
- inst_027: Hard block on instruction-history.json edits
- Conventional commit format enforcement (inst_066)
- CSP + test validation in pre-commit hook

📊 Current Enforcement Status:
- Baseline: 11/39 imperative instructions enforced (28%)
- Framework fade detection operational
- Token checkpoints architecturally monitored

🎯 Philosophy:
"If it's MANDATORY, it must be ENFORCED architecturally, not documented."

This addresses the root cause of voluntary compliance failures identified
when Claude missed "ffs" trigger and token checkpoints despite active
HIGH persistence instructions.

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-25 13:15:06 +13:00

61 lines
2.2 KiB
JavaScript
Executable file
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* Token Checkpoint Monitor Hook
*
* Runs after tool execution to check if token usage has exceeded checkpoints.
* Enforces inst_075: Token checkpoint monitoring is MANDATORY, not optional.
*
* This hook reads system context to extract current token count and compares
* against checkpoints in .claude/token-checkpoints.json.
*/
const fs = require('fs');
const path = require('path');
const input = JSON.parse(process.argv[2] || '{}');
// Extract token usage from system warnings in context
// Claude Code provides token counts in <system_warning> tags
const contextText = JSON.stringify(input);
const tokenMatch = contextText.match(/Token usage: (\d+)\/(\d+)/);
if (!tokenMatch) {
// No token info available - skip silently
process.exit(0);
}
const currentTokens = parseInt(tokenMatch[1]);
const budgetTokens = parseInt(tokenMatch[2]);
// Read checkpoint configuration
const checkpointPath = path.join(__dirname, '../token-checkpoints.json');
let checkpoints;
try {
checkpoints = JSON.parse(fs.readFileSync(checkpointPath, 'utf8'));
} catch (err) {
console.error('\x1b[31m❌ Failed to read token-checkpoints.json\x1b[0m');
process.exit(0);
}
const nextCheckpoint = checkpoints.next_checkpoint;
// Check if we've passed a checkpoint
if (currentTokens > nextCheckpoint) {
console.log('\x1b[33m⚠ TOKEN CHECKPOINT EXCEEDED\x1b[0m');
console.log(`\x1b[36mCurrent: ${currentTokens.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens (${((currentTokens/budgetTokens)*100).toFixed(1)}%)\x1b[0m`);
console.log(`\x1b[36mCheckpoint: ${nextCheckpoint.toLocaleString()} tokens\x1b[0m`);
console.log('\x1b[31m📊 MANDATORY: Run checkpoint analysis NOW\x1b[0m');
console.log(`\x1b[36mnode scripts/check-token-checkpoint.js --tokens ${currentTokens}/${budgetTokens}\x1b[0m`);
console.log('\x1b[36mSee inst_075 for checkpoint requirements\x1b[0m');
process.exit(0);
}
// Approaching checkpoint - warn at 90%
const approachThreshold = nextCheckpoint * 0.9;
if (currentTokens > approachThreshold) {
const remaining = nextCheckpoint - currentTokens;
console.log(`\x1b[33m⚠ Approaching ${(nextCheckpoint/budgetTokens*100)}% checkpoint: ${remaining.toLocaleString()} tokens remaining\x1b[0m`);
}
process.exit(0);