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 (codex): close the remaining ledger races and stop dropping/mispricing measured tokens

[._.]/ Adam Eivya6756f5ca3f1
diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.js
index e3de2b23b6..aeacbc1f12 100644
--- a/server/lib/modelPricing.js
+++ b/server/lib/modelPricing.js
@@ -234,7 +234,13 @@ const FREE_ID = /ollama|lmstudio|lm-studio/i;
// 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.-]+$/;
+
+// The `org/repo` GGUF form is NOT a local marker on its own: paid hosted
+// catalogs use the same shape (`cohere/command-r`, OpenRouter's
+// `provider/model`), and pricing an unknown one at $0 under-bills real usage.
+// Only the tagged form above is self-evidently an Ollama/LM Studio id, so a
+// slash-form id needs corroborating evidence from the PROVIDER — which is what
+// `isFreeProvider` already supplies — rather than being inferred from syntax.
/**
* True when a MODEL id is local-inference (free), independent of which provider
@@ -257,7 +263,7 @@ export function isFreeModelId(model) {
// 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);
+ return LOCAL_TAGGED_MODEL.test(id);
}
/**
diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.js
index db0a6c52c9..f75fd5e833 100644
--- a/server/lib/modelPricing.test.js
+++ b/server/lib/modelPricing.test.js
@@ -209,8 +209,14 @@ describe('isFreeModelId', () => {
}
});
- it('treats an org/repo GGUF reference as local', () => {
- expect(isFreeModelId('unsloth/Qwen3-30B')).toBe(true);
+ // An `org/repo` id is NOT self-evidently local: paid hosted catalogs use the
+ // same shape (`cohere/command-r`, OpenRouter's `provider/model`), and calling
+ // an unknown one free would under-bill real usage. Locality for that shape has
+ // to come from the provider (isFreeProvider), not the model syntax.
+ it('does NOT infer local from a bare org/repo shape', () => {
+ for (const id of ['unsloth/Qwen3-30B', 'cohere/command-r', 'meta-llama/Llama-3-70B', 'mistralai/Mistral-Large']) {
+ expect(isFreeModelId(id)).toBe(false);
+ }
});
it('does NOT treat hosted model ids as local', () => {
diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.js
index c37231197f..d9ffea1b6c 100644
--- a/server/lib/providerTranscriptUsage.js
+++ b/server/lib/providerTranscriptUsage.js
@@ -60,6 +60,14 @@ function parseJsonLines(text) {
const num = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0);
+/**
+ * `byModel` key for a billable message whose line names no model. Callers price
+ * from `byModel`, so these tokens need a bucket of their own or they vanish from
+ * the recorded total; a caller that sees this key prices it at the provider's
+ * default rate (`resolveModelRates(providerId, null)`).
+ */
+export const UNKNOWN_MODEL = '(unknown model)';
+
const emptyTotals = () => ({
messages: 0,
tokensIn: 0,
@@ -161,16 +169,20 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null, exclu
totals.cacheWriteTokens += num(usage.cache_creation_input_tokens);
const model = typeof entry.message?.model === 'string' ? entry.message.model : null;
- if (model) {
- modelCounts.set(model, (modelCounts.get(model) || 0) + 1);
- if (!byModel.has(model)) byModel.set(model, emptyTotals());
- const bucket = byModel.get(model);
- bucket.messages += 1;
- bucket.tokensIn += num(usage.input_tokens);
- bucket.tokensOut += num(usage.output_tokens);
- bucket.cacheReadTokens += num(usage.cache_read_input_tokens);
- bucket.cacheWriteTokens += num(usage.cache_creation_input_tokens);
- }
+ if (model) modelCounts.set(model, (modelCounts.get(model) || 0) + 1);
+ // Bucket EVERY billable message, including one whose line carries no
+ // `message.model` — callers price from `byModel`, so leaving an unnamed
+ // message out of it would silently drop its tokens from the recorded total
+ // (measured: 500 output tokens lost on a two-message fixture). The
+ // UNKNOWN_MODEL key keeps them attributable at the provider's default rate.
+ const bucketKey = model ?? UNKNOWN_MODEL;
+ if (!byModel.has(bucketKey)) byModel.set(bucketKey, emptyTotals());
+ const bucket = byModel.get(bucketKey);
+ bucket.messages += 1;
+ bucket.tokensIn += num(usage.input_tokens);
+ bucket.tokensOut += num(usage.output_tokens);
+ bucket.cacheReadTokens += num(usage.cache_read_input_tokens);
+ bucket.cacheWriteTokens += num(usage.cache_creation_input_tokens);
if (typeof entry.timestamp === 'string' && entry.timestamp) {
if (!firstTs || entry.timestamp < firstTs) firstTs = entry.timestamp;
@@ -290,10 +302,14 @@ export function parseCodexRollout(jsonlText, { from = null, to = null } = {}) {
const cachedIn = delta('cached_input_tokens');
const totalIn = delta('input_tokens');
+ const bounded = from != null || to != null;
const totals = {
- // Codex reports no per-message split; a rollout is one recorded exchange
- // when it produced any assistant message.
- messages: messages || 1,
+ // Codex reports no per-message split, so an UNBOUNDED read of a rollout that
+ // produced tokens counts as one exchange. A BOUNDED read must keep a genuine
+ // zero: a rollout whose only `agent_message` predates this run's window has
+ // an in-window token delta but no in-window message, and synthesizing one
+ // there would inflate the message count of every later overlapping run.
+ messages: bounded ? messages : (messages || 1),
// `input_tokens` INCLUDES the cached portion — split it so each tier is
// priced at its own rate instead of billing cache reads as fresh input.
tokensIn: Math.max(0, totalIn - cachedIn),
diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.js
index 502737d347..4f00237926 100644
--- a/server/lib/providerTranscriptUsage.test.js
+++ b/server/lib/providerTranscriptUsage.test.js
@@ -3,7 +3,8 @@ import {
claudeProjectSlug,
parseClaudeTranscript,
parseCodexRollout,
- totalTranscriptTokens
+ totalTranscriptTokens,
+ UNKNOWN_MODEL
} from './providerTranscriptUsage.js';
// Fixtures are hand-authored to match the real formats (verified against a live
@@ -362,3 +363,51 @@ describe('per-model token buckets', () => {
});
});
});
+
+describe('no billable tokens are dropped from byModel', () => {
+ // Callers price from `byModel`, so a billable message whose line carries no
+ // `message.model` must still get a bucket — otherwise its tokens vanish from
+ // the recorded total (measured: 500 output tokens lost on a 2-message file).
+ it('buckets a model-less message under UNKNOWN_MODEL', () => {
+ const noModel = JSON.parse(claudeLine({ id: 'm2', output: 500, cacheRead: 2000, input: 5, cacheWrite: 0 }));
+ delete noModel.message.model;
+ const text = [
+ claudeLine({ id: 'm1', model: 'claude-opus-5', output: 100, cacheRead: 1000, input: 10, cacheWrite: 0 }),
+ JSON.stringify(noModel)
+ ].join('\n');
+
+ const result = parseClaudeTranscript(text);
+ expect(result.byModel[UNKNOWN_MODEL]).toMatchObject({ tokensOut: 500, cacheReadTokens: 2000 });
+ // byModel must account for the whole aggregate — nothing dropped.
+ const sum = (f) => Object.values(result.byModel).reduce((s, b) => s + b[f], 0);
+ expect(sum('tokensOut')).toBe(result.tokensOut);
+ expect(sum('tokensIn')).toBe(result.tokensIn);
+ expect(sum('cacheReadTokens')).toBe(result.cacheReadTokens);
+ expect(sum('messages')).toBe(result.messages);
+ });
+});
+
+describe('Codex message count under a window', () => {
+ // Synthesizing a message for a bounded read would inflate every later
+ // overlapping run's message total.
+ it('keeps zero when the window contains a token delta but no agent_message', () => {
+ const text = [
+ codexMeta(),
+ JSON.stringify({ timestamp: '2026-07-01T09:00:00.000Z', type: 'event_msg', payload: { type: 'agent_message', message: 'before the window' } }),
+ codexTokenCount({ timestamp: '2026-07-01T09:00:01.000Z', input: 1000, cached: 800, output: 100 }),
+ codexTokenCount({ timestamp: '2026-07-01T12:00:00.000Z', input: 3000, cached: 2400, output: 250 })
+ ].join('\n');
+
+ const result = parseCodexRollout(text, { from: Date.parse('2026-07-01T11:00:00.000Z') });
+ expect(result.messages).toBe(0);
+ expect(result.tokensOut).toBe(150); // the delta is still billed
+ });
+
+ it('still synthesizes one on an unbounded read that produced tokens', () => {
+ const text = [
+ codexMeta(),
+ codexTokenCount({ timestamp: '2026-07-01T10:00:01.000Z', input: 1000, cached: 0, output: 60 })
+ ].join('\n');
+ expect(parseCodexRollout(text).messages).toBe(1);
+ });
+});
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index 263088dfcc..568acae493 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -30,7 +30,9 @@ import { join } from 'path';
import { readdir } from 'fs/promises';
import { tryReadFile } from '../lib/fileUtils.js';
import { estimateTokens, estimateTokensFromChars } from '../lib/contextBudget.js';
+import { isFreeModelId, resolveModelRates } from '../lib/modelPricing.js';
import {
+ UNKNOWN_MODEL,
claudeProjectSlug,
parseClaudeTranscript,
parseCodexRollout,
@@ -59,9 +61,16 @@ const WINDOW_SLACK_MS = 60_000;
// but a run that already completed is never reconciled again.
const claimedMessages = new Set();
+// Highest cumulative boundary (epoch ms of the billed end snapshot) already
+// charged per Codex rollout path. Codex bills as a cumulative delta, so a
+// per-snapshot claim can't stop a GROWN rollout from re-including an earlier
+// run's tokens — only a high-water mark can.
+const codexHighWater = new Map();
+
/** Test-only: forget every claim so suites start from a clean ledger. */
export function __resetUsageClaims() {
claimedMessages.clear();
+ codexHighWater.clear();
}
// A run is attributed only to transcripts whose cwd matches. A CoS agent works
@@ -78,6 +87,34 @@ const cwdMatches = (transcriptCwd, workspacePath) => {
const CLAUDE_ID = /claude/i;
const CODEX_ID = /codex/i;
+/**
+ * Which model id to record for a measured bucket.
+ *
+ * PortOS's own id is preferable when the two AGREE, because it carries the
+ * provider's shape (a Bedrock prefix, a `[1m]` suffix) that the transcript
+ * strips but the pricing table resolves. It must NOT win when they disagree:
+ * a run launched as `claude-opus-5` that actually fell back to a local
+ * `qwen3.6:35b` would otherwise be priced at Opus rates instead of $0.
+ *
+ * "Agree" is tested by resolving both through the rate table — that treats
+ * `global.anthropic.claude-opus-5[1m]` and `claude-opus-5` as the same model
+ * (both resolve to `claude-opus-5`) while catching a genuine substitution.
+ * A bucket with no model name at all resolves to null so the caller prices it
+ * at the provider default.
+ */
+function attributedModel(recordedModel, transcriptModel, singleModel) {
+ const fromTranscript = transcriptModel === UNKNOWN_MODEL ? null : transcriptModel;
+ if (!singleModel || !recordedModel) return fromTranscript;
+ if (!fromTranscript) return recordedModel;
+ if (recordedModel === fromTranscript) return recordedModel;
+ // A local model can never be an alias of a hosted one — always trust the
+ // transcript there, or free inference gets billed at the launch model's rate.
+ if (isFreeModelId(fromTranscript) !== isFreeModelId(recordedModel)) return fromTranscript;
+ const sameFamily = resolveModelRates(null, recordedModel).rateModel
+ === resolveModelRates(null, fromTranscript).rateModel;
+ return sameFamily ? recordedModel : fromTranscript;
+}
+
/**
* Which transcript family a provider writes, or null for providers that write
@@ -195,9 +232,11 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
}
};
- // Keys counted by THIS call, claimed only once the whole read succeeds — so a
- // mid-read failure can't strand messages as billed-to-nobody.
- const toClaim = [];
+ // Keys reserved by THIS call, so a failed/empty read can release them.
+ const reserved = [];
+ // Codex high-water marks advanced by this call, as [path, previousValue], so
+ // an empty read restores the prior boundary instead of stranding it.
+ const codexReserved = [];
// Per-file view of the global ledger: a message key is only meaningful within
// its own transcript, so scope the claim by file path to avoid a same-id
// collision across two different sessions.
@@ -207,8 +246,26 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
has: (messageKey) => claimedMessages.has(prefix + messageKey)
};
};
- const claimFrom = (fileKey, parsed) => {
- for (const key of parsed.countedKeys || []) toClaim.push(`${fileKey}:${key}`);
+ // Reserve IMMEDIATELY after each file is parsed, before the next `await`.
+ // Deferring every claim to the end of the read would reopen the race the
+ // ledger exists to close: this function awaits once per file, so two
+ // overlapping runs could both parse file A, both see it unclaimed, and both
+ // bill it. Reserving synchronously per file means the second run's read of
+ // file A already sees the first run's claim.
+ const reserveFrom = (fileKey, parsed) => {
+ for (const key of parsed.countedKeys || []) {
+ const claimKey = `${fileKey}:${key}`;
+ claimedMessages.add(claimKey);
+ reserved.push(claimKey);
+ }
+ };
+ // Nothing was attributable after all — release so a later run can claim it.
+ const releaseReserved = () => {
+ for (const key of reserved) claimedMessages.delete(key);
+ for (const [path, previous] of codexReserved) {
+ if (previous == null) codexHighWater.delete(path);
+ else codexHighWater.set(path, previous);
+ }
};
if (family === 'claude') {
@@ -221,7 +278,7 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
const text = await tryReadFile(path);
if (!text) continue;
const parsed = parseClaudeTranscript(text, { from, to, exclude: excludeFor(path) });
- claimFrom(path, parsed);
+ reserveFrom(path, parsed);
fold(parsed);
}
} else {
@@ -232,22 +289,39 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
const path = join(dir, file);
const text = await tryReadFile(path);
if (!text) continue;
+ // A Codex rollout bills as a cumulative DELTA, so a timestamp claim is
+ // not enough: a rollout that GROWS between two overlapping runs presents
+ // a later snapshot under a different key, and its delta (measured from a
+ // baseline before both runs) re-includes what the first run already
+ // billed. Track the highest cumulative boundary billed per file and
+ // re-parse from there, so each run charges only the genuinely new part.
+ const billedTo = codexHighWater.get(path);
+ // Start strictly AFTER the billed boundary: the window is inclusive, so
+ // passing `billedTo` itself would make the already-billed snapshot the
+ // window's end state instead of its baseline, and its whole cumulative
+ // total would be charged again.
+ const windowFrom = billedTo != null ? Math.max(from ?? 0, billedTo + 1) : from;
// Rollouts are filed by date, not cwd — confirm the cwd before folding.
- const parsed = parseCodexRollout(text, { from, to });
+ const parsed = parseCodexRollout(text, { from: windowFrom, to });
if (!cwdMatches(parsed.cwd, workspacePath)) continue;
- // A Codex rollout is billed as a cumulative DELTA, so its claim is the
- // end snapshot it consumed: a second overlapping run that reads the same
- // rollout must not re-bill the same delta.
- const snapshotKey = `${path}:${parsed.lastTs || ''}`;
- if (claimedMessages.has(snapshotKey)) continue;
- toClaim.push(snapshotKey);
+ if (totalTranscriptTokens(parsed) === 0) continue;
+ const boundary = Date.parse(parsed.lastTs || '');
+ if (Number.isNaN(boundary)) continue;
+ if (billedTo != null && boundary <= billedTo) continue;
+ // Advance the high-water mark before the next `await`, for the same
+ // reason the Claude claim reserves per file: two overlapping runs must
+ // not both read the pre-update boundary.
+ codexHighWater.set(path, boundary);
+ codexReserved.push([path, billedTo]);
fold(parsed);
}
}
}
- if (totals.sessions === 0) return null;
- for (const key of toClaim) claimedMessages.add(key);
+ if (totals.sessions === 0) {
+ releaseReserved();
+ return null;
+ }
totals.model = [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
totals.byModel = Object.fromEntries(byModel);
return totals;
@@ -310,10 +384,7 @@ export async function reconcileRunUsage(run, estimate, { home = homedir() } = {}
if (perModel.length > 0) {
return perModel.map(([model, bucket]) => ({
providerId: run?.providerId ?? null,
- // Keep PortOS's recorded model id when the transcript agrees on the single
- // model it ran — PortOS's id carries the provider's own shape (e.g. a
- // Bedrock prefix the pricing table resolves) that the transcript strips.
- model: perModel.length === 1 ? (run?.model ?? model) : model,
+ model: attributedModel(run?.model ?? null, model, perModel.length === 1),
messages: bucket.messages || 0,
tokensIn: bucket.tokensIn,
tokensOut: bucket.tokensOut,
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index 901995aea0..ce71388dac 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -447,3 +447,136 @@ describe('overlapping runs must not double-bill one transcript', () => {
expect(second).toBeNull();
});
});
+
+describe('claim ledger — concurrency and cumulative rollouts', () => {
+ const runA = {
+ providerId: 'claude-code-tui',
+ model: 'claude-opus-5',
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z'
+ };
+ const runB = { ...runA, startTime: '2026-07-01T10:02:00.000Z', endTime: '2026-07-01T10:12:00.000Z' };
+
+ // The reads interleave at every `await` (one per transcript file), so a ledger
+ // that only claims AFTER the whole read finishes lets both runs bill the same
+ // messages. Reserving per file closes that window.
+ it('bills each message once when two overlapping reads run CONCURRENTLY', async () => {
+ // Several files, so each read awaits more than once and truly interleaves.
+ await writeClaudeSession('a.jsonl', [claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', output: 50, cacheRead: 0, cacheWrite: 0, input: 0 })]);
+ await writeClaudeSession('b.jsonl', [claudeAssistant({ id: 'm2', timestamp: '2026-07-01T10:06:00.000Z', output: 25, cacheRead: 0, cacheWrite: 0, input: 0 })]);
+ await writeClaudeSession('c.jsonl', [claudeAssistant({ id: 'm3', timestamp: '2026-07-01T10:07:00.000Z', output: 10, cacheRead: 0, cacheWrite: 0, input: 0 })]);
+
+ const [first, second] = await Promise.all([
+ readMeasuredUsage({ ...runA, family: 'claude', home }),
+ readMeasuredUsage({ ...runB, family: 'claude', home })
+ ]);
+
+ const billed = (first?.tokensOut || 0) + (second?.tokensOut || 0);
+ expect(billed).toBe(85); // the transcript total, NOT 170
+ });
+
+ // A Codex rollout bills as a cumulative delta. If it GROWS between two runs,
+ // a per-snapshot claim doesn't help: the later snapshot has a different key and
+ // its delta re-includes the first run's tokens.
+ it('bills only the new part of a rollout that grew between two runs', async () => {
+ const rollout = (entries) => [
+ JSON.stringify({ timestamp: '2026-07-01T10:00:00.000Z', type: 'session_meta', payload: { id: 'rollout-1', cwd: WORKSPACE, model: 'gpt-5.3-codex' } }),
+ ...entries
+ ].join('\n');
+ const snap = (timestamp, input, cached, output) => JSON.stringify({
+ timestamp, type: 'event_msg',
+ payload: { type: 'token_count', info: { total_token_usage: { input_tokens: input, cached_input_tokens: cached, output_tokens: output, total_tokens: input + output } } }
+ });
+
+ // First run sees cumulative output 100.
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ snap('2026-07-01T10:05:00.000Z', 1000, 0, 100)
+ ]));
+ const first = await readMeasuredUsage({ ...runA, family: 'codex', home });
+ expect(first.tokensOut).toBe(100);
+
+ // The rollout grows to cumulative 250 before the second (overlapping) run.
+ await writeCodexRollout(['2026', '07', '01'], 'rollout-1.jsonl', rollout([
+ snap('2026-07-01T10:05:00.000Z', 1000, 0, 100),
+ snap('2026-07-01T10:11:00.000Z', 3000, 0, 250)
+ ]));
+ const second = await readMeasuredUsage({ ...runB, family: 'codex', home });
+
+ // Only the 150 that is genuinely new — not the full 250.
+ expect(second.tokensOut).toBe(150);
+ expect(first.tokensOut + second.tokensOut).toBe(250);
+ });
+
+ it('releases its reservations when nothing was attributable', async () => {
+ // Another repo's session: reserved during the read, then released because
+ // this run folded nothing — so a run that DOES own it can still bill it.
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ], '-work-some-other-repo');
+
+ // This run's own project dir is empty, so it folds nothing and returns null.
+ const miss = await readMeasuredUsage({ ...runA, family: 'claude', home });
+ expect(miss).toBeNull();
+
+ // The repo that actually owns that session still bills it — proving the
+ // failed read released whatever it had reserved instead of stranding it.
+ const real = await readMeasuredUsage({
+ workspacePath: '/work/some-other-repo',
+ startTime: runA.startTime, endTime: runA.endTime, family: 'claude', home
+ });
+ expect(real?.tokensOut).toBe(50);
+
+ // …and a SECOND read by the true owner is now correctly blocked (claimed).
+ expect(await readMeasuredUsage({
+ workspacePath: '/work/some-other-repo',
+ startTime: runA.startTime, endTime: runA.endTime, family: 'claude', home
+ })).toBeNull();
+ });
+});
+
+describe('model attribution when the transcript disagrees', () => {
+ const run = {
+ providerId: 'claude-code-tui-bedrock',
+ model: 'global.anthropic.claude-opus-5[1m]',
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z'
+ };
+
+ it('keeps the recorded Bedrock id when it resolves to the same model', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'claude-opus-5' })
+ ]);
+ const [record] = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ // The Bedrock prefix/suffix carries provider shape the transcript strips.
+ expect(record.model).toBe('global.anthropic.claude-opus-5[1m]');
+ });
+
+ // A run launched as Opus that actually fell back to a local model must NOT be
+ // billed at Opus rates.
+ it('prefers the transcript when the run fell back to a local model', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'qwen3.6:35b' })
+ ]);
+ const [record] = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.model).toBe('qwen3.6:35b');
+ });
+
+ it('prefers the transcript when it names a different hosted model', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z', model: 'claude-haiku-4-5' })
+ ]);
+ const [record] = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.model).toBe('claude-haiku-4-5');
+ });
+
+ it('falls back to the recorded model for a model-less transcript bucket', async () => {
+ const noModel = JSON.parse(claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' }));
+ delete noModel.message.model;
+ await writeClaudeSession('a.jsonl', [JSON.stringify(noModel)]);
+ const [record] = await reconcileRunUsage(run, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.model).toBe('global.anthropic.claude-opus-5[1m]');
+ expect(record.tokensOut).toBe(50);
+ });
+});