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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: key unidentified transcript lines by content, not position
[._.]/ Adam Eivy19655fe44d55
diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.jsindex c240c378a2..42da770f90 100644--- a/server/lib/providerTranscriptUsage.js+++ b/server/lib/providerTranscriptUsage.js@@ -68,6 +68,26 @@ const num = (value) => (typeof value === 'number' && Number.isFinite(value) && v*/export const UNKNOWN_MODEL = '(unknown model)';+/**+ * Stable identity for an assistant line that carries NO `message.id` and no+ * `uuid`. Derived from the fields that describe the billable event — its+ * timestamp, request id, model, and token counts — so the key survives any+ * reordering of the file. A POSITIONAL key does not: prepending or inserting a+ * line shifts every index after it, the shifted key reads as unclaimed, and the+ * cross-run double-bill reopens (measured: 100 billed for 70 after a prepend).+ */+function contentKey(entry, usage) {+ return [+ entry.timestamp || '',+ entry.requestId || '',+ entry.message?.model || '',+ num(usage.input_tokens),+ num(usage.output_tokens),+ num(usage.cache_read_input_tokens),+ num(usage.cache_creation_input_tokens)+ ].join('|');+}+const emptyTotals = () => ({messages: 0,tokensIn: 0,@@ -142,12 +162,11 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null, exclulet firstTs = null;let lastTs = null;- // Position of the current line within the file, so a line carrying no- // identifier at all still gets a stable key (see `dedupeKey` below).- let lineIndex = -1;+ // Occurrence counter per content key, so two genuinely distinct lines with+ // identical content still get distinct keys (see `dedupeKey` below).+ const contentSeen = new Map();for (const entry of parseJsonLines(jsonlText)) {- lineIndex += 1;if (!sessionId && typeof entry.sessionId === 'string') sessionId = entry.sessionId;if (!cwd && typeof entry.cwd === 'string') cwd = entry.cwd;@@ -160,11 +179,24 @@ export function parseClaudeTranscript(jsonlText, { from = null, to = null, exclu// One response spans multiple lines with identical usage — count it once.//// EVERY counted line needs a key, including one carrying neither- // `message.id` nor `uuid`: a keyless line is invisible to the cross-run- // claim ledger, so two overlapping runs each bill it (measured: 100 billed- // for 50 reported). Fall back to the line's position, which is stable for an- // append-only transcript — the `@` prefix can't collide with a real id.- const dedupeKey = entry.message?.id || entry.uuid || `@line-${lineIndex}`;+ // `message.id` nor `uuid`: a keyless line is invisible to the cross-run claim+ // ledger, so two overlapping runs each bill it (measured: 100 billed for 50+ // reported). The fallback is derived from the line's CONTENT, not its+ // position: a positional key shifts if anything is ever prepended or+ // inserted, which re-opens the double-bill (measured: 100 billed for 70 after+ // a prepend). Content is stable under any reordering, and the `@` prefix+ // can't collide with a real id. The trailing `#<occurrence>` is only a+ // tiebreaker so two genuinely distinct lines with identical content don't+ // collapse into one — it is not part of the identity.+ let dedupeKey = entry.message?.id || entry.uuid;+ if (!dedupeKey) {+ const content = contentKey(entry, usage);+ // Nth occurrence of this exact content within this file — deterministic and+ // unaffected by lines added elsewhere.+ const occurrence = contentSeen.get(content) ?? 0;+ contentSeen.set(content, occurrence + 1);+ dedupeKey = `@${content}#${occurrence}`;+ }if (seen.has(dedupeKey)) continue;// Already billed to another run whose window also covers this message —// skip it so overlapping runs can't each claim the same tokens.diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.jsindex 07d37fdeec..f9076f8778 100644--- a/server/services/usageReconciler.test.js+++ b/server/services/usageReconciler.test.js@@ -867,3 +867,68 @@ describe('assistant lines carrying no identifier', () => {expect(result.messages).toBe(2);});});++describe('keyless-line claims survive the file changing shape', () => {+ const keyless = (output, ts) => JSON.stringify({+ type: 'assistant',+ cwd: WORKSPACE,+ timestamp: ts,+ message: {+ model: 'claude-opus-5',+ usage: { input_tokens: 1, output_tokens: output, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }+ }+ });+ const read = (startTime, endTime) => readMeasuredUsage({+ workspacePath: WORKSPACE, startTime, endTime, family: 'claude', home+ });+ const A = ['2026-07-01T10:00:00.000Z', '2026-07-01T10:10:00.000Z'];+ const B = ['2026-07-01T10:02:00.000Z', '2026-07-01T10:12:00.000Z'];++ // Regression: a POSITIONAL fallback key shifts when anything is prepended, so+ // the shifted key read as unclaimed and the line was billed twice (measured:+ // 100 billed for 70 reported). A content-derived key is stable.+ it('does not re-bill a keyless line after a line is prepended', async () => {+ await writeClaudeSession('a.jsonl', [keyless(50, '2026-07-01T10:05:00.000Z')]);+ const first = await read(...A);++ // A new line lands BEFORE the existing one, shifting its index.+ await writeClaudeSession('a.jsonl', [+ keyless(20, '2026-07-01T10:04:00.000Z'),+ keyless(50, '2026-07-01T10:05:00.000Z')+ ]);+ const second = await read(...B);++ expect((first?.tokensOut || 0) + (second?.tokensOut || 0)).toBe(70);+ });++ it('does not re-bill after the file is reordered', async () => {+ await writeClaudeSession('a.jsonl', [+ keyless(50, '2026-07-01T10:05:00.000Z'),+ keyless(30, '2026-07-01T10:06:00.000Z')+ ]);+ const first = await read(...A);++ await writeClaudeSession('a.jsonl', [+ keyless(30, '2026-07-01T10:06:00.000Z'),+ keyless(50, '2026-07-01T10:05:00.000Z')+ ]);+ const second = await read(...B);++ expect((first?.tokensOut || 0) + (second?.tokensOut || 0)).toBe(80);+ });++ // The content key must not collapse two genuinely distinct lines that happen+ // to carry identical content.+ it('counts two identical keyless lines separately, once each', async () => {+ await writeClaudeSession('a.jsonl', [+ keyless(50, '2026-07-01T10:05:00.000Z'),+ keyless(50, '2026-07-01T10:05:00.000Z')+ ]);+ const first = await read(...A);+ expect(first.tokensOut).toBe(100);++ // …and an overlapping run re-bills neither.+ const second = await read(...B);+ expect((first?.tokensOut || 0) + (second?.tokensOut || 0)).toBe(100);+ });+});