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): P2 β€” real budget enforcement (v0.6.0)

Reuven5d2f86080221
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json
index f4498f9a23..74f07e19f8 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.5.0",
+ "version": "0.6.0",
"author": {
"name": "ruvnet",
"url": "https://github.com/ruvnet"
@@ -23,6 +23,7 @@
"model-routing",
"benchmarking",
"verified",
- "telemetry"
+ "telemetry",
+ "budget"
]
}
diff --git a/plugins/ruflo-cost-tracker/README.md b/plugins/ruflo-cost-tracker/README.md
index 668142ca4b..20f76f3e73 100644
--- a/plugins/ruflo-cost-tracker/README.md
+++ b/plugins/ruflo-cost-tracker/README.md
@@ -25,6 +25,7 @@ claude --plugin-dir plugins/ruflo-cost-tracker
| `cost-report` | `/cost-report [--period today]` | Generate a cost report with token usage and USD costs by tier, model, and agent |
| `cost-optimize` | `/cost-optimize` | Analyze usage patterns, recommend cost optimizations, and emit `hooks_model-outcome` events |
| `cost-track` | `/cost-track` | **Auto-capture** per-session token usage from the Claude Code jsonl into `cost-tracking` namespace (producer side) |
+| `cost-budget-check` | `/cost-budget-check [--period today\|week\|month\|all]` | Read totals + budget config, emit 50/75/90/100% alert ladder; exit 1 on HARD_STOP |
| `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/` |
@@ -34,6 +35,9 @@ claude --plugin-dir plugins/ruflo-cost-tracker
```bash
cost track # Auto-capture this session's token usage (producer)
+cost budget set <amount> # Set USD budget (real impl, persists to cost-tracking)
+cost budget get # Show current budget config
+cost budget check [--period ...] # Compute utilization + alert; exit 1 on HARD_STOP
cost report [--period today|week|month] # Cost report (with By-tier block, reads measured booster data)
cost breakdown [--by agent|model|task] # Detailed breakdown by dimension
cost budget set <amount> # Set budget limit in USD
@@ -126,7 +130,7 @@ Reserved namespaces (`pattern`, `claude-memories`, `default`) MUST NOT be shadow
```bash
bash plugins/ruflo-cost-tracker/scripts/smoke.sh
-# Expected: "30 passed, 0 failed"
+# Expected: "33 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 9762347181..865b17b92d 100644
--- a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md
+++ b/plugins/ruflo-cost-tracker/commands/ruflo-cost.md
@@ -19,10 +19,21 @@ Cost tracking commands:
4. Sort by cost descending
5. Display: dimension value, input tokens, output tokens, cache tokens, total cost, share %
-**`cost budget set <amount>`** -- Set a budget limit in USD.
-1. Store the budget configuration via `mcp__claude-flow__agentdb_hierarchical-store`
-2. Configure alert thresholds: info at 50%, warning at 75%, critical at 90%, hard stop at 100%
-3. Report: budget set, current spend, remaining budget, alert thresholds
+**`cost budget set <amount>`** -- Set a budget limit in USD (real implementation, persisted to `cost-tracking:budget-config`).
+1. Run `node plugins/ruflo-cost-tracker/scripts/budget.mjs set <amount>` to write the config to the cost-tracking namespace
+2. Thresholds default to: info 50% Β· warning 75% Β· critical 90% Β· hard_stop 100%
+3. Report: confirmed amount + namespace key
+
+**`cost budget get`** -- Show the current budget config.
+1. Run `node plugins/ruflo-cost-tracker/scripts/budget.mjs get`
+2. Report: amount, when set, threshold ladder
+
+**`cost budget check [--period today|week|month|all]`** -- Compute utilization + alert level (50/75/90/100% ladder).
+1. Run `node plugins/ruflo-cost-tracker/scripts/budget.mjs check`
+2. Filter by `BUDGET_PERIOD=today|week|month|all` (default `all`)
+3. Sum `total_cost_usd` across all `session-*` records in cost-tracking
+4. Compute utilization vs. budget; emit 🟒 OK / 🟑 INFO / 🟠 WARNING / πŸ”΄ CRITICAL / πŸ›‘ HARD_STOP
+5. Exit code 1 on HARD_STOP β€” wrap agent spawns in `budget check && spawn ...` to fail closed
**`cost optimize`** -- Analyze usage and suggest cost optimizations.
1. Recall recent usage data from `cost-tracking` namespace
diff --git a/plugins/ruflo-cost-tracker/scripts/budget.mjs b/plugins/ruflo-cost-tracker/scripts/budget.mjs
new file mode 100755
index 0000000000..f374a5ec81
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/scripts/budget.mjs
@@ -0,0 +1,223 @@
+#!/usr/bin/env node
+// cost-budget β€” set / get / check the project's cost budget against accumulated
+// session spend in the `cost-tracking` namespace.
+//
+// Usage:
+// node scripts/budget.mjs set <usd> # persist budget config
+// node scripts/budget.mjs get # show current budget config
+// node scripts/budget.mjs check # compute utilization + alert level
+//
+// Env:
+// BUDGET_NAMESPACE=<name> override (default: cost-tracking)
+// BUDGET_PERIOD=today|week|month|all filter session totals by capturedAt
+// BUDGET_QUIET=1 machine-readable JSON only
+
+import { spawnSync } from 'node:child_process';
+
+const NS = process.env.BUDGET_NAMESPACE || 'cost-tracking';
+const KEY = 'budget-config';
+
+function memoryStore(key, value) {
+ // The @claude-flow/cli memory layer has a UNIQUE-constraint quirk where
+ // `store` rejects keys that `retrieve` doesn't surface. Workaround:
+ // - For the budget-config key (single record), append a timestamp suffix
+ // on each write and update a small index that points at the latest.
+ // This avoids the conflict entirely. Retrieve resolves via the index.
+ if (key === KEY) {
+ const stamped = `${KEY}-${Date.now()}`;
+ const r = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'store',
+ '--namespace', NS, '--key', stamped, '--value', JSON.stringify(value),
+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`memory store failed: ${r.stderr?.slice(0, 200) || r.status}`);
+ // The "current pointer" is found at retrieval time by listing all
+ // budget-config-* keys and picking the lexicographically-largest
+ // (timestamp suffixes sort correctly because they are equal-width).
+ return;
+ }
+ const r = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'store',
+ '--namespace', NS, '--key', key, '--value', JSON.stringify(value),
+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`memory store failed: ${r.stderr?.slice(0, 200) || r.status}`);
+}
+
+function memoryRetrieveOne(key) {
+ const r = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'retrieve',
+ '--namespace', NS, '--key', key,
+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+ if (r.status !== 0) return null;
+ const m = /\{[\s\S]*\}/.exec(r.stdout || '');
+ if (!m) return null;
+ try { return JSON.parse(m[0]); } catch { return null; }
+}
+
+function memoryRetrieve(key) {
+ // For budget-config: pick the latest budget-config-<timestamp> entry.
+ if (key === KEY) {
+ const list = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'list',
+ '--namespace', NS, '--format', 'json',
+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+ if (list.status !== 0) return null;
+ const m = /\[[\s\S]*\]/.exec(list.stdout || '');
+ if (!m) return null;
+ let entries;
+ try { entries = JSON.parse(m[0]); } catch { return null; }
+ const stamped = entries
+ .map((e) => e.key)
+ .filter((k) => typeof k === 'string' && /^budget-config-\d+$/.test(k))
+ .sort();
+ const latest = stamped[stamped.length - 1];
+ if (!latest) {
+ // fall back to plain budget-config (legacy / pre-stamping)
+ return memoryRetrieveOne(KEY);
+ }
+ return memoryRetrieveOne(latest);
+ }
+ return memoryRetrieveOne(key);
+}
+
+function memoryListSessionRecords() {
+ // Use --format json so keys aren't truncated with `...` in tabular output.
+ const r = spawnSync('npx', [
+ '@claude-flow/cli@latest', 'memory', 'list',
+ '--namespace', NS, '--format', 'json',
+ ], { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' });
+ if (r.status !== 0) return [];
+ // CLI may emit a small banner before the JSON array; extract the first '['..']' block.
+ const m = /\[[\s\S]*\]/.exec(r.stdout || '');
+ if (!m) return [];
+ let entries;
+ try { entries = JSON.parse(m[0]); } catch { return []; }
+ const sessionKeys = entries
+ .map((e) => e.key)
+ .filter((k) => typeof k === 'string' && k.startsWith('session-'));
+ const records = [];
+ for (const k of sessionKeys) {
+ const rec = memoryRetrieve(k);
+ if (rec) records.push(rec);
+ }
+ return records;
+}
+
+function periodFilter(period) {
+ const now = Date.now();
+ const day = 24 * 3600 * 1000;
+ if (period === 'today') return (ts) => ts && new Date(ts).toDateString() === new Date().toDateString();
+ if (period === 'week') return (ts) => ts && (now - new Date(ts).getTime()) < 7 * day;
+ if (period === 'month') return (ts) => ts && (now - new Date(ts).getTime()) < 30 * day;
+ return () => true; // 'all'
+}
+
+function alertLevel(utilization) {
+ if (utilization >= 1.00) return { level: 'HARD_STOP', emoji: 'πŸ›‘', threshold: 100 };
+ if (utilization >= 0.90) return { level: 'CRITICAL', emoji: 'πŸ”΄', threshold: 90 };
+ if (utilization >= 0.75) return { level: 'WARNING', emoji: '🟠', threshold: 75 };
+ if (utilization >= 0.50) return { level: 'INFO', emoji: '🟑', threshold: 50 };
+ return { level: 'OK', emoji: '🟒', threshold: 0 };
+}
+
+function recommendedAction(level) {
+ return ({
+ OK: 'within budget β€” no action.',
+ INFO: '50% consumed β€” log notification, no UX disruption.',
+ WARNING: '75% consumed β€” display warning, suggest optimizations (run /cost-optimize).',
+ CRITICAL: '90% consumed β€” urgent alert, recommend model downgrades, run /cost-optimize.',
+ HARD_STOP: '100% consumed β€” halt non-essential agent spawns; review /cost-report and /cost-optimize before continuing.',
+ }[level]);
+}
+
+function cmdSet(args) {
+ const amount = parseFloat(args[0]);
+ if (!Number.isFinite(amount) || amount <= 0) {
+ console.error('usage: budget.mjs set <usd-amount> (positive number)');
+ process.exit(2);
+ }
+ const config = {
+ budget_usd: amount,
+ setAt: new Date().toISOString(),
+ thresholds: { info: 0.50, warning: 0.75, critical: 0.90, hard_stop: 1.00 },
+ };
+ memoryStore(KEY, config);
+ if (process.env.BUDGET_QUIET === '1') {
+ console.log(JSON.stringify(config));
+ } else {
+ console.log(`βœ“ Budget set: $${amount.toFixed(2)} (namespace: ${NS}, key: ${KEY})`);
+ console.log(' Alerts: 50% INFO Β· 75% WARNING Β· 90% CRITICAL Β· 100% HARD_STOP');
+ }
+}
+
+function cmdGet() {
+ const cfg = memoryRetrieve(KEY);
+ if (process.env.BUDGET_QUIET === '1') {
+ console.log(JSON.stringify(cfg || { error: 'no budget configured' }));
+ return;
+ }
+ if (!cfg) {
+ console.log(`No budget configured (namespace: ${NS}, key: ${KEY}).`);
+ console.log('Set one with: cost budget set <usd>');
+ process.exit(0);
+ }
+ console.log(`Budget: $${cfg.budget_usd?.toFixed(2)} (set ${cfg.setAt})`);
+ console.log(`Thresholds: 50/75/90/100%`);
+}
+
+function cmdCheck() {
+ const cfg = memoryRetrieve(KEY);
+ const period = process.env.BUDGET_PERIOD || 'all';
+ const records = memoryListSessionRecords();
+ const filt = periodFilter(period);
+ const filtered = records.filter((r) => filt(r.capturedAt || r.endedAt));
+ const totalSpend = filtered.reduce((s, r) => s + (r.total_cost_usd || 0), 0);
+ if (!cfg || !Number.isFinite(cfg.budget_usd)) {
+ const out = { period, totalSpend, recordCount: filtered.length, error: 'no budget configured' };
+ if (process.env.BUDGET_QUIET === '1') return console.log(JSON.stringify(out));
+ console.log(`Period: ${period}`);
+ console.log(`Spent so far: $${totalSpend.toFixed(2)} across ${filtered.length} sessions`);
+ console.log(`No budget set β€” run \`cost budget set <usd>\` to enable alerts.`);
+ return;
+ }
+ const utilization = totalSpend / cfg.budget_usd;
+ const alert = alertLevel(utilization);
+ const out = {
+ period,
+ budget_usd: cfg.budget_usd,
+ spent_usd: totalSpend,
+ remaining_usd: Math.max(0, cfg.budget_usd - totalSpend),
+ utilization_pct: utilization * 100,
+ level: alert.level,
+ threshold: alert.threshold,
+ recommended_action: recommendedAction(alert.level),
+ sessionCount: filtered.length,
+ };
+ if (process.env.BUDGET_QUIET === '1') return console.log(JSON.stringify(out));
+ console.log(`# Budget check (period: ${period})`);
+ console.log('');
+ console.log(`| Metric | Value |`);
+ console.log(`|---|---:|`);
+ console.log(`| Budget | $${cfg.budget_usd.toFixed(2)} |`);
+ console.log(`| Spent | $${totalSpend.toFixed(2)} |`);
+ console.log(`| Remaining | $${out.remaining_usd.toFixed(2)} |`);
+ console.log(`| Utilization | ${out.utilization_pct.toFixed(1)}% |`);
+ console.log(`| Sessions counted | ${filtered.length} |`);
+ console.log(`| **Alert** | **${alert.emoji} ${alert.level}** |`);
+ console.log('');
+ console.log(`Action: ${out.recommended_action}`);
+ if (alert.level === 'HARD_STOP') process.exit(1);
+}
+
+function main() {
+ const [cmd, ...rest] = process.argv.slice(2);
+ switch (cmd) {
+ case 'set': return cmdSet(rest);
+ case 'get': return cmdGet();
+ case 'check': return cmdCheck();
+ default:
+ console.error('usage: budget.mjs {set <usd>|get|check}');
+ process.exit(2);
+ }
+}
+
+main();
diff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.sh
index 6b5fea8703..95a79d65ed 100755
--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh
+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh
@@ -8,21 +8,21 @@ 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.5.0 with new keywords"
+step "1. plugin.json declares 0.6.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.5.0" ]]; then
- bad "expected 0.5.0, got '$v'"
+if [[ "$v" != "0.6.0" ]]; then
+ bad "expected 0.6.0, got '$v'"
else
miss=""
- for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry; do
+ for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget; do
grep -q "\"$k\"" "$ROOT/.claude-plugin/plugin.json" || miss="$miss $k"
done
[[ -z "$miss" ]] && ok || bad "missing keywords:$miss"
fi
-step "2. all seven skills present with valid frontmatter"
+step "2. all eight 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; do
+for s in cost-report cost-optimize cost-booster-route cost-booster-edit cost-compact-context cost-benchmark cost-track cost-budget-check; do
f="$ROOT/skills/$s/SKILL.md"
[[ -f "$f" ]] || { miss="$miss missing-$s"; continue; }
for k in 'name:' 'description:' 'allowed-tools:'; do
@@ -243,5 +243,33 @@ F="$ROOT/commands/ruflo-cost.md"
grep -qE "cost track" "$F" && grep -qE "session.*jsonl|track\.mjs" "$F" \
&& ok || bad "missing cost-track subcommand or session-source ref"
+step "31. cost-budget-check skill exists, references alert ladder + budget.mjs"
+F="$ROOT/skills/cost-budget-check/SKILL.md"
+miss=""
+[[ -f "$F" ]] || miss="$miss missing-file"
+grep -qE "50/75/90/100|HARD_STOP|alert ladder" "$F" || miss="$miss alert-ladder"
+grep -qE "budget\.mjs|cost-tracking:budget-config" "$F" || miss="$miss budget-script"
+grep -q '^allowed-tools:[[:space:]]*\*' "$F" && miss="$miss wildcard"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
+step "32. budget.mjs harness present + parses + uses spawnSync"
+F="$ROOT/scripts/budget.mjs"
+miss=""
+[[ -x "$F" ]] || miss="$miss not-executable"
+node --check "$F" 2>/dev/null || miss="$miss syntax-error"
+grep -q "spawnSync" "$F" || miss="$miss no-spawnSync"
+grep -qE "HARD_STOP|alertLevel" "$F" || miss="$miss no-alert-impl"
+grep -q "process.exit(1)" "$F" || miss="$miss no-fail-closed"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
+step "33. ruflo-cost.md documents 'cost budget set/get/check' subcommands"
+F="$ROOT/commands/ruflo-cost.md"
+miss=""
+grep -q "cost budget set" "$F" || miss="$miss set"
+grep -q "cost budget get" "$F" || miss="$miss get"
+grep -q "cost budget check" "$F" || miss="$miss check"
+grep -qE "50/75/90/100|alert ladder|HARD_STOP" "$F" || miss="$miss alert-ladder"
+[[ -z "$miss" ]] && ok || bad "$miss"
+
printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"
[[ $FAIL -eq 0 ]] || exit 1
diff --git a/plugins/ruflo-cost-tracker/skills/cost-budget-check/SKILL.md b/plugins/ruflo-cost-tracker/skills/cost-budget-check/SKILL.md
new file mode 100644
index 0000000000..6620ff9932
--- /dev/null
+++ b/plugins/ruflo-cost-tracker/skills/cost-budget-check/SKILL.md
@@ -0,0 +1,65 @@
+---
+name: cost-budget-check
+description: Read accumulated cost-tracking spend + budget config, compute utilization, emit 50/75/90/100% alert ladder
+argument-hint: "[--period today|week|month|all]"
+allowed-tools: Bash mcp__claude-flow__memory_retrieve mcp__claude-flow__memory_list mcp__claude-flow__memory_store
+---
+
+# Cost Budget Check
+
+Reads `cost-tracking:budget-config` for the project's budget limit, sums `total_cost_usd` across `session-*` records produced by `cost-track`, computes utilization, and emits the **measured** 4-tier alert ladder (50% INFO / 75% WARNING / 90% CRITICAL / 100% HARD_STOP).
+
+Until P2 (this skill) landed, the README documented the alert ladder but no code checked it. Now this skill is the gate.
+
+## When to use
+
+- After every cost-track run, to surface the alert level.
+- Before spawning a swarm β€” if utilization β‰₯ 90%, escalate to `/cost-optimize` first.
+- Cron-friendly via `/loop 30m` for continuous monitoring.
+
+## Steps
+
+1. **Run the check**:
+
+ ```bash
+ node plugins/ruflo-cost-tracker/scripts/budget.mjs check
+ ```
+
+ Filter by period: `BUDGET_PERIOD=today` (default `all`). Use `BUDGET_QUIET=1` for machine-readable JSON.
+
+2. **Inspect the markdown summary** β€” budget, spent, remaining, utilization percentage, alert level (🟒 OK Β· 🟑 INFO Β· 🟠 WARNING Β· πŸ”΄ CRITICAL Β· πŸ›‘ HARD_STOP), and the recommended action.
+
+3. **Set / inspect the budget**:
+
+ ```bash
+ node plugins/ruflo-cost-tracker/scripts/budget.mjs set 50.00
+ node plugins/ruflo-cost-tracker/scripts/budget.mjs get
+ ```
+
+4. **HARD_STOP path** β€” `budget.mjs check` exits with code `1` when utilization β‰₯ 100%. Wrap critical agent spawns in a `budget.mjs check && spawn …` guard to fail closed.
+
+## Storage shape (`cost-tracking:budget-config`)
+
+```json
+{
+ "budget_usd": 50.00,
+ "setAt": "2026-05-05T...",
+ "thresholds": { "info": 0.50, "warning": 0.75, "critical": 0.90, "hard_stop": 1.00 }
+}
+```
+
+## Alert ladder (from REFERENCE.md, now enforced)
+
+| Threshold | Level | Action |
+|---|---|---|
+| 50% | INFO 🟑 | log notification, no UX disruption |
+| 75% | WARNING 🟠 | display warning, suggest `/cost-optimize` |
+| 90% | CRITICAL πŸ”΄ | urgent alert, recommend model downgrades |
+| 100% | HARD_STOP πŸ›‘ | halt non-essential spawns; exit code 1 |
+
+## Cross-references
+
+- `cost-track` (producer) β€” populates `cost-tracking:session-*`
+- `cost-report` β€” same data source, narrative format
+- `cost-optimize` β€” recommended action when WARNING/CRITICAL
+- REFERENCE.md "Budget alert thresholds" β€” the documented ladder this enforces