diff --git a/hooks/README.md b/hooks/README.md index f367ae48b..13fbbbae1 100644 --- a/hooks/README.md +++ b/hooks/README.md @@ -13,7 +13,7 @@ User request → Claude picks a tool → PreToolUse hook runs → Tool executes - **Stop** hooks run after each Claude response. - **SessionStart/SessionEnd** hooks run at session lifecycle boundaries. - **PreCompact** hooks run before context compaction, useful for saving state. -- **UserPromptSubmit** hooks run when the user submits a prompt, before Claude sees it. Their JSON output can inject `additionalContext` for the turn (used by `user-prompt:context-gate` to enforce an end-of-session checkpoint protocol at high context usage). Above the gate threshold the advisory hooks defer: `suggest-compact` and `ecc-context-monitor` suppress their `/compact` suggestions and context warnings (via `scripts/lib/context-gate-state.js`) so the gate owns end-of-session messaging without contradiction. +- **UserPromptSubmit** hooks run when the user submits a prompt, before Claude sees it. Their JSON output can inject `additionalContext` for the turn (used by `user-prompt:context-gate` to enforce an end-of-session checkpoint protocol at high context usage). At or above the gate threshold the advisory hooks defer: `suggest-compact` and `ecc-context-monitor` suppress their `/compact` suggestions and context warnings (via `scripts/lib/context-gate-state.js`) so the gate owns end-of-session messaging without contradiction; when the gate cannot evaluate usage (missing/unreadable transcript) they fall back to their own warnings. ## Hooks in This Plugin diff --git a/scripts/hooks/context-gate.js b/scripts/hooks/context-gate.js index 98454fa4a..acaa3377c 100644 --- a/scripts/hooks/context-gate.js +++ b/scripts/hooks/context-gate.js @@ -127,7 +127,7 @@ function run(rawInput, options = {}) { const latest = readLatestContextTokens(input.transcript_path); if (!latest) return ''; - const { windowTokens, inferred } = resolveContextWindow(latest.tokens, latest.model); + const { windowTokens, inferred } = resolveContextWindow(latest.tokens, latest.model, env); const pct = Math.floor((latest.tokens / windowTokens) * 100); if (pct < gatePct) return ''; diff --git a/scripts/hooks/ecc-context-monitor.js b/scripts/hooks/ecc-context-monitor.js index 9652c833f..4b517a1fa 100644 --- a/scripts/hooks/ecc-context-monitor.js +++ b/scripts/hooks/ecc-context-monitor.js @@ -14,7 +14,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); const { sanitizeSessionId, readBridge, renameWithRetry } = require('../lib/session-bridge'); -const { resolveGatePct, isGateEnabled } = require('../lib/context-gate-state'); +const { gateOwnsTranscript } = require('../lib/context-gate-state'); const CONTEXT_WARNING_PCT = 35; const CONTEXT_CRITICAL_PCT = 25; @@ -122,18 +122,18 @@ function detectLoop(recentTools) { function evaluateConditions(bridge, options = {}) { const warnings = []; const remaining = bridge.context_remaining_pct; - const env = options.env || process.env; - // Defer to the context-gate inside its band: the critical message below - // ("ask the user ... do NOT autonomously save state or write handoff - // files") directly contradicts the gate's checkpoint order on the same - // turns. `remaining` here is Claude Code's native statusline percentage — - // a different denominator than the gate's transcript-token computation — - // so this comparison is an intentional approximation. - const gateOwnsBand = isGateEnabled(env) && remaining !== null && remaining !== undefined && remaining <= 100 - resolveGatePct(env); + // Defer to the context-gate ONLY when the caller confirmed it is active + // (options.gateActive, resolved from the transcript by gateOwnsTranscript): + // the critical message below ("ask the user ... do NOT autonomously save + // state or write handoff files") directly contradicts the gate's checkpoint + // order on the same turns. A gate that cannot evaluate usage (missing or + // unreadable transcript) reports inactive, so this warning stays as the + // fallback and a low-context session is never left with no guidance. + const gateActive = options.gateActive === true; - // Context warnings (skip if no context data, or if the gate owns the band) - if (remaining !== null && remaining !== undefined && !gateOwnsBand) { + // Context warnings (skip if no context data, or if the gate is active) + if (remaining !== null && remaining !== undefined && !gateActive) { if (remaining <= CONTEXT_CRITICAL_PCT) { warnings.push({ severity: 3, @@ -239,7 +239,17 @@ function run(rawInput) { // If bridge is stale, null out context data (still check cost/scope/loop) const evalBridge = isStale ? { ...bridge, context_remaining_pct: null } : bridge; - const warnings = evaluateConditions(evalBridge, { costWarnings: costWarningsEnabled() }); + // Gate deference needs the transcript (gateOwnsTranscript reads real + // usage, never the bridge approximation). Only pay that read when a + // context warning could actually fire. + const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : ''; + const remainingPct = evalBridge.context_remaining_pct; + const contextWarningPossible = remainingPct !== null && remainingPct !== undefined && remainingPct <= CONTEXT_WARNING_PCT; + + const warnings = evaluateConditions(evalBridge, { + costWarnings: costWarningsEnabled(), + gateActive: contextWarningPossible && gateOwnsTranscript(transcriptPath) + }); if (warnings.length === 0) { // Clear dedupe state when the condition resolves, so the SAME warning text // recurring later (context dips, recovers, dips again; a loop that stops diff --git a/scripts/hooks/suggest-compact.js b/scripts/hooks/suggest-compact.js index 975001346..8f4aa2201 100644 --- a/scripts/hooks/suggest-compact.js +++ b/scripts/hooks/suggest-compact.js @@ -40,7 +40,7 @@ const { computeContextBucket, formatWindowLabel } = require('../lib/transcript-context'); -const { isGateActive } = require('../lib/context-gate-state'); +const { isGateActive, gateOwnsTranscript } = require('../lib/context-gate-state'); const COUNTER_FILE_PREFIX = 'claude-tool-count-'; const CONTEXT_BUCKET_FILE_PREFIX = 'claude-context-bucket-'; @@ -159,23 +159,6 @@ function readLastContextBucket(bucketFile) { } } -/** - * True when the context-gate owns the current transcript band (gate enabled - * and occupancy at/above its threshold) — the tool-count /compact messages - * must stay silent there too. Reads the transcript, so callers only invoke - * it when a message would otherwise fire. Never throws. - */ -function gateOwnsTranscript(transcriptPath, env) { - try { - const usage = readLatestContextTokens(transcriptPath); - if (!usage) return false; - const { windowTokens } = resolveContextWindow(usage.tokens, usage.model); - return isGateActive({ tokens: usage.tokens, windowTokens, env }); - } catch { - return false; - } -} - /** * Build the context-size suggestion when the transcript shows the session has * crossed into a new context bucket. Returns null when the signal is silent @@ -190,9 +173,9 @@ function buildContextSuggestion(transcriptPath, bucketFile, env) { const usage = readLatestContextTokens(transcriptPath); if (!usage) return null; - const { windowTokens, inferred } = resolveContextWindow(usage.tokens, usage.model); + const { windowTokens, inferred } = resolveContextWindow(usage.tokens, usage.model, env); - // Defer to the context-gate above its threshold: the gate is ordering a + // Defer to the context-gate at/above its threshold: the gate is ordering a // checkpoint-and-restart there, and a /compact suggestion in the same // band is a contradictory instruction (compaction is the lossy path the // gate exists to preempt). diff --git a/scripts/lib/context-gate-state.js b/scripts/lib/context-gate-state.js index 9394bd7e5..c4e9d5c3a 100644 --- a/scripts/lib/context-gate-state.js +++ b/scripts/lib/context-gate-state.js @@ -12,6 +12,7 @@ 'use strict'; const { isHookEnabled } = require('./hook-flags'); +const { readLatestContextTokens, resolveContextWindow } = require('./transcript-context'); const DEFAULT_GATE_PCT = 90; const DEFAULT_EMERGENCY_PCT = 96; @@ -94,8 +95,31 @@ function isGateActive({ tokens, windowTokens, env = process.env }) { return pct >= resolveGatePct(env); } +/** + * True when the gate is CONFIRMED active for the given session transcript: + * gate enabled, transcript readable, usage resolved, and occupancy at/above + * the threshold. Returns false whenever the gate cannot evaluate usage + * (missing/unreadable transcript, no usage record) — callers use this to + * decide whether to defer to the gate, and a gate that cannot fire must + * never silence its fallbacks. Never throws. + * @param {string} transcriptPath + * @param {object} [env] + * @returns {boolean} + */ +function gateOwnsTranscript(transcriptPath, env = process.env) { + try { + const usage = readLatestContextTokens(transcriptPath); + if (!usage) return false; + const { windowTokens } = resolveContextWindow(usage.tokens, usage.model, env); + return isGateActive({ tokens: usage.tokens, windowTokens, env }); + } catch { + return false; + } +} + module.exports = { resolvePct, + gateOwnsTranscript, resolveGatePct, resolveEmergencyPct, isGateEnabled, diff --git a/scripts/lib/transcript-context.js b/scripts/lib/transcript-context.js index 853a35b2a..ac1b9b41d 100644 --- a/scripts/lib/transcript-context.js +++ b/scripts/lib/transcript-context.js @@ -168,14 +168,20 @@ function readLatestContextTokens(transcriptPath, options = {}) { * unmarked intermediate size such as 400k. Callers must not present inferred * windows as fact. * + * @param {number} tokens + * @param {string} [model] + * @param {object} [env] - Environment to read overrides from; defaults to + * process.env. Callers supporting injected environments (hook run() + * options.env) must pass theirs through so window overrides are honored + * consistently with the threshold controls. * @returns {{ windowTokens: number, inferred: boolean }} */ -function resolveContextWindow(tokens, model) { +function resolveContextWindow(tokens, model, env) { // Explicit window override wins: 400k models (e.g. Opus 4.x) match neither the // 200k default nor the 1M marker and would otherwise report ~double usage (#2290). // Honor ECC's own knob and Claude Code's native CLAUDE_CODE_AUTO_COMPACT_WINDOW. - const env = (typeof process !== 'undefined' && process.env) || {}; - const envWindow = Number.parseInt(env.ECC_CONTEXT_WINDOW_TOKENS || env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10); + const environment = env || (typeof process !== 'undefined' && process.env) || {}; + const envWindow = Number.parseInt(environment.ECC_CONTEXT_WINDOW_TOKENS || environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10); if (Number.isInteger(envWindow) && envWindow > 0) { return { windowTokens: envWindow, inferred: false }; } diff --git a/tests/hooks/context-gate.test.js b/tests/hooks/context-gate.test.js index c157cd6f4..40e593808 100644 --- a/tests/hooks/context-gate.test.js +++ b/tests/hooks/context-gate.test.js @@ -175,17 +175,32 @@ function runTests() { passed++; else failed++; + if ( + test('injected env window override reaches resolveContextWindow', () => { + // 185k on an unknown model would infer a 200k window (92%, gate + // fires); an injected 1M override must make it 18% and stay silent. + const t = writeTranscript(185000, 'claude-unknown-experimental'); + cleanup.push(t); + assert.strictEqual(run(inputFor(t), { env: { ECC_CONTEXT_WINDOW_TOKENS: '1000000' } }), ''); + }) + ) + passed++; + else failed++; + if ( test('window override is honored (200k forced onto a fable transcript)', () => { const t = writeTranscript(185000); cleanup.push(t); - // 185k of 1M would be 18%; forced 200k window makes it 92%. The - // override is read from process.env by transcript-context.js. + // 185k of 1M would be 18%; forced 200k window makes it 92%. + // Injected form: options.env governs window resolution too. + const out = JSON.parse(run(inputFor(t), { env: { ECC_CONTEXT_WINDOW_TOKENS: '200000' } })); + assert.ok(out.systemMessage.includes('92%')); + // Registered-path form: metadata second arg falls back to process.env. const original = process.env.ECC_CONTEXT_WINDOW_TOKENS; try { process.env.ECC_CONTEXT_WINDOW_TOKENS = '200000'; - const out = JSON.parse(run(inputFor(t), { env })); - assert.ok(out.systemMessage.includes('92%')); + const viaProcess = JSON.parse(run(inputFor(t), { hookId: 'user-prompt:context-gate' })); + assert.ok(viaProcess.systemMessage.includes('92%')); } finally { if (original === undefined) delete process.env.ECC_CONTEXT_WINDOW_TOKENS; else process.env.ECC_CONTEXT_WINDOW_TOKENS = original; diff --git a/tests/hooks/ecc-context-monitor.test.js b/tests/hooks/ecc-context-monitor.test.js index a0c3c3c73..d8fbb811f 100644 --- a/tests/hooks/ecc-context-monitor.test.js +++ b/tests/hooks/ecc-context-monitor.test.js @@ -84,32 +84,35 @@ function runTests() { console.log('\nevaluateConditions (context-gate deference):'); if ( - test('suppresses context warnings inside the context-gate band', () => { - // remaining 8% = 92% used, past the 90% gate threshold: the gate owns - // end-of-session messaging there and the critical "ask the user / do - // NOT write handoff files" text would contradict its checkpoint order. - const warnings = evaluateConditions({ context_remaining_pct: 8 }, { env: {} }); + test('suppresses context warnings when the gate is confirmed active', () => { + // The critical "ask the user / do NOT write handoff files" text would + // contradict the gate's checkpoint order on the same turns. + const warnings = evaluateConditions({ context_remaining_pct: 8 }, { gateActive: true }); const ctx = warnings.find(w => w.type === 'context'); - assert.strictEqual(ctx, undefined, 'Context warning must defer to the gate'); + assert.strictEqual(ctx, undefined, 'Context warning must defer to the active gate'); }) ) passed++; else failed++; if ( - test('ECC_CONTEXT_GATE_PCT=0 restores context warnings in the band', () => { - const warnings = evaluateConditions({ context_remaining_pct: 8 }, { env: { ECC_CONTEXT_GATE_PCT: '0' } }); - const ctx = warnings.find(w => w.type === 'context'); - assert.ok(ctx, 'Expected the critical warning with the gate disabled'); - assert.strictEqual(ctx.severity, 3); + test('keeps context warnings when gate activity is not confirmed', () => { + // gateActive false/absent covers gate disabled AND gate unable to + // evaluate (missing transcript) — the warning is the fallback. + for (const options of [{ gateActive: false }, {}, undefined]) { + const warnings = evaluateConditions({ context_remaining_pct: 8 }, options); + const ctx = warnings.find(w => w.type === 'context'); + assert.ok(ctx, 'Expected the critical warning without confirmed gate activity'); + assert.strictEqual(ctx.severity, 3); + } }) ) passed++; else failed++; if ( - test('non-context warnings still fire inside the gate band', () => { - const warnings = evaluateConditions({ context_remaining_pct: 8, total_cost_usd: 55 }, { env: {} }); + test('non-context warnings still fire while the gate is active', () => { + const warnings = evaluateConditions({ context_remaining_pct: 8, total_cost_usd: 55 }, { gateActive: true }); assert.ok(warnings.find(w => w.type === 'cost'), 'Cost warning must be unaffected by gate deference'); assert.strictEqual(warnings.find(w => w.type === 'context'), undefined); }) @@ -117,6 +120,61 @@ function runTests() { passed++; else failed++; + if ( + test('run(): missing transcript keeps CONTEXT CRITICAL as the fallback', () => { + // The gate cannot evaluate usage without a transcript, so it emits + // nothing — the monitor must NOT go silent too (8% remaining with no + // guidance at all is the failure mode this guards against). + const sessionId = `ctx-monitor-gate-fallback-${process.pid}-${Date.now()}`; + const warnPath = path.join(os.tmpdir(), `ecc-ctx-warn-${sessionId}.json`); + const input = JSON.stringify({ session_id: sessionId, tool_name: 'Bash' }); + try { + writeBridgeAtomic(sessionId, { context_remaining_pct: 8, last_timestamp: new Date().toISOString() }); + const result = JSON.parse(run(input)); + assert.ok( + result.hookSpecificOutput.additionalContext.includes('CONTEXT CRITICAL'), + 'Critical warning must survive when the gate cannot evaluate usage' + ); + } finally { + fs.rmSync(getBridgePath(sessionId), { force: true }); + fs.rmSync(warnPath, { force: true }); + } + }) + ) + passed++; + else failed++; + + if ( + test('run(): readable transcript in the gate band suppresses the context warning', () => { + const sessionId = `ctx-monitor-gate-active-${process.pid}-${Date.now()}`; + const warnPath = path.join(os.tmpdir(), `ecc-ctx-warn-${sessionId}.json`); + const transcript = path.join(os.tmpdir(), `ecc-ctx-monitor-transcript-${sessionId}.jsonl`); + // 190k of an assumed 200k window = 95% >= the 90% gate threshold. + fs.writeFileSync( + transcript, + JSON.stringify({ + type: 'assistant', + message: { + model: 'claude-unknown-x', + usage: { input_tokens: 190000, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 50 } + } + }) + '\n' + ); + const input = JSON.stringify({ session_id: sessionId, tool_name: 'Bash', transcript_path: transcript }); + try { + writeBridgeAtomic(sessionId, { context_remaining_pct: 8, last_timestamp: new Date().toISOString() }); + const result = run(input); + assert.strictEqual(result, input, 'Monitor must defer to the confirmed-active gate'); + } finally { + fs.rmSync(getBridgePath(sessionId), { force: true }); + fs.rmSync(warnPath, { force: true }); + fs.rmSync(transcript, { force: true }); + } + }) + ) + passed++; + else failed++; + // evaluateConditions — cost warnings console.log('\nevaluateConditions (cost):'); diff --git a/tests/lib/context-gate-state.test.js b/tests/lib/context-gate-state.test.js new file mode 100644 index 000000000..7c73b2aad --- /dev/null +++ b/tests/lib/context-gate-state.test.js @@ -0,0 +1,150 @@ +'use strict'; +/** + * Tests for scripts/lib/context-gate-state.js + * + * Covers gate threshold resolution, the enabled/active checks the advisory + * hooks (suggest-compact, ecc-context-monitor) use to defer to the + * context-gate, and the transcript-confirmed gateOwnsTranscript helper. + * + * Run with: node tests/lib/context-gate-state.test.js + */ + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { + resolvePct, + resolveGatePct, + resolveEmergencyPct, + isGateEnabled, + isGateActive, + gateOwnsTranscript, + DEFAULT_GATE_PCT, + DEFAULT_EMERGENCY_PCT, + GATE_HOOK_ID +} = require('../../scripts/lib/context-gate-state'); + +console.log('=== Testing context-gate-state.js ===\n'); + +let passed = 0; +let failed = 0; + +function test(desc, fn) { + try { + fn(); + console.log(` ✓ ${desc}`); + passed++; + } catch (e) { + console.log(` ✗ ${desc}`); + console.log(` ${e.message}`); + failed++; + } +} + +function writeTranscript(tokens, model = 'claude-unknown-x') { + const file = path.join(os.tmpdir(), `ecc-gate-state-test-${process.pid}-${Math.random().toString(16).slice(2)}.jsonl`); + const record = JSON.stringify({ + type: 'assistant', + message: { + model, + usage: { input_tokens: tokens, cache_read_input_tokens: 0, cache_creation_input_tokens: 0, output_tokens: 50 } + } + }); + fs.writeFileSync(file, record + '\n', 'utf8'); + return file; +} + +// ── resolveGatePct / resolveEmergencyPct ── + +test('defaults: gate 90, emergency 96', () => { + assert.strictEqual(resolveGatePct({}), DEFAULT_GATE_PCT); + assert.strictEqual(resolveEmergencyPct({}), DEFAULT_EMERGENCY_PCT); +}); + +test('env overrides are honored and 0 disables', () => { + assert.strictEqual(resolveGatePct({ ECC_CONTEXT_GATE_PCT: '70' }), 70); + assert.strictEqual(resolveGatePct({ ECC_CONTEXT_GATE_PCT: '0' }), 0); + assert.strictEqual(resolveEmergencyPct({ ECC_CONTEXT_GATE_EMERGENCY_PCT: '99' }), 99); +}); + +test('resolvePct rejects partial and non-decimal values', () => { + assert.strictEqual(resolvePct({ X: '90abc' }, 'X', DEFAULT_GATE_PCT), DEFAULT_GATE_PCT); + assert.strictEqual(resolvePct({ X: '0x1' }, 'X', DEFAULT_GATE_PCT), DEFAULT_GATE_PCT); + assert.strictEqual(resolvePct({ X: '150' }, 'X', DEFAULT_GATE_PCT), DEFAULT_GATE_PCT); +}); + +// ── isGateEnabled ── + +test('enabled by default profile, disabled by threshold 0', () => { + assert.strictEqual(isGateEnabled({}), true); + assert.strictEqual(isGateEnabled({ ECC_CONTEXT_GATE_PCT: '0' }), false); +}); + +test('disabled via ECC_DISABLED_HOOKS', () => { + assert.strictEqual(isGateEnabled({ ECC_DISABLED_HOOKS: GATE_HOOK_ID }), false); +}); + +// ── isGateActive ── + +test('active at/above the threshold, inactive below', () => { + assert.strictEqual(isGateActive({ tokens: 180000, windowTokens: 200000, env: {} }), true); + assert.strictEqual(isGateActive({ tokens: 179999, windowTokens: 200000, env: {} }), false); +}); + +test('inactive on invalid inputs or disabled gate', () => { + assert.strictEqual(isGateActive({ tokens: NaN, windowTokens: 200000, env: {} }), false); + assert.strictEqual(isGateActive({ tokens: 190000, windowTokens: 0, env: {} }), false); + assert.strictEqual(isGateActive({ tokens: 190000, windowTokens: 200000, env: { ECC_CONTEXT_GATE_PCT: '0' } }), false); +}); + +// ── gateOwnsTranscript ── + +test('true for a readable transcript in the gate band', () => { + const t = writeTranscript(190000); + try { + assert.strictEqual(gateOwnsTranscript(t, {}), true); + } finally { + fs.unlinkSync(t); + } +}); + +test('false below the band and with the gate disabled', () => { + const t = writeTranscript(100000); + const t2 = writeTranscript(190000); + try { + assert.strictEqual(gateOwnsTranscript(t, {}), false); + assert.strictEqual(gateOwnsTranscript(t2, { ECC_CONTEXT_GATE_PCT: '0' }), false); + } finally { + fs.unlinkSync(t); + fs.unlinkSync(t2); + } +}); + +test('false when the gate cannot evaluate usage (missing/unreadable transcript)', () => { + // The advisory hooks use false to KEEP their own warnings — a gate that + // cannot fire must never silence its fallbacks. + assert.strictEqual(gateOwnsTranscript(path.join(os.tmpdir(), `ecc-gate-state-nope-${process.pid}.jsonl`), {}), false); + assert.strictEqual(gateOwnsTranscript('', {}), false); + const broken = path.join(os.tmpdir(), `ecc-gate-state-broken-${process.pid}.jsonl`); + fs.writeFileSync(broken, 'not json\n{broken', 'utf8'); + try { + assert.strictEqual(gateOwnsTranscript(broken, {}), false); + } finally { + fs.unlinkSync(broken); + } +}); + +test('honors an injected env window override', () => { + // 190k reads as 95% of an inferred 200k window, but an injected 1M + // override puts it at 19% — not in the gate band. + const t = writeTranscript(190000); + try { + assert.strictEqual(gateOwnsTranscript(t, { ECC_CONTEXT_WINDOW_TOKENS: '1000000' }), false); + } finally { + fs.unlinkSync(t); + } +}); + +console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); +process.exit(failed > 0 ? 1 : 0);