/miranda:setting-up-usage-trackingfrom miranda
Use when installing the Miranda plugin into a repo ("set up token tracking", "enable usage tracking", "install miranda"), when a repo is missing .miranda/USING-MIRANDA.md or the miranda section in CLAUDE.md/AGENTS.md, or after a Miranda plugin update to refresh a stale doc — copies the canonical USING-MIRANDA.md agent doc into the repo, wires an evergreen Miranda section into the agent instruction files (with the user's permission), enrols this machine for usage collection, writes Miranda's identifying headers into the config of any coding agent routed through an AI gateway, and registers the current repository as a Miranda project if it isn't one. Idempotent; safe to re-run.
Ships in miranda. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Wire Miranda into the current repo so every coding agent that works here declares the GitHub issue it's working on and this machine's token usage gets collected. Two files carry that:
.miranda/USING-MIRANDA.md — the agent playbook, copied verbatim
from the USING-MIRANDA.md that sits next to this SKILL.md (the skill's
base directory). Committed to the repo.CLAUDE.md
and/or AGENTS.md) that points unconditionally at the doc. The section is
evergreen — it names no features, so it never changes across Miranda
releases; only the doc does.Then, once those are wired, enrol this machine so the collector daemon the
Miranda plugin installs actually starts reporting usage, and make sure this
repository is a Miranda project — the collector attributes a session to a
project only when the session's origin remote matches one of a project's repositories, so an
unregistered repository's spend all lands in Unassigned.
If a coding agent here sends its requests through an AI gateway (LiteLLM, Cloudflare AI Gateway, Bifrost, or an OTLP exporter), Miranda can also import its usage from the gateway. For that, each request has to say which machine and project it came from, so the skill writes those two values (the carrier) into that agent's own config (step 6).
Never modify the user's files without showing them exactly what will change and getting a yes first. Registering the repository writes no file, and is done without asking (step 7).
Tell the user this when you propose enrolling a machine (step 2). It is what they are consenting to.
Workflow events — off by default. Your organization admin can turn workflow collection on for the whole organization in Miranda's settings; until they do, the collector reports token usage exactly as described here and nothing more. When it is on, the collector also reports the structure of each session, not the conversation, for every session it already reads: sizes, names, and flags. Prompts, replies and tool output never leave your machine. Shell commands are sent with secrets and home-directory paths removed, and agent instruction files such as CLAUDE.md with secrets removed; the working directory is sent as a path. These are the event kinds:
session_start: branch, repository, entrypoint, and the working directory's pathsession_end: why it ended and how long it ranhuman_turn: prompt size and slash-command name, never the promptassistant_turn: model, effort, stop reason and size, never the replymodel_request: the token counts already reported todaytool_call: tool name, argument names, repo-relative file path, and a shell command with secrets and home-directory paths removed, plus the names of any wrappers a hook added to it before it ran (such as rtk); for a web tool, the host and URL path, never the query stringtool_result: error flag, size, exit code and test counts, never the outputproject_facts: manifest and instruction file names, sizes and hashes, each instruction file's contents, with secrets removed, and the MCP server names the repo's agent config files declareskill_invoked: skill name and whether it came from a plugin, the project, or the usersubagent_spawned: subagent type, model override and whether it ran in the background, never its promptplan_mode: entering or leaving plan mode, never the plancompaction: whether a context compaction was automatic or manual, and the context size before itvcs_event: commit, push, PR create or merge, or rebase, with PR and issue numbers only, never a branch, message or remotehook_fired: hook name, the first word of the hook's own command (such as rtk), and whether it blocked, never its arguments or outputmcp_tool_call: MCP server and tool name, never arguments or resultsmachine_facts: the MCP server names the session's agent has configured on the machine, and whether each is on, never their commands, URLs, headers or envInsert this text exactly, markers included. The markers are how re-runs find and replace the section instead of duplicating it.
<!-- miranda:start -->
## Miranda
This project uses [Miranda](https://miranda.co) to track coding-agent
token cost and attribute it to the GitHub issues the work was for.
Before starting work in this repo, read `.miranda/USING-MIRANDA.md`. It
explains the one thing required at the start of every session — declaring
the work item — plus the Miranda MCP tools available to you. Treat it as a
commitment the team has made, not a suggestion.
<!-- miranda:end -->
git rev-parse --show-toplevel; fall back to the
working directory if not a git repo).USING-MIRANDA.md in this skill's base
directory. If it is missing, stop and tell the user the plugin install
looks broken — do not synthesize the doc from memory..miranda/USING-MIRANDA.md — present?
CLAUDE.md, AGENTS.md — which exist, and does each already contain a
<!-- miranda:start --> ... <!-- miranda:end --> block?
Is this machine already enrolled? Look for the collector's
config.json, in both places, in this order:
$XDG_CONFIG_HOME/sandgarden/config.json, defaulting to
~/.config/sandgarden/config.json when XDG_CONFIG_HOME is unset;~/.gloria/config.json — the pre-rename location. A machine set up
before the rename still has its credential here; the collector
migrates it automatically on its next run, so this counts as
"already enabled" too.Either one present means usage tracking is already on for this machine (per-machine, not per-repo) and step 5 is a no-op — say so rather than re-minting a key.
Richer answer, when the collector binary is reachable:
daemon status additionally reports which service supervises the
collector and whether a daemon is running. The binary is not on
PATH — nothing puts it there. The plugin's download stub caches it
inside the state directory, so invoke it by path, or through the stub:
# the stub, which is what every hook uses (works even before the first
# download); <plugin> is the installed plugin's root directory
sh <plugin>/collector/stub.sh daemon status
# or the cached binary directly, if one is there already
ls ~/.config/sandgarden/bin/ # miranda-collector, or miranda-collector-<version>
~/.config/sandgarden/bin/miranda-collector daemon status
Substitute whichever path collectorHome() resolves to (SANDGARDEN_HOME
→ the deprecated GLORIA_HOME → $XDG_CONFIG_HOME/sandgarden →
~/.config/sandgarden). daemon status always exits 0, so "not
enrolled" is not an error. Treat this as extra detail for the report in
step 8, not as the enrolment test — the config.json check above is the
one that has to work on every machine.
Is any agent routed through an AI gateway? Read only; change nothing. Look for a base URL each agent is pointed at:
ANTHROPIC_BASE_URL in the shell environment, or in the
env block of ~/.claude/settings.json, .claude/settings.json or
.claude/settings.local.json.model_provider in $CODEX_HOME/config.toml
(default ~/.codex/config.toml), naming a custom
[model_providers.<id>] block with a base_url.options.baseURL in the repo's
opencode.json or in ~/.config/opencode/opencode.json.For each base URL found, ask the script which gateway it is:
node <skill-dir>/scripts/write-gateway-carriers.mjs gateway-for <base-url>
<skill-dir> is this skill's base directory. It prints
{ "gateway": … }: cloudflare-ai-gateway or openrouter when the host
says so, otherwise null, and then you ask (step 2). An agent with no
base URL talks to its provider directly and needs nothing here. Never
print an API key or token you see while reading these files.
Tell the user precisely what will happen, in one message, and ask a single yes/no. Cover only the actions actually needed, e.g.:
.miranda/USING-MIRANDA.md;CLAUDE.md and AGENTS.md (or "replace
the existing Miranda section in ...");AGENTS.md containing the section, when neither instruction file
exists;litellm), Cloudflare AI Gateway (cloudflare-ai-gateway),
Bifrost (bifrost), an OTLP exporter (otlp), or OpenRouter
(openrouter). Miranda imports from no other gateway yet, so for any other
answer say so and leave that agent alone.If everything is already current, say so and skip to step 7. Registering the repository is not part of this yes/no — step 7 does it without asking. If the user declines the file edits, stop — do not partially apply.
Copy the shipped USING-MIRANDA.md to .miranda/USING-MIRANDA.md
verbatim (create the .miranda/ directory if needed). Do not edit,
reformat, or "improve" the content — refreshes must stay a pure file copy.
For each of CLAUDE.md and AGENTS.md that exists at the repo root:
<!-- miranda:start --> through <!-- miranda:end --> (inclusive) with
the section above.If neither file exists, create AGENTS.md containing only the section
(AGENTS.md is the cross-agent standard; Claude Code reads it too).
Only when step 1 found this machine unenrolled.
Prefer browser enrolment. Both paths below hand the machine its credential without this session ever seeing a secret, which is why they come first:
config.json itself. Nothing for you to do but
tell the user it is waiting for them.setup verb (by path or through the stub, per step 1
— it is not on PATH). It prints a miranda.co URL with a short one-time
code, opens the browser, and writes the same config.json once the user
approves the machine while signed in. It also registers the daemon's service
if the machine has none.Fall back to minting through MCP — the steps below — for an agent that
cannot open a browser or drive an interactive terminal, and for a headless
machine. On a headless machine you can also hand the minted key straight to
the collector with setup --token <ingestToken>, which writes the same
config.json for you rather than you writing it by hand.
Check before offering one: daemon status (invoked as step 1 describes) is
how you find out what this build of the collector can do, and a collector
predating #1227 answers an unrecognised setup verb with usage and a non-zero
exit — go straight to the fallback if so. Whichever path runs, the result is
the same config.json — never do two of them.
Read this machine's id first. It is the collector's own enrolment id, and the command creates it, in the collector's format, if the machine has none yet:
node <skill-dir>/scripts/write-gateway-carriers.mjs machine-id
It prints { "machineId": …, "source": …, "file": … }. The id is not a
secret.
Call the miranda MCP tool enable_usage_tracking, passing that
machineId and always passing a machineLabel — never omit either.
machineId links this machine to you on the server, which is what lets
a gateway request carrying it count as yours even before the collector
reports anything. Clerk key names must be unique per org,
and omitting machineLabel falls back to a non-unique default name, so a
second machine (or a re-run after a partial failure) collides with an
already-minted key and the call fails with a Clerk 409 token_creation_conflict.
Generate a default that's unique per machine, e.g. the hostname plus a
short random or timestamp suffix (<hostname>-<4 random hex chars>), and
use that unless the user asks for a friendlier label — if they supply
one, keep it unique the same way (append a short suffix) rather than
passing their label bare. It mints a write-only, org-scoped Clerk API key
and returns { apiBaseUrl, ingestToken } plus write instructions.
Write $XDG_CONFIG_HOME/sandgarden/config.json — ~/.config/sandgarden/config.json
when XDG_CONFIG_HOME is unset — directly from the tool result, merging
with any existing keys in the file. The directory is per-machine, not
per-repo, and shared with the gloria plugin if that's also installed:
{
"ingestToken": "<ingestToken from the tool result>"
}
Leave the tool's apiBaseUrl out of the file: the collector defaults to
https://gloria.dev, the only production host. Write it only when it is
something else, i.e. a local or dev stack.
Never echo the ingestToken into the conversation, logs, or any other
file — write it straight to the config file. The secret is shown
exactly once; a compromised or lost key is revoked from the Clerk
organization settings, and re-running the tool mints a fresh one.
Work-item cost attribution needs no config beyond this: the collector
resolves which gloria/Miranda project a session belongs to itself, per
session, from that session's own git remote — never from a value in
this file, so one machine works correctly across as many
gloria-registered repos as the developer has checked out. The collector
needs no runtime install: the plugin's first hook fire downloads a
compiled, checksum-verified collector binary for this platform (~50 MB,
once per collector release) and caches it under bin/ in that same
directory.
Manual fallback (MCP not connected on this machine): any org member
can mint the key from a machine that does have the miranda MCP server
connected (the credential is per-machine, so mint one per machine), or an
org admin can create an API key with scope usage:ingest for the
organization in Clerk and supply it the same way. Have the user write the
file themselves — never ask them to paste the secret into the chat.
Verify the write landed — never assume it did. Read config.json
back and confirm it parses and carries both keys. A sandboxed agent
session can have this write refused: on Codex under Windows the sandbox is
process-wide and inherited, and the collector's state directory is outside
any workspace root. If the file is absent or unparseable, do not report
tracking as enabled. Tell the user what to add to
%USERPROFILE%\.codex\config.toml:
[sandbox_workspace_write]
writable_roots = ['C:\Users\<you>\.config\sandgarden']
substituting whichever path collectorHome() resolves to for them
(SANDGARDEN_HOME → GLORIA_HOME → %XDG_CONFIG_HOME%\sandgarden →
C:\Users\<you>\.config\sandgarden). You cannot apply this edit
yourself from a sandboxed session — ~/.codex is a protected control
directory, read-only to the agent even inside a writable root.
Then say plainly that the minted credential is gone: ingestToken is
shown exactly once, and it was never persisted. After they fix the config,
re-run enable_usage_tracking with a fresh, different machineLabel —
reusing the previous one collides with the already-minted key and fails
with a Clerk 409 token_creation_conflict.
Collection starts within a minute of that file appearing — the collector
daemon idles while it is missing and begins the moment it shows up, with no
restart. The daemon collects Claude Code, Codex and OpenCode usage from
this machine's local session stores whether or not any agent plugin fires, so
no further wiring is needed. See USING-MIRANDA.md's "Codex, OpenCode, and
Cursor" section for per-agent notes.
Only for the agents step 1 found routed through a gateway, and only after the user said yes in step 2. For each one, run:
node <skill-dir>/scripts/write-gateway-carriers.mjs write --agent <claude-code|codex|opencode> --gateway <gateway> --repo <repo-root>
Add --provider <id> for Codex or OpenCode when step 1 found the provider
id and the script would otherwise have to guess.
The script uses this machine's id (creating it as the machine-id command
does) and the repository's origin URL, normalized, and writes the carrier
the gateway records:
| Gateway | What the agent will send |
|---|---|
litellm | Headers Miranda-Machine and Miranda-Project |
cloudflare-ai-gateway | One cf-aig-metadata header: miranda_machine, miranda_project, miranda_agent |
bifrost | Headers x-bf-lh-miranda-machine and x-bf-lh-miranda-project |
otlp | OTEL_RESOURCE_ATTRIBUTES: miranda.machine.id, miranda.project, miranda.agent |
openrouter | Nothing: OpenRouter has no carrier |
into one place per agent, merged with any headers the agent already sends:
env.ANTHROPIC_CUSTOM_HEADERS in the repo's
.claude/settings.local.json (per user, per project, not committed).
Never the committed .claude/settings.json. Tell the user it needs Claude
Code v2.1.227 or later (claude --version), and takes effect once they
trust the folder. For otlp the script writes OTEL_RESOURCE_ATTRIBUTES
in the same env block.http_headers on the active custom [model_providers.<id>]
block in $CODEX_HOME/config.toml. Codex reads providers only from that
user-level file, so tell the user the project value now applies to every
repository they run Codex in, until the skill is re-run in another one.options.headers on the gateway provider in the repo's
opencode.json. OpenCode merges it with the provider defined globally.
If git ls-files --error-unmatch opencode.json succeeds the file is
committed: tell the user the change holds their personal machine id and
should stay out of the commit.On success it prints { "status": "written" | "unchanged", "file": … }.
A re-run with the same values is unchanged. A run naming a different
gateway replaces the old carrier rather than adding a second one.
Exit code 2 is a refusal, and nothing was written. Relay its stderr to the
user as it is: it says what to fix. The refusals are OpenRouter (it has no
carrier, so recommend running the collector for that agent), a Codex
built-in provider (openai, ollama, lmstudio can't carry headers), a
cf-aig-metadata that would pass Cloudflare's five-entry limit, otlp for
Codex or OpenCode (their config has no place for it, so the user sets
OTEL_RESOURCE_ATTRIBUTES in the exporter's environment), and a config file
the script can't safely rewrite. Exit code 1 means you passed bad arguments.
The script only adds Miranda's values. It never sets ANTHROPIC_BASE_URL,
a base_url or baseURL, or any credential: pointing the agent at the
gateway is the user's job. The work item still comes from
tag_session_work_item, as USING-MIRANDA.md says.
Run this after step 6, whichever enrolment path ran — and also when steps 2–6
had nothing to do. Do it without asking: the developer is setting up
tracking for exactly this repository, and registering it is the only way its
spend stops landing in Unassigned. Use the miranda MCP tools only.
Read the remote. At the repo root (git rev-parse --show-toplevel),
run:
git remote get-url origin | sed -E 's#://[^/@]*@#://#'
The sed drops any userinfo (user:token@) before the URL is printed: an
https remote can carry a credential, and it must never reach the
transcript, a tool argument or the report. Use origin and nothing else —
it is the only remote the collector reads. If this isn't a git repository,
or the command prints nothing on stdout (no origin remote — git's
error: No such remote goes to stderr), skip the rest of step 7 and say
why in the report (e.g. "this repository has no origin remote, so there
is no URL a project could match").
Normalize it the way the server does, so the comparison means what ingest means:
git@host:owner/repo.git → https://host/owner/repo;ssh://, git:// and git+ssh:// URLs → https:// on the same host
(port included) and path; http:// and https:// keep their scheme;.git (and any / after it),
then any trailing /.Change nothing else — not even letter case.
Look for a match. A project owns a set of repositories. Call
list_projects, normalize every URL in each project's repoUrls (the
project's repositories, its primary first) the same way (older rows can
carry a trailing / or .git), and compare exactly, case-sensitive —
ingest matches the same way, so a case-only difference is not a match.
Compare against all of them, not just the primary repoUrl: a repository
attached to a project is that project's as much as its primary is. If a
project matches, name the existing project — its name and slug (all of
them, if more than one matches) — say spend from this repository is
already attributed to it, and register nothing. Never overwrite an existing
description, even a blank or weak one: a person may have written it, and
they can edit it on the project's page.
Register when nothing matches. Call register_project with
{ "project": { "slug": …, "name": …, "description": …, "repoUrls": [<normalized URL>] } }:
name — the repository name: the last path segment of the normalized
URL (https://github.com/sandgardenhq/gloria.dev → gloria.dev);slug — that name lowercased, every run of characters outside a-z0-9
replaced by -, leading and trailing - trimmed (gloria-dev);description — one or two plain sentences, at most about 300
characters, saying what this project is and what it does, written from
what you can read at the repo root: the README first, then the manifest's
own description (package.json, pyproject.toml, Cargo.toml, go.mod
and the like), the agent instruction file, and the top-level layout. Be
specific: say who or what it serves and the main things it does, e.g.
"Next.js dashboard and Cloudflare Workers API that monitors a team's
third-party service dependencies and alerts on outages." Not the
project's name or its URL restated, no boilerplate ("A software
project", "This repository contains code"), no markdown. Never claim a
capability, user or integration the files don't show. If they show too
little to say anything concrete, omit description rather than guess.
The developer can edit it on the project's page afterwards.register_project upserts by slug: sending a slug some other project
already has overwrites that project's name and repository. So if
list_projects already has the slug — whatever its repoUrls, set or not —
or the slug came out empty, use <owner>-<repo> built the same way
(sandgardenhq-gloria-dev). <owner> is the path segment before the
repository name (for https://gitlab.com/group/sub/repo, sub). If that is
taken too, append a number to it — <owner>-<repo>-2, -3, … — until it
is free. Slugs can't be changed later, so never guess past this rule.
If the result's status is "held_by", another project already holds
this repository (it was attached after your list_projects call, or the
comparison missed it): nothing was created. Name that project from
heldBy (its slug and name), say this repository's spend is already
attributed to it, and register nothing more.
Registering never attaches: you can't tell from the code whether two
repositories are one product, and attaching moves spend between projects.
Never call attach_project_repository yourself.
Report what happened in step 8, from the result's project and
backfill:
slug it registered under (and the name, when it isn't the same as
the slug);backfill.status "ran" with sessionCount above 0 — that many earlier
sessions moved from Unassigned onto the project, worth spendMicros ÷
1,000,000 dollars (round to cents), the earliest from earliestSessionAt
(Unix seconds; show it as a date). When unpriced is true, some of that
spend has no price yet, so the dollar figure is a lower bound — say so;"ran" with sessionCount 0 — there was no earlier Unassigned spend
from this repository to move;"failed" — the project is saved, but its earlier spend didn't move;
sessions from now on are attributed to it;"skipped" — nothing moved;Say how to attach instead. After registering, tell the user that if
this repository is part of an existing product rather than a product of
its own, an org admin (settings:manage) can attach it to that product's
project: on the new project's page in Miranda, Merge into… that
project, which attaches this repository to it and moves the spend that
just moved here along with it. (attach_project_repository attaches a
repository no active project holds, so it won't take this one while the
new project does — it's how an admin adds a repository that isn't
registered yet.) Name the org's other projects from list_projects (name
and slug; the first ten and how many more, if there are more than ten) so
they can pick one. Skip this when the org had no other project.
If list_projects or register_project fails with a transient error (a
dropped connection, a timeout), retry it once. If it still fails, or the
miranda MCP server isn't connected, or the call returns an error — say so,
with the error, and carry on to the report. It doesn't undo the file edits or the enrolment.
Summarize what changed (files created/updated, section inserted where,
usage tracking configured or already present, each gateway carrier written,
unchanged or refused and why, the project registered or matched — or why
the step was skipped — with what step 7 moved) and suggest committing the
changes, e.g. chore: wire miranda agent doc into instruction files. Leave
.claude/settings.local.json, the Codex config and any opencode.json
carrier change out of that commit: they hold this machine's id.
unchanged); with a different gateway it replaces the carrier.config.json
in either location (including the pre-rename ~/.gloria/config.json). Offer
to add machineLabel or rotate only if the user asks..miranda/USING-MIRANDA.md → offer initial setup.config.json in either
location → offer to set it up.What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub sandgardenhq/plugins --plugin miranda