mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 14:16:34 +09:00
* fix(#1927): ruflo-cost-tracker encodeProjectPath handles Windows `\` + drive `:` `track.mjs` couldn't find Claude Code session jsonls on Windows because `encodeProjectPath()` only replaced `/` — a no-op on `D:\project\Foo`, so it looked under a corrupt `~/.claude/projects/D:\project\Foo` instead of the real `~/.claude/projects/D--project-Foo`. Now replaces `/`, `\`, and `:` with `-` (matching Claude Code's encoding); POSIX paths are unchanged. CI guard: smoke.sh step 29b runs `track.mjs` with `TRACK_CWD='D:\project\Subcloudy'` and asserts the (expected-to-fail) "looked under" line shows `D--project-Subcloudy` and not the corrupt un-encoded form. Negative-tested. Also fixed smoke.sh step 8 (ADR-0001 is `Accepted`, not `Proposed` — the check was stale; cost-tracker-smoke was already red on main because of it). Witness marker #1927. Not fixed here (secondary issue in the report): on long Windows sessions `spawnSync('npx', ['claude-flow', 'memory', 'store', '--value', JSON.stringify(summary)])` can exceed the CreateProcess argv limit when `summary` is large — a follow-up (write to a temp file / stream via stdin). Co-Authored-By: RuFlo <ruv@ruv.net> * ci: green up witness-verify (sync linux/windows manifests) + cost-tracker-smoke (.ci-bench npm-init) Two pre-existing CI reds, surfaced while making sure all builds pass: - witness-verify on ubuntu/windows failed after #1923: it verifies the per-OS manifest (verification/{linux,windows}/manifest.md.json), but regen-witness.mjs only ever rewrites the *current* OS's manifest (macos on the maintainer's machine), so the linux/windows snapshots still had the pre-#1923 `#1862` marker — which #1923 changed when it moved the hook invocation behind ruflo-hook.sh. Synced linux + windows manifests to the current macos one (byte-identical at the same commit — the Ed25519 seed is derived from gitCommit only, not OS, and the dist .js are LF everywhere). All 3 verify clean (pass=113, 0 regressed). - cost-tracker-smoke `Install agent-booster for the bench` step did `npm init -y` inside `.ci-bench/`, and npm 11 rejects a package name starting with `.`. Write the manifest explicitly instead. Co-Authored-By: RuFlo <ruv@ruv.net> * ci(v3): run v3-ci.yml on pull_request when verification/** changes (witness-verify on PRs) Without this, a PR that bumps witness-fixes.json / regenerates a per-OS manifest doesn't trigger witness-verify, so a stale per-OS manifest only fails after merge to main (the push trigger does have verification/**). Co-Authored-By: RuFlo <ruv@ruv.net> --------- Co-authored-by: Reuven <cohen@ruv-mac-mini.local>
199 lines
7.8 KiB
JavaScript
Executable File
199 lines
7.8 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
// cost-track — auto-capture token usage from a Claude Code session jsonl
|
|
// and persist a structured record to the `cost-tracking` AgentDB namespace.
|
|
//
|
|
// Resolution: by default reads the most-recently-modified session jsonl in
|
|
// ~/.claude/projects/<encoded-cwd>/. Override with TRACK_CWD or TRACK_SESSION.
|
|
//
|
|
// Optional env:
|
|
// TRACK_CWD=<path> override which project's sessions to scan
|
|
// TRACK_SESSION=<file> pin to a specific session jsonl
|
|
// TRACK_OUT=<path> also write the JSON summary to this path
|
|
// TRACK_DRY_RUN=1 skip the memory_store call
|
|
// TRACK_QUIET=1 suppress markdown summary
|
|
// TRACK_NAMESPACE=<name> override (default: cost-tracking)
|
|
|
|
import { readFileSync, writeFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { homedir } from 'node:os';
|
|
import { spawnSync } from 'node:child_process';
|
|
|
|
const PROJECTS_DIR = join(homedir(), '.claude', 'projects');
|
|
|
|
// USD per 1M tokens — kept in sync with REFERENCE.md "Model pricing" table.
|
|
const PRICING = {
|
|
haiku: { input: 0.25, output: 1.25, cache_write: 0.30, cache_read: 0.03 },
|
|
sonnet: { input: 3.00, output: 15.00, cache_write: 3.75, cache_read: 0.30 },
|
|
opus: { input: 15.00, output: 75.00, cache_write: 18.75, cache_read: 1.50 },
|
|
};
|
|
|
|
function modelTier(model) {
|
|
if (!model) return 'unknown';
|
|
const m = String(model).toLowerCase();
|
|
if (m.includes('haiku')) return 'haiku';
|
|
if (m.includes('sonnet')) return 'sonnet';
|
|
if (m.includes('opus')) return 'opus';
|
|
return 'unknown';
|
|
}
|
|
|
|
function costForUsage(tier, usage) {
|
|
const p = PRICING[tier];
|
|
if (!p || !usage) return 0;
|
|
return (usage.input_tokens || 0) / 1e6 * p.input
|
|
+ (usage.output_tokens || 0) / 1e6 * p.output
|
|
+ (usage.cache_creation_input_tokens || 0) / 1e6 * p.cache_write
|
|
+ (usage.cache_read_input_tokens || 0) / 1e6 * p.cache_read;
|
|
}
|
|
|
|
function encodeProjectPath(cwd) {
|
|
// #1927: Claude Code encodes an absolute path by replacing path separators
|
|
// AND the Windows drive colon with `-`. So:
|
|
// POSIX: /home/user/proj -> -home-user-proj
|
|
// Windows: D:\project\Subcloudy -> D--project-Subcloudy (`:` -> `-`, `\` -> `-`)
|
|
// The old code only replaced `/`, a no-op on Windows paths.
|
|
return cwd.replace(/[/\\:]/g, '-');
|
|
}
|
|
|
|
function findProjectDir(cwd) {
|
|
const candidate = join(PROJECTS_DIR, encodeProjectPath(cwd));
|
|
return existsSync(candidate) ? candidate : null;
|
|
}
|
|
|
|
function findActiveSession(projectDir) {
|
|
const entries = readdirSync(projectDir)
|
|
.filter((f) => f.endsWith('.jsonl'))
|
|
.map((f) => ({ f, mtime: statSync(join(projectDir, f)).mtimeMs }))
|
|
.sort((a, b) => b.mtime - a.mtime);
|
|
return entries[0] ? join(projectDir, entries[0].f) : null;
|
|
}
|
|
|
|
function summarizeSession(jsonlPath) {
|
|
const text = readFileSync(jsonlPath, 'utf-8');
|
|
const lines = text.split('\n').filter(Boolean);
|
|
const byModel = {};
|
|
const byTier = { haiku: 0, sonnet: 0, opus: 0, unknown: 0 };
|
|
let messageCount = 0, totalCost = 0;
|
|
let firstTs = null, lastTs = null;
|
|
let sessionId = null, cwd = null;
|
|
|
|
for (const line of lines) {
|
|
let m;
|
|
try { m = JSON.parse(line); } catch { continue; }
|
|
if (!sessionId && m.sessionId) sessionId = m.sessionId;
|
|
if (!cwd && m.cwd) cwd = m.cwd;
|
|
if (m.timestamp) {
|
|
if (!firstTs || m.timestamp < firstTs) firstTs = m.timestamp;
|
|
if (!lastTs || m.timestamp > lastTs) lastTs = m.timestamp;
|
|
}
|
|
if (m.type !== 'assistant' || !m.message?.usage) continue;
|
|
messageCount++;
|
|
const model = m.message.model || 'unknown';
|
|
const tier = modelTier(model);
|
|
const u = m.message.usage;
|
|
const cost = costForUsage(tier, u);
|
|
const slot = byModel[model] || {
|
|
tier,
|
|
input_tokens: 0, output_tokens: 0,
|
|
cache_creation_input_tokens: 0, cache_read_input_tokens: 0,
|
|
messages: 0, cost_usd: 0,
|
|
};
|
|
slot.input_tokens += u.input_tokens || 0;
|
|
slot.output_tokens += u.output_tokens || 0;
|
|
slot.cache_creation_input_tokens += u.cache_creation_input_tokens || 0;
|
|
slot.cache_read_input_tokens += u.cache_read_input_tokens || 0;
|
|
slot.messages++;
|
|
slot.cost_usd += cost;
|
|
byModel[model] = slot;
|
|
byTier[tier] += cost;
|
|
totalCost += cost;
|
|
}
|
|
|
|
return {
|
|
sessionId, cwd, startedAt: firstTs, endedAt: lastTs,
|
|
messageCount, byModel, byTier, total_cost_usd: totalCost,
|
|
capturedAt: new Date().toISOString(),
|
|
};
|
|
}
|
|
|
|
function persistToMemory(summary) {
|
|
const ns = process.env.TRACK_NAMESPACE || 'cost-tracking';
|
|
const key = `session-${summary.sessionId || 'unknown'}`;
|
|
// ADR-100 / #1748 Issue 3 — opt into cli-core's lite path with CLI_CORE=1.
|
|
// Cold-cache wall-time drops from ~25s to ~2s. JSON backend instead of
|
|
// SQLite/HNSW; semantic search degrades to substring (fine for cost-track
|
|
// which never invokes search — only store/list/retrieve). See
|
|
// v3/@claude-flow/cli-core/MIGRATION.md.
|
|
const cliPkg = process.env.CLI_CORE === '1'
|
|
? '@claude-flow/cli-core@alpha'
|
|
: '@claude-flow/cli@latest';
|
|
// spawnSync with explicit args avoids shell-escape pitfalls for the JSON value.
|
|
const r = spawnSync('npx', [
|
|
cliPkg, 'memory', 'store',
|
|
'--namespace', ns,
|
|
'--key', key,
|
|
'--value', JSON.stringify(summary),
|
|
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
|
|
if (r.status !== 0) {
|
|
return { ok: false, reason: r.stderr?.slice(0, 300) || `exit ${r.status}` };
|
|
}
|
|
return { ok: true, namespace: ns, key };
|
|
}
|
|
|
|
function main() {
|
|
const targetCwd = process.env.TRACK_CWD || process.cwd();
|
|
const projectDir = findProjectDir(targetCwd);
|
|
if (!projectDir) {
|
|
console.error(`cost-track: no Claude Code project dir for cwd=${targetCwd}`);
|
|
console.error(`looked under ${PROJECTS_DIR}/${encodeProjectPath(targetCwd)}`);
|
|
process.exit(2);
|
|
}
|
|
const sessionPath = process.env.TRACK_SESSION || findActiveSession(projectDir);
|
|
if (!sessionPath || !existsSync(sessionPath)) {
|
|
console.error(`cost-track: no session jsonl in ${projectDir}`);
|
|
process.exit(2);
|
|
}
|
|
|
|
const summary = summarizeSession(sessionPath);
|
|
|
|
if (process.env.TRACK_OUT) {
|
|
writeFileSync(process.env.TRACK_OUT, JSON.stringify(summary, null, 2));
|
|
}
|
|
|
|
let storeResult = { ok: false, reason: 'dry-run' };
|
|
if (process.env.TRACK_DRY_RUN !== '1') {
|
|
storeResult = persistToMemory(summary);
|
|
}
|
|
|
|
if (process.env.TRACK_QUIET === '1') return;
|
|
|
|
console.log(`# cost-track — session ${(summary.sessionId || '').slice(0, 8) || 'unknown'}`);
|
|
console.log('');
|
|
console.log(`| Metric | Value |`);
|
|
console.log(`|---|---:|`);
|
|
console.log(`| Session ID | \`${summary.sessionId}\` |`);
|
|
console.log(`| Project | \`${summary.cwd}\` |`);
|
|
console.log(`| First message | ${summary.startedAt} |`);
|
|
console.log(`| Last message | ${summary.endedAt} |`);
|
|
console.log(`| Assistant messages | ${summary.messageCount} |`);
|
|
console.log(`| **Total cost** | **$${summary.total_cost_usd.toFixed(6)}** |`);
|
|
console.log(`| Persisted | ${storeResult.ok ? `\`${storeResult.namespace}:${storeResult.key}\`` : `**FAILED** (${storeResult.reason})`} |`);
|
|
console.log('');
|
|
console.log('## Per-model breakdown');
|
|
console.log('');
|
|
console.log('| Model | Tier | Messages | Input | Output | Cache write | Cache read | Cost |');
|
|
console.log('|---|---|---:|---:|---:|---:|---:|---:|');
|
|
for (const [m, s] of Object.entries(summary.byModel).sort((a, b) => b[1].cost_usd - a[1].cost_usd)) {
|
|
console.log(`| \`${m}\` | ${s.tier} | ${s.messages} | ${s.input_tokens} | ${s.output_tokens} | ${s.cache_creation_input_tokens} | ${s.cache_read_input_tokens} | $${s.cost_usd.toFixed(6)} |`);
|
|
}
|
|
console.log('');
|
|
console.log('## Per-tier breakdown');
|
|
console.log('');
|
|
console.log('| Tier | Cost |');
|
|
console.log('|---|---:|');
|
|
for (const [t, c] of Object.entries(summary.byTier).sort((a, b) => b[1] - a[1])) {
|
|
if (c > 0) console.log(`| ${t} | $${c.toFixed(6)} |`);
|
|
}
|
|
}
|
|
|
|
main();
|