Files
ruflo/plugins/ruflo-cost-tracker/scripts/compact.mjs
T
randclaude-flow ab18c33548 fix(deps): zod ^4.6.7 floor, integration agentic-flow ^2.0.14, mcp/codex/shared advisory floors
zod (GHSA-mrhx-c7xc-m3w5): shared, claims, the twelve v3 plugins,
ruvector-upstream, plugins/ruflo-{arena,ai-team,chatgpt-federation,x-gateway}
and goal_ui move to zod ^4.6.7. hooks declared zod but never imported it, so
the dependency is dropped.

gastown-bridge drops uuid/@types/uuid (GHSA-w5hq-g745-h8pq).

integration: peer agentic-flow ^2.0.0-alpha -> ^2.0.14 || ^3.0.0
(GHSA-vcv2-r9jh-99m5). The repo source already matched the published 3.0.2,
so this ships as 3.0.3. A patched agentic-flow leaves a ReasoningBank timer
alive, which made plugins/ruflo-cost-tracker/scripts/compact.mjs print its
result and never exit; compact.mjs now exits after stdout drains, guarded by
scripts/smoke-compact-exit.mjs (hangs on main, passes here) in
cost-tracker-smoke.

Stale ranges outside the cli: mcp ws ^8.21.0 (GHSA-96hv-2xvq-fx4p), express
^4.22.3 (GHSA-qw6h-vgh9-j6wx), ajv ^8.20.0 (GHSA-2g4f-4pwh-qvx6); codex yaml
^2.8.3 (GHSA-48c2-rrv3-qjmp); shared express ^4.22.3 || ^5.1.0. Each package
gets an advisory-ranges test over its own manifest.

ADR-356 metadata on every published manifest: homepage https://ruv.io,
canonical repository with directory, bugs, 8-20 keywords, description
<= 200 characters.

Versions: shared 3.0.8, hooks 3.0.3, claims 3.0.1, integration 3.0.3,
mcp 3.1.7, codex 3.0.7, gastown-bridge 0.1.6, prime-radiant 0.1.7, other
v3 plugins one alpha up. Marketplace plugin.json bumps for the five changed
plugins. The cli, claude-flow and ruflo pins are left for the release lane.

Lockfiles: v3/pnpm-lock.yaml drops the agentic-flow@2.0.0-alpha tree;
standalone plugin locks were regenerated with npm 11 (npm 10 crashed on a
stale optional peer in four of them).

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-11-09 02:21:15 -05:00

168 lines
6.5 KiB
JavaScript
Executable File

#!/usr/bin/env node
// cost-compact — wraps getTokenOptimizer().getCompactContext() so the
// cost-compact-context skill can invoke a single command instead of an
// inlined Node one-liner.
//
// Resolution strategy (#1930): pnpm-workspace marketplace installs don't
// hoist `@claude-flow/integration` into `v3/node_modules/`. The resolved
// module is imported, so it never comes from the cwd (the project). Try:
// 1. createRequire(script-dir) — works when run from inside the plugin
// 2. absolute path from this file — works on the marketplace layout
// (script lives at <ruflo>/plugins/ruflo-cost-tracker/scripts/, the
// integration package at <ruflo>/v3/@claude-flow/integration/)
//
// Also: agentic-flow's index.js binds `process.env.HEALTH_PORT || 8080`
// unconditionally on import. On any host with something already on 8080
// (k8s NodePort, forwarded dev server) the import EADDRINUSEs. Set
// HEALTH_PORT to 0 by default so the OS picks a free port — users can
// still override with an explicit value.
//
// Usage:
// node scripts/compact.mjs "<query>"
//
// Optional env:
// COMPACT_QUIET=1 emit JSON only (no markdown banner)
// HEALTH_PORT=<n> override agentic-flow's health-server port (default 0)
//
// The script always exits when it is done, even if agentic-flow leaves a
// timer or server handle open.
import { createRequire } from 'node:module';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { join, resolve, dirname, isAbsolute } from 'node:path';
import { existsSync } from 'node:fs';
// #1930 step 4: pick a free port unless caller pinned one. Set BEFORE the
// dynamic import below — agentic-flow reads HEALTH_PORT at module-load time.
if (!process.env.HEALTH_PORT) process.env.HEALTH_PORT = '0';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function tryResolveFrom(anchorPath) {
try {
const req = createRequire(anchorPath);
return req.resolve('@claude-flow/integration/token-optimizer');
} catch {
return null;
}
}
function tryAbsolutePath() {
// Walk up from this script looking for `v3/@claude-flow/integration/dist/token-optimizer.js`.
// Handles the marketplace layout (script at plugins/ruflo-cost-tracker/scripts/) and the
// dev-repo layout. Caps depth at 6 to avoid runaway traversal.
let dir = __dirname;
for (let i = 0; i < 6; i++) {
const candidate = join(dir, 'v3', '@claude-flow', 'integration', 'dist', 'token-optimizer.js');
if (existsSync(candidate)) return candidate;
const parent = dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
async function main() {
const query = process.argv[2] || '';
if (!query) {
console.error('usage: compact.mjs "<query>"');
process.exit(2);
}
// Resolution chain — script dir → absolute fallback (#1930 step 5). Not the
// cwd: the module found here is imported, and the cwd is the project.
const candidates = [
tryResolveFrom(join(__dirname, 'package.json')),
tryAbsolutePath(),
].filter(Boolean);
let mod;
let lastErr = null;
for (const resolved of candidates) {
try {
// Skip dangling resolutions that point at a non-existent file (a
// common pnpm-workspace symptom when dist/ wasn't built — see
// #1930 step 1).
const abs = isAbsolute(resolved) ? resolved : resolve(resolved);
if (!existsSync(abs)) {
lastErr = new Error(`token-optimizer.js missing at ${abs} — run \`cd v3/@claude-flow/integration && pnpm run build\` (#1930 step 1)`);
continue;
}
mod = await import(pathToFileURL(abs).href);
break;
} catch (err) {
lastErr = err;
}
}
if (!mod) {
const reason = lastErr
? String(lastErr.message || lastErr).slice(0, 300)
: 'Cannot find module @claude-flow/integration/token-optimizer';
const out = {
bridgeUnavailable: true,
reason,
memoriesRetrieved: 0,
tokensSaved: 0,
agenticFlowAvailable: false,
hint: 'Tried the script dir and the absolute path from this script — see #1930 for full troubleshooting.',
};
if (process.env.COMPACT_QUIET === '1') return console.log(JSON.stringify(out));
console.log(`# cost-compact-context\n\nbridge unavailable: ${reason}`);
console.log('');
console.log('Tried:');
console.log(' - resolve from cwd');
console.log(' - resolve from script dir');
console.log(' - absolute path walk from this script (looking for v3/@claude-flow/integration/dist/token-optimizer.js)');
console.log('');
console.log('If `@claude-flow/integration` is installed but `dist/` is missing, run:');
console.log(' cd v3/@claude-flow/integration && pnpm run build');
return;
}
const { getTokenOptimizer } = mod;
const opt = await getTokenOptimizer();
const ctx = await opt.getCompactContext(query);
const stats = opt.getStats();
const out = {
query,
memoriesRetrieved: ctx.memories?.length ?? 0,
tokensSaved: ctx.tokensSaved ?? 0,
agenticFlowAvailable: !!stats?.agenticFlowAvailable,
cacheHitRate: stats?.cacheHitRate || '0%',
upstreamReported: 'tokensSaved is bridge-reported (heuristic), not measured against a no-RAG baseline',
};
if (process.env.COMPACT_QUIET === '1') return console.log(JSON.stringify(out));
console.log(`# cost-compact-context — query: "${query}"`);
console.log('');
console.log('| Metric | Value |');
console.log('|---|---:|');
console.log(`| Memories retrieved | ${out.memoriesRetrieved} |`);
console.log(`| Tokens saved (bridge-reported) | ${out.tokensSaved} |`);
console.log(`| agentic-flow bridge available | ${out.agenticFlowAvailable} |`);
console.log(`| Cache hit rate | ${out.cacheHitRate} |`);
console.log('');
console.log(`> ${out.upstreamReported}`);
if (!out.agenticFlowAvailable) {
console.log('');
console.log('agentic-flow not installed — bridge returns inert results. No compact-context savings.');
}
}
// Exit explicitly once stdout has drained. A patched agentic-flow (>= 2.0.14)
// leaves a ReasoningBank timer alive after getTokenOptimizer(), so the event
// loop never empties and the script would print its result and then hang. The
// empty write's callback runs after every earlier console.log chunk has been
// flushed, so piped output is not truncated.
function exitAfterFlush(code) {
process.stdout.write('', () => process.exit(code));
}
main().then(
() => exitAfterFlush(0),
(e) => { console.error('compact.mjs failed:', e.message || e); exitAfterFlush(1); },
);