Repository navigation
Description
Summary
Add an export subcommand that sends AI usage telemetry to a remote OpenTelemetry-compatible endpoint, authenticated via OIDC browser login with refresh tokens stored in the OS credential store.
Motivation
codeburn tracks AI usage locally per-developer. Teams want to aggregate this data across developers for:
- Adoption dashboards — which tools/models are being used, by whom, how much
- Budget tracking — team-level AI spend with alerts
- ROI measurement — correlate AI usage with velocity/quality metrics
Today there's no standard way to get codeburn data off a developer's machine into a shared backend. Teams resort to custom scripts parsing codeburn report --format json output. A first-class export with secure auth solves this cleanly.
UX
Setup (one-time)
codeburn export setup https://metrics.example.comWhat happens:
- Fetches
https://metrics.example.com/.well-known/openid-configuration - Opens system browser for OIDC Authorization Code + PKCE login
- Stores refresh token in OS credential store (Keychain / Credential Manager / libsecret)
- Saves
{ "baseUrl": "https://metrics.example.com" }to~/.config/codeburn/export.json
That's it. One URL, zero prompts. The base URL serves as both the OIDC provider and the telemetry endpoint — .well-known provides auth config, and a known subpath (e.g. /v1/traces) receives OTEL data.
Export — Manual (on-demand)
# Export last 7 days (default)
codeburn export push
# Export specific period
codeburn export push --since 30d
# Dry-run (show what would be sent)
codeburn export push --dry-runWhat happens:
- Reads refresh token from OS credential store
- Exchanges for access token (silent refresh, no browser)
- Collects
ParsedProviderCalldata for the period (same data ascodeburn report) - Sends as OTEL spans/metrics to
{baseUrl}/v1/traceswithAuthorization: Bearer <access_token> - Prints summary: "Exported 234 calls ($45.20) to metrics.example.com"
Export — Daemon (daily auto-export)
# Enable daily auto-export
codeburn export daemon start
# Check daemon status
codeburn export daemon status
# Disable
codeburn export daemon stopWhat happens:
- Registers a daily background job (platform-native: launchd plist on macOS, systemd user timer on Linux, Task Scheduler on Windows)
- Runs once per day (configurable time, default: 9am local)
- Exports the previous day's activity (midnight-to-midnight)
- Silently succeeds or logs failures to
~/.cache/codeburn/export.log - No terminal output, no user interaction — fully headless
The daemon uses the same stored refresh token as manual export. If the token expires and can't refresh, it logs a warning and stops retrying until the user runs codeburn export setup again.
// ~/.config/codeburn/export.json (with daemon enabled)
{
"baseUrl": "https://metrics.example.com",
"clientId": "codeburn-cli",
"lastExport": "2026-07-05T14:00:00Z",
"daemon": {
"enabled": true,
"schedule": "09:00",
"lastRun": "2026-07-05T09:00:02Z",
"lastStatus": "ok"
}
}Status / Logout
# Check config and auth status
codeburn export status
# Output: Endpoint: https://metrics.example.com | Auth: valid (expires in 47d) | Last export: 2h ago
# Remove stored credentials
codeburn export logoutAuth Design
OIDC Flow
- Grant type: Authorization Code with PKCE (public/native client — no client secret)
- Redirect URI:
http://localhost:<ephemeral-port>/callback(temporary server during login, same pattern asaws sso login,gcloud auth login,gh auth login) - Scopes:
openid offline_access(offline_access provides refresh token) - Token refresh: Automatic on every
export push— transparent to user - Re-login: Only required when refresh token expires or is revoked
Credential Storage
| Platform | Store | Suggested implementation |
|---|---|---|
| macOS | Keychain | keytar or security CLI |
| Windows | Credential Manager | keytar or @aspect-build/wincred |
| Linux | libsecret (GNOME Keyring / KWallet) | keytar or secret-tool CLI |
keytar is the cross-platform standard (used by VS Code, GitHub CLI, Azure CLI). If keytar native module is undesirable for a pure-JS tool, fall back to encrypted file with OS-derived key.
Token Lifetime and Rotation
Recommended refresh token lifetime: 90 days. Balances convenience (quarterly re-auth) against exposure risk for a low-blast-radius telemetry endpoint.
Rotation: supported but not required. OIDC providers vary:
| Provider | Rotation | Notes |
|---|---|---|
| Auth0 / Okta / Azure AD | ✅ On by default for public clients | Issues new RT on each use, invalidates old |
| Keycloak / Ory Hydra / Zitadel | ✅ Configurable | Off by default, enable per-client |
| Cognito / Google | ❌ Not supported | RT is reusable for full lifetime |
codeburn's behavior is provider-agnostic:
- After every token refresh, store whatever refresh token the server returns (new or same)
- If the server returns a new RT (rotation), overwrite the old one in keychain immediately
- If the server returns the same RT (no rotation), keep using it
- On
invalid_granterror — don't retry, prompt user: "Export auth expired. Runcodeburn export setup"
This works correctly with Cognito (no rotation, 90-day reusable token), Auth0 (rotation on, new RT each use), and everything in between. The client doesn't need to know whether rotation is active.
Server-side recommendation (for reference implementations):
- Enable rotation if the provider supports it
- Set reuse grace window to 30 seconds (handles network-drop retries)
- Enable token family invalidation on reuse detection (theft signal)
- For non-rotating providers (Cognito): rely on the 90-day expiry as the primary security boundary
Config File (non-secret)
// ~/.config/codeburn/export.json
{
"baseUrl": "https://metrics.example.com",
"clientId": "codeburn-cli",
"lastExport": "2026-07-05T14:00:00Z"
}No tokens, secrets, or credentials in this file. clientId is auto-discovered from .well-known response or defaults to "codeburn-cli".
Data Schema
Each ParsedProviderCall becomes one OTEL span with these attributes:
ai.provider = "kiro" | "cursor" | "claude" | ...
ai.model = "claude-sonnet-4-6"
ai.input_tokens = 12500
ai.output_tokens = 3200
ai.cost_usd = 0.085
ai.project = "sample-prism-d1-velocity"
ai.session_id = "421b64df-..."
ai.tools = ["Edit", "Bash", "Read"]
ai.speed = "standard"
ai.cost_estimated = true | false
Data minimization (critical)
NOT exported by default:
userMessage— contains actual prompts (PII, proprietary code context)- File paths — may leak repo structure
- Bash commands — may contain secrets
Opt-in flag for teams that want it:
codeburn export push --include-messagesServer-side Contract
The server at baseUrl must implement:
GET /.well-known/openid-configuration— standard OIDC discoveryPOST /v1/traces— accepts OTEL protobuf or JSON, validates Bearer token
This is intentionally minimal. Any OTEL-compatible backend (Grafana Alloy, AWS ADOT Collector, Datadog Agent) behind an OIDC-aware reverse proxy satisfies it.
.well-known requirement
If /.well-known/openid-configuration returns 404 or is unreachable, exit with an error:
Error: https://metrics.example.com/.well-known/openid-configuration not found.
The server must implement OIDC discovery. See https://openid.net/specs/openid-connect-discovery-1_0.html
No fallback, no prompts, no alternative auth methods. The server either supports the protocol or it doesn't.
Alternatives Considered
| Approach | Why not |
|---|---|
| API key in env var | Insecure, easy to leak, no rotation |
| API key in config file | File permissions are unreliable across OS |
| mTLS client certs | Complex setup, cert rotation burden |
| Multiple auth methods | Complexity for marginal gain — one protocol, one flow, zero config |
OIDC + keychain is the same pattern as aws sso login, gcloud auth login, gh auth login — developers already understand it. If the server doesn't support .well-known, it doesn't support codeburn export.
Implementation Notes
Gap Detection and Backfill
The daemon exports "yesterday" — but what if yesterday's export failed, or the machine was off for a week?
Approach: watermark-based catch-up
The config tracks a lastSuccessfulExport timestamp (the newest data point successfully sent). On each daemon run:
- Compare
lastSuccessfulExportto now - If gap > 1 day, export the entire gap (capped at 30 days to avoid first-run flood)
- Update
lastSuccessfulExportonly after the server acknowledges receipt
{
"baseUrl": "https://metrics.example.com",
"lastSuccessfulExport": "2026-07-03T00:00:00Z"
}If today is Jul 5 and last successful was Jul 3 → daemon exports Jul 3 + Jul 4 in one batch before exporting today's window.
First-run behavior: lastSuccessfulExport doesn't exist → export last 7 days as initial seed (configurable via --seed-days). Not the full 6-month history — that's what codeburn export push --since 6m is for.
Manual backfill: If someone was offline for months:
codeburn export push --since 90dThis explicitly backfills the gap. The daemon's 30-day cap prevents accidental flood; manual push has no cap (other than codeburn's 6-month data retention).
Deduplication: The server uses deduplicationKey (already present on every ParsedProviderCall) as an idempotency key. Re-exporting the same period is safe — duplicates are ignored server-side. This means gap-fill and manual push can overlap without double-counting.
Failure modes:
| Scenario | Behavior |
|---|---|
| Network down | Log error, lastSuccessfulExport unchanged, retry next run |
| Token expired (refresh fails) | Log warning, stop daemon retries, notify on next interactive codeburn run: "Export auth expired. Run codeburn export setup to re-authenticate." |
| Server returns 5xx | Retry with backoff (3 attempts), then defer to next day |
| Server returns 409 (duplicate) | Treat as success, advance watermark |
| Machine off for 2 weeks | Next daemon run exports the full 14-day gap in one batch |
| Machine off for 2 months | Daemon exports last 30 days, prints note: "Gap exceeds 30d. Run codeburn export push --since 60d to backfill fully." |
- The export should be idempotent — re-exporting the same period deduplicates via
deduplicationKeyas span ID - Batch size: send in chunks of ~1000 spans to avoid payload limits
- Retry: exponential backoff on 429/5xx, fail-fast on 401 (trigger re-login prompt)
- Offline queue: if export fails, optionally queue to
~/.cache/codeburn/export-queue/for retry on next run --sinceshould respect the same 6-month lookback cap ascodeburn report -p all
Future Extensions
- Team enrollment — server returns team config (which fields to include, export frequency) during setup
- Anonymization mode — hash session IDs and project names for privacy-sensitive deployments
- Export hooks — trigger export automatically after each
codeburn report/ dashboard refresh
Activity
iamtoruk commentedon Jul 6, 2026
Thanks for this spec, this is excellent work. The architecture is right: push from the machine, no git dependency, privacy by default, provider-agnostic auth. Green light, with the design amendments below locked in first. Most of them come from checking the auth flow against real IdP behavior (mainly Cognito) and the export path against the OTLP spec.
Auth and setup
1. Discovery doc moves to the app level.
/.well-known/openid-configurationwill not live on the metrics host for most IdPs. Cognito serves it fromcognito-idp.<region>.amazonaws.com/<userPoolId>/...(docs), and OIDC requires theissuerinside the doc to match the discovery URL, so proxying it does not work either. Instead the metrics host serves a small codeburn-specific doc:The client runs standard OIDC discovery against
issuer. Setup stays one URL, zero prompts. This also fixesclient_id: OIDC discovery does not publish client IDs, and providers like Cognito generate them, so acodeburn-clidefault would never match a real deployment.2. Fixed loopback port,
127.0.0.1literal. Cognito matches registered callback URLs by string comparison, no wildcard ports, so an ephemeral port fails withredirect_mismatch. We pick one documented default port (with a short fallback list) so admins register exactly one URL. RFC 8252 also recommends the loopback IP literal overlocalhost(RFC 8252). The callback server binds loopback only, verifiesstate, times out after 5 minutes, and shuts down after one callback.3. Scopes come from the discovery doc.
offline_accessis required by some IdPs (Auth0) and rejected asinvalid_scopeby others (Cognito issues refresh tokens without it, docs). The client requests whatever the discovery doc lists, addingoffline_accessonly when the IdP'sscopes_supportedadvertises it. Deployments should also define a custom scope for the telemetry endpoint;openidproves identity, it does not authorize writes.4. Rotation table correction. Cognito supports refresh token rotation now, and its default refresh expiry is 30 days, configurable (docs). Your client behavior (store whatever the server returns) is exactly right and stays; only the table and the 90-day recommendation change.
5. Credential storage without keytar. keytar is archived and is a native module, so it is out on both counts (repo). We shell out to OS stores instead:
securityon macOS,secret-toolon Linux, PowerShell DPAPI on Windows. Where none is available, the fallback is a plain 0600 file, reported honestly instatus. A file "encrypted with an OS-derived key" that the same user can derive is the same file with extra steps.Export correctness
6. Dedup lives in the client. Stock OTLP backends do not dedupe on a custom attribute and do not return 409 per duplicate; the OTLP spec explicitly tolerates duplicates on retry (spec). So the client keeps a local sent-ledger of
deduplicationKeys as the source of truth for what has been exported. The ledger also replaces the timestamp watermark, which would silently skip late-arriving calls forever (long-running sessions, providers that update rows in place). Each push exports "window minus ledger", default window 7 days,--sincefor more. Span identity is derived deterministically:span_id= first 8 bytes of SHA-256(deduplicationKey),trace_id= 16 bytes of SHA-256(sessionId), so any re-send is byte-identical. Server-side dedup becomes defense in depth, not a requirement, which makes the "any OTLP backend" claim actually true.7. Partial success is not success. OTLP reports partial failure as HTTP 200 with
partial_success.rejected_spansin the body. Ifrejected_spans > 0, the chunk stays out of the ledger, gets logged, and retries on the next push.8. Strict OTLP encoding, traces only. OTLP/HTTP JSON is the protobuf-JSON mapping of
ExportTraceServiceRequest: lowerCamelCase fields, hex IDs, integer enums. A golden-payload test pins the encoding. Metrics have their own path (/v1/metrics) and are out of scope until a backend asks.9. Server contract additions. The endpoint derives developer identity from the validated token's
subclaim; the payload deliberately carries no name, email, or hostname. The backend must accept spans with start times up to 6 months in the past. We add a pseudonymouscodeburn.device_idresource attribute so multi-machine developers aggregate correctly.Packaging
10. Command group is
codeburn sync.codeburn exportalready writes local CSV/JSON files, so this lands assync setup | push | status | logout.11. v1 is manual push only. The daemon is the riskiest slice of the spec: three schedulers, each with missed-run, locked-keychain, and logged-out-session failure modes on real laptops. We get the same effect cheaper: any regular codeburn invocation (menubar refresh, statusline, report) checks whether a push is due (>24h) and spawns one detached. That ships as a fast follow after v1. A true daemon stays on the table for headless machines.
12.
--include-messagesis dropped. Prompts carry secrets and proprietary code, and a single flag that exfiltrates them undercuts the local-first stance that makes codeburn trustworthy in exactly the deployments this feature targets. If a team ever truly needs it, it would have to be server-declared and config-gated, but it is out for now.Everything else stands as written; the failure-mode table, batching, and backoff behavior are solid.
If you want to take the implementation, it is yours. v1 scope:
sync setup / push / status / logout, the sent-ledger, strict OTLP JSON, and a mock-IdP test suite that runs fully offline in CI. Happy to talk through any of the amendments, and I will review the auth code especially closely since that is where this feature can hurt users.Enclavet commentedon Jul 6, 2026
Thanks @iamtoruk for the feedback. Will incorporate your feedback/comments and will start implementation.
Enclavet commentedon Jul 13, 2026
PR merged: #660