diff --git a/README.md b/README.md index c495a3f3d..ca373b169 100644 --- a/README.md +++ b/README.md @@ -992,7 +992,7 @@ ECC/ | | |-- session-end.js # Save state on session end | | |-- pre-compact.js # Pre-compaction state saving | | |-- suggest-compact.js # Strategic compaction suggestions -| | |-- context-gate.js # Deterministic checkpoint-and-restart gate at 90% context +| | |-- context-gate.js # Opt-in checkpoint-and-restart gate at 90% context (ECC_CONTEXT_GATE_MODE=enforce; advisory by default) | | |-- evaluate-session.js # Extract patterns from sessions | |-- setup-package-manager.js # Interactive PM setup | diff --git a/hooks/README.md b/hooks/README.md index 13fbbbae1..5bd27528f 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). 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. +- **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 run an end-of-session checkpoint protocol at high context usage). **Enforcement is opt-in**: by default the gate runs in `advisory` mode — completely inert, doing no per-prompt work and suppressing nothing. Setting `ECC_CONTEXT_GATE_MODE=enforce` turns on the protocol: at or above the gate threshold it orders a clean stopping point and a session-scoped checkpoint (written under the handoff dir, never the project root), and 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), or is left in advisory mode, those hooks keep their own warnings. ## Hooks in This Plugin diff --git a/hooks/hooks.metadata.json b/hooks/hooks.metadata.json index 3a608f51b..4ab2f61ab 100644 --- a/hooks/hooks.metadata.json +++ b/hooks/hooks.metadata.json @@ -138,7 +138,7 @@ "UserPromptSubmit": [ { "id": "user-prompt:context-gate", - "description": "Deterministic checkpoint-and-restart gate: at >=90% context, order a clean stopping point, a RESUME.md checkpoint, and a fresh-session resume command instead of per-turn stop suggestions", + "description": "Opt-in checkpoint-and-restart gate (ECC_CONTEXT_GATE_MODE=enforce): at >=90% context, order a clean stopping point, a session-scoped checkpoint under the handoff dir, and a fresh-session resume command. Default mode is advisory — inert, suppresses nothing", "fingerprint": "13d8180d18ec" } ] diff --git a/scripts/hooks/context-gate.js b/scripts/hooks/context-gate.js index 9b7df38ac..9f02d4d30 100644 --- a/scripts/hooks/context-gate.js +++ b/scripts/hooks/context-gate.js @@ -4,13 +4,26 @@ * * Cross-platform (Windows, macOS, Linux) * - * Deterministic end-of-session protocol. At >=90% context-window occupancy - * (measured from the latest assistant `usage` record in the session - * transcript, same signal as suggest-compact), injects a mandatory order: - * bring the in-flight unit of work to its nearest clean stopping point, - * write a structured checkpoint file (RESUME.md), hand the operator a - * one-line resume command, and instruct closing the session. At >=96% the - * order escalates to checkpoint-immediately, mid-task if necessary. + * Enforcement is OPT-IN. On a default install the gate runs in `advisory` + * mode: it returns immediately, does no per-prompt transcript work, and + * suppresses nothing — the advisory hooks (suggest-compact, + * ecc-context-monitor) keep their normal behavior. The operator turns on the + * deterministic protocol by setting ECC_CONTEXT_GATE_MODE=enforce. + * + * In enforce mode: at >=90% context-window occupancy (measured from the + * latest assistant `usage` record in the session transcript, same signal as + * suggest-compact), the hook injects an order: bring the in-flight unit of + * work to its nearest clean stopping point, write a structured checkpoint + * file, hand the operator a one-line resume command, and instruct closing + * the session. At >=96% the order escalates to checkpoint-immediately, + * mid-task if necessary. + * + * The checkpoint is written to a collision-safe, identity-bearing path under + * the plugin's session-handoff directory + * (/resume/-.md) — NOT the project + * root — so an operator's own RESUME.md is never a target and repeated fires + * in one session overwrite only that session's own checkpoint. The resume + * command naming that exact path is the handoff receipt. * * Why an order instead of a suggestion (contrast with suggest-compact and * ecc-context-monitor, which advise and ask): @@ -29,17 +42,20 @@ * gate would never fire. With auto-compact on the hook is harmless but * inert. * - * Precedence over the advisory hooks: once occupancy reaches the gate - * threshold, suggest-compact and ecc-context-monitor suppress their - * /compact suggestions and context warnings (via isGateActive / - * isGateEnabled in lib/context-gate-state.js) so the model never receives - * contradictory instructions in the gate band. + * Precedence over the advisory hooks: in enforce mode only, once occupancy + * reaches the gate threshold, suggest-compact and ecc-context-monitor + * suppress their /compact suggestions and context warnings (via isGateActive + * / isGateEnabled in lib/context-gate-state.js) so the model never receives + * contradictory instructions in the gate band. In advisory mode isGateEnabled + * is false, so there is no suppression and the advisory hooks are unaffected. * * The gate deliberately re-fires on every prompt while above threshold — * that is the enforcement, not a defect: the order stands until the session * is closed. Below threshold the hook is completely silent. * * Controls: + * - ECC_CONTEXT_GATE_MODE advisory (default; inert) | enforce (opt in to + * the order + advisory-hook deference) | off (same as PCT=0) * - ECC_CONTEXT_GATE_PCT gate threshold percent (default 90; 0 disables) * - ECC_CONTEXT_GATE_EMERGENCY_PCT escalation percent (default 96; always * clamped to at least gate+1 so the two-tier order is preserved) @@ -51,20 +67,46 @@ 'use strict'; +const path = require('path'); const { readLatestContextTokens, resolveContextWindow, formatWindowLabel } = require('../lib/transcript-context'); -const { resolvePct, resolveGatePct, resolveEmergencyPct, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT } = require('../lib/context-gate-state'); +const { resolvePct, resolveGateMode, resolveGatePct, resolveEmergencyPct, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT } = require('../lib/context-gate-state'); +const { getSessionsDir, getProjectName, sanitizeSessionId } = require('../lib/utils'); /** - * Build the checkpoint order injected as additionalContext. + * Compute a collision-safe, identity-bearing checkpoint path under the + * plugin's session-handoff directory. Never the project root, so an + * operator's own RESUME.md is never a target; the session id in the name + * keeps repeated fires in one session pointed at the same file (idempotent + * — the model overwrites only its own checkpoint, never a user file). + * @param {object} input - Parsed hook stdin ({ cwd, session_id }). + * @returns {string} Absolute path to the session-scoped checkpoint file. + */ +function resolveCheckpointPath(input) { + const resumeDir = path.join(getSessionsDir(), 'resume'); + const project = + sanitizeSessionId(input && input.cwd ? path.basename(String(input.cwd)) : null) || + sanitizeSessionId(getProjectName()) || + 'project'; + const sessionId = + sanitizeSessionId(input && input.session_id) || + sanitizeSessionId(process.env.ECC_SESSION_ID) || + sanitizeSessionId(process.env.CLAUDE_SESSION_ID) || + 'session'; + return path.join(resumeDir, `${project}-${sessionId}.md`); +} + +/** + * Build the checkpoint order injected as additionalContext (enforce mode). * @param {object} params * @param {number} params.pct - Occupancy percent (integer, floored). * @param {number} params.tokens - Context tokens observed. * @param {number} params.windowTokens - Resolved window size. * @param {boolean} params.inferred - Window size was assumed, not detected. * @param {boolean} params.emergency - Past the emergency threshold. + * @param {string} params.checkpointPath - Session-scoped checkpoint target. * @returns {string} */ -function buildOrderText({ pct, tokens, windowTokens, inferred, emergency }) { +function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath }) { const windowLabel = formatWindowLabel(windowTokens); // An inferred window means the true denominator may be larger (an // unrecognized 1M-window model would read as 90% at 180k of an assumed @@ -74,11 +116,16 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency }) { // never forces a restart. const lines = [ inferred - ? `CONTEXT GATE TRIPPED (deterministic hook): context at ~${pct}% of an INFERRED ${windowLabel} window ` + - `(${tokens.toLocaleString('en-US')} tokens; the true window may be larger — set ` + - 'ECC_CONTEXT_WINDOW_TOKENS to correct it). Treat the following as a strong recommendation:' - : `CONTEXT GATE TRIPPED (deterministic hook — this is an order, not a suggestion): context at ${pct}% ` + - `(${tokens.toLocaleString('en-US')} tokens of a ${windowLabel} window).`, + ? `CONTEXT GATE TRIPPED (enforce mode — operator opted in): context at ~${pct}% of an INFERRED ` + + `${windowLabel} window (${tokens.toLocaleString('en-US')} tokens; the true window may be larger — ` + + 'set ECC_CONTEXT_WINDOW_TOKENS to correct it). Treat the following as a strong recommendation:' + : `CONTEXT GATE TRIPPED (enforce mode — operator opted in; this is an order, not a suggestion): ` + + `context at ${pct}% (${tokens.toLocaleString('en-US')} tokens of a ${windowLabel} window).`, + '', + // Occupancy is a measurement, not by itself authority to abandon the task. + // The authority here is the operator's explicit opt-in to enforce mode. + 'The occupancy figure above is an observed measurement, not by itself permission to abandon the task. ' + + 'The authority to checkpoint-and-hand-off now comes from the operator having enabled enforce mode.', '' ]; @@ -93,13 +140,16 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency }) { lines.push( '1. Do NOT start any new work stream. Bring only the unit of work currently in flight to its nearest ' + 'clean stopping point (finish the edit/test/verification underway; do not begin the next one).', - '2. Write a checkpoint file: RESUME.md at the root of the active project directory (or under ' + - '~/.claude/resume/ if no single project applies) containing: the objective; current state with ' + - 'VERIFIED facts strictly separated from hypotheses; decisions the operator approved; approaches ' + - 'ruled out and WHY; exact next steps; files touched; any pending or half-applied changes.', + '2. Write the checkpoint to EXACTLY this session-scoped path (create parent directories if needed):', + ` ${checkpointPath}`, + ' It must contain: the objective; current state with VERIFIED facts strictly separated from ' + + 'hypotheses; decisions the operator approved; approaches ruled out and WHY; exact next steps; files ' + + 'touched; any pending or half-applied changes. Do NOT overwrite or modify an existing RESUME.md or ' + + 'any other file in the project — this path is dedicated to this session\'s handoff and preserves ' + + 'whatever the operator already has.', '3. Then state plainly that this session must now be closed, and give the operator this exact resume ' + - 'command on its own line:', - ' claude "Read and continue the work described there."', + 'command on its own line (the receipt for this handoff):', + ` claude "Read ${checkpointPath} and continue the work described there."`, '4. Do NOT ask whether to stop, do NOT offer alternatives ("good stopping point", "want to pause?"), ' + 'and do NOT take on further work in this session after the checkpoint is written. If the operator ' + 'sends further prompts here, answer only from existing context and repeat the restart instruction.' @@ -120,6 +170,10 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency }) { function run(rawInput, options = {}) { try { const env = (options && options.env) || process.env; + // Enforcement is opt-in. In the default advisory mode the gate is inert: + // return before any transcript work so a default install adds zero + // per-prompt cost and leaves the advisory hooks unsuppressed. + if (resolveGateMode(env) !== 'enforce') return ''; const gatePct = resolveGatePct(env); if (gatePct === 0) return ''; // Emergency must sit in a strictly tighter band than the gate. Otherwise a @@ -138,12 +192,14 @@ function run(rawInput, options = {}) { if (pct < gatePct) return ''; const emergency = pct >= emergencyPct; + const checkpointPath = resolveCheckpointPath(input); const orderText = buildOrderText({ pct, tokens: latest.tokens, windowTokens, inferred, - emergency + emergency, + checkpointPath }); return JSON.stringify({ diff --git a/scripts/lib/context-gate-state.js b/scripts/lib/context-gate-state.js index 907e2fc09..413a0e8b0 100644 --- a/scripts/lib/context-gate-state.js +++ b/scripts/lib/context-gate-state.js @@ -19,6 +19,19 @@ const DEFAULT_EMERGENCY_PCT = 96; const MIN_PCT = 1; const MAX_PCT = 100; +/** + * Gate operating mode. Enforcement is OPT-IN: a default install leaves the + * gate in `advisory`, where it is completely inert and suppresses nothing — + * the advisory hooks (suggest-compact, ecc-context-monitor) keep their normal + * behavior. Only `enforce` turns on the checkpoint-and-restart order and the + * advisory-hook deference. + */ +const DEFAULT_GATE_MODE = 'advisory'; +const GATE_MODE_ADVISORY = 'advisory'; +const GATE_MODE_ENFORCE = 'enforce'; +const GATE_MODE_OFF = 'off'; +const VALID_GATE_MODES = new Set([GATE_MODE_ADVISORY, GATE_MODE_ENFORCE, GATE_MODE_OFF]); + /** Hook id and profiles exactly as registered in hooks/hooks.json. */ const GATE_HOOK_ID = 'user-prompt:context-gate'; const GATE_HOOK_PROFILES = 'standard,strict'; @@ -48,6 +61,46 @@ function warnRejected(name, raw, fallback) { } } +/** + * Emit a one-time stderr note that ECC_CONTEXT_GATE_MODE was present but + * unrecognized. Shares the per-process dedupe Set with warnRejected so a + * typo can never turn the re-firing hook into a stderr spam stream, and a + * typo'd mode can never silently flip enforcement on. Never throws. + * @param {*} raw + */ +function warnRejectedMode(raw) { + const name = 'ECC_CONTEXT_GATE_MODE'; + if (warnedEnvNames.has(name)) return; + warnedEnvNames.add(name); + try { + process.stderr.write( + `[context-gate] ignoring invalid ${name}="${raw}" ` + + `(expected advisory, enforce, or off); using default ${DEFAULT_GATE_MODE}.\n` + ); + } catch { + /* stderr unavailable — resolution still returns the deterministic fallback */ + } +} + +/** + * Resolve the gate operating mode from the environment. Enforcement is + * opt-in: an unset, blank, or unrecognized value resolves to `advisory` + * (inert, suppresses nothing). A rejected value also surfaces a one-time + * stderr note, so a mistyped mode never silently enables — or disables — + * the checkpoint-and-restart order. + * @param {object} [env] + * @returns {'advisory'|'enforce'|'off'} + */ +function resolveGateMode(env = process.env) { + const raw = env && env.ECC_CONTEXT_GATE_MODE; + if (raw === undefined || raw === null) return DEFAULT_GATE_MODE; + const str = String(raw).trim().toLowerCase(); + if (str === '') return DEFAULT_GATE_MODE; + if (VALID_GATE_MODES.has(str)) return str; + warnRejectedMode(raw); + return DEFAULT_GATE_MODE; +} + /** * Resolve a percent setting from the environment. * `0` disables the gate entirely; invalid values fall back to the default. @@ -100,13 +153,16 @@ function resolveEmergencyPct(env = process.env) { } /** - * True when the context-gate hook is installed-and-enabled for this - * environment (profile allows it, not in ECC_DISABLED_HOOKS, threshold - * not set to 0). Says nothing about current occupancy. + * True when the context-gate hook is ENFORCING for this environment: the + * operator opted into enforce mode, the profile allows it, it is not in + * ECC_DISABLED_HOOKS, and the threshold is not 0. Says nothing about current + * occupancy. In the default (advisory) mode this is false, so the advisory + * hooks never defer and the gate never fires — enforcement is opt-in. * @param {object} [env] * @returns {boolean} */ function isGateEnabled(env = process.env) { + if (resolveGateMode(env) !== GATE_MODE_ENFORCE) return false; if (resolveGatePct(env) === 0) return false; return isHookEnabled(GATE_HOOK_ID, { profiles: GATE_HOOK_PROFILES, env }); } @@ -154,6 +210,7 @@ function gateOwnsTranscript(transcriptPath, env = process.env) { module.exports = { resolvePct, + resolveGateMode, gateOwnsTranscript, resolveGatePct, resolveEmergencyPct, @@ -161,6 +218,7 @@ module.exports = { isGateActive, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT, + DEFAULT_GATE_MODE, GATE_HOOK_ID, GATE_HOOK_PROFILES }; diff --git a/tests/hooks/context-gate.test.js b/tests/hooks/context-gate.test.js index 9b2f92640..a234628e1 100644 --- a/tests/hooks/context-gate.test.js +++ b/tests/hooks/context-gate.test.js @@ -50,8 +50,8 @@ function writeTranscript(tokens, model = 'claude-fable-5') { return file; } -function inputFor(transcriptPath) { - return JSON.stringify({ session_id: 'test', transcript_path: transcriptPath, prompt: 'continue' }); +function inputFor(transcriptPath, extra = {}) { + return JSON.stringify({ session_id: 'test', transcript_path: transcriptPath, prompt: 'continue', ...extra }); } function runTests() { @@ -60,9 +60,37 @@ function runTests() { let passed = 0; let failed = 0; const cleanup = []; - const env = {}; // isolated env: no ECC_* leakage from the host + // Enforcement is opt-in: the gate only fires in enforce mode. These tests + // exercise the firing path, so they run with enforce set. The default + // (advisory) posture is covered separately below. Isolated env object: no + // ECC_* leakage from the host. + const env = { ECC_CONTEXT_GATE_MODE: 'enforce' }; - console.log('run() — gate behavior:'); + console.log('opt-in / default posture:'); + + if ( + test('default install (no mode set) stays silent even deep in the band', () => { + // 97% occupancy, but with no ECC_CONTEXT_GATE_MODE the gate is inert and + // does no per-prompt checkpoint work. + const t = writeTranscript(970000); + cleanup.push(t); + assert.strictEqual(run(inputFor(t), { env: {} }), ''); + }) + ) + passed++; + else failed++; + + if ( + test('ECC_CONTEXT_GATE_MODE=off stays silent in the band', () => { + const t = writeTranscript(970000); + cleanup.push(t); + assert.strictEqual(run(inputFor(t), { env: { ECC_CONTEXT_GATE_MODE: 'off' } }), ''); + }) + ) + passed++; + else failed++; + + console.log('\nrun() — gate behavior (enforce mode):'); if ( test('below threshold (50% of 1M) stays completely silent', () => { @@ -79,11 +107,14 @@ function runTests() { const t = writeTranscript(905000); cleanup.push(t); const out = JSON.parse(run(inputFor(t), { env })); + const ctx = out.hookSpecificOutput.additionalContext; assert.strictEqual(out.hookSpecificOutput.hookEventName, 'UserPromptSubmit'); - assert.ok(out.hookSpecificOutput.additionalContext.includes('CONTEXT GATE TRIPPED')); - assert.ok(out.hookSpecificOutput.additionalContext.includes('RESUME.md')); + assert.ok(ctx.includes('CONTEXT GATE TRIPPED')); + // Checkpoint targets the session-scoped handoff path, not project-root RESUME.md. + assert.ok(/[/\\]resume[/\\].*-test\.md/.test(ctx), `expected handoff path with session id. Got: ${ctx}`); + assert.ok(ctx.includes('Do NOT overwrite or modify an existing RESUME.md')); assert.ok(out.systemMessage.includes('90%')); - assert.ok(!out.hookSpecificOutput.additionalContext.includes('EMERGENCY')); + assert.ok(!ctx.includes('EMERGENCY')); }) ) passed++; @@ -103,10 +134,14 @@ function runTests() { if ( test('order forbids asking to stop and demands a resume command', () => { - const text = buildOrderText({ pct: 91, tokens: 910000, windowTokens: 1000000, inferred: false, emergency: false }); + const cp = '/home/me/.claude/session-data/resume/myproj-abc123.md'; + const text = buildOrderText({ pct: 91, tokens: 910000, windowTokens: 1000000, inferred: false, emergency: false, checkpointPath: cp }); assert.ok(text.includes('Do NOT ask whether to stop')); - assert.ok(text.includes('claude "Read ')); + assert.ok(text.includes(`claude "Read ${cp} and continue`)); + assert.ok(text.includes(cp)); assert.ok(text.includes('VERIFIED facts strictly separated from hypotheses')); + // Observed usage is distinguished from permission to stop. + assert.ok(text.includes('not by itself permission to abandon the task')); }) ) passed++; @@ -124,7 +159,7 @@ function runTests() { assert.ok(!text.includes('an order, not a suggestion')); assert.ok(text.includes('INFERRED')); assert.ok(text.includes('strong recommendation')); - assert.ok(text.includes('RESUME.md')); + assert.ok(/[/\\]resume[/\\].*-test\.md/.test(text)); assert.ok(out.systemMessage.includes('strongly advised')); assert.ok(!out.systemMessage.includes('ordered')); }) @@ -155,10 +190,10 @@ function runTests() { console.log('\nenvironment controls:'); if ( - test('ECC_CONTEXT_GATE_PCT=0 disables the gate', () => { + test('ECC_CONTEXT_GATE_PCT=0 disables the gate (even in enforce mode)', () => { const t = writeTranscript(990000); cleanup.push(t); - assert.strictEqual(run(inputFor(t), { env: { ECC_CONTEXT_GATE_PCT: '0' } }), ''); + assert.strictEqual(run(inputFor(t), { env: { ...env, ECC_CONTEXT_GATE_PCT: '0' } }), ''); }) ) passed++; @@ -168,7 +203,7 @@ function runTests() { test('ECC_CONTEXT_GATE_PCT=70 lowers the trigger', () => { const t = writeTranscript(750000); cleanup.push(t); - const out = JSON.parse(run(inputFor(t), { env: { ECC_CONTEXT_GATE_PCT: '70' } })); + const out = JSON.parse(run(inputFor(t), { env: { ...env, ECC_CONTEXT_GATE_PCT: '70' } })); assert.ok(out.hookSpecificOutput.additionalContext.includes('CONTEXT GATE TRIPPED')); }) ) @@ -181,7 +216,7 @@ function runTests() { // clamp every fire (pct >= 98) would also be >= 96 and skip step 1. // Clamp makes emergency 99, so 98% fires as a full order (step 1 kept) // and only 99%+ escalates. - const gateEnv = { ECC_CONTEXT_GATE_PCT: '98' }; + const gateEnv = { ...env, ECC_CONTEXT_GATE_PCT: '98' }; const at98 = writeTranscript(980000); cleanup.push(at98); const out98 = JSON.parse(run(inputFor(at98), { env: gateEnv })); @@ -206,7 +241,7 @@ function runTests() { // 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' } }), ''); + assert.strictEqual(run(inputFor(t), { env: { ...env, ECC_CONTEXT_WINDOW_TOKENS: '1000000' } }), ''); }) ) passed++; @@ -218,17 +253,22 @@ function runTests() { cleanup.push(t); // 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' } })); + const out = JSON.parse(run(inputFor(t), { env: { ...env, ECC_CONTEXT_WINDOW_TOKENS: '200000' } })); assert.ok(out.systemMessage.includes('92%')); - // Registered-path form: metadata second arg falls back to process.env. + // Registered-path form: metadata second arg falls back to process.env + // (including the opt-in mode). const original = process.env.ECC_CONTEXT_WINDOW_TOKENS; + const originalMode = process.env.ECC_CONTEXT_GATE_MODE; try { process.env.ECC_CONTEXT_WINDOW_TOKENS = '200000'; + process.env.ECC_CONTEXT_GATE_MODE = 'enforce'; 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; + if (originalMode === undefined) delete process.env.ECC_CONTEXT_GATE_MODE; + else process.env.ECC_CONTEXT_GATE_MODE = originalMode; } }) ) @@ -268,19 +308,67 @@ function runTests() { const t = writeTranscript(990000); cleanup.push(t); const original = process.env.ECC_CONTEXT_GATE_PCT; + const originalMode = process.env.ECC_CONTEXT_GATE_MODE; try { + // Enforce mode on, but PCT=0 — read from process.env on the metadata + // path — must still disable, proving the override is honored there. + process.env.ECC_CONTEXT_GATE_MODE = 'enforce'; process.env.ECC_CONTEXT_GATE_PCT = '0'; const meta = { hookId: 'user-prompt:context-gate', pluginRoot: '/nonexistent', truncated: false }; assert.strictEqual(run(inputFor(t), meta), ''); } finally { if (original === undefined) delete process.env.ECC_CONTEXT_GATE_PCT; else process.env.ECC_CONTEXT_GATE_PCT = original; + if (originalMode === undefined) delete process.env.ECC_CONTEXT_GATE_MODE; + else process.env.ECC_CONTEXT_GATE_MODE = originalMode; } }) ) passed++; else failed++; + console.log('\nhandoff checkpoint ownership (enforce mode):'); + + if ( + test('a pre-existing project RESUME.md is never targeted and is left untouched', () => { + const projDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-gate-proj-')); + const existing = path.join(projDir, 'RESUME.md'); + fs.writeFileSync(existing, 'OPERATOR CONTENT — must survive\n', 'utf8'); + const t = writeTranscript(950000); + cleanup.push(t); + try { + const out = JSON.parse(run(inputFor(t, { cwd: projDir }), { env })); + const ctx = out.hookSpecificOutput.additionalContext; + // Checkpoint goes to the session-handoff dir, not the project root. + assert.ok(/[/\\]resume[/\\]/.test(ctx), 'checkpoint must live under the handoff resume dir'); + assert.ok(!ctx.includes(existing), 'order must not target the operator RESUME.md'); + assert.ok(ctx.includes('preserves whatever the operator already has')); + // The hook injects an order; it writes nothing itself — the file stands. + assert.strictEqual(fs.readFileSync(existing, 'utf8'), 'OPERATOR CONTENT — must survive\n'); + } finally { + fs.rmSync(projDir, { recursive: true, force: true }); + } + }) + ) + passed++; + else failed++; + + if ( + test('repeated fires in one session resolve to the same stable checkpoint path', () => { + const t = writeTranscript(950000); + cleanup.push(t); + const extract = (raw) => { + const ctx = JSON.parse(raw).hookSpecificOutput.additionalContext; + return ctx.match(/\S*[/\\]resume[/\\]\S*-test\.md/)[0]; + }; + const first = extract(run(inputFor(t, { cwd: '/tmp/ecc-demo-proj' }), { env })); + const second = extract(run(inputFor(t, { cwd: '/tmp/ecc-demo-proj' }), { env })); + assert.strictEqual(first, second, 'same session must reuse one checkpoint path (idempotent)'); + }) + ) + passed++; + else failed++; + for (const file of cleanup) { try { fs.unlinkSync(file); diff --git a/tests/hooks/ecc-context-monitor.test.js b/tests/hooks/ecc-context-monitor.test.js index d8fbb811f..08e00d50a 100644 --- a/tests/hooks/ecc-context-monitor.test.js +++ b/tests/hooks/ecc-context-monitor.test.js @@ -161,11 +161,16 @@ function runTests() { }) + '\n' ); const input = JSON.stringify({ session_id: sessionId, tool_name: 'Bash', transcript_path: transcript }); + const originalMode = process.env.ECC_CONTEXT_GATE_MODE; try { + // gateOwnsTranscript reads process.env — enforcement is opt-in. + process.env.ECC_CONTEXT_GATE_MODE = 'enforce'; 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 { + if (originalMode === undefined) delete process.env.ECC_CONTEXT_GATE_MODE; + else process.env.ECC_CONTEXT_GATE_MODE = originalMode; fs.rmSync(getBridgePath(sessionId), { force: true }); fs.rmSync(warnPath, { force: true }); fs.rmSync(transcript, { force: true }); @@ -175,6 +180,43 @@ function runTests() { passed++; else failed++; + if ( + test('run(): default (advisory) gate does NOT suppress the context warning', () => { + // Same in-band transcript, but with no ECC_CONTEXT_GATE_MODE the gate is + // inert — the monitor must keep emitting CONTEXT CRITICAL. + const sessionId = `ctx-monitor-gate-advisory-${process.pid}-${Date.now()}`; + const transcript = path.join(os.tmpdir(), `ecc-ctx-monitor-transcript-${sessionId}.jsonl`); + 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 }); + const originalMode = process.env.ECC_CONTEXT_GATE_MODE; + try { + delete process.env.ECC_CONTEXT_GATE_MODE; + 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 stand on a default install (advisory gate)' + ); + } finally { + if (originalMode === undefined) delete process.env.ECC_CONTEXT_GATE_MODE; + else process.env.ECC_CONTEXT_GATE_MODE = originalMode; + fs.rmSync(getBridgePath(sessionId), { force: true }); + fs.rmSync(transcript, { force: true }); + } + }) + ) + passed++; + else failed++; + // evaluateConditions — cost warnings console.log('\nevaluateConditions (cost):'); diff --git a/tests/hooks/suggest-compact.test.js b/tests/hooks/suggest-compact.test.js index d83ef6b71..49b6bc232 100644 --- a/tests/hooks/suggest-compact.test.js +++ b/tests/hooks/suggest-compact.test.js @@ -898,15 +898,15 @@ function runTests() { console.log('\nContext-gate deference:'); - if (test('context suggestion stays silent while the context-gate is active', () => { - // 190k of an assumed 200k window = 95% >= the 90% gate threshold; the - // gate owns this band, so no /compact suggestion may fire. + if (test('context suggestion stays silent while the context-gate is enforcing', () => { + // 190k of an assumed 200k window = 95% >= the 90% gate threshold; in + // enforce mode the gate owns this band, so no /compact suggestion may fire. const ctx = createContextContext(); const transcript = writeTranscriptFixture(190000); try { const result = runCompactWithInput( { session_id: ctx.sessionId, transcript_path: transcript }, - { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '' } + { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_MODE: 'enforce' } ); assert.strictEqual(result.code, 0); assert.strictEqual(result.stdout.trim(), '', `Expected silence in the gate band. Got: "${result.stdout}"`); @@ -917,13 +917,34 @@ function runTests() { })) passed++; else failed++; - if (test('ECC_CONTEXT_GATE_PCT=0 restores the context suggestion', () => { + if (test('default (advisory) gate does NOT suppress the context suggestion', () => { + // With no ECC_CONTEXT_GATE_MODE, enforcement is off — the advisory + // suggestion must behave exactly as before the gate existed. const ctx = createContextContext(); const transcript = writeTranscriptFixture(190000); try { const result = runCompactWithInput( { session_id: ctx.sessionId, transcript_path: transcript }, - { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_PCT: '0' } + { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '' } + ); + assert.ok( + result.stdout.includes('Context ~190k tokens'), + `Expected the advisory suggestion on a default install. Got: "${result.stdout}"` + ); + } finally { + try { fs.unlinkSync(transcript); } catch (_err) { /* ignore */ } + ctx.cleanup(); + } + })) passed++; + else failed++; + + if (test('ECC_CONTEXT_GATE_PCT=0 restores the context suggestion (even in enforce mode)', () => { + const ctx = createContextContext(); + const transcript = writeTranscriptFixture(190000); + try { + const result = runCompactWithInput( + { session_id: ctx.sessionId, transcript_path: transcript }, + { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_MODE: 'enforce', ECC_CONTEXT_GATE_PCT: '0' } ); assert.ok( result.stdout.includes('Context ~190k tokens'), @@ -936,7 +957,7 @@ function runTests() { })) passed++; else failed++; - if (test('tool-count suggestion stays silent while the context-gate is active', () => { + if (test('tool-count suggestion stays silent while the context-gate is enforcing', () => { const ctx = createContextContext(); const transcript = writeTranscriptFixture(190000); ctx.cleanup(); @@ -946,7 +967,7 @@ function runTests() { try { const result = runCompactWithInput( { session_id: ctx.sessionId, transcript_path: transcript }, - { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '' } + { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_MODE: 'enforce' } ); assert.strictEqual(result.code, 0); assert.strictEqual(result.stdout.trim(), '', `Count message must not fire in the gate band. Got: "${result.stdout}"`); @@ -970,7 +991,7 @@ function runTests() { try { const result = runCompactWithInput( { session_id: ctx.sessionId, transcript_path: transcript }, - { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_PCT: '0' } + { ECC_CONTEXT_WINDOW_TOKENS: '', CLAUDE_CODE_AUTO_COMPACT_WINDOW: '', ECC_CONTEXT_GATE_MODE: 'enforce', ECC_CONTEXT_GATE_PCT: '0' } ); assert.ok( result.stdout.includes('50 tool calls reached'), diff --git a/tests/lib/context-gate-state.test.js b/tests/lib/context-gate-state.test.js index 67ad8af80..e1a7ad153 100644 --- a/tests/lib/context-gate-state.test.js +++ b/tests/lib/context-gate-state.test.js @@ -15,6 +15,7 @@ const os = require('os'); const path = require('path'); const { resolvePct, + resolveGateMode, resolveGatePct, resolveEmergencyPct, isGateEnabled, @@ -22,9 +23,13 @@ const { gateOwnsTranscript, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT, + DEFAULT_GATE_MODE, GATE_HOOK_ID } = require('../../scripts/lib/context-gate-state'); +// Enforcement is opt-in; the active/suppression checks only hold in this mode. +const ENFORCE = { ECC_CONTEXT_GATE_MODE: 'enforce' }; + console.log('=== Testing context-gate-state.js ===\n'); let passed = 0; @@ -113,36 +118,80 @@ test('resolvePct stays silent for valid, zero-disable, and unset values', () => assert.strictEqual(out.split('\n').filter((l) => l.includes('QUIET_')).length, 0); }); -// ── isGateEnabled ── +// ── resolveGateMode ── -test('enabled by default profile, disabled by threshold 0', () => { - assert.strictEqual(isGateEnabled({}), true); - assert.strictEqual(isGateEnabled({ ECC_CONTEXT_GATE_PCT: '0' }), false); +test('mode defaults to advisory (enforcement is opt-in)', () => { + assert.strictEqual(resolveGateMode({}), DEFAULT_GATE_MODE); + assert.strictEqual(DEFAULT_GATE_MODE, 'advisory'); + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: '' }), 'advisory'); + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: ' ' }), 'advisory'); }); -test('disabled via ECC_DISABLED_HOOKS', () => { - assert.strictEqual(isGateEnabled({ ECC_DISABLED_HOOKS: GATE_HOOK_ID }), false); +test('mode accepts enforce/off (case- and whitespace-insensitive)', () => { + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: 'enforce' }), 'enforce'); + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: ' ENFORCE ' }), 'enforce'); + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: 'off' }), 'off'); +}); + +test('mode falls back to advisory on a garbage value, with a one-time note', () => { + const out = captureStderr(() => { + // A mistyped mode must never silently enable enforcement. + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: 'enforced' }), 'advisory'); + assert.strictEqual(resolveGateMode({ ECC_CONTEXT_GATE_MODE: 'enforced' }), 'advisory'); + }); + const hits = out.split('\n').filter((l) => l.includes('ECC_CONTEXT_GATE_MODE')); + assert.strictEqual(hits.length, 1, 'rejected mode must be surfaced exactly once'); + assert.ok(hits[0].includes('[context-gate]')); + assert.ok(hits[0].includes('enforced')); +}); + +// ── isGateEnabled ── + +test('disabled by default (advisory); enabled only in enforce mode', () => { + // The default install must not enforce or suppress the advisory hooks. + assert.strictEqual(isGateEnabled({}), false); + assert.strictEqual(isGateEnabled(ENFORCE), true); +}); + +test('enforce mode still disabled by threshold 0, off mode, and ECC_DISABLED_HOOKS', () => { + assert.strictEqual(isGateEnabled({ ...ENFORCE, ECC_CONTEXT_GATE_PCT: '0' }), false); + assert.strictEqual(isGateEnabled({ ECC_CONTEXT_GATE_MODE: 'off' }), false); + assert.strictEqual(isGateEnabled({ ...ENFORCE, 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('advisory default never active even deep in the band (no suppression)', () => { + assert.strictEqual(isGateActive({ tokens: 195000, windowTokens: 200000, env: {} }), false); +}); + +test('active at/above the threshold, inactive below (enforce mode)', () => { + assert.strictEqual(isGateActive({ tokens: 180000, windowTokens: 200000, env: ENFORCE }), true); + assert.strictEqual(isGateActive({ tokens: 179999, windowTokens: 200000, env: ENFORCE }), 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); + assert.strictEqual(isGateActive({ tokens: NaN, windowTokens: 200000, env: ENFORCE }), false); + assert.strictEqual(isGateActive({ tokens: 190000, windowTokens: 0, env: ENFORCE }), false); + assert.strictEqual(isGateActive({ tokens: 190000, windowTokens: 200000, env: { ...ENFORCE, ECC_CONTEXT_GATE_PCT: '0' } }), false); }); // ── gateOwnsTranscript ── -test('true for a readable transcript in the gate band', () => { +test('advisory default: false even for a readable transcript in the band', () => { + // Proves a default install adds no advisory suppression. const t = writeTranscript(190000); try { - assert.strictEqual(gateOwnsTranscript(t, {}), true); + assert.strictEqual(gateOwnsTranscript(t, {}), false); + } finally { + fs.unlinkSync(t); + } +}); + +test('true for a readable transcript in the gate band (enforce mode)', () => { + const t = writeTranscript(190000); + try { + assert.strictEqual(gateOwnsTranscript(t, ENFORCE), true); } finally { fs.unlinkSync(t); } @@ -152,8 +201,8 @@ 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); + assert.strictEqual(gateOwnsTranscript(t, ENFORCE), false); + assert.strictEqual(gateOwnsTranscript(t2, { ...ENFORCE, ECC_CONTEXT_GATE_PCT: '0' }), false); } finally { fs.unlinkSync(t); fs.unlinkSync(t2); @@ -163,12 +212,12 @@ test('false below the band and with the gate disabled', () => { 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); + assert.strictEqual(gateOwnsTranscript(path.join(os.tmpdir(), `ecc-gate-state-nope-${process.pid}.jsonl`), ENFORCE), false); + assert.strictEqual(gateOwnsTranscript('', ENFORCE), 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); + assert.strictEqual(gateOwnsTranscript(broken, ENFORCE), false); } finally { fs.unlinkSync(broken); } @@ -179,7 +228,7 @@ test('honors an injected env window override', () => { // 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); + assert.strictEqual(gateOwnsTranscript(t, { ...ENFORCE, ECC_CONTEXT_WINDOW_TOKENS: '1000000' }), false); } finally { fs.unlinkSync(t); }