Files
ruflo/plugins/ruflo-cost-tracker/scripts/_sessions.mjs
T
randRuFlo 7c0ad84e5e fix(cost-tracker): warm an npx CLI once before parallel subchecks; a failed CLI read is an error (#4711)
cost-health started four subchecks at once, each running
npx -y @claude-flow/cli@latest. With a cold npm cache the four first
installs raced in one ~/.npm/_npx directory and left a broken install. Its
memory reads then exited 1, and budget/_sessions read that as no data, so
the budget check reported "no budget set" and Case 2 of the integration
test failed about half the time.

- health.mjs resolves the CLI once, serially, when it comes from npx
  (HEALTH_SKIP_WARMUP=1 skips it).
- A non-zero memory list is reported as an error with the CLI's stderr
  (exit 2) by budget, burn, anomaly and projection.
- New test-cli-failure-4711.mjs, in smoke step 48 and the CI workflow; the
  integration test runs with RUFLO_DAEMON_AUTOSTART=0.
- ruflo-cost-tracker 0.31.2.

Closes #4711

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-11-05 17:52:20 -05:00

82 lines
3.2 KiB
JavaScript

// _sessions.mjs — shared session-loader for the cost-tracking namespace.
//
// Iter 73 consolidation. Six analytics scripts (anomaly, burn, conversation,
// counterfactual, projection, budget) previously duplicated identical
// boilerplate for reading sessions from the `cost-tracking` namespace.
// This module is the single source of truth. Math is byte-identical to
// the per-script copies it replaces.
//
// CONTRACT
// - `memoryListSessionKeys(ns)` → keys starting with `session-` only
// - `memoryListAllKeys(ns)` → ALL keys in namespace (for non-session lookups)
// - `memoryRetrieve(ns, key)` → parsed JSON value, or null on failure
// - `loadSessions(ns)` → array of session records (filters out nulls)
// - `sessionTs(rec)` → ms-since-epoch from capturedAt|endedAt|startedAt
// - `parseDurationMs(spec)` → ms for "Nh"/"Nd"/"Nw"/"Nm"; null on parse fail
import { spawnNpxSync } from './_npx.mjs';
const CLI_PKG = process.env.CLI_CORE === '1'
? '@claude-flow/cli-core@alpha'
: '@claude-flow/cli@latest';
/** One-line description of a failed CLI call, with its stderr. */
export function cliFailure(what, r) {
const detail = (r.error?.message || String(r.stderr || '')).trim().split('\n').slice(-3).join(' ').slice(0, 300);
return `${what} failed (exit ${r.status ?? 'none'})${detail ? `: ${detail}` : ''}`;
}
export function memoryListAllKeys(namespace) {
const r = spawnNpxSync([
CLI_PKG, 'memory', 'list',
'--namespace', namespace, '--format', 'json',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
// A fresh namespace lists [] with exit 0, so a non-zero exit is a real
// failure (e.g. a broken npx install, #4711). Reporting it as "no data"
// made a budget check say "no budget set".
if (r.status !== 0) throw new Error(cliFailure('memory list', r));
const m = /\[[\s\S]*\]/.exec(r.stdout || '');
if (!m) return [];
let entries;
try { entries = JSON.parse(m[0]); } catch { return []; }
return entries
.map((e) => e.key)
.filter((k) => typeof k === 'string');
}
export function memoryListSessionKeys(namespace) {
return memoryListAllKeys(namespace).filter((k) => k.startsWith('session-'));
}
export function memoryRetrieve(namespace, key) {
const r = spawnNpxSync([
CLI_PKG, 'memory', 'retrieve',
'--namespace', namespace, '--key', key, '--value-only',
], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8', shell: process.platform === 'win32' });
if (r.status !== 0) return null;
try { return JSON.parse((r.stdout || '').trim()); } catch { return null; }
}
export function loadSessions(namespace) {
const keys = memoryListSessionKeys(namespace);
const records = [];
for (const k of keys) {
const rec = memoryRetrieve(namespace, k);
if (rec) records.push(rec);
}
return records;
}
export function sessionTs(rec) {
const t = rec.capturedAt || rec.endedAt || rec.startedAt;
return t ? new Date(t).getTime() : 0;
}
export function parseDurationMs(spec) {
const m = /^(\d+)([hdwm])$/.exec(spec);
if (!m) return null;
const n = parseInt(m[1], 10);
const unit = { h: 3600_000, d: 86400_000, w: 7 * 86400_000, m: 30 * 86400_000 }[m[2]];
return unit ? n * unit : null;
}