diff --git a/scripts/hooks/context-gate.js b/scripts/hooks/context-gate.js index 9f02d4d30..1f8d3968d 100644 --- a/scripts/hooks/context-gate.js +++ b/scripts/hooks/context-gate.js @@ -67,36 +67,117 @@ 'use strict'; +const fs = require('fs'); const path = require('path'); const { readLatestContextTokens, resolveContextWindow, formatWindowLabel } = require('../lib/transcript-context'); const { resolvePct, resolveGateMode, resolveGatePct, resolveEmergencyPct, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT } = require('../lib/context-gate-state'); const { getSessionsDir, getProjectName, sanitizeSessionId } = require('../lib/utils'); +/** Max disambiguation attempts before declining rather than guess a path. */ +const MAX_CHECKPOINT_CANDIDATES = 50; + /** - * 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. + * Read the owning session id recorded in a checkpoint file's ownership + * marker (its first line), or null when the file has no recognizable marker + * or cannot be read. The model writes this marker verbatim from the order + * (see buildOrderText); the hook itself never writes the file, so a checkpoint + * with no marker is treated as NOT owned by any session — a file the gate must + * not target. Never throws: a read failure is "not owned", not a crash. + * @param {string} filePath + * @returns {string|null} Sanitized owner session id, or null. */ -function resolveCheckpointPath(input) { - const resumeDir = path.join(getSessionsDir(), 'resume'); - const project = - sanitizeSessionId(input && input.cwd ? path.basename(String(input.cwd)) : null) || - sanitizeSessionId(getProjectName()) || - 'project'; +function readOwnerSession(filePath) { + let fd; + try { + fd = fs.openSync(filePath, 'r'); + const buf = Buffer.alloc(512); + const bytes = fs.readSync(fd, buf, 0, buf.length, 0); + const firstLine = buf.toString('utf8', 0, bytes).split(/\r?\n/, 1)[0]; + const m = firstLine.match(/ecc-handoff\s+session=(\S+)/); + return m ? m[1] : null; + } catch { + return null; + } finally { + if (fd !== undefined) { + try { fs.closeSync(fd); } catch { /* already closed / never opened */ } + } + } +} + +/** + * Pick an ownership-safe checkpoint destination under resumeDir for the given + * base name. The first candidate is `.md`; if a candidate already exists + * and is NOT owned by this session (no matching ecc-handoff marker, including + * an unmarked or unreadable file), the gate refuses to target it and tries + * `-2.md`, `-3.md`, … A candidate that does not exist, or that is already + * owned by this session (idempotent re-fire), is returned. Returns null if no + * safe candidate is found within MAX_CHECKPOINT_CANDIDATES — the caller then + * declines rather than overwrite someone else's handoff. + * @param {string} resumeDir + * @param {string} base - `-` + * @param {string} sessionId - sanitized owner id to match against markers + * @returns {string|null} + */ +function pickOwnedDestination(resumeDir, base, sessionId) { + for (let i = 1; i <= MAX_CHECKPOINT_CANDIDATES; i++) { + const name = i === 1 ? `${base}.md` : `${base}-${i}.md`; + const candidate = path.join(resumeDir, name); + let exists; + try { + exists = fs.existsSync(candidate); + } catch { + exists = false; + } + // Free slot: safe to propose. + if (!exists) return candidate; + // Occupied: reuse only when THIS session already owns it (idempotent); + // otherwise step past it so an operator's / another session's handoff is + // never a write target. + if (readOwnerSession(candidate) === sessionId) return candidate; + } + return null; +} + +/** + * Resolve a collision-safe, identity-bearing checkpoint destination under the + * plugin's session-handoff directory, plus the identity it is bound to. + * + * Enforcement requires a REAL handoff identity: a session id resolved from the + * hook input or a session environment override, and a project name resolved + * from the working directory or git repo. There is no literal 'session' / + * 'project' fallback — two owners with no session id must NOT collide on one + * shared path — so when identity cannot be established this returns null and + * the caller declines checkpoint enforcement (never the project root, so an + * operator's own RESUME.md is never a target). + * @param {object} input - Parsed hook stdin ({ cwd, session_id }). + * @param {object} env - Resolved environment (options.env || process.env). + * @returns {{ checkpointPath: string, project: string, sessionId: string }|null} + */ +function resolveCheckpointIdentity(input, env) { 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`); + sanitizeSessionId(env && env.ECC_SESSION_ID) || + sanitizeSessionId(env && env.CLAUDE_SESSION_ID); + if (!sessionId) return null; + const project = + sanitizeSessionId(input && input.cwd ? path.basename(String(input.cwd)) : null) || + sanitizeSessionId(getProjectName()); + if (!project) return null; + const resumeDir = path.join(getSessionsDir(), 'resume'); + const checkpointPath = pickOwnedDestination(resumeDir, `${project}-${sessionId}`, sessionId); + if (!checkpointPath) return null; + return { checkpointPath, project, sessionId }; } /** * Build the checkpoint order injected as additionalContext (enforce mode). + * + * The hook only injects this order; it does not write or verify any file. + * The checkpoint is therefore described as a PROPOSAL — the resume command is + * valid only once the model has written the file and verified it exists and is + * non-empty. The model is instructed to stamp an ownership marker (so a later + * fire can recognize this session's own checkpoint — see readOwnerSession) and + * to bind the handoff to a source revision. * @param {object} params * @param {number} params.pct - Occupancy percent (integer, floored). * @param {number} params.tokens - Context tokens observed. @@ -104,9 +185,11 @@ function resolveCheckpointPath(input) { * @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. + * @param {string} params.sessionId - Owner session id for the marker. + * @param {string} params.project - Project segment for the marker. * @returns {string} */ -function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath }) { +function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath, sessionId, project }) { 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 @@ -140,17 +223,25 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkp 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 the checkpoint to EXACTLY this session-scoped path (create parent directories if needed):', + '2. Write the PROPOSED 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 (the receipt for this handoff):', + ' Make its FIRST line this exact ownership marker, replacing with the current source ' + + 'revision (run `git rev-parse HEAD`; use `unknown` if this is not a git repo) so the handoff bytes ' + + 'are bound to a revision:', + ` `, + ' After the marker 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. After writing, VERIFY the checkpoint file exists and is non-empty. Until that verification ' + + 'succeeds the handoff is only a PROPOSAL — do NOT announce a completed handoff before it does.', + '4. Only once the checkpoint is written and verified, state plainly that this session must now be ' + + 'closed and give the operator this exact resume command on its own line (valid only because the ' + + 'checkpoint above now exists):', ` 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?"), ' + + '5. 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.' ); @@ -158,6 +249,47 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkp return lines.join('\n'); } +/** + * Build the degraded-advisory text injected when enforce mode is on and the + * gate has tripped, but no handoff identity could be established (no session + * id), so no collision-safe checkpoint destination can be bound. + * + * This is NOT silent: the operator opted into enforce, so dropping all + * guidance deep in the context band would hide exactly the warning they asked + * for. Instead the gate declines the automatic checkpoint — it names NO path + * and orders NO write — and tells the operator how to enable it. + * @param {object} params + * @param {number} params.pct + * @param {number} params.tokens + * @param {number} params.windowTokens + * @param {boolean} params.inferred + * @param {boolean} params.emergency + * @returns {string} + */ +function buildDeclineText({ pct, tokens, windowTokens, inferred, emergency }) { + const windowLabel = formatWindowLabel(windowTokens); + const lines = [ + `CONTEXT GATE TRIPPED (enforce mode — operator opted in): context at ${pct}% ` + + `(${tokens.toLocaleString('en-US')} tokens of a ${windowLabel} window${inferred ? ', inferred' : ''}).`, + '', + 'Enforcement is on, but NO session handoff identity is available (no session id), so the gate cannot ' + + 'bind a collision-safe checkpoint destination and WILL NOT guess one. It is declining the automatic ' + + 'checkpoint rather than risk writing over another session\'s handoff.', + '' + ]; + if (emergency) { + lines.push('*** EMERGENCY: past the escalation threshold — the context pressure is still real. ***', ''); + } + lines.push( + '1. Do NOT auto-write a checkpoint to any guessed, shared, or project-root path.', + '2. Bring the unit of work currently in flight to its nearest clean stopping point; do not start new work.', + '3. To enable the automatic, identity-bound checkpoint, the operator should set ECC_SESSION_ID (or run ' + + 'in a harness that provides a session id). Until then, if a handoff is needed, save one explicitly ' + + '(e.g. /save-session) and point the operator at the file they choose — the gate will not pick one.' + ); + return lines.join('\n'); +} + /** * @param {string} rawInput - Raw JSON string from stdin * @param {object} [options] - Runner metadata from run-with-flags.js @@ -192,14 +324,36 @@ function run(rawInput, options = {}) { if (pct < gatePct) return ''; const emergency = pct >= emergencyPct; - const checkpointPath = resolveCheckpointPath(input); + + // Enforcement requires a real handoff identity. When none can be + // established, decline the automatic checkpoint (degraded advisory) rather + // than bind a collision-prone shared path. + const identity = resolveCheckpointIdentity(input, env); + if (!identity) { + return JSON.stringify({ + systemMessage: + `[context-gate] ${pct}% of ${formatWindowLabel(windowTokens)} window used` + + `${inferred ? ' (window size inferred)' : ''}${emergency ? ' (EMERGENCY)' : ''}. ` + + 'Enforce mode is on but no session identity is available, so no checkpoint destination can be ' + + 'safely bound. Set ECC_SESSION_ID to enable the automatic checkpoint; Claude has been told to ' + + 'reach a clean stopping point and not to auto-write a handoff.', + hookSpecificOutput: { + hookEventName: 'UserPromptSubmit', + additionalContext: buildDeclineText({ pct, tokens: latest.tokens, windowTokens, inferred, emergency }) + } + }); + } + + const { checkpointPath, project, sessionId } = identity; const orderText = buildOrderText({ pct, tokens: latest.tokens, windowTokens, inferred, emergency, - checkpointPath + checkpointPath, + sessionId, + project }); return JSON.stringify({ diff --git a/tests/hooks/context-gate.test.js b/tests/hooks/context-gate.test.js index a234628e1..74f466246 100644 --- a/tests/hooks/context-gate.test.js +++ b/tests/hooks/context-gate.test.js @@ -135,13 +135,22 @@ function runTests() { if ( test('order forbids asking to stop and demands a resume command', () => { 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 }); + const text = buildOrderText({ pct: 91, tokens: 910000, windowTokens: 1000000, inferred: false, emergency: false, checkpointPath: cp, sessionId: 'abc123', project: 'myproj' }); assert.ok(text.includes('Do NOT ask whether to stop')); 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')); + // Proposal framing: the hook writes nothing, so it must NOT claim a + // completed handoff "receipt". The resume command is gated on a verify + // step, and the checkpoint carries an ownership marker bound to this + // session plus a source revision. + assert.ok(!text.toLowerCase().includes('receipt'), 'must not claim a completed receipt'); + assert.ok(text.includes('PROPOSED')); + assert.ok(text.includes('VERIFY the checkpoint file exists and is non-empty')); + assert.ok(text.includes('ecc-handoff session=abc123 project=myproj')); + assert.ok(text.includes('source-rev=')); }) ) passed++; @@ -329,6 +338,10 @@ function runTests() { console.log('\nhandoff checkpoint ownership (enforce mode):'); + // This case only proves the order never points at a project-root RESUME.md + // (a file the hook never writes). Ownership of the SELECTED checkpoint file — + // the real collision surface — is exercised by the identity/disambiguation + // cases that follow. 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-')); @@ -369,6 +382,112 @@ function runTests() { passed++; else failed++; + if ( + test('missing identity: same-named projects never collide on a shared destination', () => { + // Sandbox the handoff home so the fire touches tmp only. ECC_AGENT_DATA_HOME + // is read by getSessionsDir() from process.env, so it must be set there. + const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-gate-home-')); + const resumeDir = path.join(sandbox, 'session-data', 'resume'); + fs.mkdirSync(resumeDir, { recursive: true }); + // A pre-existing handoff at the exact path the OLD literal-fallback code + // produced for any unidentified session ("project-session.md"). + const seeded = path.join(resumeDir, 'project-session.md'); + const original = 'OWNER-A HANDOFF — must survive\n'; + fs.writeFileSync(seeded, original, 'utf8'); + const t = writeTranscript(950000); + cleanup.push(t); + const prevHome = process.env.ECC_AGENT_DATA_HOME; + const prevSid = process.env.ECC_SESSION_ID; + const prevCsid = process.env.CLAUDE_SESSION_ID; + try { + process.env.ECC_AGENT_DATA_HOME = sandbox; + delete process.env.ECC_SESSION_ID; + delete process.env.CLAUDE_SESSION_ID; + // Two different owners, same basename "project", NO session id. + const envEnforce = { ECC_CONTEXT_GATE_MODE: 'enforce' }; + const outA = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/tmp/owner-a/project', prompt: 'go' }), { env: envEnforce })); + const outB = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/tmp/owner-b/project', prompt: 'go' }), { env: envEnforce })); + for (const out of [outA, outB]) { + const ctx = out.hookSpecificOutput.additionalContext; + // Enforcement declined: NO checkpoint path is named... + assert.ok(!/[/\\]resume[/\\]\S*\.md/.test(ctx), `decline must name no checkpoint path. Got: ${ctx}`); + // ...but the operator still gets actionable guidance (not silent). + assert.ok(ctx.includes('ECC_SESSION_ID'), 'decline must tell the operator how to enable it'); + assert.ok(ctx.includes('Do NOT auto-write'), 'decline must forbid a guessed write'); + } + // The pre-existing handoff survives byte-for-byte. + assert.strictEqual(fs.readFileSync(seeded, 'utf8'), original); + } finally { + if (prevHome === undefined) delete process.env.ECC_AGENT_DATA_HOME; + else process.env.ECC_AGENT_DATA_HOME = prevHome; + if (prevSid === undefined) delete process.env.ECC_SESSION_ID; + else process.env.ECC_SESSION_ID = prevSid; + if (prevCsid === undefined) delete process.env.CLAUDE_SESSION_ID; + else process.env.CLAUDE_SESSION_ID = prevCsid; + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }) + ) + passed++; + else failed++; + + if ( + test('a destination owned by a different session is disambiguated, not overwritten', () => { + const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-gate-home-')); + const resumeDir = path.join(sandbox, 'session-data', 'resume'); + fs.mkdirSync(resumeDir, { recursive: true }); + // Seed the exact path this session resolves to, owned by ANOTHER session. + const taken = path.join(resumeDir, 'demoproj-mysess.md'); + const foreign = '\nFOREIGN\n'; + fs.writeFileSync(taken, foreign, 'utf8'); + const t = writeTranscript(950000); + cleanup.push(t); + const prevHome = process.env.ECC_AGENT_DATA_HOME; + try { + process.env.ECC_AGENT_DATA_HOME = sandbox; + const out = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/x/demoproj', session_id: 'mysess', prompt: 'go' }), { env: { ECC_CONTEXT_GATE_MODE: 'enforce' } })); + const ctx = out.hookSpecificOutput.additionalContext; + // Targets a disambiguated sibling, never the foreign file. + assert.ok(ctx.includes('demoproj-mysess-2.md'), `expected disambiguated path. Got: ${ctx}`); + assert.ok(!ctx.includes(taken), 'must not target another session\'s handoff'); + // Foreign handoff survives byte-for-byte. + assert.strictEqual(fs.readFileSync(taken, 'utf8'), foreign); + } finally { + if (prevHome === undefined) delete process.env.ECC_AGENT_DATA_HOME; + else process.env.ECC_AGENT_DATA_HOME = prevHome; + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }) + ) + passed++; + else failed++; + + if ( + test('a destination owned by the same session is reused (idempotent)', () => { + const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-gate-home-')); + const resumeDir = path.join(sandbox, 'session-data', 'resume'); + fs.mkdirSync(resumeDir, { recursive: true }); + const own = path.join(resumeDir, 'demoproj-mysess.md'); + fs.writeFileSync(own, '\nMINE\n', 'utf8'); + const t = writeTranscript(950000); + cleanup.push(t); + const prevHome = process.env.ECC_AGENT_DATA_HOME; + try { + process.env.ECC_AGENT_DATA_HOME = sandbox; + const out = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/x/demoproj', session_id: 'mysess', prompt: 'go' }), { env: { ECC_CONTEXT_GATE_MODE: 'enforce' } })); + const ctx = out.hookSpecificOutput.additionalContext; + assert.ok(ctx.includes(own), 'this session must reuse its own checkpoint'); + assert.ok(!ctx.includes('demoproj-mysess-2.md'), 'must not disambiguate away from its own file'); + } finally { + if (prevHome === undefined) delete process.env.ECC_AGENT_DATA_HOME; + else process.env.ECC_AGENT_DATA_HOME = prevHome; + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }) + ) + passed++; + else failed++; + for (const file of cleanup) { try { fs.unlinkSync(file);