mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-23 16:25:30 +00:00
fix(hooks): bind context-gate checkpoint to real identity; frame handoff as a proposal
Round-6 ownership revision for the enforce-mode checkpoint (PR #3106,
@haelyra requested-changes on fffda19).
1. Require real handoff identity, preserve an occupied destination.
- resolveCheckpointPath -> resolveCheckpointIdentity: drops the literal
'project'/'session' fallbacks. A session id (input.session_id or a
session env override) AND a project are now required; when neither
resolves it returns null and the hook declines enforcement, so two
same-named projects with no session id can no longer collide on one
shared <sessions>/resume/project-session.md path.
- New pickOwnedDestination + readOwnerSession: before targeting an
existing destination the gate checks an ecc-handoff ownership marker.
A file owned by this session is reused (idempotent); an unmarked,
unreadable, or foreign-owned file is never overwritten — the gate
disambiguates to a sibling (-2, -3, ...) or declines.
- Missing-identity fire now emits a degraded advisory (buildDeclineText):
it names no checkpoint path and orders no write, but still warns and
tells the operator to set ECC_SESSION_ID — not a silent drop.
2. Report a proposed handoff until a write is verified.
- buildOrderText no longer calls the resume command a completed "receipt".
The checkpoint is a PROPOSAL; the resume command is gated on an explicit
"verify the file exists and is non-empty" step. The model is instructed
to stamp the exact ownership marker (session+project) and record the
source revision (git rev-parse HEAD), binding the handoff to a revision.
Tests: existing buildOrderText case extended for proposal framing; three new
disposable, sandboxed (ECC_AGENT_DATA_HOME) ownership cases — missing-identity
same-named projects with a pre-existing destination that survives byte-for-byte,
foreign-owned destination disambiguated, same-owner destination reused. Full
suite 4765/4765 serial.
This commit is contained in:
1 parent
fffda19ce6
commit
5a565cf1d1
2 files changed
+303
-30
No files matched your search
+183
-29
@@ -67,36 +67,117 @@
|
|||||||
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { readLatestContextTokens, resolveContextWindow, formatWindowLabel } = require('../lib/transcript-context');
|
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 { resolvePct, resolveGateMode, resolveGatePct, resolveEmergencyPct, DEFAULT_GATE_PCT, DEFAULT_EMERGENCY_PCT } = require('../lib/context-gate-state');
|
||||||
const { getSessionsDir, getProjectName, sanitizeSessionId } = require('../lib/utils');
|
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
|
* Read the owning session id recorded in a checkpoint file's ownership
|
||||||
* plugin's session-handoff directory. Never the project root, so an
|
* marker (its first line), or null when the file has no recognizable marker
|
||||||
* operator's own RESUME.md is never a target; the session id in the name
|
* or cannot be read. The model writes this marker verbatim from the order
|
||||||
* keeps repeated fires in one session pointed at the same file (idempotent
|
* (see buildOrderText); the hook itself never writes the file, so a checkpoint
|
||||||
* — the model overwrites only its own checkpoint, never a user file).
|
* with no marker is treated as NOT owned by any session — a file the gate must
|
||||||
* @param {object} input - Parsed hook stdin ({ cwd, session_id }).
|
* not target. Never throws: a read failure is "not owned", not a crash.
|
||||||
* @returns {string} Absolute path to the session-scoped checkpoint file.
|
* @param {string} filePath
|
||||||
|
* @returns {string|null} Sanitized owner session id, or null.
|
||||||
*/
|
*/
|
||||||
function resolveCheckpointPath(input) {
|
function readOwnerSession(filePath) {
|
||||||
const resumeDir = path.join(getSessionsDir(), 'resume');
|
let fd;
|
||||||
const project =
|
try {
|
||||||
sanitizeSessionId(input && input.cwd ? path.basename(String(input.cwd)) : null) ||
|
fd = fs.openSync(filePath, 'r');
|
||||||
sanitizeSessionId(getProjectName()) ||
|
const buf = Buffer.alloc(512);
|
||||||
'project';
|
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 `<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) {
|
||||||
|
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 =
|
const sessionId =
|
||||||
sanitizeSessionId(input && input.session_id) ||
|
sanitizeSessionId(input && input.session_id) ||
|
||||||
sanitizeSessionId(process.env.ECC_SESSION_ID) ||
|
sanitizeSessionId(env && env.ECC_SESSION_ID) ||
|
||||||
sanitizeSessionId(process.env.CLAUDE_SESSION_ID) ||
|
sanitizeSessionId(env && env.CLAUDE_SESSION_ID);
|
||||||
'session';
|
if (!sessionId) return null;
|
||||||
return path.join(resumeDir, `${project}-${sessionId}.md`);
|
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).
|
* 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 {object} params
|
||||||
* @param {number} params.pct - Occupancy percent (integer, floored).
|
* @param {number} params.pct - Occupancy percent (integer, floored).
|
||||||
* @param {number} params.tokens - Context tokens observed.
|
* @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.inferred - Window size was assumed, not detected.
|
||||||
* @param {boolean} params.emergency - Past the emergency threshold.
|
* @param {boolean} params.emergency - Past the emergency threshold.
|
||||||
* @param {string} params.checkpointPath - Session-scoped checkpoint target.
|
* @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}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath }) {
|
function buildOrderText({ pct, tokens, windowTokens, inferred, emergency, checkpointPath, sessionId, project }) {
|
||||||
const windowLabel = formatWindowLabel(windowTokens);
|
const windowLabel = formatWindowLabel(windowTokens);
|
||||||
// An inferred window means the true denominator may be larger (an
|
// An inferred window means the true denominator may be larger (an
|
||||||
// unrecognized 1M-window model would read as 90% at 180k of an assumed
|
// 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(
|
lines.push(
|
||||||
'1. Do NOT start any new work stream. Bring only the unit of work currently in flight to its nearest ' +
|
'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).',
|
'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}`,
|
` ${checkpointPath}`,
|
||||||
' It must contain: the objective; current state with VERIFIED facts strictly separated from ' +
|
' Make its FIRST line this exact ownership marker, replacing <GIT_HEAD> with the current source ' +
|
||||||
'hypotheses; decisions the operator approved; approaches ruled out and WHY; exact next steps; files ' +
|
'revision (run `git rev-parse HEAD`; use `unknown` if this is not a git repo) so the handoff bytes ' +
|
||||||
'touched; any pending or half-applied changes. Do NOT overwrite or modify an existing RESUME.md or ' +
|
'are bound to a revision:',
|
||||||
'any other file in the project — this path is dedicated to this session\'s handoff and preserves ' +
|
` <!-- ecc-handoff session=${sessionId} project=${project} source-rev=<GIT_HEAD> -->`,
|
||||||
'whatever the operator already has.',
|
' After the marker it must contain: the objective; current state with VERIFIED facts strictly ' +
|
||||||
'3. Then state plainly that this session must now be closed, and give the operator this exact resume ' +
|
'separated from hypotheses; decisions the operator approved; approaches ruled out and WHY; exact ' +
|
||||||
'command on its own line (the receipt for this handoff):',
|
'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."`,
|
` 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 ' +
|
'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.'
|
'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');
|
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 {string} rawInput - Raw JSON string from stdin
|
||||||
* @param {object} [options] - Runner metadata from run-with-flags.js
|
* @param {object} [options] - Runner metadata from run-with-flags.js
|
||||||
@@ -192,14 +324,36 @@ function run(rawInput, options = {}) {
|
|||||||
if (pct < gatePct) return '';
|
if (pct < gatePct) return '';
|
||||||
|
|
||||||
const emergency = pct >= emergencyPct;
|
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({
|
const orderText = buildOrderText({
|
||||||
pct,
|
pct,
|
||||||
tokens: latest.tokens,
|
tokens: latest.tokens,
|
||||||
windowTokens,
|
windowTokens,
|
||||||
inferred,
|
inferred,
|
||||||
emergency,
|
emergency,
|
||||||
checkpointPath
|
checkpointPath,
|
||||||
|
sessionId,
|
||||||
|
project
|
||||||
});
|
});
|
||||||
|
|
||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
|
|||||||
@@ -135,13 +135,22 @@ function runTests() {
|
|||||||
if (
|
if (
|
||||||
test('order forbids asking to stop and demands a resume command', () => {
|
test('order forbids asking to stop and demands a resume command', () => {
|
||||||
const cp = '/home/me/.claude/session-data/resume/myproj-abc123.md';
|
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('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(cp));
|
||||||
assert.ok(text.includes('VERIFIED facts strictly separated from hypotheses'));
|
assert.ok(text.includes('VERIFIED facts strictly separated from hypotheses'));
|
||||||
// Observed usage is distinguished from permission to stop.
|
// Observed usage is distinguished from permission to stop.
|
||||||
assert.ok(text.includes('not by itself permission to abandon the task'));
|
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++;
|
passed++;
|
||||||
@@ -329,6 +338,10 @@ function runTests() {
|
|||||||
|
|
||||||
console.log('\nhandoff checkpoint ownership (enforce mode):');
|
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 (
|
if (
|
||||||
test('a pre-existing project RESUME.md is never targeted and is left untouched', () => {
|
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 projDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-gate-proj-'));
|
||||||
@@ -369,6 +382,112 @@ function runTests() {
|
|||||||
passed++;
|
passed++;
|
||||||
else failed++;
|
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 = '<!-- 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 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, '<!-- ecc-handoff session=mysess project=demoproj source-rev=abc123 -->\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) {
|
for (const file of cleanup) {
|
||||||
try {
|
try {
|
||||||
fs.unlinkSync(file);
|
fs.unlinkSync(file);
|
||||||
|
|||||||
Reference in new issue
Block a user