feat: add ECC statusline observability hooks

Salvages the useful statusline/context monitor work from stale PR #1504 while preserving the current continuous-learning hook runner wiring.

Adds the metrics bridge, context monitor, statusline script, shared cost/session bridge utilities, and tests. Fixes the reviewed false loop-detection hash collision for non-file tools, avoids default-session cost inflation, sanitizes statusline task lookup, and records hook payload session IDs in cost-tracker.
This commit is contained in:
Affaan Mustafa
2026-05-11 23:30:56 -04:00
committed by Affaan Mustafa
parent e9c8845833
commit 940135ea47
14 changed files with 1744 additions and 33 deletions

View File

@@ -152,6 +152,28 @@ function runTests() {
fs.rmSync(tmpHome, { recursive: true, force: true });
}) ? passed++ : failed++);
// 7. Uses sanitized hook input session_id when environment session IDs are absent
(test('uses input session_id for session correlation when env vars are absent', () => {
const tmpHome = makeTempDir();
const input = {
session_id: 'hook-session-abc',
model: 'claude-sonnet-4-20250514',
usage: { input_tokens: 120, output_tokens: 30 },
};
const result = runScript(input, {
...withTempHome(tmpHome),
ECC_SESSION_ID: '',
CLAUDE_SESSION_ID: '',
});
assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`);
const metricsFile = path.join(tmpHome, '.claude', 'metrics', 'costs.jsonl');
const row = JSON.parse(fs.readFileSync(metricsFile, 'utf8').trim());
assert.strictEqual(row.session_id, 'hook-session-abc', 'Expected input session_id to be recorded');
fs.rmSync(tmpHome, { recursive: true, force: true });
}) ? passed++ : failed++);
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
}

View File

@@ -0,0 +1,238 @@
/**
* Tests for scripts/hooks/ecc-context-monitor.js
*
* Run with: node tests/hooks/ecc-context-monitor.test.js
*/
const assert = require('assert');
const { run, evaluateConditions, detectLoop, severityLabel } = require('../../scripts/hooks/ecc-context-monitor');
// Test helper
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
return true;
} catch (err) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${err.message}`);
return false;
}
}
function runTests() {
console.log('\n=== Testing ecc-context-monitor.js ===\n');
let passed = 0;
let failed = 0;
// evaluateConditions — context warnings
console.log('evaluateConditions (context):');
if (
test('remaining 20% triggers CRITICAL context warning', () => {
const warnings = evaluateConditions({ context_remaining_pct: 20 });
const ctx = warnings.find(w => w.type === 'context');
assert.ok(ctx, 'Expected a context warning');
assert.strictEqual(ctx.severity, 3);
assert.ok(ctx.message.includes('CRITICAL'), 'Message should contain CRITICAL');
})
)
passed++;
else failed++;
if (
test('remaining 30% triggers WARNING context warning', () => {
const warnings = evaluateConditions({ context_remaining_pct: 30 });
const ctx = warnings.find(w => w.type === 'context');
assert.ok(ctx, 'Expected a context warning');
assert.strictEqual(ctx.severity, 2);
assert.ok(ctx.message.includes('WARNING'), 'Message should contain WARNING');
})
)
passed++;
else failed++;
if (
test('remaining 50% triggers no context warning', () => {
const warnings = evaluateConditions({ context_remaining_pct: 50 });
const ctx = warnings.find(w => w.type === 'context');
assert.strictEqual(ctx, undefined);
})
)
passed++;
else failed++;
// evaluateConditions — cost warnings
console.log('\nevaluateConditions (cost):');
if (
test('cost $55 triggers CRITICAL cost warning', () => {
const warnings = evaluateConditions({ total_cost_usd: 55 });
const cost = warnings.find(w => w.type === 'cost');
assert.ok(cost, 'Expected a cost warning');
assert.strictEqual(cost.severity, 3);
assert.ok(cost.message.includes('CRITICAL'), 'Message should contain CRITICAL');
})
)
passed++;
else failed++;
if (
test('cost $12 triggers WARNING cost warning', () => {
const warnings = evaluateConditions({ total_cost_usd: 12 });
const cost = warnings.find(w => w.type === 'cost');
assert.ok(cost, 'Expected a cost warning');
assert.strictEqual(cost.severity, 2);
assert.ok(cost.message.includes('WARNING'), 'Message should contain WARNING');
})
)
passed++;
else failed++;
if (
test('cost $6 triggers NOTICE cost warning', () => {
const warnings = evaluateConditions({ total_cost_usd: 6 });
const cost = warnings.find(w => w.type === 'cost');
assert.ok(cost, 'Expected a cost warning');
assert.strictEqual(cost.severity, 1);
assert.ok(cost.message.includes('NOTICE'), 'Message should contain NOTICE');
})
)
passed++;
else failed++;
if (
test('cost $2 triggers no cost warning', () => {
const warnings = evaluateConditions({ total_cost_usd: 2 });
const cost = warnings.find(w => w.type === 'cost');
assert.strictEqual(cost, undefined);
})
)
passed++;
else failed++;
// evaluateConditions — scope warnings
console.log('\nevaluateConditions (scope):');
if (
test('25 files triggers scope WARNING', () => {
const warnings = evaluateConditions({ files_modified_count: 25 });
const scope = warnings.find(w => w.type === 'scope');
assert.ok(scope, 'Expected a scope warning');
assert.strictEqual(scope.severity, 2);
assert.ok(scope.message.includes('SCOPE'), 'Message should contain SCOPE');
})
)
passed++;
else failed++;
if (
test('10 files triggers no scope warning', () => {
const warnings = evaluateConditions({ files_modified_count: 10 });
const scope = warnings.find(w => w.type === 'scope');
assert.strictEqual(scope, undefined);
})
)
passed++;
else failed++;
// detectLoop tests
console.log('\ndetectLoop:');
if (
test('3 identical entries returns detected true', () => {
const entries = [
{ tool: 'Bash', hash: 'aabbccdd' },
{ tool: 'Bash', hash: 'aabbccdd' },
{ tool: 'Bash', hash: 'aabbccdd' }
];
const result = detectLoop(entries);
assert.strictEqual(result.detected, true);
assert.strictEqual(result.tool, 'Bash');
assert.ok(result.count >= 3);
})
)
passed++;
else failed++;
if (
test('all different entries returns detected false', () => {
const entries = [
{ tool: 'Bash', hash: '11111111' },
{ tool: 'Edit', hash: '22222222' },
{ tool: 'Write', hash: '33333333' }
];
const result = detectLoop(entries);
assert.strictEqual(result.detected, false);
})
)
passed++;
else failed++;
if (
test('empty array returns detected false', () => {
const result = detectLoop([]);
assert.strictEqual(result.detected, false);
})
)
passed++;
else failed++;
// severityLabel tests
console.log('\nseverityLabel:');
if (
test('severity 3 returns critical', () => {
assert.strictEqual(severityLabel(3), 'critical');
})
)
passed++;
else failed++;
if (
test('severity 2 returns warning', () => {
assert.strictEqual(severityLabel(2), 'warning');
})
)
passed++;
else failed++;
if (
test('severity 1 returns notice', () => {
assert.strictEqual(severityLabel(1), 'notice');
})
)
passed++;
else failed++;
// run tests
console.log('\nrun:');
if (
test('empty input returns input unchanged', () => {
const result = run('');
assert.strictEqual(result, '');
})
)
passed++;
else failed++;
if (
test('input without session_id returns input unchanged', () => {
const input = JSON.stringify({ tool_name: 'Bash' });
const result = run(input);
assert.strictEqual(result, input);
})
)
passed++;
else failed++;
// Summary
console.log(`\nResults: ${passed} passed, ${failed} failed\n`);
return { passed, failed };
}
const { failed } = runTests();
process.exit(failed > 0 ? 1 : 0);

View File

@@ -0,0 +1,219 @@
/**
* Tests for scripts/hooks/ecc-metrics-bridge.js
*
* Run with: node tests/hooks/ecc-metrics-bridge.test.js
*/
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { run, hashToolCall, extractFilePaths, readSessionCost } = require('../../scripts/hooks/ecc-metrics-bridge');
// Test helper
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
return true;
} catch (err) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${err.message}`);
return false;
}
}
function makeTempHome() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-metrics-bridge-test-'));
}
function runTests() {
console.log('\n=== Testing ecc-metrics-bridge.js ===\n');
let passed = 0;
let failed = 0;
// hashToolCall tests
console.log('hashToolCall:');
if (
test('returns 8-char hex string', () => {
const hash = hashToolCall('Bash', { command: 'ls' });
assert.strictEqual(hash.length, 8);
assert.ok(/^[0-9a-f]{8}$/.test(hash), `Expected hex, got: ${hash}`);
})
)
passed++;
else failed++;
if (
test('different Bash commands produce different hashes', () => {
const h1 = hashToolCall('Bash', { command: 'ls' });
const h2 = hashToolCall('Bash', { command: 'pwd' });
assert.notStrictEqual(h1, h2);
})
)
passed++;
else failed++;
if (
test('different Edit file_paths produce different hashes', () => {
const h1 = hashToolCall('Edit', { file_path: 'a.js' });
const h2 = hashToolCall('Edit', { file_path: 'b.js' });
assert.notStrictEqual(h1, h2);
})
)
passed++;
else failed++;
if (
test('same inputs produce same hash (deterministic)', () => {
const h1 = hashToolCall('Write', { file_path: 'x.txt' });
const h2 = hashToolCall('Write', { file_path: 'x.txt' });
assert.strictEqual(h1, h2);
})
)
passed++;
else failed++;
if (
test('non-file tools hash by stable input to avoid false loop collisions', () => {
const h1 = hashToolCall('Glob', { pattern: '**/*.js', path: '/repo/a' });
const h2 = hashToolCall('Glob', { pattern: '**/*.md', path: '/repo/a' });
const h3 = hashToolCall('Glob', { path: '/repo/a', pattern: '**/*.js' });
assert.notStrictEqual(h1, h2);
assert.strictEqual(h1, h3);
})
)
passed++;
else failed++;
// extractFilePaths tests
console.log('\nextractFilePaths:');
if (
test('Edit with file_path returns [file_path]', () => {
const paths = extractFilePaths('Edit', { file_path: 'a.js' });
assert.deepStrictEqual(paths, ['a.js']);
})
)
passed++;
else failed++;
if (
test('MultiEdit with edits array returns all file_paths', () => {
const paths = extractFilePaths('MultiEdit', {
edits: [{ file_path: 'a.js' }, { file_path: 'b.js' }]
});
assert.deepStrictEqual(paths, ['a.js', 'b.js']);
})
)
passed++;
else failed++;
if (
test('Bash with command returns empty array', () => {
const paths = extractFilePaths('Bash', { command: 'ls' });
assert.deepStrictEqual(paths, []);
})
)
passed++;
else failed++;
if (
test('null toolInput returns empty array', () => {
const paths = extractFilePaths('Edit', null);
assert.deepStrictEqual(paths, []);
})
)
passed++;
else failed++;
// readSessionCost tests
console.log('\nreadSessionCost:');
if (
test('nonexistent session returns object with numeric fields', () => {
const result = readSessionCost('nonexistent-session-cost-test-xyz-999');
assert.strictEqual(typeof result.totalCost, 'number');
assert.strictEqual(typeof result.totalIn, 'number');
assert.strictEqual(typeof result.totalOut, 'number');
assert.ok(result.totalCost >= 0, 'totalCost should be non-negative');
})
)
passed++;
else failed++;
if (
test('readSessionCost does not include unrelated default-session rows', () => {
const tmpHome = makeTempHome();
const originalHome = process.env.HOME;
const originalUserProfile = process.env.USERPROFILE;
try {
process.env.HOME = tmpHome;
process.env.USERPROFILE = tmpHome;
const metricsDir = path.join(tmpHome, '.claude', 'metrics');
fs.mkdirSync(metricsDir, { recursive: true });
fs.writeFileSync(
path.join(metricsDir, 'costs.jsonl'),
[
JSON.stringify({ session_id: 'default', estimated_cost_usd: 50, input_tokens: 1000, output_tokens: 2000 }),
JSON.stringify({ session_id: 'target-session', estimated_cost_usd: 1.25, input_tokens: 10, output_tokens: 20 })
].join('\n') + '\n',
'utf8'
);
const result = readSessionCost('target-session');
assert.strictEqual(result.totalCost, 1.25);
assert.strictEqual(result.totalIn, 10);
assert.strictEqual(result.totalOut, 20);
} finally {
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
if (originalUserProfile === undefined) delete process.env.USERPROFILE;
else process.env.USERPROFILE = originalUserProfile;
fs.rmSync(tmpHome, { recursive: true, force: true });
}
})
)
passed++;
else failed++;
// run tests
console.log('\nrun:');
if (
test('empty input returns empty input without crashing', () => {
const result = run('');
assert.strictEqual(result, '');
})
)
passed++;
else failed++;
if (
test('whitespace-only input returns input unchanged', () => {
const result = run(' ');
assert.strictEqual(result, ' ');
})
)
passed++;
else failed++;
if (
test('input without session_id returns input unchanged', () => {
const input = JSON.stringify({ tool_name: 'Bash', tool_input: { command: 'ls' } });
const result = run(input);
assert.strictEqual(result, input);
})
)
passed++;
else failed++;
// Summary
console.log(`\nResults: ${passed} passed, ${failed} failed\n`);
return { passed, failed };
}
const { failed } = runTests();
process.exit(failed > 0 ? 1 : 0);

View File

@@ -0,0 +1,213 @@
/**
* Tests for scripts/hooks/ecc-statusline.js
*
* Run with: node tests/hooks/ecc-statusline.test.js
*/
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { formatDuration, buildContextBar, readCurrentTask } = require('../../scripts/hooks/ecc-statusline');
// Test helper
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
return true;
} catch (err) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${err.message}`);
return false;
}
}
function makeTempConfig() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-statusline-test-'));
}
function runTests() {
console.log('\n=== Testing ecc-statusline.js ===\n');
let passed = 0;
let failed = 0;
// formatDuration tests
console.log('formatDuration:');
if (
test('null returns "?"', () => {
assert.strictEqual(formatDuration(null), '?');
})
)
passed++;
else failed++;
if (
test('undefined returns "?"', () => {
assert.strictEqual(formatDuration(undefined), '?');
})
)
passed++;
else failed++;
if (
test('timestamp 30 seconds ago ends with "s"', () => {
const ts = new Date(Date.now() - 30 * 1000).toISOString();
const result = formatDuration(ts);
assert.ok(result.endsWith('s'), `Expected ending in "s", got: ${result}`);
})
)
passed++;
else failed++;
if (
test('timestamp 5 minutes ago ends with "m"', () => {
const ts = new Date(Date.now() - 5 * 60 * 1000).toISOString();
const result = formatDuration(ts);
assert.ok(result.endsWith('m'), `Expected ending in "m", got: ${result}`);
})
)
passed++;
else failed++;
if (
test('timestamp 90 minutes ago contains "h"', () => {
const ts = new Date(Date.now() - 90 * 60 * 1000).toISOString();
const result = formatDuration(ts);
assert.ok(result.includes('h'), `Expected "h" in result, got: ${result}`);
})
)
passed++;
else failed++;
if (
test('future timestamp returns "?"', () => {
const ts = new Date(Date.now() + 60 * 1000).toISOString();
const result = formatDuration(ts);
assert.strictEqual(result, '?');
})
)
passed++;
else failed++;
// buildContextBar tests
console.log('\nbuildContextBar:');
if (
test('null returns empty string', () => {
assert.strictEqual(buildContextBar(null), '');
})
)
passed++;
else failed++;
if (
test('undefined returns empty string', () => {
assert.strictEqual(buildContextBar(undefined), '');
})
)
passed++;
else failed++;
if (
test('80% remaining contains green ANSI code', () => {
const bar = buildContextBar(80);
assert.ok(bar.includes('\x1b[32m'), `Expected green ANSI in: ${JSON.stringify(bar)}`);
})
)
passed++;
else failed++;
if (
test('50% remaining contains yellow ANSI code', () => {
const bar = buildContextBar(50);
assert.ok(bar.includes('\x1b[33m'), `Expected yellow ANSI in: ${JSON.stringify(bar)}`);
})
)
passed++;
else failed++;
if (
test('20% remaining contains red blink ANSI code', () => {
const bar = buildContextBar(20);
assert.ok(bar.includes('\x1b[5;31m'), `Expected red blink ANSI in: ${JSON.stringify(bar)}`);
})
)
passed++;
else failed++;
if (
test('context bar contains block characters', () => {
const bar = buildContextBar(60);
assert.ok(bar.includes('\u2588') || bar.includes('\u2591'), 'Expected block characters in bar');
})
)
passed++;
else failed++;
if (
test('context bar contains percentage', () => {
const bar = buildContextBar(70);
assert.ok(bar.includes('%'), 'Expected percentage in bar');
})
)
passed++;
else failed++;
// readCurrentTask tests
console.log('\nreadCurrentTask:');
if (
test('nonexistent session returns empty string', () => {
const result = readCurrentTask('nonexistent-session-xyz-999');
assert.strictEqual(result, '');
})
)
passed++;
else failed++;
if (
test('empty string session returns empty string', () => {
const result = readCurrentTask('');
assert.strictEqual(result, '');
})
)
passed++;
else failed++;
if (
test('reads in-progress task for sanitized session ID only', () => {
const tmpConfig = makeTempConfig();
const originalConfig = process.env.CLAUDE_CONFIG_DIR;
try {
process.env.CLAUDE_CONFIG_DIR = tmpConfig;
const todosDir = path.join(tmpConfig, 'todos');
fs.mkdirSync(todosDir, { recursive: true });
fs.writeFileSync(
path.join(todosDir, 'safe-session-agent-main.json'),
JSON.stringify([{ status: 'in_progress', activeForm: 'Fix auth flow' }]),
'utf8'
);
assert.strictEqual(readCurrentTask('safe-session'), 'Fix auth flow');
assert.strictEqual(readCurrentTask('../safe-session'), '');
} finally {
if (originalConfig === undefined) delete process.env.CLAUDE_CONFIG_DIR;
else process.env.CLAUDE_CONFIG_DIR = originalConfig;
fs.rmSync(tmpConfig, { recursive: true, force: true });
}
})
)
passed++;
else failed++;
// Summary
console.log(`\nResults: ${passed} passed, ${failed} failed\n`);
return { passed, failed };
}
const { failed } = runTests();
process.exit(failed > 0 ? 1 : 0);

View File

@@ -0,0 +1,114 @@
/**
* Tests for scripts/lib/cost-estimate.js
*
* Run with: node tests/lib/cost-estimate.test.js
*/
const assert = require('assert');
const { estimateCost, RATE_TABLE } = require('../../scripts/lib/cost-estimate');
// Test helper
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
return true;
} catch (err) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${err.message}`);
return false;
}
}
function runTests() {
console.log('\n=== Testing cost-estimate.js ===\n');
let passed = 0;
let failed = 0;
// RATE_TABLE structure
console.log('RATE_TABLE:');
if (
test('RATE_TABLE has haiku, sonnet, opus keys', () => {
assert.ok(RATE_TABLE.haiku, 'Missing haiku');
assert.ok(RATE_TABLE.sonnet, 'Missing sonnet');
assert.ok(RATE_TABLE.opus, 'Missing opus');
assert.strictEqual(typeof RATE_TABLE.haiku.in, 'number');
assert.strictEqual(typeof RATE_TABLE.haiku.out, 'number');
assert.strictEqual(typeof RATE_TABLE.sonnet.in, 'number');
assert.strictEqual(typeof RATE_TABLE.sonnet.out, 'number');
assert.strictEqual(typeof RATE_TABLE.opus.in, 'number');
assert.strictEqual(typeof RATE_TABLE.opus.out, 'number');
})
)
passed++;
else failed++;
// estimateCost tests
console.log('\nestimateCost:');
if (
test('opus 1M/1M tokens returns 90', () => {
const cost = estimateCost('opus', 1_000_000, 1_000_000);
assert.strictEqual(cost, 90);
})
)
passed++;
else failed++;
if (
test('sonnet 1M/1M tokens returns 18', () => {
const cost = estimateCost('sonnet', 1_000_000, 1_000_000);
assert.strictEqual(cost, 18);
})
)
passed++;
else failed++;
if (
test('haiku 1M/1M tokens returns 4.8', () => {
const cost = estimateCost('haiku', 1_000_000, 1_000_000);
assert.strictEqual(cost, 4.8);
})
)
passed++;
else failed++;
if (
test('null model with 0 tokens returns 0', () => {
const cost = estimateCost(null, 0, 0);
assert.strictEqual(cost, 0);
})
)
passed++;
else failed++;
if (
test('full model name claude-opus-4-6 uses opus rates', () => {
const cost = estimateCost('claude-opus-4-6', 500, 200);
// (500 / 1_000_000) * 15 + (200 / 1_000_000) * 75 = 0.0075 + 0.015 = 0.0225
const expected = Math.round(0.0225 * 1e6) / 1e6;
assert.strictEqual(cost, expected);
})
)
passed++;
else failed++;
if (
test('unknown model falls back to sonnet rates', () => {
const cost = estimateCost('unknown-model', 1_000_000, 1_000_000);
assert.strictEqual(cost, 18);
})
)
passed++;
else failed++;
// Summary
console.log(`\nResults: ${passed} passed, ${failed} failed\n`);
return { passed, failed };
}
const { failed } = runTests();
process.exit(failed > 0 ? 1 : 0);

View File

@@ -0,0 +1,174 @@
/**
* Tests for scripts/lib/session-bridge.js
*
* Run with: node tests/lib/session-bridge.test.js
*/
const assert = require('assert');
const fs = require('fs');
const { sanitizeSessionId, getBridgePath, readBridge, writeBridgeAtomic, resolveSessionId, MAX_SESSION_ID_LENGTH } = require('../../scripts/lib/session-bridge');
// Test helper
function test(name, fn) {
try {
fn();
console.log(` \u2713 ${name}`);
return true;
} catch (err) {
console.log(` \u2717 ${name}`);
console.log(` Error: ${err.message}`);
return false;
}
}
function runTests() {
console.log('\n=== Testing session-bridge.js ===\n');
let passed = 0;
let failed = 0;
// sanitizeSessionId tests
console.log('sanitizeSessionId:');
if (
test('valid ID passes through', () => {
assert.strictEqual(sanitizeSessionId('abc-123'), 'abc-123');
})
)
passed++;
else failed++;
if (
test('path traversal returns null', () => {
assert.strictEqual(sanitizeSessionId('../etc/passwd'), null);
})
)
passed++;
else failed++;
if (
test('forward slash returns null', () => {
assert.strictEqual(sanitizeSessionId('/tmp/evil'), null);
})
)
passed++;
else failed++;
if (
test('backslash returns null', () => {
assert.strictEqual(sanitizeSessionId('a\\b'), null);
})
)
passed++;
else failed++;
if (
test('null input returns null', () => {
assert.strictEqual(sanitizeSessionId(null), null);
})
)
passed++;
else failed++;
if (
test('empty string returns null', () => {
assert.strictEqual(sanitizeSessionId(''), null);
})
)
passed++;
else failed++;
if (
test('long string is truncated to MAX_SESSION_ID_LENGTH', () => {
const longId = 'a'.repeat(100);
const result = sanitizeSessionId(longId);
assert.ok(result, 'Should not return null for valid chars');
assert.strictEqual(result.length, MAX_SESSION_ID_LENGTH);
})
)
passed++;
else failed++;
// getBridgePath tests
console.log('\ngetBridgePath:');
if (
test('returns path containing ecc-metrics-', () => {
const p = getBridgePath('test-session');
assert.ok(p.includes('ecc-metrics-'), `Expected ecc-metrics- in path, got: ${p}`);
})
)
passed++;
else failed++;
// writeBridgeAtomic + readBridge roundtrip
console.log('\nwriteBridgeAtomic / readBridge:');
if (
test('roundtrip write then read returns same data', () => {
const testId = `test-bridge-${Date.now()}`;
const data = { session_id: testId, tool_count: 42 };
try {
writeBridgeAtomic(testId, data);
const result = readBridge(testId);
assert.deepStrictEqual(result, data);
} finally {
// Clean up
try {
fs.unlinkSync(getBridgePath(testId));
} catch {
/* ignore */
}
}
})
)
passed++;
else failed++;
if (
test('readBridge with nonexistent session returns null', () => {
const result = readBridge('nonexistent-session-id-999');
assert.strictEqual(result, null);
})
)
passed++;
else failed++;
// resolveSessionId tests
console.log('\nresolveSessionId:');
if (
test('resolveSessionId uses ECC_SESSION_ID env var', () => {
const original = process.env.ECC_SESSION_ID;
try {
process.env.ECC_SESSION_ID = 'env-session-42';
const result = resolveSessionId();
assert.strictEqual(result, 'env-session-42');
} finally {
if (original === undefined) {
delete process.env.ECC_SESSION_ID;
} else {
process.env.ECC_SESSION_ID = original;
}
}
})
)
passed++;
else failed++;
if (
test('MAX_SESSION_ID_LENGTH is 64', () => {
assert.strictEqual(MAX_SESSION_ID_LENGTH, 64);
})
)
passed++;
else failed++;
// Summary
console.log(`\nResults: ${passed} passed, ${failed} failed\n`);
return { passed, failed };
}
const { failed } = runTests();
process.exit(failed > 0 ? 1 : 0);