π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(cost): budget file, LiteLLM gateway export, per-agent/tool attribution (ADR-508) (#4592)
rUv5d2be9374a38
diff --git a/plugins/ruflo-cost-tracker/.claude-plugin/plugin.json b/plugins/ruflo-cost-tracker/.claude-plugin/plugin.jsonindex 848a480b9e..031edafdc8 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.30.0",+ "version": "0.31.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"diff --git a/plugins/ruflo-cost-tracker/CHANGELOG.md b/plugins/ruflo-cost-tracker/CHANGELOG.mdindex 89d932f4e9..96af15b17c 100644--- a/plugins/ruflo-cost-tracker/CHANGELOG.md+++ b/plugins/ruflo-cost-tracker/CHANGELOG.md@@ -2,6 +2,9 @@Newest first. One `## <version> β <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-cost-tracker`.+## 0.31.0 β 2026-10-29+- docs: `/ruflo-cost` documents the budget file and `ruflo cost budget set|export --gateway litellm [--apply]` and `ruflo cost report` (ADR-508, #4592).+## 0.30.0 β 2026-10-29- chore: operational skills are user-invoked only (`disable-model-invocation: true`) and long skill/command descriptions are cut to one sentence, so they cost less prompt on every turn (ADR-507, #4588). Every skill is still available as `/<skill>`.diff --git a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md b/plugins/ruflo-cost-tracker/commands/ruflo-cost.mdindex e5d05b1882..6f1e36fc1d 100644--- a/plugins/ruflo-cost-tracker/commands/ruflo-cost.md+++ b/plugins/ruflo-cost-tracker/commands/ruflo-cost.md@@ -35,6 +35,13 @@ Cost tracking commands:4. Compute utilization vs. budget; emit π’ OK / π‘ INFO / π WARNING / π΄ CRITICAL / π HARD_STOP5. Exit code 1 on HARD_STOP β wrap agent spawns in `budget check && spawn ...` to fail closed+**`cost budget file / gateway export / attribution`** (ADR-508) -- One budget file read by the ruflo-mods cost ladder and by gateways; per-agent and per-tool attribution from the mod.+1. `npx @claude-flow/cli@latest cost budget set --daily 10 --monthly 100 [--hard-stop] [--fallback-model haiku]` writes `.claude-flow/cost/budget.json` (no credentials in it). The ruflo-mods ladder uses its smallest window per session when `costBudgetUsd` is 0.+2. `npx @claude-flow/cli@latest cost budget export --gateway litellm [--format json] [--model <gateway model>]` prints LiteLLM key budget fields as YAML (`--format json`: the `/key/generate` body) (`budget_limits`; with `--model`, `model_max_budget` and `budget_fallbacks`).+3. `... --apply --url https://<proxy> --key-env LITELLM_MASTER_KEY` posts them to `<proxy>/key/generate`. HTTPS only unless the host is loopback; the master key is read only from the named environment variable.+4. `--gateway meta-llm` fails on purpose: meta-llm documents no budget API yet, and ruflo does not guess an endpoint.+5. `npx @claude-flow/cli@latest cost report [--days 30] [--json]` shows spend by subagent type and by tool (each turn's cost split evenly across its tool calls, an estimate), from `.claude-flow/cost/attribution.jsonl` (written by the ruflo-mods `costLedger` option, on by default).+**`cost optimize`** -- Analyze usage and suggest cost optimizations.1. Recall recent usage data from `cost-tracking` namespace2. For each agent, analyze: average task complexity, model used, token efficiencydiff --git a/plugins/ruflo-cost-tracker/scripts/smoke.sh b/plugins/ruflo-cost-tracker/scripts/smoke.shindex 6d13a4273a..a543cd941c 100755--- a/plugins/ruflo-cost-tracker/scripts/smoke.sh+++ b/plugins/ruflo-cost-tracker/scripts/smoke.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Structural smoke test for ruflo-cost-tracker v0.30.0.+# Structural smoke test for ruflo-cost-tracker v0.31.0.set -u# `pwd -W` (Git Bash on Windows) gives C:/Users/...; plain pwd gives /c/Users/..., which a Windows node cannot open. Elsewhere -W fails and pwd answers.ROOT="$(cd "$(dirname "$0")/.." && { pwd -W 2>/dev/null || pwd; })"@@ -9,10 +9,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.30.0 with new keywords"+step "1. plugin.json declares 0.31.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.30.0" ]]; then- bad "expected 0.30.0, got '$v'"+if [[ "$v" != "0.31.0" ]]; then+ bad "expected 0.31.0, got '$v'"elsemiss=""for k in namespace-routing mcp agentic-flow agent-booster tier1-routing model-routing benchmarking verified telemetry budget projection forecast counterfactual drift-detection trend-alert anomaly-detection outlier-detection health-check composite-gate auto-track stop-hook snapshot-diff pr-regression git-context traceability drill-down per-message; dodiff --git a/plugins/ruflo-mods/.claude-plugin/plugin.json b/plugins/ruflo-mods/.claude-plugin/plugin.jsonindex 8399686f8a..d782bd59ae 100644--- a/plugins/ruflo-mods/.claude-plugin/plugin.json+++ b/plugins/ruflo-mods/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ruflo-mods","description": "ruflo as a Claude Code mod (function hooks, ADR-404): in-process prompt routing, edit learning signals, tighten-only tool checks from ruflo policy, the cost-tracker budget ladder, a mod trust gate for newly installed mods, and the $.ruflo noun other mods compose their status with. Opt-in and removable: the classic hook-handler hooks stay the default and take every event back whenever the mod is not loaded.",- "version": "0.10.0",+ "version": "0.11.0","author": {"name": "ruvnet","url": "https://github.com/ruvnet"@@ -47,6 +47,13 @@"required": false,"default": false},+ "costLedger": {+ "type": "boolean",+ "title": "Cost ledger and budget file",+ "description": "In a ruflo project: take the session budget from .claude-flow/cost/budget.json when costBudgetUsd is 0, charge each cost delta to the subagent type and tool behind it (.claude-flow/cost/attribution.jsonl, read by ruflo cost report), and toast once when a gateway refuses a request for budget (ADR-508).",+ "required": false,+ "default": true+ },"toolHints": {"type": "boolean","title": "Usage hints on ruflo tools",diff --git a/plugins/ruflo-mods/CHANGELOG.md b/plugins/ruflo-mods/CHANGELOG.mdindex bf0886cc49..66c9d934af 100644--- a/plugins/ruflo-mods/CHANGELOG.md+++ b/plugins/ruflo-mods/CHANGELOG.md@@ -2,6 +2,9 @@Newest first. One `## <version> β <date>` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-mods`.+## 0.11.0 β 2026-10-29+- feat: option `costLedger` (default on, ADR-508, #4592): with `costBudgetUsd` at 0 the cost ladder takes its limit from the smallest window in `.claude-flow/cost/budget.json` and names that window; each `session.measure` cost delta is charged to the subagent type and the tool that ran before it, written as one line per session to `.claude-flow/cost/attribution.jsonl` (read by `ruflo cost report`); a gateway budget refusal is toasted once and counted, never retried.+## 0.10.0 β 2026-10-29- feat: option `compactSnapshot` (default on, ADR-505, #4591): before a main-loop compaction, the transcript is saved (role, 2,000-character text cut, tool names; screened; tool inputs and outputs never written) to one of ten rotating slots under `.claude-flow/sessions/compactions/`; after it, the next prompt carries one bounded `[RUFLO_AFTER_COMPACT]` block (recent lessons and loop outcomes, open swarm and claim ids, the snapshot path). Never blocks or rewrites the compaction; set `false` to turn it off.diff --git a/plugins/ruflo-mods/README.md b/plugins/ruflo-mods/README.mdindex d787ab38ee..f454542a78 100644--- a/plugins/ruflo-mods/README.md+++ b/plugins/ruflo-mods/README.md@@ -99,7 +99,7 @@ In a session, `/ruflo mods` (through ruflo-console's `/ruflo`) reports what the- **Tool checks:** `tool.check` only tightens. It applies the dangerous-command list and ruflo policy rules that name `claude-code.*` actions (written by the CLI to `.claude-flow/policy/claude-code.json`). It never loosens a verdict. A projection whose mode is `legacy` (or anything but `observe`/`enforce`) is rejected as unreadable, because the CLI never writes one (it deletes the file), so the call is put to you; `/ruflo-mods` shows `policy: <mode> (projection read)` or `policy: unreadable` (ADR-450 T10).- **Trust gate:** `plugin.register` names what a later-installed mod can do (host commands, network, environment, tool verdicts, agent spawns, prompt changes) and, under `modTrust: refuse-risky`, refuses it unless allow-listed.- **`$.ruflo`:** other mods add a status segment with `$.ruflo.segment({ id, text })` instead of drawing a second bar; `lastRoute()` and `snapshot()` read what the mod measured. Contract: `types/index.d.ts`.-- **Budget:** `session.measure` applies the cost-tracker budget ladder to live session cost (`costBudgetUsd`); Each rung is announced once per session, even if cost falls and rises again. `costHardStop` halts new subagents at 100%.+- **Budget:** `session.measure` applies the cost-tracker budget ladder to live session cost (`costBudgetUsd`); Each rung is announced once per session, even if cost falls and rises again. `costHardStop` halts new subagents at 100%. With `costLedger` (default on, ADR-508) the ladder can read its limit from `.claude-flow/cost/budget.json`, and each session's cost is broken down by subagent type and tool for `ruflo cost report`.The classic `hook-handler.cjs` hooks stay installed and remain the fallback. The mod takes an event only where the classic helper hands it over (`RUFLO_MODS_OWNS`), so nothing fires twice. When the mod is not loaded, every classic hook runs as before.@@ -121,6 +121,7 @@ Claude Code reads a plugin's options from `pluginConfigs["ruflo-mods@ruflo"].opt| `statusLine` | `true` | One-line ruflo status under the prompt; skipped where the ruflo statusLine helper is configured. Evidence: [live paths](../../v3/docs/validation/ruflo-mods-live-paths-2026-10.md) || `costBudgetUsd` | `0` (off) | Session budget for the 50/75/90/100% ladder; each rung is announced once. Evidence: [capability review](../../v3/docs/validation/mod-capability-review-2026-10.md) || `costHardStop` | `false` | Refuse new subagents at 100% of the budget. Live canary run: [evidence](../../v3/docs/validation/ruflo-mods-compact-live-2026-10.md) (10/14 recalled with it on, 0/7 off); design in [ADR-404](../../v3/docs/adr/ADR-404-claude-code-mods-function-hooks.md) |+| `costLedger` | `true` | ADR-508, in a ruflo project only. When `costBudgetUsd` is `0`, the ladder takes its limit from `.claude-flow/cost/budget.json` (written by `ruflo cost budget set --daily 10 --monthly 100`; its smallest window, named in the toast; its `hardStop` acts as `costHardStop`; a file that fails validation is no budget). Each `session.measure` cost delta (one per main-thread turn) is split evenly across the tool calls completed in it, by subagent type and by tool (an estimate by call count; a turn with no tool calls goes to `main` / `(model)`); one line per session goes to `.claude-flow/cost/attribution.jsonl` (500 lines) for `ruflo cost report`. A turn that ends on a gateway budget refusal (LiteLLM `budget_exceeded`) is toasted once and counted; to see it, on a main-loop turn that ended on an API error the mod reads the transcript's last message through `$.session.messages()`, only when it starts with `API Error` (a model answer is never read); nothing retries or changes model. Enforcement across sessions is the gateway's: `ruflo cost budget export --gateway litellm`. Design in [ADR-508](../../v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md) || `toolHints` | `false` | Add one short static hint, restating the project's own CLAUDE.md, to a few ruflo MCP tool descriptions. Live: hints appear on exactly the hinted tools, none when off. Evidence: [live validation](../../v3/docs/validation/ruflo-mods-live-2026-10.md) || `agentTrim` | `false` | Keep agent types the project does not use out of the agent listing. Measured saving about 4,000 tokens per request (4,236 on a 69-type catalogue, one model); a hidden type the prompt does not name is refused at dispatch, one the prompt names can still be dispatched. Evidence: [trim measurement](../../v3/docs/validation/ruflo-mods-trim-measure-2026-10.md) || `agentTrimKeep` | empty | Comma-separated agent type names `agentTrim` must keep offered. Evidence: [live validation](../../v3/docs/validation/ruflo-mods-live-2026-10.md) |diff --git a/plugins/ruflo-mods/hooks/cost/attribution.ts b/plugins/ruflo-mods/hooks/cost/attribution.tsnew file mode 100644index 0000000000..13507e0c2d--- /dev/null+++ b/plugins/ruflo-mods/hooks/cost/attribution.ts@@ -0,0 +1,159 @@+/**+ * Per-session cost attribution (ADR-508 Β§2.3). Pure.+ *+ * A gateway sees every request but not which subagent or tool caused it. The+ * mod sees more, but not per request: Claude Code measures cost once per+ * main-thread turn (`session.measure`), and a foreground subagent runs inside+ * the main loop's Agent tool call, so its tool calls all land before that+ * turn's one measurement. So each measured delta is split across the tool+ * calls completed since the last measurement, one equal share per call: a+ * subagent's calls go to its type (from `agent.spawn`), the main loop's to+ * `main` (its Agent/Task call that wrapped the subagent counts as one main+ * share). A delta with no tool call in it (a plain answer) goes to `main` and+ * `(model)`. This is a split by call count, an estimate, not a per-request+ * price. At session end one line goes to `.claude-flow/cost/attribution.jsonl`,+ * which `ruflo cost report` reads.+ */++export const ATTRIBUTION_PATH = '.claude-flow/cost/attribution.jsonl'+/** Lines the file keeps (oldest dropped). */+export const MAX_LINES = 500+/** Distinct agent or tool names kept per session; the rest are charged to `other`. */+export const MAX_KEYS = 64+/** Spawned-agent ids remembered per session. */+export const MAX_AGENTS = 256++/** The agent a cost is charged to when the main loop ran the last tool. */+export const MAIN = 'main'+/** The tool a cost is charged to when no tool has run yet (a plain answer). */+export const NO_TOOL = '(model)'++const NAME = /^[A-Za-z0-9_.:@/-]{1,80}$/++export type Attribution = {+ /** The session's cumulative cost at the last measurement (the base for the next delta). */+ lastUsd: number+ totalUsd: number+ /** Tool calls completed since the last charged measurement, counted by agent and by tool. */+ pendingCalls: number+ pendingAgent: Map<string, number>+ pendingTool: Map<string, number>+ byAgent: Map<string, number>+ byTool: Map<string, number>+ /** Spawned subagent id β its type, so a subagent's tool calls are charged to its type. */+ agents: Map<string, string>+ refusals: number+ toasted: boolean+}++export const createAttribution = (): Attribution => ({+ lastUsd: 0,+ totalUsd: 0,+ pendingCalls: 0,+ pendingAgent: new Map(),+ pendingTool: new Map(),+ byAgent: new Map(),+ byTool: new Map(),+ agents: new Map(),+ refusals: 0,+ toasted: false,+})++/** A name as kept: a plain identifier, else `other`. */+export const nameOf = (value: unknown) => (typeof value === 'string' && NAME.test(value) ? value : 'other')++/** Remembers a started subagent's type under its id. */+export function noteSpawn(a: Attribution, agentId: unknown, subagentType: unknown): void {+ if (typeof agentId !== 'string' || agentId === '' || agentId.length > 128) return+ if (!a.agents.has(agentId) && a.agents.size >= MAX_AGENTS) return+ a.agents.set(agentId, nameOf(subagentType))+}++function charge(map: Map<string, number>, key: string, usd: number) {+ const k = map.has(key) || map.size < MAX_KEYS ? key : 'other'+ map.set(k, (map.get(k) ?? 0) + usd)+}++/** A tool call that just completed, and whose loop it ran in: one share of the next measured delta. */+export function noteTool(a: Attribution, tool: unknown, agentId: unknown): void {+ charge(a.pendingTool, nameOf(tool), 1)+ charge(a.pendingAgent, typeof agentId === 'string' ? a.agents.get(agentId) ?? 'subagent' : MAIN, 1)+ a.pendingCalls+++}++/**+ * Splits the delta since the last measurement across the tool calls completed+ * since then, one equal share per call; with none, it goes to `main` and+ * `(model)`. A total below the base means the host counted from zero again (a+ * /clear): the new total is the delta. A measurement with no cost change (a+ * rate-limit move) keeps the pending calls for the next one. Returns the delta.+ */+export function noteCost(a: Attribution, usd: number): number {+ if (!Number.isFinite(usd) || usd < 0) return 0+ const delta = usd < a.lastUsd ? usd : usd - a.lastUsd+ a.lastUsd = usd+ if (delta <= 0) return 0+ a.totalUsd += delta+ if (a.pendingCalls === 0) {+ charge(a.byAgent, MAIN, delta)+ charge(a.byTool, NO_TOOL, delta)+ } else {+ for (const [agent, calls] of a.pendingAgent) charge(a.byAgent, agent, (delta * calls) / a.pendingCalls)+ for (const [tool, calls] of a.pendingTool) charge(a.byTool, tool, (delta * calls) / a.pendingCalls)+ }+ a.pendingCalls = 0+ a.pendingAgent.clear()+ a.pendingTool.clear()+ return delta+}++const round = (usd: number) => Math.round(usd * 1e6) / 1e6+const sorted = (map: Map<string, number>) => Object.fromEntries([...map].sort((x, y) => y[1] - x[1]).map(([k, v]) => [k, round(v)]))++/** The JSONL line `ruflo cost report` reads (`parseAttributionLine` in cli/src/cost/attribution.ts). */+export function attributionLine(a: Attribution, reason: string, now: number, window?: { usd: number; period: string }): string {+ return JSON.stringify({+ v: 1,+ endedAt: now,+ reason: nameOf(reason),+ totalUsd: round(a.totalUsd),+ byAgent: sorted(a.byAgent),+ byTool: sorted(a.byTool),+ refusals: a.refusals,+ budget: window ? { usd: window.usd, period: window.period } : null,+ })+}++/** `existing` plus `lines`, capped to the newest MAX_LINES; blank lines dropped. */+export function appendLines(existing: string, lines: readonly string[]): string {+ const all = [...existing.split('\n').filter(l => l.trim()), ...lines]+ return `${all.slice(-MAX_LINES).join('\n')}\n`+}++/**+ * Whether a turn's error text is a gateway's budget refusal: LiteLLM's+ * `budget_exceeded` type and `ExceededTokenBudget` / "Budget has been+ * exceeded" messages, or a plain "budget exceeded". Only ever read for a turn+ * that ended on an API error; a model answer is never read.+ */+export function isBudgetRefusal(text: unknown): boolean {+ if (typeof text !== 'string' || text === '') return false+ const t = text.slice(0, 4096)+ return /budget_exceeded|ExceededTokenBudget|budget has been exceeded|exceeded (?:the |your |its )?(?:max )?budget|budget (?:limit )?exceeded/i.test(t)+}++/**+ * The text of a transcript message Claude Code wrote for an API error+ * (`API Error: <status> ...`), else ''. A model-written message never starts+ * that way in practice, and this is only read for a turn whose reason is+ * already `error`.+ */+export function apiErrorText(message: unknown): string {+ const m = message as { role?: unknown; text?: unknown } | undefined+ return m?.role === 'assistant' && typeof m.text === 'string' && /^API Error\b/.test(m.text) ? m.text.slice(0, 4096) : ''+}++/** Clears the per-session figures (after a line is written, or at /clear); spawned ids are dropped too. */+export function resetAttribution(a: Attribution): void {+ Object.assign(a, createAttribution())+}diff --git a/plugins/ruflo-mods/hooks/cost/file.ts b/plugins/ruflo-mods/hooks/cost/file.tsnew file mode 100644index 0000000000..f946d0115a--- /dev/null+++ b/plugins/ruflo-mods/hooks/cost/file.ts@@ -0,0 +1,83 @@+/**+ * The shared budget file (ADR-508 Β§2.1): `.claude-flow/cost/budget.json`,+ * version 1, written by `ruflo cost budget set` and read by both this mod and+ * `ruflo cost budget export`. Pure.+ *+ * The file is project-writable, so it is untrusted: a file that fails any rule+ * is no budget at all (the ladder stays off), never a zero budget that halts+ * at once. Unknown fields never survive. The CLI keeps a second copy of these+ * rules (v3/@claude-flow/cli/src/cost/budget-file.ts); a parity test runs both+ * over the same hostile corpus.+ */++export const BUDGET_PATH = '.claude-flow/cost/budget.json'++/** Windows a file may hold; more is a hostile file, not a richer budget. */+export const MAX_WINDOWS = 8+/** The largest window, in USD, a file may state. */+export const MAX_USD = 1_000_000+/** LiteLLM's `budget_duration` grammar (`30s`, `30m`, `30h`, `30d`), with a bounded count. */+export const PERIOD = /^[1-9][0-9]{0,3}[smhd]$/+const MODEL = /^[A-Za-z0-9._:/@-]{1,128}$/++export type BudgetWindow = { readonly usd: number; readonly period: string }++export type BudgetFile = {+ readonly version: 1+ readonly windows: readonly BudgetWindow[]+ readonly hardStop: boolean+ readonly fallbackModel?: string+}++const SECONDS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400 }++/** A period's length in seconds (for ordering windows). */+export const periodSeconds = (period: string) => Number(period.slice(0, -1)) * SECONDS[period.slice(-1)]!++/**+ * A budget file's value, validated, or undefined when it breaks any rule:+ * not an object, a version other than 1, no windows or more than MAX_WINDOWS,+ * a `usd` that is not a finite number in (0, MAX_USD], a period outside the+ * grammar or repeated, a non-boolean `hardStop`, or a `fallbackModel` outside+ * a plain model-name charset.+ */+export function validateBudget(value: unknown): BudgetFile | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined+ const o = value as Record<string, unknown>+ if (o.version !== 1) return undefined+ if (!Array.isArray(o.windows) || o.windows.length === 0 || o.windows.length > MAX_WINDOWS) return undefined+ const windows: BudgetWindow[] = []+ const seen = new Set<string>()+ for (const w of o.windows as unknown[]) {+ if (!w || typeof w !== 'object' || Array.isArray(w)) return undefined+ const { usd, period } = w as Record<string, unknown>+ if (typeof usd !== 'number' || !Number.isFinite(usd) || usd <= 0 || usd > MAX_USD) return undefined+ if (typeof period !== 'string' || !PERIOD.test(period) || seen.has(period)) return undefined+ seen.add(period)+ windows.push({ usd, period })+ }+ if (o.hardStop !== undefined && typeof o.hardStop !== 'boolean') return undefined+ if (o.fallbackModel !== undefined && (typeof o.fallbackModel !== 'string' || !MODEL.test(o.fallbackModel))) return undefined+ return {+ version: 1,+ windows,+ hardStop: o.hardStop === true,+ ...(typeof o.fallbackModel === 'string' ? { fallbackModel: o.fallbackModel } : {}),+ }+}++/** The file's text parsed and validated; throws on any failure (the reader turns that into "no budget"). */+export function parseBudget(text: string): BudgetFile {+ const budget = validateBudget(JSON.parse(text))+ if (!budget) throw new Error('budget.json fails validation')+ return budget+}++/**+ * The window the per-session ladder uses: the smallest `usd` (ties: the+ * shorter period). The mod sees one session's spend, so of every window the+ * smallest is always the nearest to its limit; the others are the gateway's.+ */+export function ladderWindow(budget: BudgetFile): BudgetWindow {+ return [...budget.windows].sort((a, b) => a.usd - b.usd || periodSeconds(a.period) - periodSeconds(b.period))[0]!+}diff --git a/plugins/ruflo-mods/hooks/cost/index.ts b/plugins/ruflo-mods/hooks/cost/index.tsindex 127091e997..34043b469c 100644--- a/plugins/ruflo-mods/hooks/cost/index.ts+++ b/plugins/ruflo-mods/hooks/cost/index.ts@@ -1,8 +1,16 @@import type { On } from 'claude-code'+import { cachedFile, isMissing } from '../files'import type { ModOptions } from '../options'-import { redraw, type ModState } from '../state'+import { redraw, under, type ModState } from '../state'+import {+ apiErrorText, appendLines, ATTRIBUTION_PATH, attributionLine, createAttribution, isBudgetRefusal, noteCost, noteSpawn, noteTool, resetAttribution,+} from './attribution'import { alertLevel, isRaised, type BudgetLevel } from './budget'+import { BUDGET_PATH, ladderWindow, parseBudget, type BudgetWindow } from './file'++/** Matches every value of a field each event carries (#4485: the always-on modules hold the bare registrations). */+const ANY = /^[\s\S]*$//*** ruflo-cost-tracker's budget ladder on the session's live cost:@@ -10,12 +18,31 @@ import { alertLevel, isRaised, type BudgetLevel } from './budget'* and no node spawn. Crossing a rung up says so once. With `costHardStop`,* the HARD_STOP rung does what budget.mjs recommends at 100%: new subagent* spawns are refused (a deny on `agent.spawn`; tightening only).+ *+ * With `costLedger` (ADR-508), in a ruflo project:+ * - when `costBudgetUsd` is off, the ladder takes its limit from the shared+ * budget file `.claude-flow/cost/budget.json` (its smallest window) and+ * names that window; the file's `hardStop` acts as `costHardStop`;+ * - each measured cost delta (one per main-thread turn) is split across the+ * tool calls completed in it, one share per call, by subagent type and by+ * tool (an estimate: see attribution.ts), and one line per session goes to+ * `.claude-flow/cost/attribution.jsonl` for `ruflo cost report`;+ * - a turn that ends on a gateway's budget refusal is toasted once and counted.+ * Nothing retries or changes model: that is the gateway's fallback.*/export function registerCost(on: On, state: ModState, options: ModOptions) {- const limit = options.costBudgetUsd- if (limit === undefined) return- state.budget = { level: 'OK', limit }+ const optionLimit = options.costBudgetUsd+ const ledger = options.costLedger+ if (optionLimit === undefined && !ledger) return+ const file = cachedFile(() => under(state, BUDGET_PATH), parseBudget)+ const attribution = createAttribution()+ let fileWindow: BudgetWindow | undefined+ let fileHardStop = falselet announced: BudgetLevel = 'OK' // the highest rung told this session; a fall and a second rise stay quiet+ let project: boolean | undefined+ const limitNow = () => optionLimit ?? fileWindow?.usd+ const reset = () => ({ level: 'OK' as const, ...(limitNow() !== undefined ? { limit: limitNow() } : {}) })+ state.budget = reset()// The budget is per session. /clear ends one (session.end, reason clear; no// session.start follows) and the process goes on with the next one's cost@@ -23,7 +50,7 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {// after the rollup, which records this session's rung before this runs.on('session.end', { reason: /^clear$/ }, ($, e, next) => {announced = 'OK'- state.budget = { level: 'OK', limit }+ state.budget = reset()redraw(state)return next(e)})@@ -32,6 +59,19 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {const result = await next(e)const usd = e.cost?.usdif (typeof usd !== 'number' || !Number.isFinite(usd) || usd < 0) return result+ if (ledger) noteCost(attribution, usd)++ if (optionLimit === undefined) {+ // The ladder's limit from the shared budget file: one stat per measurement, a read only when it changed.+ const read = await file({ stat: path => $.fs.stat(path), read: path => $.fs.read(path) })+ fileWindow = read.kind === 'ok' ? ladderWindow(read.value) : undefined+ fileHardStop = read.kind === 'ok' && read.value.hardStop+ }+ const limit = limitNow()+ if (limit === undefined) {+ state.budget = { level: 'OK' }+ return result+ }const level = alertLevel(usd / limit)const raised = isRaised(announced, level)@@ -39,18 +79,66 @@ export function registerCost(on: On, state: ModState, options: ModOptions) {state.budget = { level, usd, limit }if (isRaised(state.rollup.rung, level)) state.rollup.rung = level // the session rollup keeps the highest rung reachedif (raised) {+ const window = optionLimit === undefined && fileWindow ? ` (${fileWindow.period} window)` : ''// INFO and WARNING are heads-up; CRITICAL and HARD_STOP are errors, which the toast policy never drops (ADR-477).- await state.say({ level: level === 'INFO' ? 'info' : level === 'WARNING' ? 'warn' : 'error', text: `ruflo budget ${level}: $${usd.toFixed(2)} of $${limit.toFixed(2)} this session`, timeoutMs: 8000 })+ await state.say({ level: level === 'INFO' ? 'info' : level === 'WARNING' ? 'warn' : 'error', text: `ruflo budget ${level}: $${usd.toFixed(2)} of $${limit.toFixed(2)} this session${window}`, timeoutMs: 8000 })redraw(state)}return result})- if (options.costHardStop) {- on('agent.spawn', ($, e, next) =>- state.budget.level === 'HARD_STOP'- ? { deny: `ruflo budget: $${(state.budget.usd ?? 0).toFixed(2)} of $${limit.toFixed(2)} spent; new agents are halted (costHardStop)` }- : next(e),- )+ if ((optionLimit !== undefined && options.costHardStop) || ledger) {+ on('agent.spawn', async ($, e, next) => {+ const halt = options.costHardStop || (optionLimit === undefined && fileHardStop)+ if (halt && state.budget.level === 'HARD_STOP' && state.budget.limit !== undefined) {+ return { deny: `ruflo budget: $${(state.budget.usd ?? 0).toFixed(2)} of $${state.budget.limit.toFixed(2)} spent; new agents are halted (${options.costHardStop ? 'costHardStop' : 'budget.json hardStop'})` }+ }+ const result = await next(e)+ if (ledger) noteSpawn(attribution, (result as { agentId?: unknown } | undefined)?.agentId, e.subagentType)+ return result+ })}++ if (!ledger) return++ on('tool.call', { tool: ANY }, async ($, e, next) => {+ const result = await next(e)+ noteTool(attribution, e.tool, e.agentId)+ return result+ })++ on('turn.complete', { turnId: ANY }, async ($, e, next) => {+ const result = await next(e)+ // Only a main-loop turn that ended on an API error is read, and only for a budget refusal's words.+ if (e.agentId !== undefined || e.reason !== 'error') return result+ // Claude Code 2.1.289 ends such a turn with `answer: ''` and puts the error in the transcript as a+ // synthetic assistant message ("API Error: 400 ..."): read that one message, and only when it is one.+ const last = e.answer ? undefined : await $.session.messages().then(m => (Array.isArray(m) ? m.at(-1) : undefined), () => undefined)+ if (!isBudgetRefusal(e.answer || apiErrorText(last))) return result+ attribution.refusals+++ if (!attribution.toasted) {+ attribution.toasted = true+ await state.say({ level: 'error', text: `budget: the gateway refused the request (${fileWindow ? `${fileWindow.period} window` : 'budget'} spent)`, timeoutMs: 10000 })+ }+ return result+ })++ on('session.end', { reason: ANY }, async ($, e, next) => {+ try {+ project ??= await $.fs.stat(under(state, '.claude-flow')).then(stat => stat.kind === 'dir', () => false)+ if (project && (attribution.totalUsd > 0 || attribution.refusals > 0)) {+ const line = attributionLine(attribution, String(e.reason), Date.now(), optionLimit === undefined ? fileWindow : { usd: optionLimit, period: 'session' })+ const path = under(state, ATTRIBUTION_PATH)+ const existing = await $.fs.read(path).catch((error: unknown) => {+ if (isMissing(error)) return ''+ throw error // a file that exists but cannot be read is never overwritten+ })+ await $.fs.write(path, appendLines(existing, [line]))+ }+ } catch {+ // the breakdown is best effort; a session must end whatever happens here+ }+ resetAttribution(attribution)+ return next(e)+ })}diff --git a/plugins/ruflo-mods/hooks/options.ts b/plugins/ruflo-mods/hooks/options.tsindex 60196d0d49..c7f7c602d6 100644--- a/plugins/ruflo-mods/hooks/options.ts+++ b/plugins/ruflo-mods/hooks/options.ts@@ -11,6 +11,7 @@ export type ModOptions = {readonly statusLine: booleanreadonly costBudgetUsd?: numberreadonly costHardStop: boolean+ readonly costLedger: booleanreadonly toolHints: booleanreadonly agentTrim: booleanreadonly agentTrimKeep: ReadonlySet<string>@@ -48,6 +49,7 @@ export function readOptions(options: PluginOptions | undefined): ModOptions {statusLine: bool(o.statusLine, true),costBudgetUsd: budgetOf(o.costBudgetUsd),costHardStop: bool(o.costHardStop, false),+ costLedger: bool(o.costLedger, true),toolHints: bool(o.toolHints, false),agentTrim: bool(o.agentTrim, false),agentTrimKeep: keepNames(o.agentTrimKeep),diff --git a/plugins/ruflo-mods/hooks/probe/index.ts b/plugins/ruflo-mods/hooks/probe/index.tsindex b5ebbb9d47..f640896436 100644--- a/plugins/ruflo-mods/hooks/probe/index.ts+++ b/plugins/ruflo-mods/hooks/probe/index.ts@@ -33,14 +33,14 @@ const MAX_LINE = 240const ALWAYS = ['command.run', 'engine.create', 'prompt.submit', 'session.end', 'session.start', 'tool.call', 'tool.check', 'turn.complete'] as consttype EventOptions = Pick<ModOptions, 'toolHints' | 'agentTrim' | 'deliveryScreen'> &- Partial<Pick<ModOptions, 'compactCarry' | 'costBudgetUsd' | 'costHardStop' | 'sessionRollup' | 'modTrust'>>+ Partial<Pick<ModOptions, 'compactCarry' | 'costBudgetUsd' | 'costHardStop' | 'costLedger' | 'sessionRollup' | 'modTrust'>>export function registeredEvents(opts: EventOptions): string[] {const names: string[] = [...ALWAYS]// Registered only under these options, so "never fired" is not reported for an event the mod did not hook.if (opts.modTrust !== 'off') names.push('plugin.register')- if (opts.costBudgetUsd !== undefined) names.push('session.measure')- if ((opts.costBudgetUsd !== undefined && opts.costHardStop) || opts.sessionRollup || opts.agentTrim) names.push('agent.spawn')+ if (opts.costBudgetUsd !== undefined || opts.costLedger) names.push('session.measure')+ if ((opts.costBudgetUsd !== undefined && opts.costHardStop) || opts.costLedger || opts.sessionRollup || opts.agentTrim) names.push('agent.spawn')if (opts.toolHints) names.push('tool.describe')if (opts.agentTrim) names.push('agent.offer')if (opts.deliveryScreen) names.push('session.receive', 'session.send')diff --git a/plugins/ruflo-mods/hooks/state.ts b/plugins/ruflo-mods/hooks/state.tsindex 695e702418..3569c9ff9a 100644--- a/plugins/ruflo-mods/hooks/state.ts+++ b/plugins/ruflo-mods/hooks/state.ts@@ -168,7 +168,7 @@ export function report(s: ModState): string {: 'none yet'const budget =s.budget.limit === undefined- ? 'off (set the costBudgetUsd option)'+ ? 'off (set the costBudgetUsd option, or .claude-flow/cost/budget.json with costLedger on)': `${s.budget.level}: $${(s.budget.usd ?? 0).toFixed(2)} of $${s.budget.limit.toFixed(2)}`const segments = sortedSegments(s).map(([id]) => id)return [diff --git a/plugins/ruflo-mods/scripts/smoke.sh b/plugins/ruflo-mods/scripts/smoke.shindex 33bb5e4895..b4a7726371 100755--- a/plugins/ruflo-mods/scripts/smoke.sh+++ b/plugins/ruflo-mods/scripts/smoke.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Structural + security smoke for ruflo-mods v0.10.0 (ADR-404, ADR-447).+# Structural + security smoke for ruflo-mods v0.11.0 (ADR-404, ADR-447).# Static only: CI has no Claude Code, so the hooks module's behaviour is held# by v3/@claude-flow/cli/__tests__/mods/*.test.ts and, where function hooks are# on, by `claude plugin test plugins/ruflo-mods`.@@ -12,9 +12,9 @@ ok() { printf "PASS\n"; PASS=$((PASS+1)); }bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); }HOOKS="$ROOT/hooks"-step "1. plugin.json declares ruflo-mods 0.10.0"+step "1. plugin.json declares ruflo-mods 0.11.0"grep -q '"name": "ruflo-mods"' "$ROOT/.claude-plugin/plugin.json" \- && grep -q '"version": "0.10.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"+ && grep -q '"version": "0.11.0"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version"step "2. hooks.json names exactly one module and no classic hook commands"grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \diff --git a/plugins/ruflo-mods/tests/probe.test.ts b/plugins/ruflo-mods/tests/probe.test.tsindex 67a47c4917..1cb81f878b 100644--- a/plugins/ruflo-mods/tests/probe.test.ts+++ b/plugins/ruflo-mods/tests/probe.test.ts@@ -36,10 +36,10 @@ describe('capability probe, pure (ADR-451 item 5)', () => {test('registeredEvents matches what register() hooks, for every option combination', () => {const B = [false, true]- for (const costBudgetUsd of [undefined, 5]) for (const costHardStop of B) for (const sessionRollup of B)+ for (const costBudgetUsd of [undefined, 5]) for (const costHardStop of B) for (const costLedger of B) for (const sessionRollup of B)for (const agentTrim of B) for (const modTrust of ['observe', 'off']) for (const toolHints of B)for (const deliveryScreen of B) for (const compactCarry of B) {- const o = { costBudgetUsd, costHardStop, sessionRollup, agentTrim, modTrust, toolHints, deliveryScreen, compactCarry, capabilityProbe: true }+ const o = { costBudgetUsd, costHardStop, costLedger, sessionRollup, agentTrim, modTrust, toolHints, deliveryScreen, compactCarry, capabilityProbe: true }const seen = new Set<string>()const chain: { catch: () => unknown } = { catch: () => chain }register(((name: string) => (name !== '*' && seen.add(name), chain)) as never, o as never)@@ -58,6 +58,7 @@ describe('capability probe, pure (ADR-451 item 5)', () => {expect(registeredEvents({ ...base, costBudgetUsd: 5, costHardStop: true })).toContain('agent.spawn')expect(registeredEvents({ ...base, costHardStop: true })).not.toContain('agent.spawn')expect(registeredEvents({ ...base, sessionRollup: true })).toContain('agent.spawn')+ expect(registeredEvents({ ...base, costLedger: true })).toEqual(expect.arrayContaining(['session.measure', 'agent.spawn']))})})diff --git a/v3/@claude-flow/cli/__tests__/cost-budget-gateway.test.ts b/v3/@claude-flow/cli/__tests__/cost-budget-gateway.test.tsnew file mode 100644index 0000000000..fa2590f9a9--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/cost-budget-gateway.test.ts@@ -0,0 +1,287 @@+/**+ * ADR-508 β `ruflo cost budget set/get/export` and `ruflo cost report`.+ *+ * - the budget file's validation (and parity with the ruflo-mods copy);+ * - the LiteLLM export, field by field against docs.litellm.ai;+ * - `--apply` refuses plain HTTP to a non-loopback host and reads the key only from the environment;+ * - `--gateway meta-llm` fails with a pointer to ADR-508.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { parse as parseYaml } from 'yaml';++import { validateBudget as modValidate, ladderWindow as modLadder } from '../../../../plugins/ruflo-mods/hooks/cost/file';+import { attributionLine, createAttribution, noteCost, noteSpawn, noteTool } from '../../../../plugins/ruflo-mods/hooks/cost/attribution';+import { BUDGET_PATH, budgetFromFlags, ladderWindow, readBudget, validateBudget } from '../src/cost/budget-file';+import { applyToLiteLLM, gatewayRefusal, keyFromEnv, keyGenerateUrl, maskKey, toLiteLLMKeyBody } from '../src/cost/litellm';+import { parseAttributionLine, summarize } from '../src/cost/attribution';+import { costCommand } from '../src/commands/cost';+import { output } from '../src/output';++const HOSTILE: unknown[] = [+ null, 1, 'x', [], {},+ { version: 2, windows: [{ usd: 1, period: '24h' }] },+ { version: '1', windows: [{ usd: 1, period: '24h' }] },+ { version: 1 },+ { version: 1, windows: [] },+ { version: 1, windows: {} },+ { version: 1, windows: [{ usd: -1, period: '24h' }] },+ { version: 1, windows: [{ usd: 0, period: '24h' }] },+ { version: 1, windows: [{ usd: Number.NaN, period: '24h' }] },+ { version: 1, windows: [{ usd: '10', period: '24h' }] },+ { version: 1, windows: [{ usd: 1e7, period: '24h' }] },+ { version: 1, windows: [{ usd: 1, period: '1mo' }] },+ { version: 1, windows: [{ usd: 1, period: 'week' }] },+ { version: 1, windows: [{ usd: 1, period: '0d' }] },+ { version: 1, windows: [{ usd: 1, period: '-1d' }] },+ { version: 1, windows: [{ usd: 1, period: '24h\n' }] },+ { version: 1, windows: [{ usd: 1, period: '99999d' }] },+ { version: 1, windows: [{ usd: 1, period: '24h' }, { usd: 2, period: '24h' }] },+ { version: 1, windows: Array.from({ length: 9 }, (_, i) => ({ usd: 1, period: `${i + 1}d` })) },+ { version: 1, windows: Array.from({ length: 10_000 }, () => ({ usd: 1, period: '24h' })) },+ { version: 1, windows: [null] },+ { version: 1, windows: [{ usd: 1, period: '24h' }], hardStop: 'yes' },+ { version: 1, windows: [{ usd: 1, period: '24h' }], fallbackModel: 'haiku; rm -rf /' },+ { version: 1, windows: [{ usd: 1, period: '24h' }], fallbackModel: '' },+ { version: 1, windows: [{ usd: 1, period: '24h' }], fallbackModel: 'x'.repeat(129) },+ { version: 1, windows: [{ usd: 1, period: '24h' }], fallbackModel: 7 },+];+const GOOD: unknown[] = [+ { version: 1, windows: [{ usd: 10, period: '24h' }, { usd: 100, period: '30d' }], hardStop: true, fallbackModel: 'haiku' },+ { version: 1, windows: [{ usd: 0.5, period: '30m' }] },+ { version: 1, windows: [{ usd: 5, period: '7d' }], fallbackModel: 'anthropic/claude-haiku-4-5', extra: 'dropped', __proto__x: 1 },+ { version: 1, windows: Array.from({ length: 8 }, (_, i) => ({ usd: i + 1, period: `${i + 1}d` })) },+];++describe('budget file validation', () => {+ it('rejects every hostile file, in both copies', () => {+ for (const v of HOSTILE) {+ expect(validateBudget(v), JSON.stringify(v)?.slice(0, 80)).toBeUndefined();+ expect(modValidate(v), JSON.stringify(v)?.slice(0, 80)).toBeUndefined();+ }+ });++ it('keeps good files, drops unknown fields, and the two copies agree exactly', () => {+ for (const v of GOOD) {+ const cli = validateBudget(v);+ expect(cli).toBeDefined();+ expect(modValidate(v)).toEqual(cli);+ expect(Object.keys(cli!).sort()).toEqual(['hardStop', 'version', 'windows', ...('fallbackModel' in cli! ? ['fallbackModel'] : [])].sort());+ expect(modLadder(modValidate(v)!)).toEqual(ladderWindow(cli!));+ }+ });++ it('the ladder window is the smallest usd', () => {+ expect(ladderWindow(validateBudget(GOOD[0])!)).toEqual({ usd: 10, period: '24h' });+ });++ it('builds a budget from set flags', () => {+ expect(budgetFromFlags({ daily: 10, monthly: '100' }).budget).toEqual({ version: 1, windows: [{ usd: 10, period: '24h' }, { usd: 100, period: '30d' }], hardStop: false });+ expect(budgetFromFlags({ weekly: 5, hardStop: true, fallbackModel: 'haiku' }).budget).toEqual({ version: 1, windows: [{ usd: 5, period: '7d' }], hardStop: true, fallbackModel: 'haiku' });+ expect(budgetFromFlags({}).error).toMatch(/at least one/);+ expect(budgetFromFlags({ daily: -1 }).error).toMatch(/--daily/);+ expect(budgetFromFlags({ daily: 'ten' }).error).toMatch(/--daily/);+ expect(budgetFromFlags({ daily: 1, fallbackModel: 'a b' }).error).toMatch(/--fallback-model/);+ });+});++describe('LiteLLM export', () => {+ const budget = validateBudget(GOOD[0])!;++ it('maps every window to a budget_limits entry with LiteLLM field names', () => {+ expect(toLiteLLMKeyBody(budget)).toEqual({+ budget_limits: [{ budget_duration: '24h', max_budget: 10 }, { budget_duration: '30d', max_budget: 100 }],+ });+ });++ it('adds model_max_budget and budget_fallbacks only for a named model, with their own documented field names', () => {+ const body = toLiteLLMKeyBody(budget, 'claude-opus-4-5');+ expect(body).toEqual({+ budget_limits: [{ budget_duration: '24h', max_budget: 10 }, { budget_duration: '30d', max_budget: 100 }],+ model_max_budget: { 'claude-opus-4-5': { budget_limit: 10, time_period: '24h' } },+ budget_fallbacks: { 'claude-opus-4-5': ['haiku'] },+ });+ // Field names exactly as docs.litellm.ai documents them (users, budget_fallbacks pages).+ expect(Object.keys(body.budget_limits[0]!).sort()).toEqual(['budget_duration', 'max_budget']);+ expect(Object.keys(body.model_max_budget!['claude-opus-4-5']!).sort()).toEqual(['budget_limit', 'time_period']);+ expect(Array.isArray(body.budget_fallbacks!['claude-opus-4-5'])).toBe(true);+ // No fallback model: no budget_fallbacks, never an invented one.+ expect(toLiteLLMKeyBody(validateBudget(GOOD[1])!, 'm').budget_fallbacks).toBeUndefined();+ expect(() => toLiteLLMKeyBody(budget, 'bad model')).toThrow(/--model/);+ });++ it('refuses meta-llm with a pointer to ADR-508, and unknown gateways', () => {+ expect(gatewayRefusal('litellm')).toBeUndefined();+ expect(gatewayRefusal('meta-llm')).toMatch(/no budget API.*ADR-508/);+ expect(gatewayRefusal('openrouter')).toMatch(/must be one of/);+ expect(gatewayRefusal(undefined)).toMatch(/must be one of/);+ });+});++describe('--apply guards', () => {+ it('refuses plain http to a non-loopback host, credentials in the URL, and non-URLs', () => {+ for (const bad of ['http://proxy.example.com', 'http://10.0.0.5:4000', 'http://0.0.0.0:4000', 'http://localhost.evil.com', 'ftp://localhost', 'https://u:[email protected]', 'https://proxy.example?x=1', 'not a url', '', undefined]) {+ expect(keyGenerateUrl(bad).url, String(bad)).toBeUndefined();+ }+ });++ it('refuses a path that would move the request to another host (protocol-relative "//" or "/\\")', () => {+ // Each of these resolved to http(s)://<evil>/key/generate before the fix, with the master key as bearer.+ for (const bad of ['http://localhost//evil.example/', 'http://127.0.0.1/\\\\attacker.example/', 'http://127.0.0.1/\\\\attacker.example:80/', 'https://ok.example//evil.example/', 'http://[::1]:4000//evil.example', 'https://ok.example/\\evil.example/']) {+ const r = keyGenerateUrl(bad);+ expect(r.url, bad).toBeUndefined();+ expect(r.error, bad).toMatch(/must not start with/);+ }+ });++ it('allows https anywhere and http to loopback, and appends /key/generate to the base path', () => {+ const cases: [string, string][] = [+ ['https://proxy.example.com', 'https://proxy.example.com/key/generate'],+ ['https://proxy.example.com/litellm/', 'https://proxy.example.com/litellm/key/generate'],+ ['https://proxy.example.com/a//b', 'https://proxy.example.com/a//b/key/generate'],+ ['http://localhost:4000', 'http://localhost:4000/key/generate'],+ ['http://127.0.0.1:4000', 'http://127.0.0.1:4000/key/generate'],+ ['http://[::1]:4000', 'http://[::1]:4000/key/generate'],+ ];+ for (const [input, href] of cases) {+ const out = keyGenerateUrl(input).url!;+ expect(out.href, input).toBe(href);+ const given = new URL(input);+ expect(out.protocol, input).toBe(given.protocol);+ expect(out.host, input).toBe(given.host);+ }+ });++ it('reads the master key only from the named environment variable', () => {+ expect(keyFromEnv('LITELLM_MASTER_KEY', { LITELLM_MASTER_KEY: 'sk-master-123456' }).key).toBe('sk-master-123456');+ expect(keyFromEnv('LITELLM_MASTER_KEY', {}).error).toMatch(/not set/);+ expect(keyFromEnv('sk-master-123456', {}).error).toMatch(/--key-env/); // a key pasted in place of a name is refused+ expect(keyFromEnv(undefined, {}).error).toMatch(/--key-env/);+ expect(maskKey('sk-1234567890abcdef')).toBe('sk-1β¦(19 chars)');+ });++ it('posts only the budget fields, with the key as a bearer and redirects refused', async () => {+ const calls: { url: string; init: RequestInit }[] = [];+ const fake = (async (url: URL, init: RequestInit) => {+ calls.push({ url: String(url), init });+ return new Response(JSON.stringify({ key: 'sk-generated-abcdefgh' }), { status: 200 });+ }) as unknown as typeof fetch;+ const body = toLiteLLMKeyBody(validateBudget(GOOD[0])!);+ const r = await applyToLiteLLM(keyGenerateUrl('http://127.0.0.1:4000').url!, 'sk-master', body, fake);+ expect(r).toEqual({ ok: true, status: 200, generatedKey: 'sk-generated-abcdefgh' });+ expect(calls).toHaveLength(1);+ expect(calls[0]!.url).toBe('http://127.0.0.1:4000/key/generate');+ expect(calls[0]!.init.method).toBe('POST');+ expect(calls[0]!.init.redirect).toBe('error');+ expect((calls[0]!.init.headers as Record<string, string>).authorization).toBe('Bearer sk-master');+ expect(JSON.parse(String(calls[0]!.init.body))).toEqual(body);+ });++ it('reports a gateway refusal without throwing', async () => {+ const fake = (async () => new Response('{"error":"bad key"}', { status: 401 })) as unknown as typeof fetch;+ const r = await applyToLiteLLM(keyGenerateUrl('https://p.example').url!, 'k', { budget_limits: [] }, fake);+ expect(r.ok).toBe(false);+ expect(r.status).toBe(401);+ });+});++describe('attribution report', () => {+ it('reads what the mod writes, and skips hostile lines', () => {+ const a = createAttribution();+ noteSpawn(a, 'ag1', 'coder');+ noteTool(a, 'Edit', 'ag1');+ noteCost(a, 0.4);+ noteTool(a, 'Bash', undefined);+ noteCost(a, 0.5);+ const line = attributionLine(a, 'prompt_input_exit', 1000, { usd: 10, period: '24h' });+ expect(parseAttributionLine(line)).toEqual({ endedAt: 1000, totalUsd: 0.5, byAgent: { coder: 0.4, main: 0.1 }, byTool: { Edit: 0.4, Bash: 0.1 }, refusals: 0 });+ const text = [line, line, '{"v":1,"endedAt":1,"totalUsd":-5,"byAgent":{},"byTool":{},"refusals":0}', '{"v":1,"endedAt":1,"totalUsd":1,"byAgent":{"<script>":1},"byTool":{},"refusals":0}', 'garbage', ''].join('\n');+ const report = summarize(text);+ expect(report.sessions).toBe(2);+ expect(report.skipped).toBe(3);+ expect(report.totalUsd).toBeCloseTo(1, 6);+ expect(report.byAgent[0]).toEqual(['coder', 0.8]);+ expect(summarize(text, 2000).sessions).toBe(0);+ });+});++describe('ruflo cost command', () => {+ let cwd: string;+ const sub = (...names: string[]) => names.reduce((cmd, n) => cmd.subcommands!.find((s) => s.name === n)!, costCommand);+ const ctx = (flags: Record<string, unknown>) => ({ args: [], flags: { _: [], ...flags }, cwd, interactive: false }) as never;+ let written: string[];++ beforeEach(() => {+ cwd = mkdtempSync(join(tmpdir(), 'ruflo-cost-'));+ written = [];+ vi.spyOn(output, 'write').mockImplementation((t: string) => void written.push(t));+ vi.spyOn(output, 'writeln').mockImplementation((t = '') => void written.push(t));+ vi.spyOn(output, 'writeErrorln').mockImplementation((t = '') => void written.push(t));+ vi.spyOn(output, 'printError').mockImplementation((t: string) => void written.push(`ERR ${t}`));+ vi.spyOn(output, 'printSuccess').mockImplementation((t: string) => void written.push(t));+ });+ afterEach(() => {+ vi.restoreAllMocks();+ rmSync(cwd, { recursive: true, force: true });+ });++ it('set writes the file the mod reads; export prints LiteLLM YAML', async () => {+ expect((await sub('budget', 'set').action!(ctx({ daily: 10, monthly: 100, hardStop: true, fallbackModel: 'haiku' }))).success).toBe(true);+ const onDisk = JSON.parse(readFileSync(join(cwd, BUDGET_PATH), 'utf8'));+ expect(modValidate(onDisk)).toEqual({ version: 1, windows: [{ usd: 10, period: '24h' }, { usd: 100, period: '30d' }], hardStop: true, fallbackModel: 'haiku' });+ expect(JSON.stringify(onDisk)).not.toMatch(/key|token|secret/i);++ written = [];+ const r = await sub('budget', 'export').action!(ctx({ gateway: 'litellm', model: 'claude-sonnet' }));+ expect(r.success).toBe(true);+ expect(parseYaml(written[0]!)).toEqual(r.data);+ });++ it('export --gateway meta-llm fails and sends nothing', async () => {+ mkdirSync(join(cwd, '.claude-flow/cost'), { recursive: true });+ writeFileSync(join(cwd, BUDGET_PATH), JSON.stringify(GOOD[0]));+ const fetchSpy = vi.spyOn(globalThis, 'fetch');+ const r = await sub('budget', 'export').action!(ctx({ gateway: 'meta-llm', apply: true, url: 'https://x.example', keyEnv: 'K' }));+ expect(r.success).toBe(false);+ expect(written.join('\n')).toMatch(/ADR-508/);+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it('--apply to plain http on a non-loopback host, or a host-escaping path, is refused before any request', async () => {+ mkdirSync(join(cwd, '.claude-flow/cost'), { recursive: true });+ writeFileSync(join(cwd, BUDGET_PATH), JSON.stringify(GOOD[0]));+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response('{}', { status: 200 }));+ process.env.RUFLO_TEST_LITELLM_KEY = 'sk-master-test';+ try {+ const r = await sub('budget', 'export').action!(ctx({ gateway: 'litellm', apply: true, url: 'http://proxy.example.com:4000', keyEnv: 'RUFLO_TEST_LITELLM_KEY' }));+ expect(r.success).toBe(false);+ expect(written.join('\n')).toMatch(/refuses http:\/\/proxy\.example\.com/);+ for (const url of ['http://localhost//evil.example/', 'http://127.0.0.1/\\\\attacker.example/', 'https://ok.example//evil.example/']) {+ written = [];+ const escaped = await sub('budget', 'export').action!(ctx({ gateway: 'litellm', apply: true, url, keyEnv: 'RUFLO_TEST_LITELLM_KEY' }));+ expect(escaped.success, url).toBe(false);+ expect(written.join('\n'), url).toMatch(/must not start with/);+ }+ expect(fetchSpy).not.toHaveBeenCalled();+ } finally {+ delete process.env.RUFLO_TEST_LITELLM_KEY;+ }+ });++ it('get and export fail clearly without a budget file, and on an invalid one', async () => {+ expect((await sub('budget', 'get').action!(ctx({}))).success).toBe(false);+ mkdirSync(join(cwd, '.claude-flow/cost'), { recursive: true });+ writeFileSync(join(cwd, BUDGET_PATH), JSON.stringify(HOSTILE[10]));+ expect(readBudget(cwd).kind).toBe('invalid');+ expect((await sub('budget', 'export').action!(ctx({ gateway: 'litellm' }))).success).toBe(false);+ });++ it('report reads the attribution file', async () => {+ mkdirSync(join(cwd, '.claude-flow/cost'), { recursive: true });+ writeFileSync(join(cwd, '.claude-flow/cost/attribution.jsonl'), '{"v":1,"endedAt":1,"totalUsd":2,"byAgent":{"coder":1.5,"main":0.5},"byTool":{"Bash":2},"refusals":1,"budget":null}\n');+ const r = await sub('report').action!(ctx({ json: true }));+ expect(r.data).toMatchObject({ sessions: 1, totalUsd: 2, refusals: 1, byAgent: [['coder', 1.5], ['main', 0.5]] });+ });+});diff --git a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts b/v3/@claude-flow/cli/__tests__/guidance-brain.test.tsindex 36b98d2f75..57f03e1230 100644--- a/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts+++ b/v3/@claude-flow/cli/__tests__/guidance-brain.test.ts@@ -50,7 +50,8 @@ describe('Ruflo capability brain', () => {expect(auth.riskFlags).toEqual(expect.arrayContaining(['network', 'credential-pii', 'approval']),);- expect(brain.cliCommands).toHaveLength(54);+ expect(brain.cliCommands).toHaveLength(55);+ expect(brain.cliCommands).toContain('cost'); // ADR-508expect(brain.cliCommands).toContain('harness');});diff --git a/v3/@claude-flow/cli/__tests__/mods/harness.ts b/v3/@claude-flow/cli/__tests__/mods/harness.tsindex 9a007ef981..49ca6f6ea3 100644--- a/v3/@claude-flow/cli/__tests__/mods/harness.ts+++ b/v3/@claude-flow/cli/__tests__/mods/harness.ts@@ -44,6 +44,8 @@ export interface World {failLog?: boolean;/** What `$.tool.list()` returns (default: none). `mcp` marks an MCP server's tool. */tools?: { name: string; description: string; mcp: boolean }[];+ /** What `$.session.messages()` returns (default: none). */+ messages?: { role: 'user' | 'assistant'; text: string; toolUses: unknown[] }[];}export function memoryWorld(root = '/work', settings: unknown = {}): World {@@ -121,6 +123,9 @@ function engineOf(world: World) {async root() {return world.root;},+ async messages() {+ return world.messages ?? [];+ },},command: {async register(spec: { name: string }) {diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-cost-ledger.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-cost-ledger.test.tsnew file mode 100644index 0000000000..57cbc973c3--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/mods/mods-cost-ledger.test.ts@@ -0,0 +1,222 @@+/**+ * ADR-508 β the ruflo-mods cost ledger: the shared budget file drives the+ * ladder, cost deltas are attributed to subagent types and tools, and a+ * gateway budget refusal is toasted once.+ */+import { describe, it, expect } from 'vitest';++import { register } from '../../../../../plugins/ruflo-mods/hooks/register';+import { isBudgetRefusal, MAX_KEYS, createAttribution, noteCost, noteTool } from '../../../../../plugins/ruflo-mods/hooks/cost/attribution';+import { parseAttributionLine } from '../../src/cost/attribution';+import { loadMod, memoryWorld, type World } from './harness';++const BUDGET = '/work/.claude-flow/cost/budget.json';+const LEDGER = '/work/.claude-flow/cost/attribution.jsonl';+const mem = (w: World) => w.files as Map<string, { text: string; mtimeMs: number }>;+const put = (w: World, path: string, value: unknown) => mem(w).set(path, { text: typeof value === 'string' ? value : JSON.stringify(value), mtimeMs: (mem(w).get(path)?.mtimeMs ?? 0) + 1 });++async function start(world: World, options: Record<string, unknown> = {}) {+ const mod = loadMod(register, world, options);+ await mod.create();+ await mod.dispatch('session.start', { cwd: world.root, surface: null, isInteractive: false }, (e) => ({ cwd: e.cwd }));+ return mod;+}+type Mod = Awaited<ReturnType<typeof start>>;+const measure = (mod: Mod, usd: number) => mod.dispatch('session.measure', { context: {}, rateLimits: [], cost: { usd }, changed: ['cost'] }, (e) => ({ changed: e.changed }));+const tool = (mod: Mod, name: string, agentId?: string) => mod.dispatch('tool.call', { tool: name, tool_use_id: `t-${name}`, ...(agentId ? { agentId } : {}) }, () => ({ result: 'ok' }));+const spawn = (mod: Mod, subagentType: string, agentId: string) => mod.dispatch('agent.spawn', { prompt: 'p', description: 'd', subagentType }, () => ({ model: 'haiku', agentId }));+const end = (mod: Mod, reason = 'prompt_input_exit') => mod.dispatch('session.end', { reason, sessionId: 's1', resume: {} }, () => ({ sessionId: 's1' }));+const turnError = (mod: Mod, answer: string, reason = 'error') => mod.dispatch('turn.complete', { turnId: 't1', reason, answer, durationMs: 1, isAborted: false }, () => ({ text: answer }));+const ladder = (w: World) => w.toasts.filter((t) => t.includes('ruflo budget'));++describe('ADR-508 budget file drives the ladder', () => {+ it('uses the smallest window when costBudgetUsd is off, and names it', async () => {+ const world = memoryWorld();+ put(world, BUDGET, { version: 1, windows: [{ usd: 100, period: '30d' }, { usd: 10, period: '24h' }] });+ const mod = await start(world);+ for (const usd of [1, 5.5, 7.6, 9.2, 10.5]) await measure(mod, usd);+ expect(ladder(world).map((t) => t.split(':')[0])).toEqual(['βΊ ruflo budget INFO', 'β ruflo budget WARNING', 'β ruflo budget CRITICAL', 'β ruflo budget HARD_STOP']);+ expect(ladder(world)[0]).toContain('of $10.00 this session (24h window)');+ });++ it('costBudgetUsd wins over the file', async () => {+ const world = memoryWorld();+ put(world, BUDGET, { version: 1, windows: [{ usd: 1, period: '24h' }] });+ const mod = await start(world, { costBudgetUsd: 100 });+ await measure(mod, 5);+ expect(ladder(world)).toEqual([]);+ });++ it('a hostile or broken file is no budget, never a zero budget', async () => {+ for (const bad of ['{not json', { version: 2, windows: [{ usd: 1, period: '24h' }] }, { version: 1, windows: [{ usd: -1, period: '24h' }] }, { version: 1, windows: [{ usd: 1, period: '1mo' }] }, { version: 1, windows: Array.from({ length: 9 }, (_, i) => ({ usd: 1, period: `${i + 1}d` })) }, { version: 1, windows: [{ usd: 0, period: '24h' }] }]) {+ const world = memoryWorld();+ put(world, BUDGET, bad);+ const mod = await start(world);+ await measure(mod, 50);+ expect(ladder(world), JSON.stringify(bad)).toEqual([]);+ expect((await spawn(mod, 'coder', 'a1')).deny).toBeUndefined();+ }+ });++ it('the file hardStop halts new agents at HARD_STOP; without it, agents still start (negative control)', async () => {+ for (const hardStop of [true, false]) {+ const world = memoryWorld();+ put(world, BUDGET, { version: 1, windows: [{ usd: 1, period: '24h' }], hardStop });+ const mod = await start(world);+ await measure(mod, 1.2);+ const r = await spawn(mod, 'coder', 'a1');+ if (hardStop) expect(r.deny).toMatch(/budget\.json hardStop/);+ else expect(r).toEqual({ model: 'haiku', agentId: 'a1' });+ }+ });+});++describe('ADR-508 attribution', () => {+ it('charges each delta to the subagent types and tools of the calls in it, and writes one line at session end', async () => {+ const world = memoryWorld();+ const mod = await start(world);+ await measure(mod, 0.1); // a plain answer, no tool yet+ await tool(mod, 'Read');+ await measure(mod, 0.3);+ await spawn(mod, 'researcher', 'agent-7');+ await tool(mod, 'WebFetch', 'agent-7');+ await measure(mod, 1.0);+ await tool(mod, 'Bash', 'agent-unknown');+ await measure(mod, 1.5);+ expect(mem(world).has(LEDGER)).toBe(false); // nothing written mid-session+ await end(mod);+ const line = parseAttributionLine(mem(world).get(LEDGER)!.text.trim())!;+ expect(line.totalUsd).toBeCloseTo(1.5, 6);+ expect(line.byAgent).toEqual({ researcher: 0.7, main: 0.3, subagent: 0.5 });+ expect(line.byTool).toEqual({ WebFetch: 0.7, Bash: 0.5, Read: 0.2, '(model)': 0.1 });+ expect(line.refusals).toBe(0);+ });++ it('host order: a foreground subagent runs inside the main Agent call, and the turn is measured once, after it', async () => {+ // Claude Code measures after each main-thread turn only. The main loop's Agent tool.call resolves after+ // the subagent's own tool calls, so it is the last tool before the measurement. Charging the whole delta+ // to the last tool (the old behaviour) put everything on main/Agent; the delta is split per tool call.+ const world = memoryWorld();+ const mod = await start(world);+ await tool(mod, 'Read'); // main, before the spawn+ await spawn(mod, 'researcher', 'agent-7'); // fires inside the main Agent tool call+ for (const name of ['WebFetch', 'WebFetch', 'Grep']) await tool(mod, name, 'agent-7');+ await tool(mod, 'Agent'); // the main loop's Agent call completes after its subagent+ await measure(mod, 1.0); // one measurement for the whole main turn+ await measure(mod, 1.4); // next turn: a plain answer, no tool calls+ await end(mod);+ const line = parseAttributionLine(mem(world).get(LEDGER)!.text.trim())!;+ expect(line.totalUsd).toBeCloseTo(1.4, 6);+ expect(line.byAgent).toEqual({ main: 0.8, researcher: 0.6 }); // 2 of 5 calls + the plain answer; 3 of 5+ expect(line.byTool).toEqual({ '(model)': 0.4, WebFetch: 0.4, Read: 0.2, Grep: 0.2, Agent: 0.2 });+ });++ it('a measurement with no cost change keeps the calls for the next delta', async () => {+ const world = memoryWorld();+ const mod = await start(world);+ await spawn(mod, 'coder', 'a1');+ await tool(mod, 'Edit', 'a1');+ await measure(mod, 0); // a rate-limit move, cost unchanged+ await tool(mod, 'Agent');+ await measure(mod, 2);+ await end(mod);+ expect(parseAttributionLine(mem(world).get(LEDGER)!.text.trim())!.byAgent).toEqual({ coder: 1, main: 1 });+ });++ it('a /clear writes the session and starts the next one from zero', async () => {+ const world = memoryWorld();+ const mod = await start(world);+ await tool(mod, 'Edit');+ await measure(mod, 2);+ await end(mod, 'clear');+ await measure(mod, 0.5); // the host counts the new session from zero+ await end(mod);+ const lines = mem(world).get(LEDGER)!.text.trim().split('\n').map((l) => parseAttributionLine(l)!);+ expect(lines.map((l) => l.totalUsd)).toEqual([2, 0.5]);+ expect(lines[1]!.byTool).toEqual({ '(model)': 0.5 });+ });++ it('writes nothing outside a ruflo project, with costLedger off, or for a session that cost nothing', async () => {+ const outside = memoryWorld();+ outside.dirs.delete('/work/.claude-flow');+ const a = await start(outside);+ await measure(a, 1);+ await end(a);+ expect(mem(outside).has(LEDGER)).toBe(false);++ const off = memoryWorld();+ const b = await start(off, { costLedger: false });+ await measure(b, 1);+ await end(b);+ expect(mem(off).has(LEDGER)).toBe(false);+ expect(b.events()).not.toContain('session.measure');++ const free = memoryWorld();+ const c = await start(free);+ await end(c);+ expect(mem(free).has(LEDGER)).toBe(false);+ });++ it('never overwrites a ledger it cannot read', async () => {+ const world = memoryWorld();+ put(world, LEDGER, 'x');+ world.failRead = (p) => (p === LEDGER ? new Error('EACCES: permission denied') : undefined);+ const mod = await start(world);+ await measure(mod, 1);+ await end(mod);+ expect(mem(world).get(LEDGER)!.text).toBe('x');+ });++ it('bounds names and keys', () => {+ const a = createAttribution();+ for (let i = 0; i < MAX_KEYS + 10; i++) {+ noteTool(a, `tool${i}`, undefined);+ noteCost(a, i + 1);+ }+ noteTool(a, 'rm -rf $(evil)', undefined);+ noteCost(a, 1000);+ expect(a.byTool.size).toBe(MAX_KEYS + 1);+ expect(a.byTool.has('other')).toBe(true);+ });+});++describe('ADR-508 gateway refusal', () => {+ it('toasts once and counts every refusal; only on a turn that ended on an API error', async () => {+ const world = memoryWorld();+ put(world, BUDGET, { version: 1, windows: [{ usd: 10, period: '24h' }] });+ const mod = await start(world);+ await measure(mod, 0.01);+ // Negative control: a model answer that talks about budgets is never read.+ await turnError(mod, 'Your budget has been exceeded, I think', 'answer');+ expect(world.toasts.filter((t) => t.includes('gateway refused'))).toEqual([]);+ const litellm = 'API Error: 400 {"error":{"message":"Authentication Error, ExceededTokenBudget: Current spend for token: 7.2e-05; Max Budget for Token: 2e-07","type":"budget_exceeded","param":null,"code":"400"}}';+ await turnError(mod, litellm);+ await turnError(mod, litellm);+ await turnError(mod, 'API Error: 529 overloaded');+ const refused = world.toasts.filter((t) => t.includes('gateway refused'));+ expect(refused).toHaveLength(1);+ expect(refused[0]).toContain('budget: the gateway refused the request (24h window spent)');+ await end(mod);+ expect(parseAttributionLine(mem(world).get(LEDGER)!.text.trim())!.refusals).toBe(2);+ });++ it('reads the synthetic API Error message when the turn carries no answer (Claude Code 2.1.289), and only that', async () => {+ const world = memoryWorld();+ const mod = await start(world);+ const error = 'API Error: 400 Authentication Error, ExceededTokenBudget: Current spend for token: 10.2; Max Budget for Token: 10.0';+ // Negative control: the model's own last words are not an API error message, so they are never read.+ world.messages = [{ role: 'user', text: 'hi', toolUses: [] }, { role: 'assistant', text: 'ExceededTokenBudget is what LiteLLM says', toolUses: [] }];+ await turnError(mod, '');+ expect(world.toasts.filter((t) => t.includes('gateway refused'))).toEqual([]);+ world.messages = [{ role: 'user', text: 'hi', toolUses: [] }, { role: 'assistant', text: error, toolUses: [] }];+ await turnError(mod, '');+ expect(world.toasts.filter((t) => t.includes('gateway refused'))).toEqual(['β budget: the gateway refused the request (budget spent)']);+ await end(mod, 'other');+ expect(parseAttributionLine(mem(world).get(LEDGER)!.text.trim())).toMatchObject({ totalUsd: 0, refusals: 1 });+ });++ it('recognises LiteLLM refusals and nothing else', () => {+ for (const yes of ['"type":"budget_exceeded"', 'ExceededTokenBudget: Current spend', 'Budget has been exceeded! Current cost: 10.2', 'Max budget exceeded for key']) expect(isBudgetRefusal(yes), yes).toBe(true);+ for (const no of ['', 'API Error: 429 rate_limit_error', 'overloaded_error', 'budget_tokens must be less than max_tokens', undefined, 42]) expect(isBudgetRefusal(no), String(no)).toBe(false);+ });+});diff --git a/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts b/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.tsindex a2c6beae2f..707b5c802b 100644--- a/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts+++ b/v3/@claude-flow/cli/__tests__/mods/mods-learn-cost.test.ts@@ -127,10 +127,12 @@ describe('ADR-404 budget ladder', () => {expect((await spawn()).deny).toContain('halted');});- it('hooks nothing when no budget is set', () => {- const mod = loadMod(register, memoryWorld(), {});+ it('hooks nothing when no budget is set and the cost ledger is off', () => {+ // costLedger (ADR-508, default on) hooks session.measure and agent.spawn for the budget file and attribution.+ expect(loadMod(register, memoryWorld(), {}).events()).toEqual(expect.arrayContaining(['session.measure', 'agent.spawn']));+ const mod = loadMod(register, memoryWorld(), { costLedger: false });expect(mod.events()).not.toContain('session.measure');expect(mod.events()).not.toContain('agent.spawn');- expect(loadMod(register, memoryWorld(), { costBudgetUsd: 5 }).events()).not.toContain('agent.spawn');+ expect(loadMod(register, memoryWorld(), { costBudgetUsd: 5, costLedger: false }).events()).not.toContain('agent.spawn');});});diff --git a/v3/@claude-flow/cli/src/commands/cost.ts b/v3/@claude-flow/cli/src/commands/cost.tsnew file mode 100644index 0000000000..96003e1b08--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/cost.ts@@ -0,0 +1,202 @@+/**+ * `ruflo cost` β the budget file and gateway export (ADR-508).+ *+ * ruflo cost budget set --daily 10 --monthly 100 [--hard-stop] [--fallback-model haiku]+ * ruflo cost budget get+ * ruflo cost budget export --gateway litellm [--format json] [--model <gateway model>] (YAML unless the global --format is json)+ * ruflo cost budget export --gateway litellm --apply --url https://proxy --key-env LITELLM_MASTER_KEY+ * ruflo cost report [--days 30] [--json]+ *+ * Attribution stays in the ruflo-mods cost ledger; enforcement across+ * sessions and machines belongs to the gateway. The budget file holds no+ * credential, and the gateway's master key is only ever read from the+ * environment variable `--key-env` names.+ */++import type { Command, CommandContext, CommandResult } from '../types.js';+import { output } from '../output.js';+import { BUDGET_PATH, budgetFromFlags, ladderWindow, readBudget, writeBudget, type BudgetFile } from '../cost/budget-file.js';+import { applyToLiteLLM, formatBody, gatewayRefusal, keyFromEnv, keyGenerateUrl, maskKey, toLiteLLMKeyBody } from '../cost/litellm.js';+import { ATTRIBUTION_PATH, readAttribution } from '../cost/attribution.js';++/** A flag by its camelCase name (the parser's) or its kebab-case spelling. */+function flag(ctx: CommandContext, name: string): unknown {+ const camel = name.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());+ return ctx.flags[camel] ?? ctx.flags[name];+}++const describe = (b: BudgetFile) =>+ `${b.windows.map((w) => `$${w.usd} per ${w.period}`).join(', ')}; hard stop ${b.hardStop ? 'on' : 'off'}${b.fallbackModel ? `; fallback ${b.fallbackModel}` : ''}`;++function loadOrFail(cwd: string): { budget?: BudgetFile; result?: CommandResult } {+ const read = readBudget(cwd);+ if (read.kind === 'ok') return { budget: read.budget };+ const message = read.kind === 'absent' ? `no budget file at ${BUDGET_PATH}; write one with: ruflo cost budget set --daily 10 --monthly 100` : read.reason;+ output.printError(message);+ return { result: { success: false, message, exitCode: 1 } };+}++const setSub: Command = {+ name: 'set',+ description: 'Write .claude-flow/cost/budget.json (read by the ruflo-mods cost ladder and by export)',+ options: [+ { name: 'daily', description: 'USD per 24h window', type: 'string' },+ { name: 'weekly', description: 'USD per 7d window', type: 'string' },+ { name: 'monthly', description: 'USD per 30d window', type: 'string' },+ { name: 'hard-stop', description: 'At 100% of the smallest window, the mod refuses new subagents', type: 'boolean', default: false },+ { name: 'fallback-model', description: 'Model a gateway falls back to when a per-model budget runs out', type: 'string' },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const { budget, error } = budgetFromFlags({+ daily: flag(ctx, 'daily'), weekly: flag(ctx, 'weekly'), monthly: flag(ctx, 'monthly'),+ hardStop: flag(ctx, 'hard-stop'), fallbackModel: flag(ctx, 'fallback-model'),+ });+ if (!budget) {+ output.printError(error ?? 'invalid budget');+ return { success: false, message: error, exitCode: 2 };+ }+ const file = writeBudget(ctx.cwd, budget);+ output.printSuccess(`Budget written to ${file}: ${describe(budget)}`);+ output.writeln(`The ruflo-mods ladder uses the $${ladderWindow(budget).usd} ${ladderWindow(budget).period} window per session when costBudgetUsd is 0.`);+ output.writeln('Enforce it across sessions at a gateway: ruflo cost budget export --gateway litellm');+ return { success: true, data: budget };+ },+};++const getSub: Command = {+ name: 'get',+ description: 'Show the budget file',+ options: [{ name: 'json', description: 'Print JSON', type: 'boolean', default: false }],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const { budget, result } = loadOrFail(ctx.cwd);+ if (!budget) return result!;+ if (flag(ctx, 'json')) output.printJson(budget);+ else output.writeln(`${BUDGET_PATH}: ${describe(budget)}`);+ return { success: true, data: budget };+ },+};++const exportSub: Command = {+ name: 'export',+ description: 'Print the budget as gateway key settings (LiteLLM), or --apply it to a proxy',+ options: [+ { name: 'gateway', description: 'Gateway: litellm (meta-llm has no documented budget API yet)', type: 'string', required: true },+ { name: 'model', description: 'Gateway model name for model_max_budget / budget_fallbacks', type: 'string' },+ { name: 'apply', description: 'POST the budget fields to <url>/key/generate', type: 'boolean', default: false },+ { name: 'url', description: 'Proxy base URL (https, or http to a loopback host only)', type: 'string' },+ { name: 'key-env', description: 'Name of the environment variable holding the proxy master key', type: 'string' },+ { name: 'print-key', description: 'Print the generated virtual key in full (masked by default)', type: 'boolean', default: false },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const refusal = gatewayRefusal(flag(ctx, 'gateway'));+ if (refusal) {+ output.printError(refusal);+ return { success: false, message: refusal, exitCode: 2 };+ }+ const { budget, result } = loadOrFail(ctx.cwd);+ if (!budget) return result!;+ const model = flag(ctx, 'model');+ let body;+ try {+ body = toLiteLLMKeyBody(budget, model === undefined ? undefined : String(model));+ } catch (error) {+ const message = String((error as Error).message);+ output.printError(message);+ return { success: false, message, exitCode: 2 };+ }++ if (!flag(ctx, 'apply')) {+ // The global --format (text|json|table): json prints the /key/generate body, anything else the YAML key settings.+ const format = flag(ctx, 'format') === 'json' ? 'json' : 'yaml';+ output.write(formatBody(body, format));+ if (model === undefined && budget.fallbackModel) {+ output.writeErrorln(`note: pass --model <gateway model> to add model_max_budget and budget_fallbacks (-> ${budget.fallbackModel})`);+ }+ return { success: true, data: body };+ }++ // --apply: every check before anything is sent.+ const target = keyGenerateUrl(flag(ctx, 'url'));+ if (!target.url) {+ output.printError(target.error!);+ return { success: false, message: target.error, exitCode: 2 };+ }+ const master = keyFromEnv(flag(ctx, 'key-env'));+ if (!master.key) {+ output.printError(master.error!);+ return { success: false, message: master.error, exitCode: 2 };+ }+ const applied = await applyToLiteLLM(target.url, master.key, body);+ if (!applied.ok) {+ const message = `LiteLLM refused /key/generate (${applied.status || 'no response'}): ${applied.error ?? ''}`;+ output.printError(message);+ return { success: false, message, exitCode: 1 };+ }+ output.printSuccess(`Budget applied at ${target.url.origin}: a virtual key with ${body.budget_limits.length} budget window(s).`);+ if (applied.generatedKey) {+ output.writeln(`Virtual key: ${flag(ctx, 'print-key') ? applied.generatedKey : maskKey(applied.generatedKey)}`);+ if (!flag(ctx, 'print-key')) output.writeln('(masked; it is shown once by LiteLLM; use --print-key to see it, or look it up in the LiteLLM UI)');+ }+ return { success: true, data: { status: applied.status } };+ },+};++const budgetCommand: Command = {+ name: 'budget',+ description: 'The shared budget file and its export to a gateway (ADR-508)',+ subcommands: [setSub, getSub, exportSub],+ action: getSub.action,+};++const reportSub: Command = {+ name: 'report',+ description: 'Which subagent types and tools spent the money (from the ruflo-mods cost ledger)',+ options: [+ { name: 'days', description: 'Only sessions that ended in the last N days (0: all)', type: 'string', default: '0' },+ { name: 'json', description: 'Print JSON', type: 'boolean', default: false },+ ],+ action: async (ctx: CommandContext): Promise<CommandResult> => {+ const days = Number(flag(ctx, 'days') ?? 0);+ const since = Number.isFinite(days) && days > 0 ? Date.now() - days * 86_400_000 : 0;+ const { report, error } = readAttribution(ctx.cwd, since);+ if (!report) {+ output.printError(error ?? 'cannot read the attribution file');+ return { success: false, message: error, exitCode: 1 };+ }+ if (flag(ctx, 'json')) {+ output.printJson(report);+ return { success: true, data: report };+ }+ if (report.sessions === 0) {+ output.writeln(`No attributed sessions in ${ATTRIBUTION_PATH}. The ruflo-mods costLedger option (default on) writes one line per session.`);+ return { success: true, data: report };+ }+ const pct = (v: number) => (report.totalUsd > 0 ? `${((v / report.totalUsd) * 100).toFixed(1)}%` : '-');+ output.writeln(`${report.sessions} session(s), $${report.totalUsd.toFixed(4)} attributed${report.refusals ? `, ${report.refusals} gateway budget refusal(s)` : ''}${report.skipped ? ` (${report.skipped} unreadable line(s) skipped)` : ''}`);+ output.writeln('Estimate: each turn\'s cost is split evenly across the tool calls made in it (a turn without tool calls goes to main / (model)).');+ for (const [title, rows] of [['By agent', report.byAgent], ['By tool', report.byTool]] as const) {+ output.writeln('');+ output.writeln(output.bold(title));+ output.printTable({+ columns: [{ key: 'name', header: 'Name', width: 28 }, { key: 'usd', header: 'USD', width: 12, align: 'right' }, { key: 'share', header: 'Share', width: 8, align: 'right' }],+ data: rows.slice(0, 20).map(([name, usd]) => ({ name, usd: usd.toFixed(4), share: pct(usd) })),+ });+ }+ return { success: true, data: report };+ },+};++export const costCommand: Command = {+ name: 'cost',+ description: 'Cost budgets, gateway budget export and per-agent/tool attribution (ADR-508)',+ subcommands: [budgetCommand, reportSub],+ examples: [+ { command: 'ruflo cost budget set --daily 10 --monthly 100', description: 'Write the shared budget file' },+ { command: 'ruflo cost budget export --gateway litellm', description: 'Print LiteLLM key budget settings (YAML)' },+ { command: 'ruflo cost budget export --gateway litellm --apply --url https://proxy.example --key-env LITELLM_MASTER_KEY', description: 'Create a budgeted LiteLLM virtual key' },+ { command: 'ruflo cost report', description: 'Spend by subagent type and by tool' },+ ],+ action: reportSub.action,+};++export default costCommand;diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.tsindex c6847d4e74..06f9ff5c26 100644--- a/v3/@claude-flow/cli/src/commands/index.ts+++ b/v3/@claude-flow/cli/src/commands/index.ts@@ -101,6 +101,8 @@ const commandLoaders: Record<string, CommandLoader> = {advisor: () => import('./advisor.js'),// Ruflo verbs in Claude Code's spinnerVerbs rotation (ADR-318)spinner: () => import('./spinner.js'),+ // Budget file, gateway budget export and per-agent/tool cost attribution (ADR-508)+ cost: () => import('./cost.js'),// ruflo as a Claude Code mod: function hooks, early access (ADR-404)mods: () => import('./mods.js'),// ADR-489: the console in a terminal of its own (read-only Overview and Cost); loads a bundle from this CLI's own install.diff --git a/v3/@claude-flow/cli/src/cost/attribution.ts b/v3/@claude-flow/cli/src/cost/attribution.tsnew file mode 100644index 0000000000..627446553e--- /dev/null+++ b/v3/@claude-flow/cli/src/cost/attribution.ts@@ -0,0 +1,109 @@+/**+ * `ruflo cost report` (ADR-508 Β§2.3): which subagent types and tools spent the+ * money, from the lines the ruflo-mods cost ledger writes to+ * `.claude-flow/cost/attribution.jsonl` (one per session; see+ * plugins/ruflo-mods/hooks/cost/attribution.ts `attributionLine`).+ *+ * The file is project-writable, so every line is validated to a fixed shape;+ * a bad line is skipped and counted, never trusted.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++export const ATTRIBUTION_PATH = '.claude-flow/cost/attribution.jsonl';+const MAX_FILE_BYTES = 4 * 1024 * 1024;+const MAX_KEYS = 64;+const NAME = /^[A-Za-z0-9_.:@/()-]{1,80}$/;+const MAX_SESSION_USD = 1_000_000;++export interface AttributionLine {+ endedAt: number;+ totalUsd: number;+ byAgent: Record<string, number>;+ byTool: Record<string, number>;+ refusals: number;+}++function amounts(value: unknown): Record<string, number> | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ const entries = Object.entries(value as Record<string, unknown>);+ if (entries.length > MAX_KEYS + 1) return undefined;+ const out: Record<string, number> = {};+ for (const [k, v] of entries) {+ if (!NAME.test(k) || typeof v !== 'number' || !Number.isFinite(v) || v < 0 || v > MAX_SESSION_USD) return undefined;+ out[k] = v;+ }+ return out;+}++/** One line validated, or undefined. */+export function parseAttributionLine(text: string): AttributionLine | undefined {+ let o: Record<string, unknown>;+ try {+ o = JSON.parse(text) as Record<string, unknown>;+ } catch {+ return undefined;+ }+ if (!o || typeof o !== 'object' || o.v !== 1) return undefined;+ const { endedAt, totalUsd, refusals } = o;+ if (typeof endedAt !== 'number' || !Number.isFinite(endedAt)) return undefined;+ if (typeof totalUsd !== 'number' || !Number.isFinite(totalUsd) || totalUsd < 0 || totalUsd > MAX_SESSION_USD) return undefined;+ if (typeof refusals !== 'number' || !Number.isInteger(refusals) || refusals < 0) return undefined;+ const byAgent = amounts(o.byAgent);+ const byTool = amounts(o.byTool);+ if (!byAgent || !byTool) return undefined;+ return { endedAt, totalUsd, byAgent, byTool, refusals };+}++export interface AttributionReport {+ sessions: number;+ skipped: number;+ totalUsd: number;+ refusals: number;+ byAgent: [string, number][];+ byTool: [string, number][];+}++const add = (map: Map<string, number>, record: Record<string, number>) => {+ for (const [k, v] of Object.entries(record)) map.set(k, (map.get(k) ?? 0) + v);+};+const ranked = (map: Map<string, number>): [string, number][] => [...map].sort((a, b) => b[1] - a[1]);++/** The report over the file's lines, optionally only sessions that ended at or after `since` (ms). */+export function summarize(text: string, since = 0): AttributionReport {+ const byAgent = new Map<string, number>();+ const byTool = new Map<string, number>();+ let sessions = 0;+ let skipped = 0;+ let totalUsd = 0;+ let refusals = 0;+ for (const raw of text.split('\n')) {+ if (!raw.trim()) continue;+ const line = parseAttributionLine(raw);+ if (!line) {+ skipped++;+ continue;+ }+ if (line.endedAt < since) continue;+ sessions++;+ totalUsd += line.totalUsd;+ refusals += line.refusals;+ add(byAgent, line.byAgent);+ add(byTool, line.byTool);+ }+ return { sessions, skipped, totalUsd, refusals, byAgent: ranked(byAgent), byTool: ranked(byTool) };+}++/** Reads the project's attribution file; an absent file is an empty report. */+export function readAttribution(cwd: string, since = 0): { report?: AttributionReport; error?: string } {+ const file = path.join(cwd, ATTRIBUTION_PATH);+ try {+ const stat = fs.statSync(file);+ if (stat.size > MAX_FILE_BYTES) return { error: `${ATTRIBUTION_PATH} is over 4 MiB` };+ return { report: summarize(fs.readFileSync(file, 'utf8'), since) };+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return { report: summarize('', since) };+ return { error: String((error as Error)?.message ?? error) };+ }+}diff --git a/v3/@claude-flow/cli/src/cost/budget-file.ts b/v3/@claude-flow/cli/src/cost/budget-file.tsnew file mode 100644index 0000000000..19a002bb2e--- /dev/null+++ b/v3/@claude-flow/cli/src/cost/budget-file.ts@@ -0,0 +1,126 @@+/**+ * The shared budget file (ADR-508 Β§2.1): `.claude-flow/cost/budget.json`,+ * version 1. `ruflo cost budget set` writes it; the ruflo-mods cost ladder and+ * `ruflo cost budget export` read it.+ *+ * Second copy of plugins/ruflo-mods/hooks/cost/file.ts (the mod may not import+ * outside its plugin folder). __tests__/cost-budget-file.test.ts runs both over+ * the same hostile corpus and requires identical answers.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';++export const BUDGET_PATH = '.claude-flow/cost/budget.json';+export const MAX_WINDOWS = 8;+export const MAX_USD = 1_000_000;+/** The largest budget file read (a budget is a few hundred bytes). */+export const MAX_FILE_BYTES = 64 * 1024;+/** LiteLLM's `budget_duration` grammar (`30s`, `30m`, `30h`, `30d`), with a bounded count. */+export const PERIOD = /^[1-9][0-9]{0,3}[smhd]$/;+const MODEL = /^[A-Za-z0-9._:/@-]{1,128}$/;++export interface BudgetWindow { readonly usd: number; readonly period: string }++export interface BudgetFile {+ readonly version: 1;+ readonly windows: readonly BudgetWindow[];+ readonly hardStop: boolean;+ readonly fallbackModel?: string;+}++const SECONDS: Record<string, number> = { s: 1, m: 60, h: 3600, d: 86400 };+export const periodSeconds = (period: string): number => Number(period.slice(0, -1)) * SECONDS[period.slice(-1)]!;++/** A budget value validated, or undefined when it breaks any rule (see the mod copy for the list). */+export function validateBudget(value: unknown): BudgetFile | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;+ const o = value as Record<string, unknown>;+ if (o.version !== 1) return undefined;+ if (!Array.isArray(o.windows) || o.windows.length === 0 || o.windows.length > MAX_WINDOWS) return undefined;+ const windows: BudgetWindow[] = [];+ const seen = new Set<string>();+ for (const w of o.windows as unknown[]) {+ if (!w || typeof w !== 'object' || Array.isArray(w)) return undefined;+ const { usd, period } = w as Record<string, unknown>;+ if (typeof usd !== 'number' || !Number.isFinite(usd) || usd <= 0 || usd > MAX_USD) return undefined;+ if (typeof period !== 'string' || !PERIOD.test(period) || seen.has(period)) return undefined;+ seen.add(period);+ windows.push({ usd, period });+ }+ if (o.hardStop !== undefined && typeof o.hardStop !== 'boolean') return undefined;+ if (o.fallbackModel !== undefined && (typeof o.fallbackModel !== 'string' || !MODEL.test(o.fallbackModel))) return undefined;+ return {+ version: 1,+ windows,+ hardStop: o.hardStop === true,+ ...(typeof o.fallbackModel === 'string' ? { fallbackModel: o.fallbackModel } : {}),+ };+}++/** The smallest-`usd` window (ties: the shorter period): the one a single session nears first. */+export function ladderWindow(budget: BudgetFile): BudgetWindow {+ return [...budget.windows].sort((a, b) => a.usd - b.usd || periodSeconds(a.period) - periodSeconds(b.period))[0]!;+}++export type ReadBudget =+ | { kind: 'absent' }+ | { kind: 'ok'; budget: BudgetFile }+ | { kind: 'invalid'; reason: string };++/** Reads and validates the project's budget file. Never throws. */+export function readBudget(cwd: string): ReadBudget {+ const file = path.join(cwd, BUDGET_PATH);+ let text: string;+ try {+ const stat = fs.statSync(file);+ if (!stat.isFile()) return { kind: 'invalid', reason: `${BUDGET_PATH} is not a file` };+ if (stat.size > MAX_FILE_BYTES) return { kind: 'invalid', reason: `${BUDGET_PATH} is over ${MAX_FILE_BYTES} bytes` };+ text = fs.readFileSync(file, 'utf8');+ } catch (error) {+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT' ? { kind: 'absent' } : { kind: 'invalid', reason: String((error as Error)?.message ?? error) };+ }+ let value: unknown;+ try {+ value = JSON.parse(text);+ } catch {+ return { kind: 'invalid', reason: `${BUDGET_PATH} is not JSON` };+ }+ const budget = validateBudget(value);+ return budget ? { kind: 'ok', budget } : { kind: 'invalid', reason: `${BUDGET_PATH} fails validation (version 1, 1-${MAX_WINDOWS} windows, usd in (0, ${MAX_USD}], period like 24h/7d/30d)` };+}++export interface BudgetFlags {+ daily?: unknown;+ weekly?: unknown;+ monthly?: unknown;+ hardStop?: unknown;+ fallbackModel?: unknown;+}++/** A budget from `set` flags (`--daily` 24h, `--weekly` 7d, `--monthly` 30d), or the reason it is not one. */+export function budgetFromFlags(flags: BudgetFlags): { budget?: BudgetFile; error?: string } {+ const windows: { usd: number; period: string }[] = [];+ for (const [flag, period] of [['daily', '24h'], ['weekly', '7d'], ['monthly', '30d']] as const) {+ const raw = flags[flag];+ if (raw === undefined || raw === false) continue;+ const usd = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN;+ if (!Number.isFinite(usd) || usd <= 0 || usd > MAX_USD) return { error: `--${flag} must be a USD amount in (0, ${MAX_USD}]` };+ windows.push({ usd, period });+ }+ if (windows.length === 0) return { error: 'give at least one of --daily, --weekly, --monthly' };+ const value: Record<string, unknown> = { version: 1, windows, hardStop: flags.hardStop === true || flags.hardStop === 'true' };+ if (flags.fallbackModel !== undefined && flags.fallbackModel !== false) value.fallbackModel = String(flags.fallbackModel);+ const budget = validateBudget(value);+ return budget ? { budget } : { error: '--fallback-model must be a plain model name (letters, digits, . _ : / @ -; at most 128)' };+}++/** Writes the budget file atomically (temp file, rename). Holds no credential. */+export function writeBudget(cwd: string, budget: BudgetFile): string {+ const file = path.join(cwd, BUDGET_PATH);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.tmp-${process.pid}`;+ fs.writeFileSync(tmp, `${JSON.stringify(budget, null, 2)}\n`, 'utf8');+ fs.renameSync(tmp, file);+ return file;+}diff --git a/v3/@claude-flow/cli/src/cost/litellm.ts b/v3/@claude-flow/cli/src/cost/litellm.tsnew file mode 100644index 0000000000..8d9182a4c8--- /dev/null+++ b/v3/@claude-flow/cli/src/cost/litellm.ts@@ -0,0 +1,138 @@+/**+ * Budget export to a gateway (ADR-508 Β§2.2).+ *+ * LiteLLM virtual-key budget fields, as docs.litellm.ai documents them+ * (checked 2026-10-29: /docs/proxy/users and /docs/proxy/budget_fallbacks):+ * budget_limits [{ budget_duration: "24h", max_budget: 10 }, ...] stacked windows+ * model_max_budget { "<model>": { budget_limit: 0.01, time_period: "1d" } }+ * budget_fallbacks { "<model>": ["<fallback>", ...] } LiteLLM >= v1.92.0+ * Durations use LiteLLM's grammar: "30s", "30m", "30h", "30d".+ *+ * meta-llm documents no budget API, so it is refused with a pointer to+ * ADR-508 rather than guessed at.+ */++import { stringify as stringifyYaml } from 'yaml';++import { ladderWindow, type BudgetFile } from './budget-file.js';++export const ADR_POINTER = 'v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md';+export const GATEWAYS = ['litellm', 'meta-llm'] as const;+const MODEL = /^[A-Za-z0-9._:/@-]{1,128}$/;+const ENV_NAME = /^[A-Z_][A-Z0-9_]{0,127}$/;++export interface LiteLLMKeyBody {+ budget_limits: { budget_duration: string; max_budget: number }[];+ model_max_budget?: Record<string, { budget_limit: number; time_period: string }>;+ budget_fallbacks?: Record<string, string[]>;+}++/** Why a gateway cannot be exported to, or undefined when it can. */+export function gatewayRefusal(gateway: unknown): string | undefined {+ if (gateway === 'litellm') return undefined;+ if (gateway === 'meta-llm') {+ return `--gateway meta-llm: meta-llm documents no budget API yet, so ruflo does not guess an endpoint. Its allowance tiers stay as they are; see ${ADR_POINTER} Β§2.2.`;+ }+ return `--gateway must be one of: litellm (meta-llm is reserved until it documents a budget API; see ${ADR_POINTER})`;+}++/**+ * The LiteLLM `/key/generate` budget fields for a budget. Every window becomes+ * one `budget_limits` entry. `model_max_budget` (the ladder's window, on the+ * named model) and `budget_fallbacks` (model β [fallbackModel]) are added only+ * when `model` is given: the file names no primary model, and ruflo never+ * invents a gateway model name.+ */+export function toLiteLLMKeyBody(budget: BudgetFile, model?: string): LiteLLMKeyBody {+ const body: LiteLLMKeyBody = {+ budget_limits: budget.windows.map((w) => ({ budget_duration: w.period, max_budget: w.usd })),+ };+ if (model !== undefined) {+ if (!MODEL.test(model)) throw new Error('--model must be a plain model name (letters, digits, . _ : / @ -; at most 128)');+ const w = ladderWindow(budget);+ body.model_max_budget = { [model]: { budget_limit: w.usd, time_period: w.period } };+ if (budget.fallbackModel) body.budget_fallbacks = { [model]: [budget.fallbackModel] };+ }+ return body;+}++/** The body as YAML (LiteLLM key settings) or as the `/key/generate` JSON body. */+export function formatBody(body: LiteLLMKeyBody, format: 'yaml' | 'json'): string {+ return format === 'json' ? `${JSON.stringify(body, null, 2)}\n` : stringifyYaml(body);+}++const LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);++/**+ * The `/key/generate` URL for a proxy URL, or the reason it is refused:+ * HTTPS only, except a loopback host (`localhost`, `127.0.0.1`, `[::1]`);+ * no credentials in the URL; no query or fragment; no path starting with `//`.+ * The result always keeps the given scheme and host.+ */+export function keyGenerateUrl(proxy: unknown): { url?: URL; error?: string } {+ if (typeof proxy !== 'string' || proxy.trim() === '') return { error: '--apply needs --url <proxy base URL>' };+ let u: URL;+ try {+ u = new URL(proxy);+ } catch {+ return { error: `--url is not a URL: ${proxy.slice(0, 200)}` };+ }+ if (u.username || u.password) return { error: '--url must not carry credentials; the key comes from --key-env' };+ if (u.search || u.hash) return { error: '--url must be the proxy base URL, without a query or fragment' };+ const loopback = LOOPBACK.has(u.hostname);+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) {+ return { error: `--apply refuses ${u.protocol}//${u.hostname}: use https, or plain http only to a loopback host (localhost, 127.0.0.1, [::1])` };+ }+ // A path starting with "//" ("/\" normalises to it) would read as a protocol-relative+ // URL if resolved as a string, and move the request, bearer key included, to another host.+ if (u.pathname.startsWith('//')) return { error: '--url path must not start with "//" or "/\\"' };+ // The path is set on a copy, never resolved from a string, so it cannot change the+ // scheme or host; the check below holds that anyway.+ const out = new URL(u.href);+ out.pathname = `${u.pathname.endsWith('/') ? u.pathname : `${u.pathname}/`}key/generate`;+ if (out.protocol !== u.protocol || out.host !== u.host) return { error: `--url would send the key to another host (${out.host}); refused` };+ return { url: out };+}++/** The master key from the environment variable `--key-env` names (never from argv), or why there is none. */+export function keyFromEnv(name: unknown, env: NodeJS.ProcessEnv = process.env): { key?: string; error?: string } {+ if (typeof name !== 'string' || !ENV_NAME.test(name)) return { error: '--apply needs --key-env <ENV_VAR_NAME> (upper-case letters, digits, _); the key itself is never taken from the command line' };+ const key = env[name];+ if (!key) return { error: `environment variable ${name} is not set or empty` };+ return { key };+}++/** A key shown masked: its first 4 characters and its length. */+export const maskKey = (key: string) => (key.length <= 8 ? '********' : `${key.slice(0, 4)}β¦(${key.length} chars)`);++export interface ApplyResult { ok: boolean; status: number; generatedKey?: string; error?: string }++/**+ * POSTs the budget fields to the proxy's `/key/generate`. Only the budget+ * fields are sent; redirects are refused (one could leave HTTPS or loopback);+ * 15 s timeout.+ */+export async function applyToLiteLLM(url: URL, masterKey: string, body: LiteLLMKeyBody, fetchImpl: typeof fetch = fetch): Promise<ApplyResult> {+ let res: Response;+ try {+ res = await fetchImpl(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${masterKey}` },+ body: JSON.stringify(body),+ redirect: 'error',+ signal: AbortSignal.timeout(15_000),+ });+ } catch (error) {+ return { ok: false, status: 0, error: String((error as Error)?.message ?? error).slice(0, 300) };+ }+ const text = (await res.text().catch(() => '')).slice(0, 64 * 1024);+ if (!res.ok) return { ok: false, status: res.status, error: text.replace(/\s+/g, ' ').slice(0, 300) };+ let generatedKey: string | undefined;+ try {+ const parsed = JSON.parse(text) as { key?: unknown };+ if (typeof parsed.key === 'string') generatedKey = parsed.key;+ } catch {+ // a 2xx without a JSON body still applied+ }+ return { ok: true, status: res.status, generatedKey };+}diff --git a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.tsindex 29c24b16a8..2f400e50d6 100644--- a/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/capability-brain.ts@@ -123,7 +123,7 @@ export const RUFLO_CLI_COMMANDS = ['doctor', 'verify', 'analyze', 'route', 'progress', 'issues', 'update','ruvector', 'benchmark', 'guidance', 'appliance', 'appliance-advanced','transfer-store', 'cleanup', 'autopilot', 'gaia-bench', 'metaharness',- 'eject', 'funnel', 'settings', 'auth', 'proxy', 'advisor', 'spinner',+ 'eject', 'funnel', 'settings', 'auth', 'proxy', 'advisor', 'spinner', 'cost','announcements', 'tui', 'harness',] as const;diff --git a/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md b/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.mdindex 0a601be90c..d056507615 100644--- a/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md+++ b/v3/docs/adr/ADR-508-cost-ladder-gateway-budgets.md@@ -1,6 +1,6 @@# ADR 508: the cost ladder feeds gateway budgets-Status: Proposed (2026-10-29)+Status: Accepted (implemented in PR #4592, 2026-10-29)Issue: #4581 follow-up 2. Builds on: ADR-404 (the mod's cost ladder), the ruflo-cost-tracker plugin, the meta-llm gateway.@@ -56,5 +56,38 @@ When a model call fails with a budget error, ruflo-mods toasts once: `budget: th- budget file validation, including hostile files: negative values, unknown periods, oversized arrays;- the ladder reads the file;- the LiteLLM export output matches LiteLLM's documented schema field by field;- - `--apply` refuses plain HTTP to a non-loopback host.+ - `--apply` refuses plain HTTP to a non-loopback host, and a URL path that would move the request to another host.- Attribution is tested in the mods harness with scripted `session.measure` and `agent.spawn` events.++## 5. Implementation notes++What shipped, and where it differs from the sketch above.++- **Option.** One new ruflo-mods option, `costLedger` (default on), covers the mod side: the budget-file fallback, attribution and the refusal toast. It does nothing outside a ruflo project (no `.claude-flow/`). With it off and `costBudgetUsd` at 0 the mod hooks no cost events, as before.+- **Budget file.** `period` follows LiteLLM's `budget_duration` grammar (`^[1-9][0-9]{0,3}[smhd]$`), so `24h`, `7d` and `30d` pass and `1mo`, `week` or `-1d` do not. A file is rejected whole if it has more than 8 windows, a `usd` outside (0, 1 000 000], a repeated period, a non-boolean `hardStop`, or a `fallbackModel` outside a plain model-name charset. A rejected file means no budget, never a zero budget. Unknown fields are dropped. The validator lives twice, in `plugins/ruflo-mods/hooks/cost/file.ts` (the mod may not import outside its folder) and in `v3/@claude-flow/cli/src/cost/budget-file.ts`. `__tests__/cost-budget-gateway.test.ts` runs both over the same hostile corpus and requires identical answers.+- **Ladder.** When `costBudgetUsd` is 0, the ladder uses the window with the smallest `usd` and names it in the toast, for example `(24h window)`. The mod sees only one session's spend, so that window is always the one nearest its limit; the longer windows are the gateway's job. The file's `hardStop` acts as `costHardStop`. As before, `session.measure` reports after each turn, so the hard stop applies from the turn after the one that crossed 100%. A single long `-p` turn is not stopped part way through.+- **Attribution.** It is written to `.claude-flow/cost/attribution.jsonl` (one line per session, newest 500 kept), not to the cost-tracker's memory namespace. The mod may not spawn the CLI, and `_ledger.mjs` is a read-only aggregator of provider logs. The new `ruflo cost report` reads this file. A subagent's tool calls are charged to the type its `agent.spawn` gave; an id it never saw is charged to `subagent`. Names are limited to 64 per session, and the rest are charged to `other`.+- **Attribution granularity (differs from Β§2.3).** Claude Code measures cost after each main-thread turn (and on rate-limit moves), not per tool call (`session.measure`, 2.1.289 types). A foreground subagent runs inside the main loop's Agent tool call, so its tool calls all complete before that turn's single measurement, and the main Agent call completes last. Charging "the tool that ran just before" each delta, as first shipped, therefore put a foreground subagent's spend on `main` / `Agent`. Instead, each measured delta is split across every tool call completed since the previous measurement, one equal share per call. A subagent's calls are charged to its type, and the main loop's Agent/Task call that wrapped it counts as one `main` share. A delta with no tool calls in it (a plain answer) goes to `main` and `(model)`. A measurement with no cost change (a rate-limit move) keeps the pending calls for the next delta. This is an estimate by call count, not a per-request price. Exact per-request cost would need `turn.step` (which carries `usage` and `agentId`) plus a price table. `turn.step` is a request-rewriting event, so hooking it would widen the mod's trust surface (`hooks/trust.ts`) and smoke step 5's event list. That is left out. `ruflo cost report` prints the estimate rule above its tables. The harness test `host order: a foreground subagent runs inside the main Agent call β¦` drives events in the host's order: main tool, spawn, subagent tools, main Agent call, then one measurement. It fails on the last-tool rule.+- **`--apply` URL (review fix).** The first version built the target as `new URL(`${path}key/generate`, origin)`. A base path starting with `//` (or `/\`, which WHATWG normalises to `//`) then reads as a protocol-relative URL, and its first segment becomes the host. `http://localhost//evil.example/` went to `http://evil.example/key/generate` with the master key. Now a path starting with `//` is refused. The path is set on a copy of the parsed URL, and the result must keep the given scheme and host.+- **Refusal detection (Β§2.4).** `turn.complete` carries no API error kind, and `turn.step` has no error field either. Live on Claude Code 2.1.289, a turn that dies on a LiteLLM budget error has `reason: 'error'` and `answer: ''`. The error text is the transcript's last message: a synthetic assistant message, `API Error: 400 β¦ ExceededTokenBudget β¦`. So, only for a main-loop turn whose reason is `error`, the mod reads that one message through `$.session.messages()`, and only when it starts with `API Error`. It matches LiteLLM's `budget_exceeded`, `ExceededTokenBudget` and "budget has been exceeded" wording. A model's own answer is never read. No new event was needed; smoke step 5 is unchanged.+- **Export.** `budget_limits` gets one `{ budget_duration, max_budget }` per window. `model_max_budget` (`{ budget_limit, time_period }` from the ladder window) and `budget_fallbacks` (`{ model: [fallbackModel] }`) are emitted only with `--model <gateway model>`. The budget file names no primary model, and ruflo does not invent a gateway model name. Field names were checked against docs.litellm.ai (`/docs/proxy/users`, `/docs/proxy/budget_fallbacks`; `budget_fallbacks` needs LiteLLM v1.92.0 or later). The format option is the CLI's global `--format`: `json` prints the `/key/generate` body, anything else prints YAML. A command-local `--format yaml` collided with the global choices (`text|json|table`), which the live run caught.+- **`--apply`.** It POSTs to `<url>/key/generate`. The rules are:+ - HTTPS only, or plain HTTP to `localhost`, `127.0.0.1` or `[::1]`;+ - no credentials, query or fragment in the URL;+ - `redirect: 'error'`, so a redirect cannot leave HTTPS or loopback;+ - a 15 s timeout;+ - only the budget fields go in the body;+ - the master key comes only from the variable `--key-env` names (an upper-case variable name; a pasted key is refused).++ The generated virtual key is printed masked unless `--print-key` is given. The `userConfig` sensitive-option source (ADR-506) is not wired yet.+- **meta-llm.** `--gateway meta-llm` exits 2 with a pointer to this ADR and sends nothing.+- **Open: the budget file is project-writable.** The model can edit or delete `.claude-flow/cost/budget.json` mid-session, for example with the Edit tool. Doing so lowers the ladder and lifts the file's `hardStop`. `costBudgetUsd` and `costHardStop`, which live in user settings, cannot be changed this way. No ruflo-mods guard protects `.claude-flow/` control files today. Whether to add a tighten-only `tool.check` deny for writes to this file is left to the integration owner.+- **Default on.** `costLedger` defaults to `true`, by analogy with `learningLoop` (ADR-502). The cost is one `stat` per `session.measure`, one append per session, and the transcript read on error turns. Default-on versus opt-in is left to the integration owner.+- **Command home.** There was no `ruflo cost` CLI command; the cost-tracker plugin's `/ruflo-cost` is a prompt command over scripts. `cost` is a new top-level CLI command (`v3/@claude-flow/cli/src/commands/cost.ts`, listed in `RUFLO_CLI_COMMANDS`). `plugins/ruflo-cost-tracker/commands/ruflo-cost.md` points to it.++### Live validation (Claude Code 2.1.289, `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1`, `--plugin-dir plugins/ruflo-mods`)++1. **Fake LiteLLM on loopback, no model spend.** Every request got LiteLLM's documented `budget_exceeded` 400. `claude -p` printed `API Error: 400 Authentication Error, ExceededTokenBudget: β¦`. The mod wrote `{"totalUsd":0,β¦,"refusals":1,"budget":{"usd":10,"period":"24h"}}`.+2. **One haiku run** (under the first, last-tool attribution rule, since replaced; see "Attribution granularity"). The model ran Bash, then spawned a `general-purpose` subagent. The mod wrote `{"totalUsd":0.196703,"byAgent":{"main":0.159246,"general-purpose":0.037457},"byTool":{"Bash":0.141942,"Agent":0.054761},β¦}`. `ruflo cost report` showed the same split.+3. **The CLI against the fake gateway.** `cost budget set --daily 10 --monthly 100 --fallback-model haiku` wrote the file. `export --gateway litellm --model claude-opus-4-5` printed `budget_limits`, `model_max_budget` and `budget_fallbacks`. `--apply --url http://127.0.0.1:47508 --key-env β¦` posted only `budget_limits`, with a bearer header. `--apply --url http://example.com:4000` was refused before any request. `--gateway meta-llm` exited 2.+4. **One haiku run after the review fix (per-call split).** Same setup. The model ran `ls` with Bash, then spawned a `general-purpose` subagent that used Read and Bash. The mod wrote `{"totalUsd":0.264993,"byAgent":{"main":0.166775,"general-purpose":0.098219},"byTool":{"(model)":0.149061,"Bash":0.057966,"Read":0.049109,"Agent":0.008857},β¦}`. The subagent's Read and Bash calls now carry its spend, and the wrapping `Agent` call carries only one share. The `(model)` row shows that this run had a cost measurement with no tool call completed before it. In practice a measurement can fall inside a turn, so the split is per measurement window.