Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (local): drop the double-counting backfill, and stop pricing Bedrock as free

[._.]/ Adam Eivy1691d5306c0e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c7f7b4db3c..b9b4f7b37e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,7 +3,7 @@
## Usage cost reporting
- **[issue-3124] Usage cost estimates now include pre-breakdown history** — Older activity is grouped as legacy usage, conflicting totals agree, missing provider IDs are labeled clearly, and the report explains which token costs remain uncounted.
-- **[issue-3124] The cost report now measures real token usage instead of guessing at it.** Claude Code and Codex runs read their actual per-message token counts — full conversation context plus prompt-cache reads and writes — from the transcripts those tools already keep on your machine, so nothing is sent anywhere and no AI credits are spent. Cache reads and writes are priced at their own published rates and shown in their own columns. Since repeated context and cache traffic are the bulk of what agentic coding actually costs, the report was previously understating real spend by roughly ten times. Every row is now labeled Measured or Estimated, and a "Measure from transcripts" button re-reads past activity to correct history you've already accumulated. Runs on local models stay correctly free.
+- **[issue-3124] The cost report now measures real token usage instead of guessing at it.** Claude Code and Codex runs read their actual per-message token counts — full conversation context plus prompt-cache reads and writes — from the transcripts those tools already keep on your machine, so nothing is sent anywhere and no AI credits are spent. Cache reads and writes are priced at their own published rates and shown in their own columns. Since repeated context and cache traffic are the bulk of what agentic coding actually costs, the report was previously understating real spend by roughly ten times. Every row is now labeled Measured or Estimated, so a figure that still rests on guesswork says so. Runs on local models stay correctly free. Measurement applies to runs from here on; activity already recorded keeps its original estimate.
## Quota-burn automation
diff --git a/client/src/pages/UsagePage.jsx b/client/src/pages/UsagePage.jsx
index 61a46c160c..e34c33f9ef 100644
--- a/client/src/pages/UsagePage.jsx
+++ b/client/src/pages/UsagePage.jsx
@@ -1,12 +1,10 @@
import { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
-import { RefreshCw, Clock, AlertTriangle, FileSearch } from 'lucide-react';
+import { RefreshCw, Clock, AlertTriangle } from 'lucide-react';
import * as api from '../services/api';
import BrailleSpinner from '../components/BrailleSpinner';
import PageSkeleton from '../components/ui/PageSkeleton';
import Pill from '../components/ui/Pill';
-import { useAsyncAction } from '../hooks/useAsyncAction';
-import toast from '../components/ui/Toast';
import { formatCompactCount } from '../utils/formatters';
const PERIOD_OPTIONS = [
@@ -349,8 +347,6 @@ function InternalUsageMetrics() {
const [usage, setUsage] = useState(null);
const [loading, setLoading] = useState(true);
- // Bumped after a backfill so the effect below re-reads the corrected buckets.
- const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
let cancelled = false;
@@ -367,20 +363,8 @@ function InternalUsageMetrics() {
setLoading(false);
});
return () => { cancelled = true; };
- }, [period, from, to, isCustom, reloadKey]);
-
- // Re-read the provider CLIs' local transcripts and replace estimated counts
- // with measured ones. `silent: true` because useAsyncAction owns the error
- // toast (the custom-catch ⇒ silent convention).
- const [runBackfill, backfilling] = useAsyncAction(async () => {
- const summary = await api.backfillUsage({ silent: true });
- const measured = summary?.sessions || 0;
- toast.success(measured
- ? `Measured ${measured.toLocaleString()} sessions across ${summary.days} days from ${summary.families.join(' + ')} transcripts.`
- : 'No provider transcripts found to measure — counts stay estimated.');
- setReloadKey((n) => n + 1);
- return summary;
- }, { errorMessage: 'Failed to read provider transcripts' });
+ }, [period, from, to, isCustom]);
+
const setPeriod = (id) => {
setSearchParams((prev) => {
@@ -458,18 +442,7 @@ function InternalUsageMetrics() {
<span className="text-xl font-bold text-port-success">{formatCost(report?.totals?.estimatedCost)}</span>
</div>
</div>
- <div className="flex flex-wrap items-center justify-between gap-2">
- <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />
- <button
- onClick={runBackfill}
- disabled={backfilling}
- className="flex items-center gap-1.5 px-3 py-1 rounded-full text-xs sm:text-sm border border-port-border text-gray-400 hover:text-white disabled:opacity-50"
- title="Re-read the provider CLIs' local transcripts to replace estimated token counts with measured ones. Reads local files only — no AI provider call."
- >
- <FileSearch size={14} className={backfilling ? 'animate-pulse' : ''} />
- {backfilling ? 'Reading transcripts…' : 'Measure from transcripts'}
- </button>
- </div>
+ <CostReportFilters period={period} from={from} to={to} isCustom={isCustom} onPeriod={setPeriod} onRange={setRange} />
<CostReportTable report={report} />
<p className="text-[10px] sm:text-xs text-gray-500">
Informational estimate of what this usage would have cost under API billing (PortOS runs on subscriptions).
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 3ad7b04b44..0fa2056607 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -58,7 +58,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiRuns.js` | Agent run history. |
| `apiScaffold.js` | App scaffolding templates. |
| `apiSchedules.js` | Automation schedules. |
-| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, and `backfillUsage` — re-reads the provider CLIs' local transcripts to replace estimated token counts with measured ones). |
+| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`). |
| `apiAuth.js` | Optional login password — status, login/logout, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 62d4596902..c260557193 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -115,11 +115,6 @@ export const getUsage = (params = {}) => {
export const getUsageRaw = () => request('/usage/raw');
export const resetUsage = () => request('/usage', { method: 'DELETE' });
-// Re-read the provider CLIs' local transcripts and replace estimated token
-// counts with measured ones. Explicit user action only (see the route comment).
-// `since` is an optional inclusive YYYY-MM-DD floor.
-export const backfillUsage = ({ since = null, ...options } = {}) =>
- request('/usage/backfill', { method: 'POST', body: JSON.stringify({ since }), ...options });
// Subscription-quota status for every enabled provider family (claude, codex,
// agy, grok). Callers own their inline error UI — silent by default.
diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.js
index 1ec0b75582..e3de2b23b6 100644
--- a/server/lib/modelPricing.js
+++ b/server/lib/modelPricing.js
@@ -222,19 +222,29 @@ export function resolveModelRates(providerId, model) {
const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
const FREE_ID = /ollama|lmstudio|lm-studio/i;
-// Ollama/LM Studio name their models `family:tag` (`qwen3.6:35b`,
-// `llama3.1:8b-instruct-q8_0`) or `org/repo` for a pulled GGUF. No hosted
-// model id in EXACT_RATES contains a colon, so the tag is an unambiguous
-// local-inference marker.
-const LOCAL_MODEL_ID = /:|^[\w.-]+\/[\w.-]+$/;
+// Ollama/LM Studio name their models `family:tag` — `qwen3.6:35b`,
+// `llama3.1:8b-instruct-q8_0` — or `org/repo` for a pulled GGUF.
+//
+// A bare `:` test is NOT safe: Bedrock model ids carry a `:0` version suffix
+// (`us.anthropic.claude-opus-4-5-20251101-v1:0`), so matching any colon would
+// price real, paid Bedrock usage at $0. The distinguishing feature is what
+// follows the colon — an Ollama tag is a size/quantization label
+// (`qwen3.6:35b`, `llama3.1:8b-instruct-q8_0`), never a bare integer version
+// the way a Bedrock `-v1:0` suffix is. Requiring at least one letter after the
+// colon separates the two. (Ollama family names may contain dots — `qwen3.6` —
+// so the prefix must allow them.)
+const LOCAL_TAGGED_MODEL = /^[\w.-]+:[\w.-]*[a-z][\w.-]*$/i;
+const LOCAL_REPO_MODEL = /^[\w.-]+\/[\w.-]+$/;
/**
* True when a MODEL id is local-inference (free), independent of which provider
* ran it. Needed because a Claude-Code-flavored CLI can be pointed at an Ollama
* backend: its transcript records `qwen3.6:35b`, which would otherwise resolve
- * through the `claude` provider default and be billed at Sonnet rates. Used by
- * the transcript backfill, where the model id is the only attribution available
- * (a transcript does not record which PortOS provider config invoked it).
+ * through the `claude` provider default and be billed at Sonnet rates.
+ *
+ * Deliberately conservative — a hosted id we can't classify must fall through to
+ * normal (paid) pricing, because under-billing a paid model is the more
+ * expensive mistake for a report whose whole purpose is "what did this cost".
* @param {string|null|undefined} model
* @returns {boolean}
*/
@@ -243,7 +253,11 @@ export function isFreeModelId(model) {
if (!id) return false;
// A hosted id we have a real rate for is never local, whatever its shape.
if (EXACT_RATES[id]) return false;
- return FREE_ID.test(id) || LOCAL_MODEL_ID.test(id);
+ // Nor is one that resolves to a known hosted family (covers Bedrock-prefixed
+ // and suffixed variants of every id in the table).
+ if (resolveModelRates(null, id).matched !== 'fallback') return false;
+ if (FREE_ID.test(id)) return true;
+ return LOCAL_TAGGED_MODEL.test(id) || LOCAL_REPO_MODEL.test(id);
}
/**
diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.js
index 3ff0f526c6..db0a6c52c9 100644
--- a/server/lib/modelPricing.test.js
+++ b/server/lib/modelPricing.test.js
@@ -185,11 +185,30 @@ describe('cache-tier rates on resolveModelRates', () => {
describe('isFreeModelId', () => {
it('treats Ollama/LM Studio family:tag ids as local (free)', () => {
- for (const id of ['qwen3.6:35b', 'llama3.1:8b-instruct-q8_0', 'gpt-oss:120b', 'deepseek-r1:7b']) {
+ for (const id of ['qwen3.6:35b', 'llama3.1:8b-instruct-q8_0', 'deepseek-r1:7b', 'codestral:latest', 'mistral-small3.2:24b']) {
expect(isFreeModelId(id)).toBe(true);
}
});
+ // A tagged id that still resolves to a KNOWN hosted family is not free — the
+ // `gpt-oss` rule prices it at its Cerebras host rate, so treating the Ollama
+ // tag as authoritative would zero out a real bill.
+ it('defers to a known hosted family over the local-tag shape', () => {
+ expect(isFreeModelId('gpt-oss:120b')).toBe(false);
+ });
+
+ // Regression: Bedrock model ids carry a `:0` version suffix, so a bare
+ // "contains a colon" test priced real paid Bedrock usage at $0.
+ it('does NOT treat a Bedrock versioned id as local, despite the colon', () => {
+ for (const id of [
+ 'us.anthropic.claude-opus-4-5-20251101-v1:0',
+ 'anthropic.claude-sonnet-4-5-20250929-v1:0',
+ 'us.anthropic.claude-haiku-4-5-20251001-v1:0'
+ ]) {
+ expect(isFreeModelId(id)).toBe(false);
+ }
+ });
+
it('treats an org/repo GGUF reference as local', () => {
expect(isFreeModelId('unsloth/Qwen3-30B')).toBe(true);
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 854271ee01..81bd2c279d 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -707,15 +707,6 @@ export const usageMessagesSchema = z.object({
inputTokenCount: z.number().int().nonnegative().optional().default(0)
});
-/**
- * Body for POST /api/usage/backfill — re-read the provider CLIs' on-disk
- * transcripts and replace estimated day buckets with measured counts. `since`
- * bounds how far back to walk (inclusive YYYY-MM-DD); omitted means every
- * transcript on disk.
- */
-export const usageBackfillSchema = z.object({
- since: isoDay.nullish()
-});
// =============================================================================
// PORTS
diff --git a/server/routes/usage.js b/server/routes/usage.js
index 8259758aa5..29a58de176 100644
--- a/server/routes/usage.js
+++ b/server/routes/usage.js
@@ -4,8 +4,7 @@ import { getClaudeCodeUsage } from '../services/claudeCodeUsage.js';
import { getProviderQuotas } from '../services/providerUsage.js';
import { getAllProviders } from '../services/providers.js';
import { asyncHandler } from '../lib/errorHandler.js';
-import { validateRequest, usageQuerySchema, usageMessagesSchema, usageBackfillSchema } from '../lib/validation.js';
-import { backfillMeasuredUsage } from '../services/usageReconciler.js';
+import { validateRequest, usageQuerySchema, usageMessagesSchema } from '../lib/validation.js';
import { resolveUsageRange } from '../lib/usageRange.js';
const router = Router();
@@ -59,18 +58,6 @@ router.post('/messages', asyncHandler(async (req, res) => {
res.json({ success: true });
}));
-// POST /api/usage/backfill - Re-read the provider CLIs' on-disk transcripts and
-// replace estimated day buckets with their measured token counts (input, output,
-// and the prompt-cache tiers). Reads local JSONL only — no provider call, no
-// tokens spent — but it rewrites recorded history and can walk a large tree, so
-// it is reachable ONLY from this explicit user action (never boot, never a
-// schedule).
-router.post('/backfill', asyncHandler(async (req, res) => {
- const { since } = validateRequest(usageBackfillSchema, req.body ?? {});
- const summary = await backfillMeasuredUsage({ since: since ?? null });
- res.json(summary);
-}));
-
// POST /api/usage/tokens - Record token usage
router.post('/tokens', asyncHandler(async (req, res) => {
const { inputTokens, outputTokens } = req.body;
diff --git a/server/routes/usage.test.js b/server/routes/usage.test.js
index b02fbe26bc..244a4b70fe 100644
--- a/server/routes/usage.test.js
+++ b/server/routes/usage.test.js
@@ -26,14 +26,10 @@ vi.mock('../services/claudeCodeUsage.js', () => ({
getClaudeCodeUsage: vi.fn()
}));
-vi.mock('../services/usageReconciler.js', () => ({
- backfillMeasuredUsage: vi.fn()
-}));
import * as usage from '../services/usage.js';
import { getAllProviders } from '../services/providers.js';
import { getProviderQuotas } from '../services/providerUsage.js';
-import { backfillMeasuredUsage } from '../services/usageReconciler.js';
import usageRoutes from './usage.js';
const buildApp = () => {
@@ -177,40 +173,3 @@ describe('usage routes', () => {
});
});
-describe('POST /api/usage/backfill', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('runs the transcript backfill and returns its summary', async () => {
- backfillMeasuredUsage.mockResolvedValue({
- days: 3, sessions: 12, tokensIn: 100, tokensOut: 200,
- cacheReadTokens: 900, cacheWriteTokens: 50, families: ['claude']
- });
-
- const res = await request(buildApp()).post('/api/usage/backfill').send({});
- expect(res.status).toBe(200);
- expect(res.body).toMatchObject({ days: 3, sessions: 12, families: ['claude'] });
- expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: null });
- });
-
- it('passes an explicit since floor through', async () => {
- backfillMeasuredUsage.mockResolvedValue({ days: 1, sessions: 1, families: ['codex'] });
- const res = await request(buildApp()).post('/api/usage/backfill').send({ since: '2026-07-01' });
- expect(res.status).toBe(200);
- expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: '2026-07-01' });
- });
-
- it('works with no body at all', async () => {
- backfillMeasuredUsage.mockResolvedValue({ days: 0, sessions: 0, families: [] });
- const res = await request(buildApp()).post('/api/usage/backfill');
- expect(res.status).toBe(200);
- expect(backfillMeasuredUsage).toHaveBeenCalledWith({ since: null });
- });
-
- it('rejects a malformed since date', async () => {
- const res = await request(buildApp()).post('/api/usage/backfill').send({ since: 'yesterday' });
- expect(res.status).toBe(400);
- expect(backfillMeasuredUsage).not.toHaveBeenCalled();
- });
-});
diff --git a/server/services/usage.js b/server/services/usage.js
index 9844f828f2..71ee43b583 100644
--- a/server/services/usage.js
+++ b/server/services/usage.js
@@ -380,68 +380,6 @@ export async function recordRunUsage(record) {
});
}
-/**
- * REPLACE a given day's measured provider/model buckets with `records` — the
- * write half of the transcript backfill (`usageReconciler.backfillMeasuredUsage`).
- *
- * Replace, not add, so re-running the backfill is idempotent: a second pass over
- * the same transcripts must not double the day. Only the buckets named in
- * `records` are touched — a provider whose usage that day came from somewhere
- * else (a local model, an API provider) keeps its existing estimate.
- *
- * The day's flat `sessions`/`messages`/`tokens` fields are deliberately left
- * alone: they are the legacy all-time-ish counters the report already reconciles
- * as residuals, and rewriting them from a partial (transcript-only) view of the
- * day would drop the providers this pass cannot see.
- *
- * @param {string} dayKey `YYYY-MM-DD`
- * @param {Array<{ providerId: string, model: string|null, sessions?: number,
- * messages?: number, tokensIn?: number, tokensOut?: number,
- * cacheReadTokens?: number, cacheWriteTokens?: number }>} records
- */
-export async function replaceMeasuredDayUsage(dayKey, records) {
- if (!usageData) await loadUsage();
- if (!DAY_KEY_RE.test(dayKey || '') || !Array.isArray(records) || records.length === 0) return;
-
- if (!usageData.dailyActivity[dayKey]) {
- usageData.dailyActivity[dayKey] = { sessions: 0, messages: 0, tokens: 0 };
- }
- const day = usageData.dailyActivity[dayKey];
-
- // Reset only the buckets this pass will rewrite, so a partial re-run can't
- // leave a stale half-count behind.
- for (const { providerId, model } of records) {
- const providerDay = providerDayBucket(day, providerId, null);
- const target = model ? modelDayBucket(providerDay, model) : providerDay;
- for (const bucket of new Set([providerDay, target])) {
- bucket.sessions = 0;
- bucket.messages = 0;
- bucket.tokensIn = 0;
- bucket.tokensOut = 0;
- bucket.cacheReadTokens = 0;
- bucket.cacheWriteTokens = 0;
- bucket.source = null;
- }
- }
-
- for (const record of records) {
- const providerDay = providerDayBucket(day, record.providerId, null);
- const apply = (bucket) => {
- bucket.sessions += record.sessions || 0;
- bucket.messages += record.messages || 0;
- bucket.tokensIn += record.tokensIn || 0;
- bucket.tokensOut += record.tokensOut || 0;
- bucket.cacheReadTokens += record.cacheReadTokens || 0;
- bucket.cacheWriteTokens += record.cacheWriteTokens || 0;
- bucket.source = mergeSource(bucket.source, 'measured');
- };
- apply(providerDay);
- if (record.model) apply(modelDayBucket(providerDay, record.model));
- }
-
- await saveUsage();
-}
-
/**
* Record tool calls
*/
diff --git a/server/services/usage.test.js b/server/services/usage.test.js
index e6e48e3997..849aa0e827 100644
--- a/server/services/usage.test.js
+++ b/server/services/usage.test.js
@@ -20,7 +20,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
}));
import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';
-import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, recordTokens, recordRunUsage, replaceMeasuredDayUsage, buildUsageReport, rollupOldDailyActivity } from './usage.js';
+import { loadUsage, getUsageSummary, getUsage, recordSession, recordMessages, recordTokens, recordRunUsage, buildUsageReport, rollupOldDailyActivity } from './usage.js';
// Helper: produce a date string N days ago (relative to today)
function daysAgo(n) {
@@ -1038,60 +1038,4 @@ describe('buildUsageReport — cache pricing and source reporting', () => {
});
});
-describe('replaceMeasuredDayUsage', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('is idempotent — a second identical backfill does not double the day', async () => {
- readJSONFile.mockResolvedValueOnce(makeUsage({}));
- await loadUsage();
-
- const records = [{
- providerId: 'claude-code',
- model: 'claude-opus-5',
- sessions: 2,
- messages: 5,
- tokensIn: 100,
- tokensOut: 200,
- cacheReadTokens: 9000,
- cacheWriteTokens: 300
- }];
-
- await replaceMeasuredDayUsage('2026-07-01', records);
- await replaceMeasuredDayUsage('2026-07-01', records);
-
- const bucket = getUsage().dailyActivity['2026-07-01'].byProvider['claude-code'];
- expect(bucket).toMatchObject({
- sessions: 2, messages: 5, tokensIn: 100, tokensOut: 200,
- cacheReadTokens: 9000, cacheWriteTokens: 300, source: 'measured'
- });
- expect(bucket.byModel['claude-opus-5']).toMatchObject({ tokensOut: 200, cacheReadTokens: 9000 });
- });
-
- it('leaves other providers in the same day untouched', async () => {
- readJSONFile.mockResolvedValueOnce(makeUsage({
- '2026-07-01': {
- sessions: 1, messages: 1, tokens: 40,
- byProvider: { ollama: { name: 'Ollama', sessions: 1, messages: 1, tokensIn: 5, tokensOut: 40, byModel: {} } }
- }
- }));
- await loadUsage();
-
- await replaceMeasuredDayUsage('2026-07-01', [
- { providerId: 'claude-code', model: null, sessions: 1, messages: 1, tokensOut: 10 }
- ]);
- const day = getUsage().dailyActivity['2026-07-01'];
- expect(day.byProvider.ollama).toMatchObject({ tokensOut: 40, tokensIn: 5 });
- expect(day.byProvider['claude-code'].source).toBe('measured');
- });
-
- it('rejects a malformed day key or empty record list', async () => {
- readJSONFile.mockResolvedValueOnce(makeUsage({}));
- await loadUsage();
- await replaceMeasuredDayUsage('not-a-day', [{ providerId: 'claude-code' }]);
- await replaceMeasuredDayUsage('2026-07-01', []);
- expect(Object.keys(getUsage().dailyActivity)).toHaveLength(0);
- });
-});
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index 71ee8429f0..e17819ed66 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -30,14 +30,13 @@ import { join } from 'path';
import { readdir } from 'fs/promises';
import { tryReadFile } from '../lib/fileUtils.js';
import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';
-import { isFreeModelId } from '../lib/modelPricing.js';
import {
claudeProjectSlug,
parseClaudeTranscript,
parseCodexRollout,
totalTranscriptTokens
} from '../lib/providerTranscriptUsage.js';
-import { recordRunUsage, replaceMeasuredDayUsage } from './usage.js';
+import { recordRunUsage } from './usage.js';
// Widen the correlation window past the recorded run bounds: the CLI writes its
// first line slightly before PortOS stamps startTime, and flushes its last
@@ -60,17 +59,6 @@ const cwdMatches = (transcriptCwd, workspacePath) => {
const CLAUDE_ID = /claude/i;
const CODEX_ID = /codex/i;
-// A transcript records the CLI that wrote it, not which PortOS provider config
-// invoked it (a single CLI backs several: `claude-code`, `claude-code-tui`,
-// `claude-code-tui-bedrock`, …). The backfill therefore attributes to one
-// stable per-CLI id rather than guessing a config. These ids intentionally match
-// the canonical provider ids so `resolveModelRates`/`isFreeProvider` classify
-// them correctly, and a later per-run reconcile refines the attribution.
-const CLAUDE_BACKFILL_PROVIDER = 'claude-code';
-const CODEX_BACKFILL_PROVIDER = 'codex';
-// Where a transcript whose model id is local inference gets attributed, so
-// `isFreeProvider` prices it at $0 instead of the hosted provider's rates.
-const FREE_LOCAL_PROVIDER = 'ollama';
/**
* Which transcript family a provider writes, or null for providers that write
@@ -292,126 +280,3 @@ export async function recordCompletedRunUsage(metadata, output, { home = homedir
console.error(`❌ Failed to record usage: ${err.message}`);
});
}
-
-/**
- * Re-read every readable transcript in the retained window and REPLACE the
- * recorded per-provider/per-model day buckets with the measured counts.
- *
- * Reconciliation normally happens per-run at completion, so this exists for the
- * history recorded before that landed — an install upgrading to #3124 Phase 2
- * has months of estimated buckets it can now correct in place.
- *
- * **Explicitly user-triggered only.** Reading local JSONL spends no tokens and
- * makes no provider call, so this does not engage the AI-provider policy — but a
- * from-zero bulk pass over a large `~/.claude/projects` tree is slow and
- * rewrites recorded history, so it must never run from boot or a schedule. The
- * only caller is `POST /api/usage/backfill`.
- *
- * Buckets are keyed by the transcript's own day, so a session is attributed to
- * the day it ran rather than today. Days with no transcript keep their existing
- * estimate untouched.
- *
- * @param {{ home?: string, since?: string|null }} [opts] `since` is an inclusive
- * `YYYY-MM-DD` floor; transcripts older than it are skipped.
- * @returns {Promise<{ days: number, sessions: number, tokensIn: number,
- * tokensOut: number, cacheReadTokens: number, cacheWriteTokens: number,
- * families: string[] }>}
- */
-export async function backfillMeasuredUsage({ home = homedir(), since = null } = {}) {
- const byDay = new Map(); // 'YYYY-MM-DD' -> Map<providerKey, totals>
- const families = new Set();
- const summary = {
- days: 0,
- sessions: 0,
- tokensIn: 0,
- tokensOut: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0,
- families: []
- };
-
- const collect = (parsed, family, providerId) => {
- if (!parsed || totalTranscriptTokens(parsed) === 0) return;
- // Attribute to the day the session ENDED — the same day PortOS's own
- // recording would have used, since it records at run completion.
- const day = (parsed.lastTs || parsed.firstTs || '').slice(0, 10);
- if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) return;
- if (since && day < since) return;
-
- families.add(family);
- if (!byDay.has(day)) byDay.set(day, new Map());
- const dayMap = byDay.get(day);
- const model = parsed.model || null;
- // A Claude-Code-flavored CLI can be pointed at a local Ollama/LM Studio
- // backend, and the transcript then records the LOCAL model id
- // (`qwen3.6:35b`). Attributing that to `claude-code` would bill free local
- // inference at Anthropic rates — measured against a real install, ~$166 of
- // cost that was never incurred. Route it to `ollama`, which
- // `isFreeProvider` prices at $0. The model id is the only signal available
- // here: a transcript does not record which PortOS provider invoked it.
- const effectiveProvider = isFreeModelId(model) ? FREE_LOCAL_PROVIDER : providerId;
- const key = `${effectiveProvider} ${model ?? ''}`;
- if (!dayMap.has(key)) {
- dayMap.set(key, {
- providerId: effectiveProvider,
- model,
- sessions: 0,
- messages: 0,
- tokensIn: 0,
- tokensOut: 0,
- cacheReadTokens: 0,
- cacheWriteTokens: 0
- });
- }
- const bucket = dayMap.get(key);
- bucket.sessions += 1;
- bucket.messages += parsed.messages || 0;
- bucket.tokensIn += parsed.tokensIn || 0;
- bucket.tokensOut += parsed.tokensOut || 0;
- bucket.cacheReadTokens += parsed.cacheReadTokens || 0;
- bucket.cacheWriteTokens += parsed.cacheWriteTokens || 0;
- };
-
- // Claude Code — every project directory, since a PortOS install drives runs in
- // the repo, its worktrees, and its subdirectories, each a separate slug.
- const projectsRoot = join(home, '.claude', 'projects');
- for (const project of await listDir(projectsRoot)) {
- for (const file of await listDir(join(projectsRoot, project))) {
- if (!file.endsWith('.jsonl')) continue;
- const text = await tryReadFile(join(projectsRoot, project, file));
- if (!text) continue;
- collect(parseClaudeTranscript(text), 'claude', CLAUDE_BACKFILL_PROVIDER);
- }
- }
-
- // Codex — walk the YYYY/MM/DD tree rather than guessing dates.
- const sessionsRoot = join(home, '.codex', 'sessions');
- for (const year of await listDir(sessionsRoot)) {
- for (const month of await listDir(join(sessionsRoot, year))) {
- for (const dayDir of await listDir(join(sessionsRoot, year, month))) {
- const dir = join(sessionsRoot, year, month, dayDir);
- for (const file of await listDir(dir)) {
- if (!file.startsWith('rollout-') || !file.endsWith('.jsonl')) continue;
- const text = await tryReadFile(join(dir, file));
- if (!text) continue;
- collect(parseCodexRollout(text), 'codex', CODEX_BACKFILL_PROVIDER);
- }
- }
- }
- }
-
- for (const [day, dayMap] of byDay) {
- await replaceMeasuredDayUsage(day, [...dayMap.values()]);
- summary.days += 1;
- for (const bucket of dayMap.values()) {
- summary.sessions += bucket.sessions;
- summary.tokensIn += bucket.tokensIn;
- summary.tokensOut += bucket.tokensOut;
- summary.cacheReadTokens += bucket.cacheReadTokens;
- summary.cacheWriteTokens += bucket.cacheWriteTokens;
- }
- }
- summary.families = [...families];
- console.log(`📊 Usage backfill: ${summary.sessions} sessions across ${summary.days} days from ${summary.families.join(', ') || 'no'} transcripts`);
- return summary;
-}
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index c43f134a1f..dec11b8921 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -4,17 +4,15 @@ import { tmpdir } from 'os';
import { join } from 'path';
vi.mock('./usage.js', () => ({
- recordRunUsage: vi.fn().mockResolvedValue(undefined),
- replaceMeasuredDayUsage: vi.fn().mockResolvedValue(undefined)
+ recordRunUsage: vi.fn().mockResolvedValue(undefined)
}));
-const { recordRunUsage, replaceMeasuredDayUsage } = await import('./usage.js');
+const { recordRunUsage } = await import('./usage.js');
const {
transcriptFamily,
readMeasuredUsage,
reconcileRunUsage,
- recordCompletedRunUsage,
- backfillMeasuredUsage
+ recordCompletedRunUsage
} = await import('./usageReconciler.js');
// Fake HOME per test so the parsers read fixtures, never the developer's real
@@ -354,114 +352,4 @@ describe('recordCompletedRunUsage', () => {
});
});
-describe('backfillMeasuredUsage', () => {
- it('attributes each session to the day it ran and reports a summary', async () => {
- await writeClaudeSession('a.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
- ]);
- await writeClaudeSession('b.jsonl', [
- claudeAssistant({ id: 'm2', timestamp: '2026-07-02T10:05:00.000Z', output: 25 })
- ]);
-
- const summary = await backfillMeasuredUsage({ home });
-
- expect(summary).toMatchObject({ days: 2, sessions: 2, tokensOut: 75, families: ['claude'] });
- const days = replaceMeasuredDayUsage.mock.calls.map(([day]) => day).sort();
- expect(days).toEqual(['2026-07-01', '2026-07-02']);
- // Provider attribution is the canonical per-CLI id, since a transcript does
- // not record which PortOS provider config invoked it.
- expect(replaceMeasuredDayUsage.mock.calls[0][1][0]).toMatchObject({ providerId: 'claude-code' });
- });
-
- it('honors the since floor', async () => {
- await writeClaudeSession('a.jsonl', [
- claudeAssistant({ id: 'old', timestamp: '2026-06-01T10:00:00.000Z' })
- ]);
- await writeClaudeSession('b.jsonl', [
- claudeAssistant({ id: 'new', timestamp: '2026-07-02T10:00:00.000Z' })
- ]);
-
- const summary = await backfillMeasuredUsage({ home, since: '2026-07-01' });
- expect(summary.days).toBe(1);
- expect(replaceMeasuredDayUsage.mock.calls.map(([day]) => day)).toEqual(['2026-07-02']);
- });
-
- it('walks every project directory, not just the current workspace', async () => {
- await writeClaudeSession('a.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z' })
- ], '-work-repo-one');
- await writeClaudeSession('b.jsonl', [
- claudeAssistant({ id: 'm2', timestamp: '2026-07-01T11:00:00.000Z' })
- ], '-work-repo-two');
-
- const summary = await backfillMeasuredUsage({ home });
- expect(summary.sessions).toBe(2);
- });
-
- it('includes codex rollouts alongside claude sessions', async () => {
- await writeClaudeSession('a.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z' })
- ]);
- await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', codexRollout({
- timestamp: '2026-07-01T11:00:00.000Z', input: 1000, cached: 400, output: 60
- }));
-
- const summary = await backfillMeasuredUsage({ home });
- expect(summary.sessions).toBe(2);
- expect(summary.families.sort()).toEqual(['claude', 'codex']);
- const records = replaceMeasuredDayUsage.mock.calls[0][1];
- expect(records.map((r) => r.providerId).sort()).toEqual(['claude-code', 'codex']);
- });
-
- it('is a clean no-op on a home with no transcripts', async () => {
- const summary = await backfillMeasuredUsage({ home });
- expect(summary).toMatchObject({ days: 0, sessions: 0, families: [] });
- expect(replaceMeasuredDayUsage).not.toHaveBeenCalled();
- });
-
- it('ignores transcripts with zero measurable tokens', async () => {
- await writeClaudeSession('empty.jsonl', [
- JSON.stringify({ type: 'user', cwd: WORKSPACE, sessionId: 'sess-1' })
- ]);
- const summary = await backfillMeasuredUsage({ home });
- expect(summary.sessions).toBe(0);
- });
-});
-
-describe('backfillMeasuredUsage — local-model attribution (regression)', () => {
- // A Claude-Code-flavored CLI pointed at an Ollama backend writes its
- // transcript under ~/.claude/projects but records the LOCAL model id.
- // Attributing that to `claude-code` billed free inference at Anthropic rates.
- it('routes a local model id to the free ollama provider, not claude-code', async () => {
- await writeClaudeSession('local.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'qwen3.6:35b' })
- ]);
- await backfillMeasuredUsage({ home });
- const records = replaceMeasuredDayUsage.mock.calls[0][1];
- expect(records).toHaveLength(1);
- expect(records[0]).toMatchObject({ providerId: 'ollama', model: 'qwen3.6:35b' });
- });
-
- it('still attributes hosted models to their own CLI provider', async () => {
- await writeClaudeSession('hosted.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'claude-opus-5' })
- ]);
-
- await backfillMeasuredUsage({ home });
- expect(replaceMeasuredDayUsage.mock.calls[0][1][0]).toMatchObject({ providerId: 'claude-code' });
- });
-
- it('splits a day that mixed local and hosted models into separate rows', async () => {
- await writeClaudeSession('local.jsonl', [
- claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:00:00.000Z', model: 'qwen3.6:35b' })
- ]);
- await writeClaudeSession('hosted.jsonl', [
- claudeAssistant({ id: 'm2', timestamp: '2026-07-01T11:00:00.000Z', model: 'claude-opus-5' })
- ]);
-
- await backfillMeasuredUsage({ home });
- const records = replaceMeasuredDayUsage.mock.calls[0][1];
- expect(records.map((r) => r.providerId).sort()).toEqual(['claude-code', 'ollama']);
- });
-});