ai-psychosis/hooks/scripts/tool-tracker.mjs
Kjell Tore Guttormsen 2c9e2de00a fix(hooks): differentiate burst and edit-ratio heuristics on tool type
The burst counter incremented on any tool call <30s apart regardless of
tool type, so a bulk read of many files produced the same "Rapid-fire"
alert as a rapid-fire editing sequence. The edit-ratio check reported
"possible stuck/spiral" for any session under 10% edits past 30 minutes,
which a read-heavy analysis session satisfies structurally whether or not
the work is productive. Both mechanisms are confirmed in
docs/BRIEF-vurdering-v2.md, verification points 1a and 1b.

tool-tracker.mjs now tracks whether the current burst run consists only
of read tools and suppresses the rapid-fire alert for such runs. A
read-dominant session (>=70% reads) reports its low edit ratio as
context rather than as a stuck/spiral claim, and never as the sole
reason for a warning. Bursts involving Edit/Write/Bash and
non-read-dominant sessions behave exactly as before.

No new data is recorded: the differentiation uses tool_name, which
events.jsonl already logs. The privacy design is untouched.

Tests first (Iron Law): 5 cases in tests/tool-tracker.test.mjs, 3 of
which failed against the previous implementation, 2 of which are
regression guards that passed before and still pass.

Verified: node --test tests/*.test.mjs -> 263 pass, 5 fail. All 5
failures are the perf wall-clock assertions, which fail identically on
HEAD without this change (measured by stashing and re-running) — they
are a pre-existing property of this machine, not a regression.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011wMhJuPFUiWqKLSQjrzCXP
2026-08-13 20:59:42 +02:00

194 lines
6.5 KiB
JavaScript

// Interaction Awareness — PostToolUse hook (Layer 2, Node.js)
// Tracks tool usage, edit ratio, burst detection, session duration.
import { existsSync } from 'fs';
import {
readStdin, initConfig, requireLayer, getSessionId, getToolName,
nowEpoch, nowIso, isLateNight,
STATE_DIR, EVENTS_LOG,
THRESHOLD_SOFT_DURATION, THRESHOLD_HARD_DURATION,
THRESHOLD_SOFT_SESSIONS, THRESHOLD_HARD_SESSIONS,
THRESHOLD_SOFT_BURST, THRESHOLD_HARD_BURST, THRESHOLD_BURST_INTERVAL,
THRESHOLD_LOW_EDIT_RATIO, THRESHOLD_LOW_EDIT_MIN_DURATION,
THRESHOLD_READ_DOMINANT_RATIO, isReadTool,
COOLDOWN_SOFT, COOLDOWN_HARD,
readState, sessionStateFile, writeState, appendJsonl, sessionsToday,
outputContinue, outputWithContext
} from './lib.mjs';
readStdin();
initConfig();
requireLayer(2);
const sid = getSessionId();
const sf = sessionStateFile();
if (!sid || !existsSync(sf)) {
process.stdout.write(JSON.stringify({ continue: true }) + '\n');
process.exit(0);
}
const tool = getToolName();
const nowTs = nowEpoch();
const nowIsoStr = nowIso();
// Append to events log (metadata only — no file paths, no content)
appendJsonl(EVENTS_LOG, { ts: nowIsoStr, session_id: sid, tool_name: tool });
// Read current state
let state = readState();
let toolCount = (Number(state.tool_count) || 0) + 1;
let editCount = Number(state.edit_count) || 0;
let readCount = Number(state.read_count) || 0;
const lastEvent = Number(state.last_event_epoch) || 0;
let burstCount = Number(state.burst_count) || 0;
// Absent in pre-calibration state files — an unseen run starts read-only.
let burstReadOnly = state.burst_read_only !== false;
const startEpoch = Number(state.start_epoch) || 0;
const lastWarning = Number(state.last_warning_epoch) || 0;
const toolIsRead = isReadTool(tool);
if (tool === 'Edit') editCount++;
if (toolIsRead) readCount++;
// Burst detection: rapid-fire if <30s since last event
if (lastEvent > 0) {
const interval = nowTs - lastEvent;
if (interval < THRESHOLD_BURST_INTERVAL) {
burstCount++;
burstReadOnly = burstReadOnly && toolIsRead;
} else {
burstCount = 0;
burstReadOnly = toolIsRead;
}
}
// Write updated state
state.tool_count = toolCount;
state.edit_count = editCount;
state.read_count = readCount;
state.last_event_epoch = nowTs;
state.burst_count = burstCount;
state.burst_read_only = burstReadOnly;
writeState(state);
// Check thresholds every 25 calls or when burst threshold hit
let shouldCheck = false;
if (toolCount % 25 === 0) shouldCheck = true;
if (burstCount === THRESHOLD_SOFT_BURST || burstCount === THRESHOLD_HARD_BURST) shouldCheck = true;
if (!shouldCheck) {
outputContinue();
process.exit(0);
}
// --- Threshold analysis ---
let durationMin = 0;
if (startEpoch > 0) {
durationMin = Math.floor((nowTs - startEpoch) / 60);
}
let editRatio = 0;
if (toolCount > 0) {
editRatio = Math.floor(editCount * 100 / toolCount);
}
const dayCount = sessionsToday();
// Determine warning level
let level = ''; // 'soft' or 'hard'
const messages = [];
// Duration thresholds
if (durationMin >= THRESHOLD_HARD_DURATION) {
level = 'hard';
const hours = Math.floor(durationMin / 60);
const mins = durationMin % 60;
messages.push(`Session duration: ${hours}h${mins}m.`);
} else if (durationMin >= THRESHOLD_SOFT_DURATION) {
level = 'soft';
messages.push(`Session: ${durationMin} min.`);
}
// Session count
if (dayCount >= THRESHOLD_HARD_SESSIONS) {
level = 'hard';
messages.push(`${dayCount} sessions today.`);
} else if (dayCount > THRESHOLD_SOFT_SESSIONS) {
if (!level) level = 'soft';
messages.push(`${dayCount} sessions today.`);
}
// Burst — a run of read-only tools is bulk reading, not rapid-fire work
if (!burstReadOnly) {
if (burstCount >= THRESHOLD_HARD_BURST) {
level = 'hard';
messages.push(`Rapid-fire: ${burstCount} consecutive fast interactions.`);
} else if (burstCount >= THRESHOLD_SOFT_BURST) {
if (!level) level = 'soft';
messages.push(`Rapid-fire: ${burstCount} consecutive fast interactions.`);
}
}
// Low edit ratio (only after minimum duration). A read-dominant session has
// a structurally low edit ratio whether or not the work is productive, so it
// is reported as context — never as a stuck/spiral claim, and never as the
// sole reason for a warning.
const readRatio = toolCount > 0 ? Math.floor(readCount * 100 / toolCount) : 0;
const readDominant = readRatio >= THRESHOLD_READ_DOMINANT_RATIO;
if (durationMin >= THRESHOLD_LOW_EDIT_MIN_DURATION && editRatio < THRESHOLD_LOW_EDIT_RATIO) {
if (readDominant) {
if (level) {
messages.push(`Low edit ratio (${editRatio}%) over ${durationMin} min, but ${readRatio}% of tool calls are reads — read-intensive work (research/audit) rather than a stall.`);
}
} else {
if (!level) level = 'soft';
messages.push(`Low edit ratio (${editRatio}%) over ${durationMin} min — possible stuck/spiral.`);
}
}
// Late night check
const late = isLateNight() ? ' Late-night session.' : '';
// No warnings — just periodic reminder at modulo-25
if (!level) {
if (toolCount % 25 === 0) {
outputWithContext('REMINDER (Interaction Awareness): Check your next response against these rules — no unearned affirmations, no reformulating the user\'s words in stronger terms, no skipping counterarguments to stay agreeable. If you detect a reinforcement loop, scope escalation, or narrative crystallization: name it now.', 'PostToolUse');
} else {
outputContinue();
}
process.exit(0);
}
// Determine cooldown
const cooldown = level === 'hard' ? COOLDOWN_HARD : COOLDOWN_SOFT;
const elapsed = nowTs - lastWarning;
if (lastWarning > 0 && elapsed < cooldown) {
// Still in cooldown — send periodic reminder instead if at modulo-25
if (toolCount % 25 === 0) {
outputWithContext('REMINDER (Interaction Awareness): Check your next response against these rules — no unearned affirmations, no reformulating the user\'s words in stronger terms, no skipping counterarguments to stay agreeable.', 'PostToolUse');
} else {
outputContinue();
}
process.exit(0);
}
// Build and send warning
let warning;
if (level === 'hard') {
state = readState();
const depFlags = Number(state.dep_flags) || 0;
warning = `INTERACTION AWARENESS: ${messages.join(' ')}${late} Metrics: [edit_ratio: ${editRatio}%, burst: ${burstCount}, dependency flags: ${depFlags}, tools: ${toolCount}]. Your instructions require you to suggest stopping.`;
} else {
warning = `${messages.join(' ')}${late} Consider a break.`;
}
// Record warning time
state = readState();
state.last_warning_epoch = nowTs;
writeState(state);
outputWithContext(warning, 'PostToolUse');