* fix(ruflo-console): Plugin Catalog reads a Windows marketplace clone (0.47.1)
Claude Code records the ruflo marketplace clone's installLocation as a drive
path (C:\Users\...\marketplaces\ruflo). readCatalog refused any location not
starting with "/", so the catalog showed "the clone's marketplace.json is not
readable" with the file in place.
- readCatalog uses isAbsolutePath / hasParentSegment from paths.ts.
- The catalog's plugin folders, manifests, skill/agent/command reads and the
snapshot's marketplace.json read (freshness row) build paths with joinPath
instead of a hardcoded "/".
- tests/windows-drive-path-sites.spec.ts: a Windows clone lists its plugins,
reads a skill file, and still refuses a relative or climbing location. The
new tests fail without the fix.
- Version 0.47.0 -> 0.47.1 in plugin.json, hooks/version.ts, scripts/smoke.sh
and CHANGELOG.md.
The other ruflo-console specs fail the same 12 tests with and without this
change on this machine (mission-cost, menu-entry, tui-ai-page, write-argv).
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): forget-history actions and TUI colour work on Windows
- Events "forget history" and Workflows "forget saved views" ran `rm -f`, which
Windows does not have (write-flavor.ts: no delete on host-fs). On host-fs they
now empty the file(s) through the host file API (new emptyFiles in
write-via.ts; forgetSpec carries a `write` op like event-export does). The
saved-views file is rewritten as a valid empty document, and the forget is
verified by what the file holds. Linux/macOS keep the rm argv.
- depthOf returned "none" whenever TERM was unset. Windows Terminal, PowerShell
and cmd leave TERM unset (COLORTERM=truecolor, OS=Windows_NT), so the
standalone TUI drew without colour. On Windows only an explicit TERM=dumb or
NO_COLOR turns colour off.
Tests: both forget actions in host-fs flavor (files emptied, no rm run, refusal
reported, missing file left alone), forgetSpec verification, depthOf on Windows.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): ADR status edits on CRLF records, and codex detection, on Windows
- withStatus / withSupersedes compared whole lines ("---") and checked
startsWith("---\n"), so a MADR record checked out with CRLF (git autocrlf is on
by default on Windows) failed with "the front matter is not closed", and other
formats got mixed line endings. Records with CRLF are now edited as LF text and
written back with CRLF.
- The Conversation board looked for codex with `which`, which Windows lacks, so
codex was never offered there. A Windows home (drive path or share) uses
`where`.
Tests: CRLF records for all three ADR formats (same edit as LF, CRLF kept, MADR
front matter found, supersede link), and the finder per platform. The ADR tests
fail without the fix.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): keep the Windows fixes under the size rule, skip POSIX-only specs on Windows (0.47.2)
- Move the forget-history spec out of events-ui.ts into events-forget.ts: the
Windows branch had taken events-ui.ts to 521 lines (smoke step 11 caps files at
500). Move the codex-finder test out of wf-control-views.spec.ts (514 lines)
into wf-convo-finder.spec.ts.
- wf-replay-views: the Forget button asks one tick later now that it awaits the
write flavor; the spec waits for it.
- write-argv.spec.ts: the real-disk POSIX script specs check Unix mode bits and
FIFOs, which NTFS has not; Windows writes through the host file API. Skipped
there. tui-ai-page.spec.ts: the --plain spec needs a runnable fake codex (a
shebang script), which Windows cannot run; it asserts the codex line exists.
- Version 0.47.1 -> 0.47.2 in plugin.json, hooks/version.ts, scripts/smoke.sh and
CHANGELOG.md (the entry lists every Windows fix of this branch).
Verified: the specs of the changed areas pass; the remaining failures in a full
run are menu-entry (a circular import, not Windows-specific, fails on the
baseline), the *.test.ts kit files (need claude-code/testing), and two
timing-sensitive specs that pass alone.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-cost-tracker): the ledger scripts run on Windows (0.28.3)
ledger.mjs, advise.mjs and local-cost.mjs ran only when
import.meta.url === `file://${process.argv[1]}`. On Windows that is
file:///C:/... against C:\..., never equal, so every call exited 0 with no
output and the plugin's own test-ledger.mjs failed 7 tests. They compare against
pathToFileURL(process.argv[1]).href now.
Two more breaks sat behind it for the ruflo console's mission spend:
- ledger.mjs --project required a leading "/", so a Windows project exited 2.
- inProject matched with "/" and exact case; transcripts record C:\Users\x\proj.
A drive-lettered path now compares with either separator and any letter case;
POSIX matching is unchanged (exact, directory boundary).
Tests: test-ledger.mjs gains Windows rows and cases (drive path in both
separator styles and letter cases, relative or climbing drive paths still exit 2,
POSIX rule stays exact). Version 0.28.2 -> 0.28.3 in plugin.json, smoke.sh and
CHANGELOG.md. smoke.sh still fails 5 steps on a Windows Git Bash for a reason
that predates this (it hands /c/... paths to a Windows node), unchanged here.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the autopilot's text checks know Windows paths, commands and shells
Groundwork for the Windows-aware path checks that ap-windows-gate.spec.ts names as
the follow-up (an autopilot start is still refused on Windows). Each rule only
parks or refuses more; none allows anything that was refused before.
- classifyTask read only POSIX paths from a task's text, so a task naming
C:\Windows\..., \\srv\share\..., ..\..\x, ~\x, %USERPROFILE%\x or
$env:USERPROFILE\x was not checked against the envelope folders. It is now.
- delete-outside-worktree knew the POSIX recursive-delete forms but not the
Windows ones: rmdir /s, del on a drive, the drive-format command,
Remove-Item -Recurse, or a recursive rm on a drive or a variable.
- verifyProblem took the program name by splitting on "/" only, so
C:\Windows\System32\cmd.exe, bash.exe or powershell passed the banned-program
check. It uses either separator, drops .exe/.cmd/.bat/.ps1, and a second set
bans the Windows shells, script hosts and destructive or system tools.
Tests (ap-windows-guard.spec.ts): path extraction and the envelope check, the deny
forms and ordinary text that must not match, verify programs allowed and refused.
Four of them fail without the change; the POSIX behaviour is asserted unchanged.
CHANGELOG: added to the unreleased 0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): the Overview heading shortens a Windows project path
"ruflo state in <last two folders>" split the cwd on "/" only, so a Windows cwd
(C:\Users\x\proj) printed whole. tailOf in paths.ts splits on either separator;
the overview uses it. Test in paths.spec.ts. CHANGELOG: added to the unreleased
0.47.2 entry.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(ruflo-console): transcript search, model keys and peer sends on Windows; smoke under Git Bash
The last Windows gaps of the sweep, each tested.
- Stopping or messaging a workflow run reads the run's task id from the session
transcript; over 2 MB that was `grep -o`, which Windows lacks. Windows now runs
PowerShell's Select-String (windowsSearchArgv in data/wf-control.ts). The path
and the pattern ride inside the script as base64, so a path with a space, a
quote, $, & or ; is only data and the script holds no double quote. Tested
against a real PowerShell on a 5 MB-class file through such a path.
- taskIdOf returned the FIRST launch when a search printed two launches of one
run (a resume), because the pattern's `[^}]` ran across both matches (nothing
prints a closing brace between them). It takes the last task id in the match.
This also affected `grep -o` on Linux and macOS.
- A model key for an HTTP endpoint was read with `printenv`, which Windows lacks.
Host gains an optional `env` (register.ts: $.env.get, already used for other
names) and SendDeps an optional `readEnv`, set only for a Windows home; elsewhere
`printenv` is unchanged.
- A send to a federation peer runs `bash <helper>`. On a Windows PATH `bash` is
the WSL launcher (System32\bash.exe), which cannot open a C:\ script path, so
the send failed obscurely. On a Windows home it now refuses, running nothing,
and says why.
- ruflo-cost-tracker scripts/smoke.sh builds ROOT with `pwd -W` under Git Bash:
a Windows node could not open /c/... paths, which failed 5 steps (now 66/0).
Checked and left alone: the npx launcher. The installed Claude Code (a native
binary with the host code inside it) runs $.process.run through a bundled execa
on cross-spawn, which finds `npx` as npx.cmd through PATHEXT and runs it via
cmd.exe /d /s /c with its own argument escaping, so ['npx', ...] works on
Windows. The same lookup is why `bash` there is the first bash.exe on the PATH
(the WSL launcher on this machine), which the peer refusal above relies on.
CHANGELOG: both plugins' unreleased entries (0.47.2, 0.28.3) list these.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): what running every view on a real Windows machine turned up
The previous commits came from pattern scans. This one comes from running the
console's own readers against a real Windows machine (every view through the
standalone terminal; the plugin catalog, ADR loader and workflow reader called
directly), plus a complete triage of the path-handling patterns in hooks/.
Found by the real run:
- The standalone terminal left state.configDir null when CLAUDE_CONFIG_DIR was
unset (the usual case), so the installed plugins, the marketplaces and the
workflow runs were all "unreadable". It now falls back to <home>/.claude, as
register.ts does in the engine. Not Windows-specific.
- research.ts kept its own POSIX-only safeInstallPath, so ruflo-goals was never
found on Windows. It uses the Windows-aware one in cost-ledger.ts (same
character set on POSIX); on this machine goalsOf now answers ready with the
real C:\ root.
Found by triaging every `split('/')`, `lastIndexOf('/')` and `startsWith('/')`:
- isRunPath, isRunFile and isUnder checked for ".." only between slashes, so a
segment written with a backslash passed on Windows; a config folder ending in
a backslash did not match. They use hasParentSegment / trimTrailing, as does
under().
- The menu and the boot screen named the project by splitting cwd on "/", which
printed a whole C:\ path. baseOf in paths.ts.
Test-suite and cycle fixes so the smoke's own command passes here:
- views/pane built BODIES = { menu: menuView, ... } at load time, but
views/menu reaches pane through mission-control > mission-claude > model-tools,
so loading menu first left menuView undefined under the test runner (native
ESM hoists the function; the app loads pane first). It is read at call time.
- tui-actions waited a fixed 1.2 s for a 1 s retry plus a redraw, and failed
under CPU contention in a full run (also on the baseline). It waits for the
outcome it asserts, up to 10 s.
Verified: the smoke's exact command (every spec, 30 s timeout) is 239 files
passed, 0 failed, 3486 tests; the console smoke is 20 passed, 0 failed; all 34
views render with exit 0 and no stderr; an ADR project with a space in its path
and CRLF records loads and plans a status change keeping its CRLF.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the install record of a plugin that applies to this project, compared the Windows way
installed_plugins.json holds one record per install of a plugin, and a project-scope
record names the project it was made for. The snapshot took entries[0], so a plugin
installed for several projects showed another project's version and install folder.
On a real Windows machine ruflo-console@ruflo has five records (four project, one
user) and the first is a different project's 0.44.7; everything derived from it,
the version shown and the installPath used to find a plugin's scripts, could point
at the wrong copy.
- parseInstalled(text, cwd) picks the project or local record whose projectPath is
the session folder or holds it, else the user record, else the first.
- insideOrSame in paths.ts is that comparison, Windows-aware (case, either
separator, a folder inside the project); hooks/updates.ts decides which installs
to update with it too. It compared with === and startsWith(path + "/"), so on
Windows a session in a subfolder of the project, or with a different drive-letter
case, did not count the project's own install and left it stale.
tui-actions: "a read runs at once" waited a fixed 500 ms for a stand-in CLI process
to start; it waits for the run it asserts, and its neighbour, which failed only
because that run landed late in the shared log, no longer does.
Tests (windows-path-guards.spec.ts): the record chosen for the project under both
separators, other letter case, a subfolder, a sibling sharing the prefix, no match,
no user record, no cwd; the updater's rule; insideOrSame. Verified: the smoke's
exact command (every spec, 30 s timeout) is 239 files passed, 0 failed, 3491 tests.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the focus-lost spec waits for the output to go quiet before it asserts silence
"stops drawing while the terminal reports focus lost" marked the output length 60 ms
after the focus-lost report and then expected no growth. A frame already in flight
when focus was lost lands after that mark on a busy machine, which reads as the page
still drawing; the smoke's first vitest pass failed on it and only the retry passed.
It now waits until the output stops changing before it marks, still asserts 500 ms of
silence after that, and waits for the redraw on focus regained instead of a fixed
300 ms. Passes 4 of 4 isolated runs.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the hostile-regex spec bounds the scan's CPU time, not the wall clock
"a slow pattern over ten thousand 200-character events stops at its budget" asserted
that the scan finished in under 2500 ms of wall-clock time. The scan is CPU-bound, and
the wall clock also counts every other worker of a parallel run, so the spec passed
alone (all 12 specs of the file in 316 ms) and failed in full runs, including both
tries of the smoke's step 14 on the previous HEAD. It now bounds the scan's CPU time
(process.cpuUsage) at the same 2500 ms and keeps a 30 s wall-clock bound as a guard
against a hang. The product code is untouched.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): the host-boundary spec does not scan the mutation specs' temporary files
tui-boundary.spec.ts reads every .ts under hooks/ when it loads. adr-mutation and
mission-advisor-mutation make temporary .mut-N-*.ts copies of hooks modules inside
hooks/ and delete them, in other workers of the same run. Two ways that disturbs this
spec: a copy that is still there is checked as if it were a hooks module (shown with a
throwaway .mut- file that imports a Node module: the spec failed before this change,
passes after), and a copy listed and then deleted can throw at load, which fails the
whole file (the smoke's step 14 showed one such file-level failure that did not repeat;
six runs of the three specs together did not reproduce it, so that part is the likely
cause, not a demonstrated one).
The walk skips .mut- names and tolerates a file that vanishes. A real violation in
hooks/ is still caught (checked with a throwaway file).
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* fix(ruflo-console): the mod loads again: $.env.get takes a literal name
An earlier commit on this branch (f54772424) gave the host an `env` read that was
`async name => $.env.get(name)`. The engine lists the variables a module reads, so
`claude plugin validate` refuses a computed name:
$.env.get takes a literal name as its first argument ...
and when it refuses register.ts the mod does not load at all: no /ruflo command, no
pane. Vitest never runs the engine's validator, so no test caught it; it showed up
when the branch was installed into a real Claude Code.
- register.ts reads only the one key it can name literally,
$.env.get('OPENROUTER_API_KEY'); any other name answers undefined.
- wf-send says, for a custom endpoint key on Windows, that it cannot be read here and
that only $OPENROUTER_API_KEY can, instead of claiming the variable is unset. The
OpenRouter key keeps the "is not set" wording.
- tui-boundary.spec.ts: no $.env.get/set in hooks/ may take a non-literal name (fails on
the old line, passes on the fix).
- smoke.sh step 21 runs `claude plugin validate` on the plugin when the CLI is present
(passes now; reports "Validation failed" against the old line).
- CHANGELOG corrected: it described the broken behaviour.
Verified with the real validator: before, "Found 1 error"; after, "Validation passed",
and the hook list shows command.run{command=ruflo}. The 9 "gating hook without .catch"
notes it prints are identical on upstream/main.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
* test(ruflo-console): specs remove their temp folder with a retry, so a still-exiting child does not fail the file on Windows
After the merge, tui-actions.spec.ts was reported as a failed FILE with all 8 of its
tests passing:
EBUSY: resource busy or locked, rmdir '...\tui-actions-XXXX\project'
On Windows a folder cannot be deleted while a process started in it is still running,
and these specs start the stand-in CLI and terminal sessions with the project folder as
their working directory. force: true does not cover EBUSY, and neither does maxRetries
on rmSync: measured on Node 22 with a child holding the folder for 1.2 s, rmSync fails
in 3 ms with or without maxRetries, while fs.promises.rm with maxRetries (and a manual
loop) removes it after about a second.
- tests/fixtures/rm-tree.ts: removeTree(), the async rm with up to ~5 s of retries.
- The ten specs that start processes or sessions in their temp folder (tui-actions,
tui-ai-host, tui-ai-page, tui-host, tui-nav, tui-pagebar, tui-parity, tui-pictures,
tui-session, wf-control-windows) use it in afterAll.
- tests/rm-tree.spec.ts: removes a tree and an already-gone one; on Windows, a real child
holding the folder makes rmSync fail with EBUSY and removeTree wait it out.
All eleven files pass.
Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_01C9t8G7o2vTPAxSFNb8rP4n
---------
Co-authored-by: RuFlo <ruv@ruv.net>
ruflo-cost-tracker
Token usage tracking, model cost attribution per agent, budget alerts, and optimization recommendations.
Overview
Tracks token usage per agent, task, and model, then computes USD cost attribution using current model pricing. Monitors configurable budgets with tiered alerts (info at 50%, warning at 75%, critical at 90%, hard stop at 100%). Analyzes usage patterns and recommends optimizations such as model downgrades, prompt caching, and batch operations.
Installation
claude --plugin-dir plugins/ruflo-cost-tracker
Agents
| Agent | Model | Role |
|---|---|---|
cost-analyst |
haiku | Token usage tracking, USD cost attribution, budget monitoring, optimization recommendations |
Skills
| Skill | Usage | Description |
|---|---|---|
cost-report |
/cost-report [--period today] |
Generate a cost report with token usage and USD costs by tier, model, and agent |
cost-optimize |
/cost-optimize |
Analyze usage patterns, recommend cost optimizations, and emit hooks_model-outcome events |
cost-track |
/cost-track |
Auto-capture per-session token usage from the Claude Code jsonl into cost-tracking namespace (producer side). Also auto-fires on session-end via the Stop hook in hooks/hooks.json — no manual invocation needed. |
cost-budget-check |
/cost-budget-check [--period today|week|month|all] |
Read totals + budget config, emit 50/75/90/100% alert ladder; exit 1 on HARD_STOP |
cost-booster-route |
/cost-booster-route <task> |
Route tasks via hooks_route and report Agent Booster (Tier 1) bypass utilization |
cost-booster-edit |
/cost-booster-edit <intent> <file> |
Apply a Tier 1 transform via agent-booster.apply() (sub-millisecond, $0, deterministic) |
cost-benchmark |
/cost-benchmark [--llm] [--anthropic] |
Run the corpus benchmark and persist measured-vs-claimed table to docs/benchmarks/runs/ |
cost-trend |
/cost-trend |
Read all bench runs and surface drift (win rate, latency, speedup) — flags regressions the smoke gate misses |
cost-projection |
/cost-projection [--window 7d] |
Forward spend extrapolation: USD/day rate × 7d/30d/90d/365d horizons + days-until-budget-exhausted (predictive counterpart to cost-budget-check) |
cost-counterfactual |
/cost-counterfactual [--since 7d] [--baseline all] |
Comparative cost analysis: actual spend vs always-haiku / always-sonnet / always-opus baselines. Negative savings flag over-escalation; positive savings quantify routing's win. |
cost-burn |
/cost-burn [--bucket 1d] [--lookback 14d] [--alert-on-acceleration-pct N] |
Trend burn-rate analysis: window-over-window delta + optional drift-alert exit code. Catches "hot loop burning 10× normal" before budget alarm fires. |
cost-anomaly |
/cost-anomaly [--since 7d] [--threshold 3.5] [--alert-on-outliers N] |
Point-anomaly MAD-based outlier detection: flags individual sessions with |modified z| > threshold (Iglewicz-Hoaglin 3.5 default). Robust to outliers themselves; works on n=10. |
cost-diff |
/cost-diff --baseline <path> --current <path> [--alert-on-pct N] [--alert-on-usd N] |
PR regression detection — diffs two cost-summary JSON snapshots. Per-tier + per-model breakdowns sorted by |delta|. Optional pct/USD alert thresholds for CI gating. |
cost-session |
/cost-session [--session-id <id>] [--top 20] [--since <iso-ts>] |
Drill-down — per-message cost breakdown within ONE session. Surfaces top-N expensive messages with cache_write column so $16 messages stop looking like 569-token outputs. Pair with cost-anomaly. |
cost-health |
/cost-health [--alert-acceleration 100] [--alert-outliers 1] [--skip burn,anomaly] |
Composite CI gate — runs budget+burn+anomaly+projection in parallel, returns max(exit). One shell-out covers all four alert ladders. |
cost-ledger |
/cost-ledger [--since 7d] [--provider claude|codex|grok|all] |
Multi-provider spend, tokens and cache hit ratio from the local Claude Code, Codex and Grok logs; unpriced models flagged, USD and credits never mixed. |
cost-advise |
/cost-advise [--since 7d] |
Optimisation findings from your own logs (cache discipline, 1h cache TTL, sub-agent tier, Codex reasoning share, context bloat) with what-if savings. |
cost-openrouter |
/cost-openrouter key|generation <id>|credits |
OpenRouter's own billed cost, key limits and credits. Network + key: asks first (--yes), key only from the environment. |
cost-local |
/cost-local --tok-per-s <n> [--busy 0.25] [--compare <model>] |
Cost per 1M tokens on your own hardware (fixed + marginal) and the utilisation at which it beats a hosted model. |
cost-conversation |
/cost-conversation |
Per-conversation cost view (different lens from cost-report's per-agent / per-model) |
cost-export |
/cost-export [--prometheus <path>] [--webhook <url>] |
Emit cost data as Prometheus textfile or POST to a webhook |
cost-federation |
/cost-federation |
ADR-097 Phase 3 consumer — per-peer 1h/24h/7d federation_spend rolling windows |
cost-summary |
/cost-summary [--format json|markdown] |
Single-shot programmatic dump of all cost data (stable JSON contract for inter-plugin consumption) |
cost-compact-context |
/cost-compact-context <query> |
Wrap getTokenOptimizer().getCompactContext() for retrieval-compacted analysis (graceful fallback when agentic-flow not installed) |
Grok prices are xAI list prices, not what a subscription bills; every Grok row is flagged approximate in the ledger output.
Commands (23 subcommands)
cost track # Auto-capture this session's token usage (producer)
cost report [--period today|week|month] # Cost report (with By-tier block, reads measured booster data)
cost breakdown [--by agent|model|task] # Detailed breakdown by dimension
cost optimize # Analyze usage and suggest savings (+ auto-emits hooks_model-outcome via outcome.mjs)
cost outcome <task> <model> <outcome> # Emit hooks_model-outcome (success|escalated|failure) so the router learns
cost budget set <amount> # Set USD budget (real impl, persists to cost-tracking)
cost budget get # Show current budget config
cost budget check [--period ...] # Compute utilization + alert; exit 1 on HARD_STOP
cost benchmark [--llm] [--anthropic] # Run measured benchmark — booster + optional Gemini/Sonnet/Opus baselines
cost trend # Drift across bench runs (win rate, latency, regressions)
cost projection [--window 7d] # Forward USD/day extrapolation + days-until-budget-exhausted
cost counterfactual [--since 7d] # Multi-baseline (haiku/sonnet/opus) — is routing earning its keep?
cost burn [--bucket 1d] [--alert ...] # Burn-rate trend + acceleration alert (exit 1 on drift)
cost anomaly [--since 7d] [--alert ...] # MAD-based per-session outlier detection (exit 1 on outliers)
cost diff --baseline <p> --current <p> ... # Snapshot delta — PR-level regression detection (exit 1 on >N% growth)
cost session [--session-id <id>] [--top N] # Per-message drill-down within one session (cache_write column!)
cost health [--alert-acceleration N] ... # Composite CI gate: budget+burn+anomaly+projection in parallel (max exit)
cost conversation # Per-conversation cost view
cost summary [--format json|markdown] # Programmatic JSON contract for inter-plugin consumption
cost export [--prometheus] [--webhook] # External observability — Prometheus textfile + webhook POST
cost federation # ADR-097 Phase 3 federation_spend consumer
cost workers # Inspect optimize + benchmark loop-workers consumed
cost history # Show cost tracking over time
Optimization integration (ADR-0002)
Four upstream capabilities are now wired to the cost-tracker surface — every optimization recommendation maps to a real tool, not a heuristic:
| Capability | Where | Surfaced by |
|---|---|---|
| Agent Booster bypass (Tier 1, $0, WASM) | hooks_route emits [AGENT_BOOSTER_AVAILABLE] (CLI: npx @claude-flow/cli@latest hooks route --task ...) |
cost-booster-route skill |
| Token optimizer / compact context | getTokenOptimizer().getCompactContext() from @claude-flow/integration (uses agentic-flow when present) |
cost-compact-context skill |
| Model-outcome feedback loop | hooks_model-outcome (typed equivalent of legacy routing-outcomes) |
cost-optimize skill step 8 |
| Optimize + benchmark loop workers | hooks_worker-status --worker optimize / --worker benchmark (declared by ruflo-loop-workers) |
cost workers command + cost-analyst agent |
CLAUDE.md root percentage claims (-32% retrieval, -15% booster edits, 352x speedup, 95% cache hit) are claimed upstream, not yet verified in this repo. The skills above tag every figure with that disclaimer; only the structural $0 cost of Tier 1 bypasses is reported as a measured saving.
See ADR-0002 for the full rationale, including the riskiest assumption (no MCP wrapper for getTokenOptimizer — cost-compact-context shells a Node one-liner).
Model Pricing (per 1M tokens)
| Model | Input | Output | Cache Write (5m) | Cache Read |
|---|---|---|---|---|
| Haiku 4.5 | $1.00 | $5.00 | $1.25 | $0.10 |
| Sonnet 5.5 | $2.00 | $10.00 | $2.50 | $0.20 |
| Opus 5.5 | $4.00 | $20.00 | $5.00 | $0.20 |
Rates live in data/prices.json (dated, sourced; COST_PRICES points at your own copy). 1-hour cache writes, per-model cache-read rates, OpenAI/Codex models and unpriced-model flagging are handled by the multi-provider ledger (cost-ledger).
Budget Alert Thresholds
| Level | Threshold | Action |
|---|---|---|
| Info | 50% consumed | Log notification |
| Warning | 75% consumed | Display warning, suggest optimizations |
| Critical | 90% consumed | Urgent alert, recommend model downgrades |
| Hard Stop | 100% consumed | Halt non-essential agent spawns |
Optimization Strategies
| Strategy | Savings | Impact |
|---|---|---|
| Downgrade simple tasks to Haiku | 80-92% | Minimal for low-complexity work |
| Enable prompt caching | 90% on reads | None (same quality) |
| Batch similar operations | 15-25% | Slight latency increase |
| Use Agent Booster (Tier 1) | 100% | Only for simple transforms |
| Shorten system prompts | 10-20% | Requires careful pruning |
Federation budget circuit breaker pairing (ruflo 3.6.25+)
This plugin pairs naturally with the federation budget envelope shipped in ADR-097. The federation_send MCP tool now accepts caller-supplied caps that this plugin's tracking should respect:
| Field | Default | Effect |
|---|---|---|
maxHops |
8 |
Hard ceiling on recursive delegation across federated peers — defangs cost cascades from runaway sub-swarms. |
maxTokens |
unbounded | Σ tokens across the whole hop chain. Returns BUDGET_EXCEEDED (constant string, no oracle leak) on overshoot. |
maxUsd |
unbounded | Σ USD across hops. Same enforcement. |
hopCount |
0 |
Pass-through for re-forwarded messages. |
spent.{tokens,usd} |
0 |
Caller-reported usage from previous legs. Negatives clamped to 0. |
Phase 1 of ADR-097 enforces at the send side. Two follow-up phases will tighten the integration:
- Phase 2 (deferred) — peer state machine
ACTIVE/SUSPENDED/EVICTEDdriven by trailing 24h cost (default suspension threshold $5) + 1h failure ratio (>50% over ≥10 sends). Auto-recovery after 30 min cooldown. - Phase 3 (deferred) —
federation_spendevent bus. Eachfederation_sendcompletion publishes{peerId, taskId, tokensUsed, usdSpent, ts}. This plugin's cost-tracker should aggregate per-peer rolling windows (1h / 24h / 7d) and expose them via the existingcost-reportskill. Breaker queries the aggregate to evaluate suspension thresholds.
Until Phase 3 ships, federated spend is not counted in the host's cost-tracker — only local agent spend. Treat cost-report numbers as a lower bound when federation is in use.
Compatibility
- CLI: pinned to
@claude-flow/cliv3.6 major+minor. - Verification:
bash plugins/ruflo-cost-tracker/scripts/smoke.shis the contract.
Namespace coordination
This plugin owns two AgentDB namespaces:
cost-tracking— usage records (consumed bycost-report)cost-patterns— optimization recommendations (consumed bycost-optimize)
Both follow the kebab-case <plugin-stem>-<intent> convention from ruflo-agentdb ADR-0001 §"Namespace convention". Both are accessed via the memory_* tool family which routes by namespace.
Routing note: The
agentdb_hierarchical-*andagentdb_pattern-*tools route by tier / ReasoningBank, not by namespace string. Earlier versions ofcost-reportandcost-optimizepassed namespace arguments to those tools and got silently-ignored behavior. ADR-0001 fixes this by switching the load path tomemory_*and documenting the dual write path for optimization patterns.
Reserved namespaces (pattern, claude-memories, default) MUST NOT be shadowed.
Verification
bash plugins/ruflo-cost-tracker/scripts/smoke.sh
# Expected: "63 passed, 0 failed"
CI: see [`.github/workflows/cost-tracker-smoke.yml`](../../.github/workflows/cost-tracker-smoke.yml).
On every PR touching this plugin, GitHub Actions runs smoke + booster-only bench
+ regression gate (Tier 1 winRate ≥ 0.80). LLM/Anthropic baselines are NOT run in CI
— they cost real money per invocation and belong in a manual / scheduled workflow.
Architecture Decisions
Related Plugins
ruflo-agentdb— namespace convention owner; defines the routing rules ADR-0001 fixes a violation ofruflo-observability-- Token usage metrics collected via observability instrumentationruflo-neural-trader-- PnL tracking and cost-adjusted return calculationruflo-federation-- Budget circuit breaker on outbound federation_send (ADR-097)
License
MIT