Files
everything-claude-code/scripts/hooks/ecc-metrics-bridge.js
Jamkris 63c9788f50 fix(hooks): scan full costs.jsonl when locating session row
`readSessionCost` read only the trailing 8 KiB of
`~/.claude/metrics/costs.jsonl` to "avoid scanning entire file".
That ceiling is the opposite-sign sibling of the double-count bug
fixed in the previous commit: once a session's most recent
cumulative row gets pushed past the 8 KiB window by newer rows
from other sessions, the bridge silently reports `totalCost: 0`,
`totalIn: 0`, `totalOut: 0` for that session — same false signal
to `ecc-context-monitor.js`, same wrong number injected into the
live model turn as `additionalContext`.

`cost-tracker.js` has no rotation policy, so on any non-trivial
workstation costs.jsonl grows past 8 KiB within minutes of normal
use. For users who keep multiple concurrent sessions, this means
the second-and-later sessions silently report zero almost
immediately.

Reproduced before this commit:

  $ HOME=/tmp/eccc node -e '
      const fs = require("fs");
      const m = require("./scripts/hooks/ecc-metrics-bridge.js");
      // S1 row at file start, then 200 rows of OTHER-session noise (~16 KiB).
      // S1 is the row we want, but it sits past the 8 KiB tail.
      const s1 = `{"session_id":"S1","estimated_cost_usd":0.5,"input_tokens":500,"output_tokens":250}`;
      const other = `{"session_id":"OTHER","estimated_cost_usd":1,"input_tokens":100,"output_tokens":50}`;
      fs.mkdirSync("/tmp/eccc/.claude/metrics", { recursive: true });
      fs.writeFileSync("/tmp/eccc/.claude/metrics/costs.jsonl",
        [s1, ...Array(200).fill(other)].join("\\n") + "\\n");
      console.log(JSON.stringify(m.readSessionCost("S1")));'
  {"totalCost":0,"totalIn":0,"totalOut":0}

Expected: `{"totalCost":0.5, "totalIn":500, "totalOut":250}` (the
S1 row that exists in the file).
Actual: zero — the row is past the 8 KiB tail.

Fix: drop the `fs.openSync` + bounded `fs.readSync` + position
arithmetic in favour of `fs.readFileSync(costsPath, 'utf8')` and
iterate every line. Each row is ~150 bytes; even 100k rows is
~15 MB and a single sync read on PreToolUse is in the low ms.
If file rotation lands in `cost-tracker.js` later, this scan
becomes proportionally cheaper.

After this commit the reproduction above returns
`{"totalCost":0.5, "totalIn":500, "totalOut":250}`.

Regression test in `tests/hooks/ecc-metrics-bridge.test.js`:
`readSessionCost finds session row beyond the old 8 KiB tail
boundary`. The test asserts the costs.jsonl fixture is > 8 KiB
before reading so any reintroduction of a bounded tail would
re-fail the test (i.e. the assertion is the contract, not the
specific number 8192).

Together with the previous commit, both directions of the
metrics-bridge cost-reporting bug are closed.
2026-05-17 21:41:24 -04:00

204 lines
6.3 KiB
JavaScript

#!/usr/bin/env node
/**
* ECC Metrics Bridge — PostToolUse hook
*
* Maintains a running session aggregate in /tmp/ecc-metrics-{session}.json.
* This bridge file is read by ecc-statusline.js and ecc-context-monitor.js,
* avoiding the need to scan large JSONL logs on every invocation.
*/
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { sanitizeSessionId, readBridge, writeBridgeAtomic } = require('../lib/session-bridge');
const { getClaudeDir } = require('../lib/utils');
const MAX_STDIN = 1024 * 1024;
const MAX_FILES_TRACKED = 200;
const RECENT_TOOLS_SIZE = 5;
const HASH_INPUT_LIMIT = 2048;
function toNumber(value) {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
}
function stableStringify(value, depth = 0) {
if (depth > 4) return '[depth-limit]';
if (value === null || typeof value !== 'object') return JSON.stringify(value);
if (Array.isArray(value)) {
return `[${value.map(item => stableStringify(item, depth + 1)).join(',')}]`;
}
return `{${Object.keys(value)
.sort()
.map(key => `${JSON.stringify(key)}:${stableStringify(value[key], depth + 1)}`)
.join(',')}}`;
}
/**
* Hash tool call for loop detection.
* Uses tool name + a key parameter when available, otherwise a stable input digest.
*/
function hashToolCall(toolName, toolInput) {
const name = String(toolName || '');
let key = '';
if (name === 'Bash') {
key = String(toolInput?.command || '').slice(0, 160);
} else if (toolInput?.file_path) {
key = String(toolInput.file_path);
} else {
key = stableStringify(toolInput || {}).slice(0, HASH_INPUT_LIMIT);
}
return crypto.createHash('sha256').update(`${name}:${key}`).digest('hex').slice(0, 8);
}
/**
* Extract modified file paths from tool input.
*/
function extractFilePaths(toolName, toolInput) {
const paths = [];
if (!toolInput || typeof toolInput !== 'object') return paths;
const fp = toolInput.file_path;
if (fp && typeof fp === 'string') paths.push(fp);
const edits = toolInput.edits;
if (Array.isArray(edits)) {
for (const edit of edits) {
if (edit?.file_path && typeof edit.file_path === 'string') {
paths.push(edit.file_path);
}
}
}
return paths;
}
/**
* Read cumulative cost for a session from costs.jsonl.
*
* Scans the full file because each row is a cumulative session total
* (see cost-tracker.js docblock) and the row we need is the last one
* matching `sessionId`. The previous implementation read only the
* trailing 8 KiB; any session whose latest cumulative row was pushed
* past that window by newer rows from other sessions silently dropped
* to zero — the opposite sign of the double-count bug fixed in the
* previous commit.
*
* costs.jsonl is append-only and unbounded today (no rotation in
* cost-tracker.js). At a typical ~150 bytes per row, even 100k rows
* is ~15 MB and a single sync read on every PreToolUse hook is in
* the low milliseconds. If rotation lands later, this scan becomes
* even cheaper.
*/
function readSessionCost(sessionId) {
try {
const costsPath = path.join(getClaudeDir(), 'metrics', 'costs.jsonl');
const content = fs.readFileSync(costsPath, 'utf8');
const lines = content.split('\n').filter(Boolean);
let totalCost = 0;
let totalIn = 0;
let totalOut = 0;
for (const line of lines) {
try {
const row = JSON.parse(line);
if (row.session_id === sessionId) {
totalCost = toNumber(row.estimated_cost_usd);
totalIn = toNumber(row.input_tokens);
totalOut = toNumber(row.output_tokens);
}
} catch {
/* skip malformed lines */
}
}
return { totalCost, totalIn, totalOut };
} catch {
return { totalCost: 0, totalIn: 0, totalOut: 0 };
}
}
/**
* @param {string} rawInput - Raw JSON string from stdin
* @returns {string} Pass-through
*/
function run(rawInput) {
try {
const input = rawInput.trim() ? JSON.parse(rawInput) : {};
const toolName = String(input.tool_name || '');
const toolInput = input.tool_input || {};
const sessionId = sanitizeSessionId(input.session_id) || sanitizeSessionId(process.env.ECC_SESSION_ID) || sanitizeSessionId(process.env.CLAUDE_SESSION_ID);
if (!sessionId) return rawInput;
const now = new Date().toISOString();
const bridge = readBridge(sessionId) || {
session_id: sessionId,
total_cost_usd: 0,
total_input_tokens: 0,
total_output_tokens: 0,
tool_count: 0,
files_modified_count: 0,
files_modified: [],
recent_tools: [],
first_timestamp: now,
last_timestamp: now,
context_remaining_pct: null
};
// Increment tool count
bridge.tool_count = (bridge.tool_count || 0) + 1;
bridge.last_timestamp = now;
if (!bridge.first_timestamp) bridge.first_timestamp = now;
// Track modified files (Write/Edit/MultiEdit only)
const isWriteOp = /^(Write|Edit|MultiEdit)$/i.test(toolName);
if (isWriteOp) {
const newPaths = extractFilePaths(toolName, toolInput);
const existing = new Set(bridge.files_modified || []);
for (const p of newPaths) {
if (existing.size < MAX_FILES_TRACKED && !existing.has(p)) {
existing.add(p);
}
}
bridge.files_modified = [...existing];
bridge.files_modified_count = existing.size;
}
// Ring buffer for loop detection
const recent = bridge.recent_tools || [];
recent.push({ tool: toolName, hash: hashToolCall(toolName, toolInput) });
if (recent.length > RECENT_TOOLS_SIZE) recent.shift();
bridge.recent_tools = recent;
// Update cost from costs.jsonl tail
const costs = readSessionCost(sessionId);
bridge.total_cost_usd = Math.round(costs.totalCost * 1e6) / 1e6;
bridge.total_input_tokens = costs.totalIn;
bridge.total_output_tokens = costs.totalOut;
writeBridgeAtomic(sessionId, bridge);
} catch {
// Never block tool execution
}
return rawInput;
}
if (require.main === module) {
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', chunk => {
if (data.length < MAX_STDIN) data += chunk.substring(0, MAX_STDIN - data.length);
});
process.stdin.on('end', () => {
process.stdout.write(run(data));
process.exit(0);
});
}
module.exports = { run, hashToolCall, extractFilePaths, readSessionCost, stableStringify };