mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 00:05:27 +00:00
fix(hooks): harden context-gate checkpoint ownership (#3106)
Maintainer carry-forward of the four edge cases reproduced on5a565cf: - Same-named project roots: bind the proposal to a SHA-256 owner key of the full real project root plus the raw session ID, and put that key in both the file name and the ownership marker. - Sanitized session-ID aliasing: hash the raw session ID before filename sanitization so IDs such as owner/a and owner?a no longer share a path. - Linked or special destinations: probe with lstat, open read-only with O_NOFOLLOW and O_NONBLOCK, require a regular single-link file whose complete first-line marker matches, and decline linked handoff directories. A FIFO at the destination previously hung the prompt. - Literal resume arguments: emit the resume prompt as one single-quoted POSIX (or PowerShell on Windows) argument. Also merge the UserPromptSubmit registration into the existing event array. The main merge left a duplicate UserPromptSubmit key in hooks.json and hooks.metadata.json, and JSON.parse kept only the last, which silently dropped prompt:hookify-runtime. Adds tests/hooks/context-gate-ownership.test.js, which fires the hook through the registered run-with-flags.js entry: 12/12 pass here, 1/12 pass on5a565cf.
This commit is contained in:
5 files changed
+404
-121
No files matched your search
+9
-11
@@ -111,6 +111,15 @@
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const s=p.join(r,'scripts/hooks/plugin-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=r;process.argv.splice(1,0,s);require(s)\" node scripts/hooks/run-with-flags.js user-prompt:context-gate scripts/hooks/context-gate.js standard,strict",
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
@@ -286,17 +295,6 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const s=p.join(r,'scripts/hooks/plugin-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=r;process.argv.splice(1,0,s);require(s)\" node scripts/hooks/run-with-flags.js user-prompt:context-gate scripts/hooks/context-gate.js standard,strict",
|
||||
"timeout": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,11 @@
|
||||
"id": "prompt:hookify-runtime",
|
||||
"description": "Evaluate project-local Hookify prompt rules before a user prompt is processed",
|
||||
"fingerprint": "e59b2f099bf7"
|
||||
},
|
||||
{
|
||||
"id": "user-prompt:context-gate",
|
||||
"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"
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
@@ -151,13 +156,6 @@
|
||||
"description": "Session end lifecycle marker (non-blocking)",
|
||||
"fingerprint": "a991d34f4d89"
|
||||
}
|
||||
],
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"id": "user-prompt:context-gate",
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@
|
||||
* 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.
|
||||
* deterministic protocol by setting ECC_CONTEXT_GATE_MODE=enforce. This is
|
||||
* prompt guidance; it does not block tools, reserve a path, or close the host session.
|
||||
*
|
||||
* In enforce mode: at >=90% context-window occupancy (measured from the
|
||||
* latest assistant `usage` record in the session transcript, same signal as
|
||||
@@ -20,10 +21,10 @@
|
||||
*
|
||||
* The checkpoint is written to a collision-safe, identity-bearing path under
|
||||
* the plugin's session-handoff directory
|
||||
* (<getSessionsDir()>/resume/<project>-<sessionId>.md) — NOT the project
|
||||
* (<getSessionsDir()>/resume/<project>-<ownerDigest>-<sessionId>.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.
|
||||
* command is a proposed continuation instruction, never a durable handoff receipt.
|
||||
*
|
||||
* Why an order instead of a suggestion (contrast with suggest-compact and
|
||||
* ecc-context-monitor, which advise and ask):
|
||||
@@ -69,104 +70,93 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
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');
|
||||
const { getSessionsDir, sanitizeSessionId } = require('../lib/utils');
|
||||
|
||||
/** Max disambiguation attempts before declining rather than guess a path. */
|
||||
const MAX_CHECKPOINT_CANDIDATES = 50;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Read-only proposal ownership, never a reservation or permission grant.
|
||||
* Symlinks and special files are occupied. Read errors decline this slot.
|
||||
*/
|
||||
function readOwnerSession(filePath) {
|
||||
function matchesOwner(candidate, observed, identity) {
|
||||
if (!observed.isFile() || observed.isSymbolicLink() || observed.nlink !== 1) return false;
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(filePath, 'r');
|
||||
fd = fs.openSync(candidate, fs.constants.O_RDONLY |
|
||||
(fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
|
||||
const opened = fs.fstatSync(fd);
|
||||
if (!opened.isFile() || opened.dev !== observed.dev || opened.ino !== observed.ino) return false;
|
||||
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;
|
||||
const marker = /^<!-- ecc-handoff owner=([a-f0-9]{64}) session=([A-Za-z0-9_-]+) project=([A-Za-z0-9_-]+) source-rev=(?:[a-f0-9]{40}|[a-f0-9]{64}|unknown) -->$/.exec(firstLine);
|
||||
return Boolean(marker && marker[1] === identity.ownerKey &&
|
||||
marker[2] === identity.sessionId && marker[3] === identity.project);
|
||||
} catch {
|
||||
return null;
|
||||
return false;
|
||||
} finally {
|
||||
if (fd !== undefined) {
|
||||
try { fs.closeSync(fd); } catch { /* already closed / never opened */ }
|
||||
}
|
||||
if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* read-only probe */ } }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick an ownership-safe checkpoint destination under resumeDir for the given
|
||||
* base name. The first candidate is `<base>.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
|
||||
* `<base>-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 - `<project>-<sessionId>`
|
||||
* @param {string} sessionId - sanitized owner id to match against markers
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function pickOwnedDestination(resumeDir, base, sessionId) {
|
||||
function safeDirectoryOrMissing(directory) {
|
||||
try {
|
||||
const st = fs.lstatSync(directory);
|
||||
return st.isDirectory() && !st.isSymbolicLink();
|
||||
} catch (error) {
|
||||
return error.code === 'ENOENT';
|
||||
}
|
||||
}
|
||||
|
||||
function pickOwnedDestination(resumeDir, base, identity) {
|
||||
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;
|
||||
const candidate = path.join(resumeDir, i === 1 ? `${base}.md` : `${base}-${i}.md`);
|
||||
let observed;
|
||||
try { observed = fs.lstatSync(candidate); }
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT') return candidate;
|
||||
return null; // An unreadable destination is not a free slot.
|
||||
}
|
||||
// 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;
|
||||
if (matchesOwner(candidate, observed, identity)) 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}
|
||||
*/
|
||||
/** Bind proposal identity to full project root and raw session, before filename sanitization. */
|
||||
function resolveCheckpointIdentity(input, env) {
|
||||
const sessionId =
|
||||
sanitizeSessionId(input && input.session_id) ||
|
||||
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 };
|
||||
const rawSession = [input && input.session_id, env && env.ECC_SESSION_ID, env && env.CLAUDE_SESSION_ID]
|
||||
.find(value => typeof value === 'string' && sanitizeSessionId(value));
|
||||
if (!rawSession) return null;
|
||||
const suppliedRoot = input && input.cwd;
|
||||
if (suppliedRoot !== undefined && (typeof suppliedRoot !== 'string' || !path.isAbsolute(suppliedRoot))) return null;
|
||||
let projectRoot = suppliedRoot || process.cwd();
|
||||
try { projectRoot = fs.realpathSync(projectRoot); }
|
||||
catch (error) { if (error.code !== 'ENOENT') return null; }
|
||||
const project = sanitizeSessionId(path.basename(projectRoot));
|
||||
const sessionId = sanitizeSessionId(rawSession);
|
||||
if (!project || !sessionId) return null;
|
||||
const ownerKey = crypto.createHash('sha256').update(JSON.stringify([projectRoot, rawSession])).digest('hex');
|
||||
const sessionsDir = getSessionsDir();
|
||||
const resumeDir = path.join(sessionsDir, 'resume');
|
||||
if (Array.from(resumeDir).some(char => char.codePointAt(0) < 32 || char.codePointAt(0) === 127) ||
|
||||
!safeDirectoryOrMissing(sessionsDir) || !safeDirectoryOrMissing(resumeDir)) return null;
|
||||
const identity = { project: project.slice(0, 64), sessionId: sessionId.slice(0, 64), ownerKey };
|
||||
const base = `${identity.project}-${ownerKey.slice(0, 32)}-${identity.sessionId}`;
|
||||
const checkpointPath = pickOwnedDestination(resumeDir, base, identity);
|
||||
return checkpointPath ? { checkpointPath, ...identity } : null;
|
||||
}
|
||||
|
||||
/** POSIX shells or PowerShell on Windows; the entire prompt is one literal argument. */
|
||||
function resumeCommand(checkpointPath) {
|
||||
const prompt = `Read ${checkpointPath} and continue the work described there.`;
|
||||
const quoted = process.platform === 'win32'
|
||||
? `'${prompt.replace(/['\u2018-\u201B]/g, '$&$&')}'`
|
||||
: `'${prompt.replace(/'/g, "'\\''")}'`;
|
||||
return `claude ${quoted}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -176,8 +166,8 @@ function resolveCheckpointIdentity(input, env) {
|
||||
* 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.
|
||||
* fire can recognize this session's own checkpoint; see matchesOwner) and
|
||||
* to record source revision metadata without claiming a content-bound receipt.
|
||||
* @param {object} params
|
||||
* @param {number} params.pct - Occupancy percent (integer, floored).
|
||||
* @param {number} params.tokens - Context tokens observed.
|
||||
@@ -189,7 +179,7 @@ function resolveCheckpointIdentity(input, env) {
|
||||
* @param {string} params.project - Project segment for the marker.
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath, sessionId, project }) {
|
||||
function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath, sessionId, project, ownerKey }) {
|
||||
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
|
||||
@@ -224,12 +214,15 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkp
|
||||
'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 PROPOSED checkpoint to EXACTLY this session-scoped path (create parent directories if ' +
|
||||
'needed):',
|
||||
'needed). This path is a read-only proposal, not an atomic reservation. At write time reject ' +
|
||||
'symlinks or special files and recheck parent directories and the complete ownership marker. ' +
|
||||
'For a new file use exclusive creation; on any collision or failed verification preserve the ' +
|
||||
'existing file and report that the proposed checkpoint could not be saved:',
|
||||
` ${checkpointPath}`,
|
||||
' Make its FIRST line this exact ownership marker, replacing <GIT_HEAD> 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:',
|
||||
` <!-- ecc-handoff session=${sessionId} project=${project} source-rev=<GIT_HEAD> -->`,
|
||||
'revision (run `git rev-parse HEAD`; use `unknown` if this is not a git repo) as source metadata. ' +
|
||||
'This marker does not verify content or create a durable receipt:',
|
||||
` <!-- ecc-handoff owner=${ownerKey} session=${sessionId} project=${project} source-rev=<GIT_HEAD> -->`,
|
||||
' 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 ' +
|
||||
@@ -240,7 +233,8 @@ function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkp
|
||||
'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."`,
|
||||
` ${resumeCommand(checkpointPath)}`,
|
||||
...(process.platform === 'win32' ? [' Run this command in PowerShell.'] : []),
|
||||
'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.'
|
||||
@@ -272,7 +266,7 @@ function buildDeclineText({ pct, tokens, windowTokens, inferred, emergency }) {
|
||||
`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 ' +
|
||||
'Enforcement is on, but no safe project/session destination is available, 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.',
|
||||
''
|
||||
@@ -283,9 +277,9 @@ function buildDeclineText({ pct, tokens, windowTokens, inferred, emergency }) {
|
||||
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.'
|
||||
'3. Check the current project, session identity (ECC_SESSION_ID where appropriate), and ownership of ' +
|
||||
'the configured handoff destination. If no safe destination is available, save a handoff explicitly ' +
|
||||
'(e.g. /save-session) and point the operator at the file they choose; the gate will not guess one.'
|
||||
);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -334,8 +328,8 @@ function run(rawInput, options = {}) {
|
||||
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 ' +
|
||||
'Enforce mode is on but the project/session identity or destination is unavailable, so no checkpoint destination can be ' +
|
||||
'safely bound. Check the project, ECC_SESSION_ID and destination ownership; Claude has been told to ' +
|
||||
'reach a clean stopping point and not to auto-write a handoff.',
|
||||
hookSpecificOutput: {
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
@@ -344,7 +338,7 @@ function run(rawInput, options = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
const { checkpointPath, project, sessionId } = identity;
|
||||
const { checkpointPath, project, sessionId, ownerKey } = identity;
|
||||
const orderText = buildOrderText({
|
||||
pct,
|
||||
tokens: latest.tokens,
|
||||
@@ -353,7 +347,8 @@ function run(rawInput, options = {}) {
|
||||
emergency,
|
||||
checkpointPath,
|
||||
sessionId,
|
||||
project
|
||||
project,
|
||||
ownerKey
|
||||
});
|
||||
|
||||
return JSON.stringify({
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Registered-hook ownership regressions for scripts/hooks/context-gate.js.
|
||||
*
|
||||
* Each case fires the gate through the same run-with-flags.js entry that
|
||||
* hooks/hooks.json registers, inside a disposable ECC_AGENT_DATA_HOME. The
|
||||
* hook only proposes a checkpoint path; these cases check that the proposal
|
||||
* never lands on another owner's file, a link, or a special file, and that
|
||||
* the resume command survives the shell as one literal argument.
|
||||
*
|
||||
* Run with: node tests/hooks/context-gate-ownership.test.js
|
||||
*/
|
||||
|
||||
const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..');
|
||||
const RUNNER = path.join(REPO_ROOT, 'scripts', 'hooks', 'run-with-flags.js');
|
||||
const UNSUPPORTED_LINK_CODES = new Set(['EPERM', 'EACCES', 'ENOSYS', 'ENOTSUP']);
|
||||
|
||||
function test(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(` ✓ ${name}`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.log(` ✗ ${name}`);
|
||||
console.log(` Error: ${err.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function createSandbox() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-context-gate-owner-'));
|
||||
const dataHome = path.join(root, 'data');
|
||||
const resumeDir = path.join(dataHome, 'session-data', 'resume');
|
||||
fs.mkdirSync(resumeDir, { recursive: true });
|
||||
const transcript = path.join(root, 'usage.jsonl');
|
||||
fs.writeFileSync(transcript, JSON.stringify({ message: { model: 'claude-test', usage: { input_tokens: 185000 } } }) + '\n');
|
||||
const env = {
|
||||
...process.env,
|
||||
HOME: path.join(root, 'home'),
|
||||
USERPROFILE: path.join(root, 'home'),
|
||||
ECC_AGENT_DATA_HOME: dataHome,
|
||||
ECC_CONTEXT_GATE_MODE: 'enforce',
|
||||
ECC_CONTEXT_WINDOW_TOKENS: '200000',
|
||||
ECC_HOOK_PROFILE: 'standard'
|
||||
};
|
||||
delete env.ECC_SESSION_ID;
|
||||
delete env.CLAUDE_SESSION_ID;
|
||||
delete env.ECC_DISABLED_HOOKS;
|
||||
return { root, resumeDir, transcript, env };
|
||||
}
|
||||
|
||||
function fire(sandbox, extra = {}) {
|
||||
const input = { cwd: '/tmp/owner-a/project', session_id: 'mysess', transcript_path: sandbox.transcript, ...extra };
|
||||
const result = spawnSync(process.execPath, [RUNNER, 'user-prompt:context-gate', 'scripts/hooks/context-gate.js', 'standard,strict'], {
|
||||
cwd: REPO_ROOT,
|
||||
env: sandbox.env,
|
||||
input: JSON.stringify(input),
|
||||
encoding: 'utf8',
|
||||
timeout: 5000
|
||||
});
|
||||
if (result.error) return { timeout: result.error.code };
|
||||
const text = JSON.parse(result.stdout).hookSpecificOutput.additionalContext;
|
||||
const lines = text.split('\n');
|
||||
const target = lines.find(line => /^\s+[/\\].*\.md$/.test(line));
|
||||
const marker = lines.find(line => line.includes('<!-- ecc-handoff'));
|
||||
return { text, target: target && target.trim(), marker: marker && marker.trim() };
|
||||
}
|
||||
|
||||
function clearResumeDir(sandbox) {
|
||||
for (const name of fs.readdirSync(sandbox.resumeDir)) {
|
||||
const entry = path.join(sandbox.resumeDir, name);
|
||||
// rmSync({ force }) can skip a dangling symlink, so unlink non-directories directly.
|
||||
if (fs.lstatSync(entry).isDirectory()) fs.rmSync(entry, { recursive: true, force: true });
|
||||
else fs.unlinkSync(entry);
|
||||
}
|
||||
}
|
||||
|
||||
function canLink(sandbox, kind) {
|
||||
const probe = path.join(sandbox.root, `probe-${kind}`);
|
||||
const source = path.join(sandbox.root, 'probe-source');
|
||||
fs.writeFileSync(source, 'probe');
|
||||
try {
|
||||
if (kind === 'symlink') fs.symlinkSync(source, probe);
|
||||
else fs.linkSync(source, probe);
|
||||
fs.unlinkSync(probe);
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (UNSUPPORTED_LINK_CODES.has(err.code)) return false;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function ownMarker(fired) {
|
||||
return fired.marker.replace('<GIT_HEAD>', 'a'.repeat(40));
|
||||
}
|
||||
|
||||
function runTests() {
|
||||
console.log('\n=== Testing context-gate checkpoint ownership (registered hook) ===\n');
|
||||
|
||||
const sandbox = createSandbox();
|
||||
const symlinks = canLink(sandbox, 'symlink');
|
||||
const hardlinks = canLink(sandbox, 'hardlink');
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
const record = ok => {
|
||||
if (ok) passed++;
|
||||
else failed++;
|
||||
};
|
||||
|
||||
try {
|
||||
record(test('same-named project roots get distinct proposals', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const a = fire(sandbox);
|
||||
const b = fire(sandbox, { cwd: '/tmp/owner-b/project' });
|
||||
assert.ok(a.target && b.target, 'both fires should propose a destination');
|
||||
assert.notStrictEqual(a.target, b.target);
|
||||
}));
|
||||
|
||||
record(test('session IDs that sanitize alike get distinct proposals', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const a = fire(sandbox, { session_id: 'owner/a' });
|
||||
const b = fire(sandbox, { session_id: 'owner?a' });
|
||||
assert.ok(a.target && b.target, 'both fires should propose a destination');
|
||||
assert.notStrictEqual(a.target, b.target);
|
||||
}));
|
||||
|
||||
record(test('a marker from another project is preserved and not reused', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
const foreign = '<!-- ecc-handoff session=mysess project=OTHER source-rev=deadbeef -->\nFOREIGN PROJECT\n';
|
||||
fs.writeFileSync(first.target, foreign);
|
||||
const again = fire(sandbox);
|
||||
assert.notStrictEqual(again.target, first.target);
|
||||
assert.strictEqual(fs.readFileSync(first.target, 'utf8'), foreign);
|
||||
}));
|
||||
|
||||
record(test('the exact complete owner marker is reused', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
fs.writeFileSync(first.target, ownMarker(first) + '\nOWN\n');
|
||||
assert.strictEqual(fire(sandbox).target, first.target);
|
||||
}));
|
||||
|
||||
record(test('a complete marker naming another project is not reused', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
fs.writeFileSync(first.target, ownMarker(first).replace('project=project', 'project=OTHER') + '\nOTHER\n');
|
||||
assert.notStrictEqual(fire(sandbox).target, first.target);
|
||||
}));
|
||||
|
||||
record(test('a marker that is not the first line is not ownership', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
fs.writeFileSync(first.target, 'ordinary text ' + ownMarker(first) + '\nUNMARKED\n');
|
||||
assert.notStrictEqual(fire(sandbox).target, first.target);
|
||||
}));
|
||||
|
||||
if (symlinks) {
|
||||
record(test('a live symlink at the destination is never targeted', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
const outside = path.join(sandbox.root, 'outside.md');
|
||||
const outsideBytes = ownMarker(first) + '\nOUTSIDE\n';
|
||||
fs.writeFileSync(outside, outsideBytes);
|
||||
fs.symlinkSync(outside, first.target);
|
||||
assert.notStrictEqual(fire(sandbox).target, first.target);
|
||||
assert.strictEqual(fs.readFileSync(outside, 'utf8'), outsideBytes);
|
||||
}));
|
||||
|
||||
record(test('a dangling symlink at the destination is never targeted', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
fs.symlinkSync(path.join(sandbox.root, 'absent.md'), first.target);
|
||||
assert.notStrictEqual(fire(sandbox).target, first.target);
|
||||
}));
|
||||
|
||||
record(test('a linked handoff directory declines the checkpoint', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const outsideDir = path.join(sandbox.root, 'outside-dir');
|
||||
fs.mkdirSync(outsideDir);
|
||||
fs.rmdirSync(sandbox.resumeDir);
|
||||
fs.symlinkSync(outsideDir, sandbox.resumeDir);
|
||||
try {
|
||||
const fired = fire(sandbox);
|
||||
assert.strictEqual(fired.target, undefined);
|
||||
assert.ok(fired.text.includes('Do NOT auto-write'));
|
||||
} finally {
|
||||
fs.unlinkSync(sandbox.resumeDir);
|
||||
fs.mkdirSync(sandbox.resumeDir);
|
||||
}
|
||||
}));
|
||||
} else {
|
||||
skipped += 3;
|
||||
}
|
||||
|
||||
if (hardlinks) {
|
||||
record(test('a multiply linked owner file is never targeted', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
const outside = path.join(sandbox.root, 'outside-owned.md');
|
||||
fs.writeFileSync(outside, ownMarker(first) + '\nOUTSIDE OWNER\n');
|
||||
fs.linkSync(outside, first.target);
|
||||
assert.notStrictEqual(fire(sandbox).target, first.target);
|
||||
}));
|
||||
} else {
|
||||
skipped++;
|
||||
}
|
||||
|
||||
const mkfifo = process.platform === 'win32' ? null : spawnSync('mkfifo', [path.join(sandbox.root, 'probe-fifo')]);
|
||||
if (mkfifo && mkfifo.status === 0) {
|
||||
record(test('a FIFO at the destination does not block the prompt', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const first = fire(sandbox);
|
||||
assert.strictEqual(spawnSync('mkfifo', [first.target]).status, 0);
|
||||
const again = fire(sandbox);
|
||||
assert.ok(!again.timeout, 'hook must not hang on a FIFO');
|
||||
assert.ok(again.target && again.target !== first.target);
|
||||
}));
|
||||
} else {
|
||||
skipped++;
|
||||
}
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
record(test('the resume prompt reaches the shell as one literal argument', () => {
|
||||
clearResumeDir(sandbox);
|
||||
const quotedHome = path.join(sandbox.root, "data '$(__ecc_quote_probe__) `literal`");
|
||||
const env = { ...sandbox.env, ECC_AGENT_DATA_HOME: quotedHome };
|
||||
const fired = fire({ ...sandbox, env });
|
||||
const command = fired.text.split('\n').find(line => line.trim().startsWith('claude ')).trim();
|
||||
const shell = spawnSync('/bin/sh', ['-c', 'claude(){ printf "%s" "$1"; }; ' + command], {
|
||||
cwd: sandbox.root,
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
timeout: 2000
|
||||
});
|
||||
assert.strictEqual(shell.status, 0, shell.stderr);
|
||||
assert.strictEqual(shell.stdout, `Read ${fired.target} and continue the work described there.`);
|
||||
}));
|
||||
} else {
|
||||
skipped++;
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(sandbox.root, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}, Skipped: ${skipped}`);
|
||||
process.exit(failed > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -8,6 +8,7 @@ const assert = require('assert');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
const { spawnSync } = require('child_process');
|
||||
|
||||
const { run, buildOrderText, resolvePct, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT } = require('../../scripts/hooks/context-gate');
|
||||
|
||||
@@ -133,11 +134,11 @@ function runTests() {
|
||||
else failed++;
|
||||
|
||||
if (
|
||||
test('order forbids asking to stop and demands a resume command', () => {
|
||||
test('order forbids asking to stop and demands a single-quoted 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, sessionId: 'abc123', project: 'myproj' });
|
||||
const text = buildOrderText({ pct: 91, tokens: 910000, windowTokens: 1000000, inferred: false, emergency: false, checkpointPath: cp, sessionId: 'abc123', project: 'myproj', ownerKey: 'a'.repeat(64) });
|
||||
assert.ok(text.includes('Do NOT ask whether to stop'));
|
||||
assert.ok(text.includes(`claude "Read ${cp} and continue`));
|
||||
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.
|
||||
@@ -146,16 +147,46 @@ function runTests() {
|
||||
// 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('does not verify content or create a durable receipt'));
|
||||
assert.ok(text.includes('not an atomic reservation'));
|
||||
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('ecc-handoff owner=' + 'a'.repeat(64) + ' session=abc123 project=myproj'));
|
||||
assert.ok(text.includes('source-rev='));
|
||||
})
|
||||
)
|
||||
passed++;
|
||||
else failed++;
|
||||
|
||||
if (
|
||||
test('PowerShell resume prompt preserves typographic quotes as one literal argument', () => {
|
||||
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
|
||||
const checkpointPath = "C:\\data\\\u2018a\u2019\u201Ab\u201B; Write-Output INJECTED; $env:PATH `n\\it's.md";
|
||||
let text;
|
||||
try {
|
||||
Object.defineProperty(process, 'platform', { ...originalPlatform, value: 'win32' });
|
||||
text = buildOrderText({ pct: 91, tokens: 910000, windowTokens: 1000000,
|
||||
inferred: false, emergency: false, checkpointPath,
|
||||
sessionId: 'abc123', project: 'myproj', ownerKey: 'a'.repeat(64) });
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', originalPlatform);
|
||||
}
|
||||
const command = text.split('\n').find(line => line.trim().startsWith('claude ')).trim();
|
||||
assert.ok(command.includes('\u2018\u2018a\u2019\u2019\u201A\u201Ab\u201B\u201B'));
|
||||
assert.ok(text.includes('Run this command in PowerShell.'));
|
||||
const shell = process.env.ECC_TEST_PWSH_PATH;
|
||||
if (shell) {
|
||||
const invocation = `function claude { param([string]$Prompt) ($Prompt.ToCharArray() | ForEach-Object { [int]$_ }) -join ',' }; ${command}`;
|
||||
const result = spawnSync(shell, ['-NoProfile', '-Command', invocation], { encoding: 'utf8', timeout: 15000 });
|
||||
assert.strictEqual(result.status, 0, result.stderr);
|
||||
const expected = `Read ${checkpointPath} and continue the work described there.`;
|
||||
assert.strictEqual(result.stdout.trim(), Array.from(expected, ch => ch.charCodeAt(0)).join(','));
|
||||
}
|
||||
})
|
||||
)
|
||||
passed++;
|
||||
else failed++;
|
||||
|
||||
if (
|
||||
test('inferred window softens the order to a strong recommendation', () => {
|
||||
// Unknown model at 185k → 200k window assumed (92%), but the true
|
||||
@@ -437,18 +468,20 @@ function runTests() {
|
||||
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');
|
||||
let taken;
|
||||
const foreign = '<!-- ecc-handoff session=othersess project=demoproj source-rev=deadbeef -->\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 first = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/x/demoproj', session_id: 'mysess' }), { env: { ECC_CONTEXT_GATE_MODE: 'enforce' } })).hookSpecificOutput.additionalContext;
|
||||
taken = first.split('\n').find(line => /^\s+[/\\].*\.md$/.test(line)).trim();
|
||||
fs.writeFileSync(taken, foreign, 'utf8');
|
||||
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.replace(/\.md$/, '-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);
|
||||
@@ -467,17 +500,20 @@ function runTests() {
|
||||
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, '<!-- ecc-handoff session=mysess project=demoproj source-rev=abc123 -->\nMINE\n', 'utf8');
|
||||
let own;
|
||||
const t = writeTranscript(950000);
|
||||
cleanup.push(t);
|
||||
const prevHome = process.env.ECC_AGENT_DATA_HOME;
|
||||
try {
|
||||
process.env.ECC_AGENT_DATA_HOME = sandbox;
|
||||
const first = JSON.parse(run(JSON.stringify({ transcript_path: t, cwd: '/x/demoproj', session_id: 'mysess' }), { env: { ECC_CONTEXT_GATE_MODE: 'enforce' } })).hookSpecificOutput.additionalContext;
|
||||
own = first.split('\n').find(line => /^\s+[/\\].*\.md$/.test(line)).trim();
|
||||
const marker = first.split('\n').find(line => line.includes('<!-- ecc-handoff')).trim().replace('<GIT_HEAD>', 'a'.repeat(40));
|
||||
fs.writeFileSync(own, marker + '\nMINE\n', 'utf8');
|
||||
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');
|
||||
assert.ok(!ctx.includes(own.replace(/\.md$/, '-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;
|
||||
|
||||
Reference in new issue
Block a user