Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(cost-tracker): P5 β€” cost-trend skill surfaces drift across bench runs (v0.9.0)

Reuven89d7584b457d
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
index a54008ea81..cd937e3c0b 100644
--- a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
+++ b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "ruflo-cost-tracker",
"description": "Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations β€” uses memory_* (namespace-routed) for cost-tracking and cost-patterns; pairs with federation budget circuit breaker (ADR-097)",
- "version": "0.8.0",
+ "version": "0.9.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -25,6 +25,7 @@
"verified",
"telemetry",
"budget",
- "model-outcome"
+ "model-outcome",
+ "trend-analysis"
]
}
diff --git a/plugins/ruflo-cost-tracker/README.md b/plugins/ruflo-cost-tracker/README.md
index c5e2d72169..fdf2559ee0 100644
--- a/plugins/ruflo-cost-tracker/README.md
+++ b/plugins/ruflo-cost-tracker/README.md
@@ -29,6 +29,7 @@ claude --plugin-dir plugins/ruflo-cost-tracker
| `cost-booster-route` | `/cost-booster-route <task>` | Route tasks via `hooks_route` and report Agent Booster (Tier 1) bypass utilization |
| `cost-booster-edit` | `/cost-booster-edit <intent> <file>` | **Apply** a Tier 1 transform via `agent-booster.apply()` (sub-millisecond, $0, deterministic) |
| `cost-benchmark` | `/cost-benchmark [--llm] [--anthropic]` | Run the corpus benchmark and persist measured-vs-claimed table to `docs/benchmarks/runs/` |
+| `cost-trend` | `/cost-trend` | Read all bench runs and surface drift (win rate, latency, speedup) β€” flags regressions the smoke gate misses |
| `cost-compact-context` | `/cost-compact-context <query>` | Wrap `getTokenOptimizer().getCompactContext()` for retrieval-compacted analysis (graceful fallback when agentic-flow not installed) |
## Commands (8 subcommands)
@@ -44,6 +45,7 @@ cost budget set <amount> # Set budget limit in USD
cost optimize # Analyze usage and suggest savings (+ auto-emits hooks_model-outcome via outcome.mjs)
cost outcome <task> <model> <outcome> # Emit hooks_model-outcome (success|escalated|failure) so the router learns
cost benchmark [--llm] [--anthropic] # Run measured benchmark β€” booster + optional Gemini/Sonnet/Opus baselines
+cost trend # Drift across bench runs (win rate, latency, regressions)
cost workers # Inspect optimize + benchmark loop-workers consumed
cost history # Show cost tracking over time
```
@@ -131,7 +133,7 @@ Reserved namespaces (`pattern`, `claude-memories`, `default`) MUST NOT be shadow
```bash
bash plugins/ruflo-cost-tracker/scripts/smoke.sh
-# Expected: "37 passed, 0 failed"
+# Expected: "39 passed, 0 failed"
```
## Architecture Decisions
diff --git a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md b/plugins/ruflo-cost-tracker/commands/ruflo-cost.md
index 983b8b89c8..1043cd91cc 100644
--- a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md
+++ b/plugins/ruflo-cost-tracker/commands/ruflo-cost.md
@@ -55,6 +55,11 @@ Cost tracking commands:
3. The script wraps `npx @claude-flow/cli hooks model-outcome -t ... -m ... -o ...` with explicit-argv spawnSync so quoting is safe
4. Without this, the router doesn't learn from cost-optimize recommendations and the Tier 1 bypass rate doesn't tighten over time
+**`cost trend`** -- Read all docs/benchmarks/runs/*.json and surface drift in the gate metrics β€” win rate, avg latency, p99, escalation rate, speedup vs LLM. Flags regressions the binary smoke gate misses.
+1. Run `node plugins/ruflo-cost-tracker/scripts/trend.mjs`
+2. Optional `TREND_FORMAT=json` for machine-readable output, `TREND_LIMIT=N` to truncate
+3. Reports: firstβ†’last deltas + per-run series + regression flags (win rate drop or β‰₯1.5Γ— latency rise)
+
**`cost benchmark [--llm] [--anthropic]`** -- Run the corpus benchmark to verify booster claims with measured numbers.
1. Without flags: booster-only (free, ~85 ms wall-time, no API keys needed)
2. `--llm`: also run Gemini 2.0 Flash baseline (uses GCP `GOOGLE_AI_API_KEY` secret)
diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.sh
index 9507d8a044..407fcd8c56 100755
--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh
+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh
@@ -8,10 +8,10 @@ step() { printf "β†’ %s ... " "$1"; }
ok() { printf "PASS\n"; PASS=$((PASS+1)); }
bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }
-step "1. plugin.json declares 0.8.0 with new keywords"
+step "1. plugin.json declares 0.9.0 with new keywords"
v=$(grep -E '"version"' "$ROOT/.claude-plugin/plugin.json" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
-if [[ "$v" != "0.8.0" ]]; then
- bad "expected 0.8.0, got '$v'"
+if [[ "$v" != "0.9.0" ]]; then
+ bad "expected 0.9.0, got '$v'"
else
miss=""
for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget; do
@@ -20,9 +20,9 @@ else
[[ -z "$miss" ]] && ok || bad "missing keywords:$miss"
fi
-step "2. all eight skills present with valid frontmatter"
+step "2. all nine skills present with valid frontmatter"
miss=""
-for s in cost-report cost-optimize cost-booster-route cost-booster-edit cost-compact-context cost-benchmark cost-track cost-budget-check; do
+for s in cost-report cost-optimize cost-booster-route cost-booster-edit cost-compact-context cost-benchmark cost-track cost-budget-check cost-trend; do
f="$ROOT/skills/$s/SKILL.md"
[[ -f "$f" ]] || { miss="$miss missing-$s"; continue; }
for k in 'name:' 'description:' 'allowed-tools:'; do
@@ -302,5 +302,22 @@ grep -q "compact\.mjs" "$F2" || miss="$miss skill-not-updated"
grep -q 'node --input-type=module -e' "$F2" && miss="$miss inline-node-still-present"
[[ -z "$miss" ]] && ok || bad "$miss"
+step "38. cost-trend skill + trend.mjs surface drift across runs"
+F1="$ROOT/scripts/trend.mjs"
+F2="$ROOT/skills/cost-trend/SKILL.md"
+miss=""
+[[ -x "$F1" ]] || miss="$miss trend-not-executable"
+node --check "$F1" 2>/dev/null || miss="$miss syntax-error"
+grep -qE "winRate|avg latency|escalationRate" "$F1" || miss="$miss no-metrics"
+grep -qE "Regression|⚠" "$F1" || miss="$miss no-regression-flag"
+[[ -f "$F2" ]] || miss="$miss skill-missing"
+grep -q "trend\.mjs" "$F2" || miss="$miss skill-no-script-ref"
+grep -q '^allowed-tools:[[:space:]]*\*' "$F2" && miss="$miss wildcard"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
+step "39. ruflo-cost.md documents 'cost trend' subcommand"
+grep -q "cost trend" "$ROOT/commands/ruflo-cost.md" \
+ && ok || bad "missing"
+
printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]] || exit 1
diff --git a/plugins/ruflo-cost-tracker/scripts/trend.mjs b/plugins/ruflo-cost-tracker/scripts/trend.mjs
new file mode 100755
index 0000000000..268f135916
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/scripts/trend.mjs
@@ -0,0 +1,128 @@
+#!/usr/bin/env node
+// cost-trend β€” read every docs/benchmarks/runs/*.json and surface drift in
+// the gate metrics (winRate, avg latency, total cost). Catches regressions
+// the smoke gate misses (gate is binary; trend is a curve).
+//
+// Usage:
+// node scripts/trend.mjs # markdown summary
+// TREND_FORMAT=json node scripts/trend.mjs # machine-readable JSON
+// TREND_LIMIT=10 node scripts/trend.mjs # consider only the most recent N runs
+
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join, resolve } from 'node:path';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const PLUGIN_ROOT = resolve(HERE, '..');
+const RUNS_DIR = join(PLUGIN_ROOT, 'docs', 'benchmarks', 'runs');
+
+function loadRuns() {
+ const files = readdirSync(RUNS_DIR)
+ .filter((f) => f.endsWith('.json') && f !== 'latest.json')
+ .map((f) => ({ f, mtime: statSync(join(RUNS_DIR, f)).mtimeMs }))
+ .sort((a, b) => a.mtime - b.mtime);
+ const limit = parseInt(process.env.TREND_LIMIT || '50', 10);
+ return files.slice(-limit).map(({ f }) => {
+ try {
+ const json = JSON.parse(readFileSync(join(RUNS_DIR, f), 'utf-8'));
+ return { file: f, summary: json.summary || {} };
+ } catch {
+ return null;
+ }
+ }).filter(Boolean);
+}
+
+function pct(n) { return `${(n * 100).toFixed(1)}%`; }
+function ms(n) { return `${(n || 0).toFixed(2)}ms`; }
+function delta(curr, prev, fmt = (x) => x.toFixed(2), unit = '') {
+ if (prev === null || prev === undefined || curr === null || curr === undefined) return '';
+ const d = curr - prev;
+ const sign = d > 0 ? '+' : '';
+ return ` (${sign}${fmt(d)}${unit})`;
+}
+
+function main() {
+ const runs = loadRuns();
+ if (runs.length === 0) {
+ console.log('No bench runs found in', RUNS_DIR);
+ process.exit(0);
+ }
+
+ const series = runs.map((r) => ({
+ file: r.file,
+ runAt: r.summary.runAt,
+ winRate: r.summary.winRate,
+ avgLatencyMs: r.summary.avgLatencyMs,
+ p99LatencyMs: r.summary.p99LatencyMs,
+ overallCorrect: r.summary.overallCorrect,
+ escalationRate: r.summary.escalationRate,
+ avgConfidence: r.summary.avgConfidence,
+ speedupVsLlm: r.summary.speedupVsLlm,
+ llmCost: r.summary.llmBaseline?.totalCostUsd,
+ anthropicSonnet:
+ r.summary.anthropic?.['claude-sonnet-4-6']?.avgLatencyMs || null,
+ anthropicOpus:
+ r.summary.anthropic?.['claude-opus-4-7']?.avgLatencyMs || null,
+ }));
+
+ const first = series[0];
+ const last = series[series.length - 1];
+
+ if (process.env.TREND_FORMAT === 'json') {
+ console.log(JSON.stringify({ runs: series.length, first, last, series }, null, 2));
+ return;
+ }
+
+ console.log(`# cost-tracker bench trend (${series.length} runs)`);
+ console.log('');
+ console.log(`First run: \`${first.file}\` (${first.runAt})`);
+ console.log(`Last run: \`${last.file}\` (${last.runAt})`);
+ console.log('');
+ console.log('## Drift summary (last vs first)');
+ console.log('');
+ console.log('| Metric | First | Last | Ξ” |');
+ console.log('|---|---:|---:|---:|');
+ if (first.winRate != null && last.winRate != null) {
+ console.log(`| Win rate (Tier 1) | ${pct(first.winRate)} | ${pct(last.winRate)} | ${pct(last.winRate - first.winRate)} |`);
+ }
+ if (first.avgLatencyMs != null && last.avgLatencyMs != null) {
+ console.log(`| Avg latency | ${ms(first.avgLatencyMs)} | ${ms(last.avgLatencyMs)} | ${ms(last.avgLatencyMs - first.avgLatencyMs)} |`);
+ }
+ if (first.p99LatencyMs != null && last.p99LatencyMs != null) {
+ console.log(`| p99 latency | ${ms(first.p99LatencyMs)} | ${ms(last.p99LatencyMs)} | ${ms(last.p99LatencyMs - first.p99LatencyMs)} |`);
+ }
+ if (first.escalationRate != null && last.escalationRate != null) {
+ console.log(`| Escalation rate | ${pct(first.escalationRate)} | ${pct(last.escalationRate)} | ${pct(last.escalationRate - first.escalationRate)} |`);
+ }
+ if (first.speedupVsLlm != null && last.speedupVsLlm != null) {
+ console.log(`| Speedup vs Gemini | ${first.speedupVsLlm.toFixed(1)}Γ— | ${last.speedupVsLlm.toFixed(1)}Γ— | ${(last.speedupVsLlm - first.speedupVsLlm).toFixed(1)}Γ— |`);
+ }
+
+ console.log('');
+ console.log('## Per-run series');
+ console.log('');
+ console.log('| Run | Win rate | Avg lat | p99 | Escalation | Sonnet 4.6 lat | Opus 4.7 lat |');
+ console.log('|---|---:|---:|---:|---:|---:|---:|');
+ for (const r of series) {
+ const wr = r.winRate != null ? pct(r.winRate) : 'β€”';
+ const al = r.avgLatencyMs != null ? ms(r.avgLatencyMs) : 'β€”';
+ const p99 = r.p99LatencyMs != null ? ms(r.p99LatencyMs) : 'β€”';
+ const er = r.escalationRate != null ? pct(r.escalationRate) : 'β€”';
+ const son = r.anthropicSonnet != null ? ms(r.anthropicSonnet) : 'β€”';
+ const opu = r.anthropicOpus != null ? ms(r.anthropicOpus) : 'β€”';
+ const tag = r.file.replace(/\.json$/, '').slice(0, 19);
+ console.log(`| \`${tag}\` | ${wr} | ${al} | ${p99} | ${er} | ${son} | ${opu} |`);
+ }
+
+ // Regression flagging
+ if (first.winRate != null && last.winRate != null && last.winRate < first.winRate) {
+ console.log('');
+ console.log(`> ⚠ Regression: win rate dropped ${pct(last.winRate - first.winRate)}`);
+ }
+ if (first.avgLatencyMs != null && last.avgLatencyMs != null && last.avgLatencyMs > first.avgLatencyMs * 1.5) {
+ console.log('');
+ console.log(`> ⚠ Regression: avg latency rose ${(last.avgLatencyMs / first.avgLatencyMs).toFixed(2)}Γ— from first run`);
+ }
+}
+
+main();
diff --git a/plugins/ruflo-cost-tracker/skills/cost-trend/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-trend/SKILL.md
new file mode 100644
index 0000000000..c1fd56cade
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/skills/cost-trend/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: cost-trend
+description: Read every docs/benchmarks/runs/*.json and surface drift in win rate, latency, escalation rate, and LLM-baseline cost over time
+argument-hint: ""
+allowed-tools: Bash
+---
+
+# Cost Trend
+
+The smoke gate is binary (`winRate β‰₯ 0.80` β†’ pass/fail). The corpus benchmarks captured over time form a curve β€” and curves catch regressions the gate misses (win rate slowly creeping from 100% to 85% is "still passing" by smoke but a real degradation).
+
+This skill reads every persisted run in `docs/benchmarks/runs/*.json` and reports first→last deltas plus a per-run series, flagging regressions in win rate or latency.
+
+## When to use
+
+- Before a release β€” check that the speedup hasn't drifted.
+- After expanding the corpus β€” verify older runs still hit the same win rate on the new corpus *they* reflected.
+- After upgrading `agent-booster` β€” surface latency / strategy changes.
+
+## Steps
+
+1. **Run the trend script** from the project root:
+
+ ```bash
+ node plugins/ruflo-cost-tracker/scripts/trend.mjs
+ ```
+
+ Optional env:
+ - `TREND_FORMAT=json` β€” emit JSON instead of markdown
+ - `TREND_LIMIT=10` β€” consider only the most recent N runs
+
+2. **Inspect the drift summary** β€” first vs last on win rate, avg latency, p99, escalation rate, speedup vs Gemini.
+
+3. **Inspect the per-run series** β€” one row per run, including Sonnet 4.6 + Opus 4.7 baseline latencies if those were enabled (`BENCH_ANTHROPIC=1` at run time).
+
+4. **Regression flags** β€” the script emits `> ⚠ Regression` callouts when:
+ - Win rate dropped between first and last run
+ - Avg latency rose β‰₯ 1.5Γ— from first run
+
+## Cross-references
+
+- `cost-benchmark` β€” the producer of the run JSONs this skill consumes
+- `bench/booster-corpus.json` β€” the corpus version is recorded in each run, so trends across corpus versions remain interpretable
+- `docs/benchmarks/runs/latest.json` β€” the most-recent run; smoke step 23 gates on `winRate β‰₯ 0.80` from this file