Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(hooks): resolve session IDs from hook payloads

Eneko Ruiz684c9711731d
diff --git a/scripts/hooks/post-edit-accumulator.js b/scripts/hooks/post-edit-accumulator.js
index c626b2dd8..2bdafba9d 100644
--- a/scripts/hooks/post-edit-accumulator.js
+++ b/scripts/hooks/post-edit-accumulator.js
@@ -18,15 +18,16 @@ const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
+const { resolveHookSessionId } = require('../lib/hook-session');
const MAX_STDIN = 1024 * 1024;
-function getAccumFile() {
+function getAccumFile(rawSessionId) {
const raw =
- process.env.CLAUDE_SESSION_ID ||
+ rawSessionId ||
crypto.createHash('sha1').update(process.cwd()).digest('hex').slice(0, 12);
// Strip path separators and traversal sequences so the value is safe to embed
- // directly in a filename regardless of what CLAUDE_SESSION_ID contains.
+ // directly in a filename regardless of the hook session ID source.
const sessionId = raw.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
return path.join(os.tmpdir(), `ecc-edited-${sessionId}.txt`);
}
@@ -37,9 +38,9 @@ function getAccumFile() {
*/
const JS_TS_EXT = /\.(ts|tsx|js|jsx)$/;
-function appendPath(filePath) {
+function appendPath(filePath, sessionId) {
if (filePath && JS_TS_EXT.test(filePath)) {
- fs.appendFileSync(getAccumFile(), filePath + '\n', 'utf8');
+ fs.appendFileSync(getAccumFile(sessionId), filePath + '\n', 'utf8');
}
}
@@ -50,12 +51,13 @@ function appendPath(filePath) {
function run(rawInput) {
try {
const input = JSON.parse(rawInput);
+ const sessionId = resolveHookSessionId(rawInput);
// Edit / Write: single file_path
- appendPath(input.tool_input?.file_path);
+ appendPath(input.tool_input?.file_path, sessionId);
// MultiEdit: array of edits, each with its own file_path
const edits = input.tool_input?.edits;
if (Array.isArray(edits)) {
- for (const edit of edits) appendPath(edit?.file_path);
+ for (const edit of edits) appendPath(edit?.file_path, sessionId);
}
} catch {
// Invalid input — pass through
diff --git a/scripts/hooks/session-end-marker.js b/scripts/hooks/session-end-marker.js
index 7b27a8eb3..5a432ee4c 100755
--- a/scripts/hooks/session-end-marker.js
+++ b/scripts/hooks/session-end-marker.js
@@ -13,6 +13,7 @@ const {
stopObserverForContext,
resolveSessionId
} = require('../lib/observer-sessions');
+const { resolveHookSessionId } = require('../lib/hook-session');
function log(message) {
process.stderr.write(`[SessionEnd] ${message}\n`);
@@ -20,10 +21,10 @@ function log(message) {
function run(rawInput) {
const output = rawInput || '';
- const sessionId = resolveSessionId();
+ const sessionId = resolveSessionId(resolveHookSessionId(output));
if (!sessionId) {
- log('No CLAUDE_SESSION_ID available; skipping observer cleanup');
+ log('No session ID available; skipping observer cleanup');
return output;
}
diff --git a/scripts/hooks/session-start.js b/scripts/hooks/session-start.js
index a7462c551..528b6fcd8 100644
--- a/scripts/hooks/session-start.js
+++ b/scripts/hooks/session-start.js
@@ -23,6 +23,7 @@ const {
log
} = require('../lib/utils');
const { resolveProjectContext, writeSessionLease, resolveSessionId, getHomunculusDir } = require('../lib/observer-sessions');
+const { resolveHookSessionId } = require('../lib/hook-session');
const { getPackageManager, getSelectionPrompt } = require('../lib/package-manager');
const { listAliases } = require('../lib/session-aliases');
const { detectProjectType } = require('../lib/project-detect');
@@ -181,6 +182,10 @@ function getSessionStartMode(rawInput) {
return SESSION_START_MODE_INVALID;
}
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
+ return SESSION_START_MODE_SKIP;
+ }
+
const supportedModes = new Set(['startup', 'resume', 'clear', 'compact']);
const hookName = typeof payload.hookName === 'string' ? payload.hookName.trim() : '';
if (hookName.startsWith('SessionStart:')) {
@@ -649,7 +654,8 @@ async function main() {
const maxContextChars = getSessionStartMaxContextChars();
const explicitContextDisabled = isSessionStartContextDisabled();
const shouldInjectContext = !explicitContextDisabled && maxContextChars !== 0;
- const sessionStartMode = getSessionStartMode(fs.readFileSync(0, 'utf8'));
+ const rawInput = fs.readFileSync(0, 'utf8');
+ const sessionStartMode = getSessionStartMode(rawInput);
// Ensure directories exist
ensureDir(sessionsDir);
@@ -665,7 +671,7 @@ async function main() {
}
}
- const observerSessionId = resolveSessionId();
+ const observerSessionId = resolveSessionId(resolveHookSessionId(rawInput));
if (observerSessionId) {
writeSessionLease(observerContext, observerSessionId, {
hook: 'SessionStart',
@@ -673,7 +679,7 @@ async function main() {
});
log(`[SessionStart] Registered observer lease for ${observerSessionId}`);
} else {
- log('[SessionStart] No CLAUDE_SESSION_ID available; skipping observer lease registration');
+ log('[SessionStart] No session ID available; skipping observer lease registration');
}
if (explicitContextDisabled) {
diff --git a/scripts/hooks/stop-format-typecheck.js b/scripts/hooks/stop-format-typecheck.js
index 8ae580db5..870af23af 100644
--- a/scripts/hooks/stop-format-typecheck.js
+++ b/scripts/hooks/stop-format-typecheck.js
@@ -23,6 +23,7 @@ const os = require('os');
const path = require('path');
const { findProjectRoot, detectFormatter, resolveFormatterBin } = require('../lib/resolve-formatter');
+const { resolveHookSessionId } = require('../lib/hook-session');
const MAX_STDIN = 1024 * 1024;
// Total ms budget reserved for all batches (leaves headroom below the 300s Stop timeout)
@@ -60,9 +61,9 @@ function isPluginClonePath(filePath, cwd = process.cwd(), homeDir = os.homedir()
});
}
-function getAccumFile() {
+function getAccumFile(rawSessionId) {
const raw =
- process.env.CLAUDE_SESSION_ID ||
+ rawSessionId ||
crypto.createHash('sha1').update(process.cwd()).digest('hex').slice(0, 12);
const sessionId = raw.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
return path.join(os.tmpdir(), `ecc-edited-${sessionId}.txt`);
@@ -156,8 +157,8 @@ function typecheckBatch(tsConfigDir, editedFiles, timeoutMs) {
}
}
-function main() {
- const accumFile = getAccumFile();
+function main(sessionId) {
+ const accumFile = getAccumFile(sessionId);
let raw;
try {
@@ -212,7 +213,7 @@ function main() {
*/
function run(rawInput) {
try {
- main();
+ main(resolveHookSessionId(rawInput));
} catch (err) {
process.stderr.write(`[Hook] stop-format-typecheck error: ${err.message}\n`);
}
diff --git a/scripts/lib/hook-session.js b/scripts/lib/hook-session.js
new file mode 100644
index 000000000..ad53d08f1
--- /dev/null
+++ b/scripts/lib/hook-session.js
@@ -0,0 +1,25 @@
+'use strict';
+
+/**
+ * Resolve a raw hook session ID from stdin before legacy environment fallbacks.
+ * Callers must retain their own filename sanitization at the storage boundary.
+ * @param {string} rawInput - Hook stdin JSON.
+ * @param {object} env - Environment variables; defaults to the current process.
+ * @returns {string} A nonblank session ID, or an empty string when unavailable.
+ */
+function resolveHookSessionId(rawInput, env = process.env) {
+ let sessionId;
+ try {
+ const input = JSON.parse(rawInput);
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
+ sessionId = input.session_id;
+ }
+ } catch {
+ // Empty or malformed hook input can still use an environment session ID.
+ }
+
+ return [sessionId, env.ECC_SESSION_ID, env.CLAUDE_SESSION_ID]
+ .find(value => typeof value === 'string' && value.trim().length > 0) || '';
+}
+
+module.exports = { resolveHookSessionId };
diff --git a/tests/hooks/observer-session-lifecycle.test.js b/tests/hooks/observer-session-lifecycle.test.js
new file mode 100644
index 000000000..b9a0d1568
--- /dev/null
+++ b/tests/hooks/observer-session-lifecycle.test.js
@@ -0,0 +1,227 @@
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const vm = require('vm');
+const { createRequire } = require('module');
+const { spawnSync } = require('child_process');
+
+const hooksDir = path.resolve(__dirname, '../../scripts/hooks');
+let passed = 0;
+let failed = 0;
+
+function test(name, fn) {
+ try {
+ fn();
+ console.log(` ✓ ${name}`);
+ passed += 1;
+ } catch (error) {
+ console.log(` ✗ ${name}`);
+ console.log(` ${error.message}`);
+ failed += 1;
+ }
+}
+
+function withFixture(fn, extraEnv = {}) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-observer-lifecycle-'));
+ const project = path.join(root, 'project');
+ const store = path.join(root, 'homunculus');
+ const observerDir = path.join(store, 'projects', 'fixture-project');
+ fs.mkdirSync(project, { recursive: true });
+ fs.mkdirSync(observerDir, { recursive: true });
+ fs.writeFileSync(path.join(store, 'projects.json'), JSON.stringify({
+ fixture: { id: 'fixture-project', root: project }
+ }));
+ const overrides = {
+ HOME: root,
+ USERPROFILE: root,
+ ECC_AGENT_DATA_HOME: path.join(root, 'agent-data'),
+ CLAUDE_CONFIG_DIR: path.join(root, 'claude-config'),
+ CLV2_HOMUNCULUS_DIR: store,
+ XDG_DATA_HOME: path.join(root, 'xdg'),
+ CLAUDE_PROJECT_DIR: project,
+ CLAUDE_PACKAGE_MANAGER: 'npm',
+ ECC_SESSION_START_CONTEXT: 'off',
+ ECC_SESSION_ID: undefined,
+ CLAUDE_SESSION_ID: undefined,
+ ...extraEnv
+ };
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']) {
+ overrides[key] = undefined;
+ }
+ const env = { ...process.env, ...overrides };
+ for (const [key, value] of Object.entries(env)) {
+ if (value === undefined) delete env[key];
+ }
+ try {
+ fn({ project, observerDir, overrides, env });
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+}
+
+function runHook(name, input, fixture) {
+ const result = spawnSync(process.execPath, [path.join(hooksDir, name)], {
+ cwd: fixture.project,
+ env: fixture.env,
+ input,
+ encoding: 'utf8',
+ timeout: 10000
+ });
+ assert.ifError(result.error);
+ assert.strictEqual(result.status, 0, result.stderr);
+ return result;
+}
+
+function leaseFile(fixture, sessionId) {
+ return path.join(fixture.observerDir, '.observer-sessions', `${sessionId}.json`);
+}
+
+function seedLease(fixture, sessionId) {
+ const filename = leaseFile(fixture, sessionId);
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
+ fs.writeFileSync(filename, JSON.stringify({ sessionId }));
+}
+
+function assertStartOutput(result) {
+ assert.deepStrictEqual(JSON.parse(result.stdout), {
+ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: '' }
+ });
+ assert.ok(!result.stderr.includes('[SessionStart] Error:'), result.stderr);
+}
+
+function withEnv(overrides, fn) {
+ const previous = Object.fromEntries(Object.keys(overrides).map(key => [key, process.env[key]]));
+ for (const [key, value] of Object.entries(overrides)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ try {
+ return fn();
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+}
+
+function loadEndMarkerWithStubbedStop(stops) {
+ const filename = path.join(hooksDir, 'session-end-marker.js');
+ const localRequire = createRequire(filename);
+ const module = { exports: {} };
+ const requireStub = id => id === '../lib/observer-sessions'
+ ? { ...localRequire(id), stopObserverForContext: context => { stops.push(context.projectId); return true; } }
+ : localRequire(id);
+ vm.runInNewContext(fs.readFileSync(filename, 'utf8'), {
+ require: requireStub, module,
+ process: { stderr: { write() {} }, env: process.env }
+ }, { filename });
+ return module.exports;
+}
+
+console.log('\n=== Observer session lifecycle tests ===\n');
+
+test('SessionStart creates separate observer leases from stdin without environment IDs', () => {
+ withFixture(fixture => {
+ for (const sessionId of ['payload-one', 'payload-two']) {
+ assertStartOutput(runHook('session-start.js', JSON.stringify({
+ session_id: sessionId, hook_event_name: 'SessionStart', source: 'startup'
+ }), fixture));
+ const lease = JSON.parse(fs.readFileSync(leaseFile(fixture, sessionId), 'utf8'));
+ assert.strictEqual(lease.sessionId, sessionId);
+ assert.strictEqual(lease.hook, 'SessionStart');
+ assert.strictEqual(lease.projectRoot, fixture.project);
+ }
+ assert.strictEqual(fs.readdirSync(path.dirname(leaseFile(fixture, 'payload-one'))).length, 2);
+ });
+});
+
+test('SessionEnd CLI removes the payload lease, retains others, then cleans up the final observer', () => {
+ withFixture(fixture => {
+ seedLease(fixture, 'first');
+ seedLease(fixture, 'second');
+ const pidFile = path.join(fixture.observerDir, '.observer.pid');
+ // PID 1 is rejected before process.kill, so this fixture never signals any process.
+ fs.writeFileSync(pidFile, '1');
+ for (const sessionId of ['first', 'second']) {
+ const input = ` {"session_id":"${sessionId}","hook_event_name":"SessionEnd"}\n`;
+ assert.strictEqual(runHook('session-end-marker.js', input, fixture).stdout, input);
+ assert.ok(!fs.existsSync(leaseFile(fixture, sessionId)));
+ assert.strictEqual(fs.existsSync(pidFile), sessionId === 'first');
+ if (sessionId === 'first') assert.ok(fs.existsSync(leaseFile(fixture, 'second')));
+ }
+ });
+});
+
+test('in-process SessionEnd stops the observer only after the final payload lease ends', () => {
+ withFixture(fixture => withEnv(fixture.overrides, () => {
+ seedLease(fixture, 'first');
+ seedLease(fixture, 'second');
+ const stops = [];
+ const { run } = loadEndMarkerWithStubbedStop(stops);
+ const first = '{"session_id":"first"}\n';
+ assert.strictEqual(run(first), first);
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'first')));
+ assert.ok(fs.existsSync(leaseFile(fixture, 'second')));
+ assert.deepStrictEqual(stops, []);
+ const second = '{"session_id":"second"}\n';
+ assert.strictEqual(run(second), second);
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'second')));
+ assert.deepStrictEqual(stops, ['fixture-project']);
+ }));
+});
+
+for (const envKey of ['ECC_SESSION_ID', 'CLAUDE_SESSION_ID']) {
+ test(`both lifecycle hooks retain ${envKey} fallback for malformed stdin`, () => {
+ withFixture(fixture => {
+ const input = '{malformed payload\n';
+ assertStartOutput(runHook('session-start.js', input, fixture));
+ assert.ok(fs.existsSync(leaseFile(fixture, 'env-session')));
+ assert.strictEqual(runHook('session-end-marker.js', input, fixture).stdout, input);
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'env-session')));
+ }, { [envKey]: 'env-session' });
+ });
+}
+
+test('payload ID overrides environment IDs in both lifecycle hooks', () => {
+ withFixture(fixture => {
+ const input = '{"session_id":"payload-session","hook_event_name":"SessionStart","source":"startup"}';
+ assertStartOutput(runHook('session-start.js', input, fixture));
+ assert.ok(fs.existsSync(leaseFile(fixture, 'payload-session')));
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'ecc-session')));
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'claude-session')));
+ seedLease(fixture, 'ecc-session');
+ assert.strictEqual(runHook('session-end-marker.js', input, fixture).stdout, input);
+ assert.ok(!fs.existsSync(leaseFile(fixture, 'payload-session')));
+ assert.ok(fs.existsSync(leaseFile(fixture, 'ecc-session')));
+ }, { ECC_SESSION_ID: 'ecc-session', CLAUDE_SESSION_ID: 'claude-session' });
+});
+
+test('observer lease filenames sanitize path characters and Windows reserved IDs', () => {
+ withFixture(fixture => {
+ for (const sessionId of ['../session\\alpha:*?', 'CON']) {
+ const input = JSON.stringify({ session_id: sessionId, hook_event_name: 'SessionStart', source: 'startup' });
+ assertStartOutput(runHook('session-start.js', input, fixture));
+ const leaseDir = path.dirname(leaseFile(fixture, 'unused'));
+ const entries = fs.readdirSync(leaseDir);
+ assert.strictEqual(entries.length, 1);
+ assert.match(entries[0], sessionId === 'CON' ? /^CON-[a-f0-9]{6}\.json$/ : /^session-alpha\.json$/);
+ assert.strictEqual(runHook('session-end-marker.js', input, fixture).stdout, input);
+ assert.deepStrictEqual(fs.readdirSync(leaseDir), []);
+ }
+ });
+});
+
+test('null JSON is harmless without session IDs and SessionEnd preserves the raw payload', () => {
+ withFixture(fixture => {
+ const input = 'null\n';
+ assertStartOutput(runHook('session-start.js', input, fixture));
+ assert.strictEqual(runHook('session-end-marker.js', input, fixture).stdout, input);
+ assert.ok(!fs.existsSync(path.dirname(leaseFile(fixture, 'unused'))));
+ });
+});
+
+console.log(`\nPassed: ${passed}`);
+console.log(`Failed: ${failed}`);
+process.exit(failed > 0 ? 1 : 0);
diff --git a/tests/hooks/stop-format-typecheck.test.js b/tests/hooks/stop-format-typecheck.test.js
index 564bae693..c1b1a5135 100644
--- a/tests/hooks/stop-format-typecheck.test.js
+++ b/tests/hooks/stop-format-typecheck.test.js
@@ -33,7 +33,9 @@ let failed = 0;
// Use a unique session ID for tests so we don't pollute real sessions
const TEST_SESSION_ID = `test-${Date.now()}`;
const origSessionId = process.env.CLAUDE_SESSION_ID;
+const origEccSessionId = process.env.ECC_SESSION_ID;
process.env.CLAUDE_SESSION_ID = TEST_SESSION_ID;
+delete process.env.ECC_SESSION_ID;
function getAccumFile() {
return path.join(os.tmpdir(), `ecc-edited-${TEST_SESSION_ID}.txt`);
@@ -233,6 +235,91 @@ if (test('stop hook passes stdin through unchanged', () => {
assert.strictEqual(result.toString(), input);
})) passed++; else failed++;
+console.log('\nsession-scoped accumulator regression (#3460)');
+
+function withPayloadSessions(fn) {
+ const sessionA = `${TEST_SESSION_ID}-payload-a`;
+ const sessionB = `${TEST_SESSION_ID}-payload-b`;
+ const fileA = path.join(os.tmpdir(), `ecc-edited-${sessionA}.txt`);
+ const fileB = path.join(os.tmpdir(), `ecc-edited-${sessionB}.txt`);
+ try {
+ cleanAccumFile();
+ fn({ sessionA, sessionB, fileA, fileB });
+ } finally {
+ for (const file of [fileA, fileB]) fs.rmSync(file, { force: true });
+ cleanAccumFile();
+ }
+}
+
+if (test('stdin session IDs isolate edits from sibling sessions in the same cwd', () => {
+ withPayloadSessions(({ sessionA, sessionB, fileA, fileB }) => {
+ accumulator.run(JSON.stringify({ session_id: sessionA, tool_input: { file_path: '/nonexistent/a.ts' } }));
+ accumulator.run(JSON.stringify({ session_id: sessionB, tool_input: { file_path: '/nonexistent/b.ts' } }));
+ assert.strictEqual(fs.readFileSync(fileA, 'utf8'), '/nonexistent/a.ts\n');
+ assert.strictEqual(fs.readFileSync(fileB, 'utf8'), '/nonexistent/b.ts\n');
+ assert.ok(!fs.existsSync(getAccumFile()), 'stdin must override the environment session');
+ });
+})) passed++; else failed++;
+
+if (test('Stop consumes only its stdin session accumulator and preserves pass-through', () => {
+ withPayloadSessions(({ sessionA, sessionB, fileA, fileB }) => {
+ fs.writeFileSync(fileA, '/nonexistent/a.ts\n');
+ fs.writeFileSync(fileB, '/nonexistent/b.ts\n');
+ const stopHook = require('../../scripts/hooks/stop-format-typecheck');
+ const inputA = JSON.stringify({ session_id: sessionA, stop_reason: 'end_turn' });
+ assert.strictEqual(stopHook.run(inputA), inputA);
+ assert.ok(!fs.existsSync(fileA), 'completed session accumulator must be removed');
+ assert.strictEqual(fs.readFileSync(fileB, 'utf8'), '/nonexistent/b.ts\n');
+ stopHook.run(JSON.stringify({ session_id: sessionB }));
+ assert.ok(!fs.existsSync(fileB), 'second session should consume its own accumulator');
+ });
+})) passed++; else failed++;
+
+if (test('MultiEdit uses the same stdin session accumulator for every edit', () => {
+ withPayloadSessions(({ sessionA, fileA }) => {
+ accumulator.run(JSON.stringify({
+ session_id: sessionA,
+ tool_input: { edits: [{ file_path: '/nonexistent/a.ts' }, { file_path: '/nonexistent/b.js' }] }
+ }));
+ assert.strictEqual(fs.readFileSync(fileA, 'utf8'), '/nonexistent/a.ts\n/nonexistent/b.js\n');
+ });
+})) passed++; else failed++;
+
+if (test('ECC_SESSION_ID precedes CLAUDE_SESSION_ID while preserving legacy filenames', () => {
+ const rawId = `${TEST_SESSION_ID}/ecc.with spaces`;
+ const safeId = rawId.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
+ const file = path.join(os.tmpdir(), `ecc-edited-${safeId}.txt`);
+ process.env.ECC_SESSION_ID = rawId;
+ try {
+ cleanAccumFile();
+ accumulator.run(JSON.stringify({ tool_input: { file_path: '/nonexistent/ecc.ts' } }));
+ assert.strictEqual(fs.readFileSync(file, 'utf8'), '/nonexistent/ecc.ts\n');
+ assert.ok(!fs.existsSync(getAccumFile()));
+ const stopHook = require('../../scripts/hooks/stop-format-typecheck');
+ assert.strictEqual(stopHook.run('malformed JSON'), 'malformed JSON');
+ assert.ok(!fs.existsSync(file), 'malformed Stop input must retain the environment fallback');
+ } finally {
+ delete process.env.ECC_SESSION_ID;
+ fs.rmSync(file, { force: true });
+ cleanAccumFile();
+ }
+})) passed++; else failed++;
+
+if (test('stdin IDs keep the existing filename sanitizer and length limit', () => {
+ const rawId = `${TEST_SESSION_ID}/../nested\\session ${'x'.repeat(100)}`;
+ const safeId = rawId.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
+ const file = path.join(os.tmpdir(), `ecc-edited-${safeId}.txt`);
+ try {
+ accumulator.run(JSON.stringify({ session_id: rawId, tool_input: { file_path: '/nonexistent/safe.ts' } }));
+ assert.strictEqual(fs.readFileSync(file, 'utf8'), '/nonexistent/safe.ts\n');
+ require('../../scripts/hooks/stop-format-typecheck').run(JSON.stringify({ session_id: rawId }));
+ assert.ok(!fs.existsSync(file));
+ } finally {
+ fs.rmSync(file, { force: true });
+ cleanAccumFile();
+ }
+})) passed++; else failed++;
+
// --- Plugin and marketplace clones are read, not owned: never format them ---
const FAKE_HOME = path.join(path.sep, 'home', 'someone');
@@ -279,6 +366,11 @@ if (origSessionId === undefined) {
} else {
process.env.CLAUDE_SESSION_ID = origSessionId;
}
+if (origEccSessionId === undefined) {
+ delete process.env.ECC_SESSION_ID;
+} else {
+ process.env.ECC_SESSION_ID = origEccSessionId;
+}
console.log(`\n=== Test Results ===`);
console.log(`Passed: ${passed}`);
diff --git a/tests/lib/hook-session.test.js b/tests/lib/hook-session.test.js
new file mode 100644
index 000000000..13bc66a35
--- /dev/null
+++ b/tests/lib/hook-session.test.js
@@ -0,0 +1,85 @@
+const assert = require('assert');
+const { resolveHookSessionId } = require('../../scripts/lib/hook-session');
+
+let passed = 0;
+let failed = 0;
+
+function test(name, fn) {
+ try {
+ fn();
+ console.log(` ✓ ${name}`);
+ passed += 1;
+ } catch (error) {
+ console.log(` ✗ ${name}`);
+ console.log(` ${error.message}`);
+ failed += 1;
+ }
+}
+
+console.log('\n=== Hook session ID tests ===\n');
+
+test('payload session_id takes precedence over both environment IDs', () => {
+ assert.strictEqual(resolveHookSessionId('{"session_id":"payload-session"}', {
+ ECC_SESSION_ID: 'ecc-session', CLAUDE_SESSION_ID: 'claude-session'
+ }), 'payload-session');
+});
+
+test('ECC_SESSION_ID takes precedence over CLAUDE_SESSION_ID', () => {
+ assert.strictEqual(resolveHookSessionId('{}', {
+ ECC_SESSION_ID: 'ecc-session', CLAUDE_SESSION_ID: 'claude-session'
+ }), 'ecc-session');
+});
+
+test('CLAUDE_SESSION_ID remains the legacy fallback', () => {
+ assert.strictEqual(resolveHookSessionId('', { CLAUDE_SESSION_ID: 'legacy-session' }), 'legacy-session');
+});
+
+test('malformed and empty input safely fall back to the environment', () => {
+ for (const input of ['', ' ', '{bad json', undefined, null]) {
+ assert.strictEqual(resolveHookSessionId(input, { ECC_SESSION_ID: 'fallback' }), 'fallback');
+ }
+});
+
+test('nonobject JSON does not supply a session ID', () => {
+ for (const input of ['null', '[]', '[{"session_id":"nested"}]', '42', 'true', '"session"']) {
+ assert.strictEqual(resolveHookSessionId(input, { CLAUDE_SESSION_ID: 'fallback' }), 'fallback');
+ }
+});
+
+test('invalid payload ID types and blank IDs fall back safely', () => {
+ for (const sessionId of [null, 42, true, {}, [], '', ' \t\n']) {
+ assert.strictEqual(resolveHookSessionId(JSON.stringify({ session_id: sessionId }), {
+ ECC_SESSION_ID: 'fallback'
+ }), 'fallback');
+ }
+});
+
+test('invalid ECC environment IDs fall back to the Claude environment ID', () => {
+ for (const sessionId of [undefined, null, 42, true, {}, [], '', ' \t\n']) {
+ assert.strictEqual(resolveHookSessionId('{}', {
+ ECC_SESSION_ID: sessionId, CLAUDE_SESSION_ID: 'legacy-session'
+ }), 'legacy-session');
+ }
+});
+
+test('missing or invalid IDs return an empty string', () => {
+ assert.strictEqual(resolveHookSessionId('{}', {}), '');
+ assert.strictEqual(resolveHookSessionId('{"session_id":false}', {
+ ECC_SESSION_ID: ' ', CLAUDE_SESSION_ID: null
+ }), '');
+});
+
+test('only the top-level session_id field is accepted', () => {
+ assert.strictEqual(resolveHookSessionId('{"nested":{"session_id":"nested"},"sessionId":"camel"}', {}), '');
+});
+
+test('raw IDs remain intact for each caller to apply its filename sanitizer', () => {
+ for (const sessionId of ['../session\\alpha:*?', 'CON', 'session:one', ' session-one ', 'sesión']) {
+ assert.strictEqual(resolveHookSessionId(JSON.stringify({ session_id: sessionId }), {}), sessionId);
+ assert.strictEqual(resolveHookSessionId('', { ECC_SESSION_ID: sessionId }), sessionId);
+ }
+});
+
+console.log(`\nPassed: ${passed}`);
+console.log(`Failed: ${failed}`);
+process.exit(failed > 0 ? 1 : 0);
diff --git a/tests/scripts/npm-publish-surface.test.js b/tests/scripts/npm-publish-surface.test.js
index 02ca28943..65bc80029 100644
--- a/tests/scripts/npm-publish-surface.test.js
+++ b/tests/scripts/npm-publish-surface.test.js
@@ -221,6 +221,7 @@ function main() {
"scripts/lib/nasiko-release.js",
"scripts/lib/memory-vault-format.js",
"scripts/lib/memory-vault.js",
+ "scripts/lib/hook-session.js",
"scripts/discussion-audit.js",
"scripts/operator-readiness-dashboard.js",
"scripts/preview-pack-smoke.js",