diff --git a/docs/architecture.md b/docs/architecture.md index b39b5077..8af507b0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -137,7 +137,7 @@ Three caches under `~/.cache/codeburn/` (override with `CODEBURN_CACHE_DIR`): | File | Owner | Invalidation | |---|---|---| | `codex-results.v.json` | `src/codex-cache.ts` | `mtimeMs + sizeBytes` per Codex `.jsonl`. Unsuffixed `codex-results.json` is adopted when versions match and never overwritten. | -| `cursor-results.v.json` | `src/cursor-cache.ts` | `mtimeMs + sizeBytes` of the Cursor SQLite db. Unsuffixed `cursor-results.json` is adopted when versions match and never overwritten. | +| `cursor-results.v.json` | `src/cursor-cache.ts` | Resolved database path plus combined modification time and size of the Cursor SQLite db and its WAL, when present. Unsuffixed `cursor-results.json` is adopted when versions match and never overwritten. | | `daily-cache.json` | `src/daily-cache.ts` | Tracks `lastComputedDate`; new days are backfilled, old days are reused. | All three use atomic write (temp file + `rename`) and write with mode `0o600`. All three carry a numeric `version` field; bumping it forces a recompute next run. diff --git a/docs/providers/copilot.md b/docs/providers/copilot.md index 80b309bc..1df26bef 100644 --- a/docs/providers/copilot.md +++ b/docs/providers/copilot.md @@ -13,6 +13,8 @@ sections). OTel is preferred when present; chatSessions are only discovered when source is found. Other discovered sources are walked on every run; results merge and dedupe. +VS Code, VS Code Insiders and VSCodium storage roots honor `APPDATA` on Windows and `XDG_CONFIG_HOME` on Linux. Unset or empty values fall back to `AppData/Roaming` under the home directory and `~/.config`, respectively; macOS keeps `~/Library/Application Support`. Workspace journals, global journals and OTel databases share these platform defaults. `CODEBURN_COPILOT_WS_STORAGE_DIR` and `CODEBURN_COPILOT_GLOBAL_STORAGE_DIR` override journal locations; `CODEBURN_COPILOT_OTEL_DB` selects the OTel database directly. New roots are discovered without invalidating Copilot's durable cached history from the previous location. + 1. **Legacy CLI sessions:** `~/.copilot/session-state/` 2. **VS Code core chat sessions:** `~/Library/Application Support/Code/User/workspaceStorage//chatSessions/*.jsonl` plus `~/Library/Application Support/Code/User/globalStorage/emptyWindowChatSessions/*.jsonl` and equivalents on Windows / Linux. Sessions saved by VS Code before 1.109 (February 2026) sit beside them as flat `*.json` files; VS Code keeps the flat file when it migrates a session to the journal, so both formats of one session dedupe on the same `copilot-chatsession:` key. 3. **VS Code transcripts:** `~/Library/Application Support/Code/User/workspaceStorage//GitHub.copilot-chat/transcripts/` and equivalents on Windows / Linux diff --git a/docs/providers/cursor.md b/docs/providers/cursor.md index 6c889bae..0b26bf96 100644 --- a/docs/providers/cursor.md +++ b/docs/providers/cursor.md @@ -14,7 +14,11 @@ A single SQLite database per platform: |---|---| | macOS | `~/Library/Application Support/Cursor/User/globalStorage/state.vscdb` | | Windows | `%APPDATA%/Cursor/User/globalStorage/state.vscdb` | -| Linux | `~/.config/Cursor/User/globalStorage/state.vscdb` | +| Linux | `$XDG_CONFIG_HOME/Cursor/User/globalStorage/state.vscdb`, falling back to `~/.config/Cursor/User/globalStorage/state.vscdb` | + +Windows honors `APPDATA`, falling back to `AppData/Roaming` under the home directory when it is unset or empty. Workspace mappings come from the database's sibling `workspaceStorage` folder, so they follow the same redirected root. Explicit database overrides take precedence. Changes to `APPDATA` or `XDG_CONFIG_HOME` invalidate Cursor's session-cache fingerprint. + +The result cache also checks the resolved database path, so a different data root cannot reuse the previous database's calls just because its size and modification time match. The daily-cache migration backfills historical usage found under corrected editor roots. ## Storage format @@ -27,7 +31,7 @@ The parser tries both and dedupes via `seenKeys`. ## Caching -`src/cursor-cache.ts` writes `~/.cache/codeburn/cursor-results.v.json` (override with `$CODEBURN_CACHE_DIR`). The unsuffixed `cursor-results.json` is left for older binaries; a matching-version copy is adopted once and never overwritten. The fingerprint is `dbMtimeMs + dbSizeBytes` of `state.vscdb`. Atomic write via temp + rename. +`src/cursor-cache.ts` writes `~/.cache/codeburn/cursor-results.v.json` (override with `$CODEBURN_CACHE_DIR`). The unsuffixed `cursor-results.json` is left for older binaries; a matching-version copy is adopted once and never overwritten. Cache identity includes the resolved database path and the combined modification time and size of `state.vscdb` and its WAL, when present. Atomic write via temp + rename. ## Deduplication diff --git a/src/cursor-cache.ts b/src/cursor-cache.ts index 6b886a8b..6c902d76 100644 --- a/src/cursor-cache.ts +++ b/src/cursor-cache.ts @@ -1,5 +1,5 @@ import { readFile, writeFile, mkdir, rename, stat, unlink } from 'fs/promises' -import { join } from 'path' +import { join, resolve } from 'path' import { randomBytes } from 'crypto' import { getCodeburnCacheDir, readExistingTextFile } from './cache-dir.js' @@ -19,7 +19,9 @@ import type { ParsedProviderCall } from './providers/types.js' // (cursor:composer-input:) with per-conversation source selection, the // agent stream regained tool/system context and stream-only sessions, and // tool names are canonicalized. v5 results mix crediting regimes. -export const CURSOR_CACHE_VERSION = 6 +// Version 7: a redirected data root can select a different database whose +// size and timestamps happen to match. Cache identity includes its path. +export const CURSOR_CACHE_VERSION = 7 export const CURSOR_LEGACY_CACHE_FILE = 'cursor-results.json' export function cursorCacheFileName(version = CURSOR_CACHE_VERSION): string { return `cursor-results.v${version}.json` @@ -27,6 +29,7 @@ export function cursorCacheFileName(version = CURSOR_CACHE_VERSION): string { type ResultCache = { version?: number + dbPath: string dbMtimeMs: number dbSizeBytes: number lookbackFloor: string @@ -41,9 +44,10 @@ function getLegacyCachePath(): string { return join(getCodeburnCacheDir(), CURSOR_LEGACY_CACHE_FILE) } -function isCurrentHit(cache: ResultCache, fp: { mtimeMs: number; size: number }, requestedFloor: string): boolean { +function isCurrentHit(cache: ResultCache, dbPath: string, fp: { mtimeMs: number; size: number }, requestedFloor: string): boolean { return ( cache.version === CURSOR_CACHE_VERSION + && cache.dbPath === resolve(dbPath) && cache.dbMtimeMs === fp.mtimeMs && cache.dbSizeBytes === fp.size && typeof cache.lookbackFloor === 'string' @@ -93,7 +97,7 @@ export async function readCachedResults( if (versioned.status === 'ok') { try { const cache = JSON.parse(versioned.text) as ResultCache - if (cache && typeof cache === 'object' && isCurrentHit(cache, fp, requestedFloor)) return cache.calls + if (cache && typeof cache === 'object' && isCurrentHit(cache, dbPath, fp, requestedFloor)) return cache.calls } catch {} return null } @@ -102,7 +106,7 @@ export async function readCachedResults( // Versioned file is absent (ENOENT). Adopt the unsuffixed file only when its // version and fingerprint match — old binaries still own that path. const legacy = await readCacheFile(getLegacyCachePath()) - if (legacy && isCurrentHit(legacy, fp, requestedFloor)) return legacy.calls + if (legacy && isCurrentHit(legacy, dbPath, fp, requestedFloor)) return legacy.calls return null } catch { return null @@ -125,6 +129,7 @@ export async function writeCachedResults( await mkdir(dir, { recursive: true }).catch(() => {}) const cache: ResultCache = { version: CURSOR_CACHE_VERSION, + dbPath: resolve(dbPath), dbMtimeMs: fp.mtimeMs, dbSizeBytes: fp.size, lookbackFloor, diff --git a/src/daily-cache.ts b/src/daily-cache.ts index 0aa11929..2d8bc156 100644 --- a/src/daily-cache.ts +++ b/src/daily-cache.ts @@ -254,7 +254,9 @@ import type { DateRange, ProjectSummary } from './types.js' // needed. // v50: Hermes uses its native Windows LOCALAPPDATA root; finalized days can // miss sessions there and must be re-derived after the default path is fixed. -export const DAILY_CACHE_VERSION = 50 +// v51: honor redirected Copilot and Cursor editor data roots. Backfill settled +// days that previously missed usage stored under APPDATA or XDG_CONFIG_HOME. +export const DAILY_CACHE_VERSION = 51 const MIN_SUPPORTED_VERSION = 28 /// Providers whose per-day CALL COUNT means something different at diff --git a/src/editor-data-dir.ts b/src/editor-data-dir.ts new file mode 100644 index 00000000..acf68268 --- /dev/null +++ b/src/editor-data-dir.ts @@ -0,0 +1,10 @@ +import { posix, win32 } from 'node:path' + +/** Default Electron editor data directory, honoring the OS's redirected root. */ +export function getEditorDataDir(editor: string, home: string, os: string): string { + if (os === 'darwin') return posix.join(home, 'Library', 'Application Support', editor) + if (os === 'win32') { + return win32.join(process.env['APPDATA'] || win32.join(home, 'AppData', 'Roaming'), editor) + } + return posix.join(process.env['XDG_CONFIG_HOME'] || posix.join(home, '.config'), editor) +} diff --git a/src/providers/copilot.ts b/src/providers/copilot.ts index c11230d6..7117faac 100644 --- a/src/providers/copilot.ts +++ b/src/providers/copilot.ts @@ -62,6 +62,7 @@ import { readdir, stat } from 'fs/promises' import { homedir, platform } from 'os' import { join, basename, dirname, posix, win32 } from 'path' import { existsSync } from 'fs' +import { getEditorDataDir } from '../editor-data-dir.js' import { createHash } from 'crypto' import { readSessionFile } from '../fs-utils.js' import { calculateCost, modelKeyMatches } from '../models.js' @@ -942,33 +943,8 @@ function getAgentTracesDbPath(): string | null { return existsSync(envOverride) ? envOverride : null } - const home = homedir() - const candidates: string[] = [] - - const p = platform() - if (p === 'darwin') { - // macOS: VS Code, VS Code Insiders, VSCodium - candidates.push( - join(home, 'Library', 'Application Support', 'Code', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(home, 'Library', 'Application Support', 'Code - Insiders', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(home, 'Library', 'Application Support', 'VSCodium', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - ) - } else if (p === 'linux') { - // Linux: VS Code, VS Code Insiders, VSCodium - candidates.push( - join(home, '.config', 'Code', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(home, '.config', 'Code - Insiders', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(home, '.config', 'VSCodium', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - ) - } else if (p === 'win32') { - // Windows - const appdata = process.env['APPDATA'] ?? join(home, 'AppData', 'Roaming') - candidates.push( - join(appdata, 'Code', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(appdata, 'Code - Insiders', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - join(appdata, 'VSCodium', 'User', 'globalStorage', 'github.copilot-chat', 'agent-traces.db'), - ) - } + const candidates = getVSCodeGlobalStorageDirs(homedir(), platform()) + .map(dir => join(dir, 'github.copilot-chat', 'agent-traces.db')) for (const candidate of candidates) { if (existsSync(candidate)) return candidate @@ -3392,54 +3368,19 @@ async function resolveJetBrainsProjectNames( * (Code, Code Insiders, VSCodium) on the given platform. Used to discover * transcript sessions written by the Copilot Chat extension. * - * Accepts explicit `home` and `os` arguments so callers (and tests) can pass - * custom values without relying on process-level globals. + * Accepts explicit `home` and `os` arguments for the platform fallback. + * APPDATA and XDG_CONFIG_HOME still come from the process environment. */ export function getVSCodeWorkspaceStorageDirs(home: string, os: string): string[] { const j = os === 'win32' ? win32.join : posix.join - if (os === 'darwin') { - return [ - j(home, 'Library', 'Application Support', 'Code', 'User', 'workspaceStorage'), - j(home, 'Library', 'Application Support', 'Code - Insiders', 'User', 'workspaceStorage'), - j(home, 'Library', 'Application Support', 'VSCodium', 'User', 'workspaceStorage'), - ] - } - if (os === 'linux') { - return [ - j(home, '.config', 'Code', 'User', 'workspaceStorage'), - j(home, '.config', 'Code - Insiders', 'User', 'workspaceStorage'), - j(home, '.config', 'VSCodium', 'User', 'workspaceStorage'), - ] - } - // win32 - return [ - j(home, 'AppData', 'Roaming', 'Code', 'User', 'workspaceStorage'), - j(home, 'AppData', 'Roaming', 'Code - Insiders', 'User', 'workspaceStorage'), - j(home, 'AppData', 'Roaming', 'VSCodium', 'User', 'workspaceStorage'), - ] + return ['Code', 'Code - Insiders', 'VSCodium'] + .map(editor => j(getEditorDataDir(editor, home, os), 'User', 'workspaceStorage')) } export function getVSCodeGlobalStorageDirs(home: string, os: string): string[] { const j = os === 'win32' ? win32.join : posix.join - if (os === 'darwin') { - return [ - j(home, 'Library', 'Application Support', 'Code', 'User', 'globalStorage'), - j(home, 'Library', 'Application Support', 'Code - Insiders', 'User', 'globalStorage'), - j(home, 'Library', 'Application Support', 'VSCodium', 'User', 'globalStorage'), - ] - } - if (os === 'linux') { - return [ - j(home, '.config', 'Code', 'User', 'globalStorage'), - j(home, '.config', 'Code - Insiders', 'User', 'globalStorage'), - j(home, '.config', 'VSCodium', 'User', 'globalStorage'), - ] - } - return [ - j(home, 'AppData', 'Roaming', 'Code', 'User', 'globalStorage'), - j(home, 'AppData', 'Roaming', 'Code - Insiders', 'User', 'globalStorage'), - j(home, 'AppData', 'Roaming', 'VSCodium', 'User', 'globalStorage'), - ] + return ['Code', 'Code - Insiders', 'VSCodium'] + .map(editor => j(getEditorDataDir(editor, home, os), 'User', 'globalStorage')) } // workspace.json holds `folder` (single root) or `workspace` (a multi-root diff --git a/src/providers/cursor.ts b/src/providers/cursor.ts index 6e079726..2a8900bb 100644 --- a/src/providers/cursor.ts +++ b/src/providers/cursor.ts @@ -1,6 +1,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'fs' import { join } from 'path' import { homedir } from 'os' +import { getEditorDataDir } from '../editor-data-dir.js' import { calculateCost } from '../models.js' import { extractBashCommands } from '../bash-utils.js' @@ -86,13 +87,7 @@ function rethrowBusy(err: unknown): void { } function getCursorDbPath(): string { - if (process.platform === 'darwin') { - return join(homedir(), 'Library', 'Application Support', 'Cursor', 'User', 'globalStorage', 'state.vscdb') - } - if (process.platform === 'win32') { - return join(homedir(), 'AppData', 'Roaming', 'Cursor', 'User', 'globalStorage', 'state.vscdb') - } - return join(homedir(), '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb') + return join(getEditorDataDir('Cursor', homedir(), process.platform), 'User', 'globalStorage', 'state.vscdb') } function getCursorWorkspaceStorageDir(globalDbPath: string): string { diff --git a/src/session-cache.ts b/src/session-cache.ts index f6f033fa..fb482a61 100644 --- a/src/session-cache.ts +++ b/src/session-cache.ts @@ -305,7 +305,7 @@ export const PROVIDER_ENV_VARS: Record = { 'lingtai-tui': ['LINGTAI_HOME', 'LINGTAI_TUI_HOME', 'LINGTAI_TUI_GLOBAL_DIR'], droid: ['FACTORY_DIR'], dsh: ['DSH_HOME'], - cursor: ['CODEBURN_CURSOR_MAX_BUBBLES'], + cursor: ['CODEBURN_CURSOR_MAX_BUBBLES', 'APPDATA', 'XDG_CONFIG_HOME'], // XDG_DATA_HOME is stale here (cursor-agent never reads it) but deliberately // kept: removing it would force a re-parse to fix nothing. 'cursor-agent': ['XDG_DATA_HOME'], diff --git a/tests/editor-data-paths.test.ts b/tests/editor-data-paths.test.ts new file mode 100644 index 00000000..d8c27433 --- /dev/null +++ b/tests/editor-data-paths.test.ts @@ -0,0 +1,141 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join, posix, win32 } from 'node:path' +import { tmpdir } from 'node:os' +import * as os from 'os' +import { createRequire } from 'node:module' +import { createCopilotProvider, getVSCodeGlobalStorageDirs, getVSCodeWorkspaceStorageDirs } from '../src/providers/copilot.js' +import { clearCursorWorkspaceMapCache, createCursorProvider } from '../src/providers/cursor.js' +import { computeEnvFingerprint } from '../src/session-cache.js' +import { isSqliteAvailable } from '../src/sqlite.js' + +const requireForTest = createRequire(import.meta.url) +vi.mock('os', async importOriginal => { + const actual = await importOriginal() + return { ...actual, platform: vi.fn(actual.platform) } +}) +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'codeburn-editor-roots-')) + vi.stubEnv('APPDATA', root) + vi.stubEnv('XDG_CONFIG_HOME', root) + vi.stubEnv('CODEBURN_COPILOT_DISABLE_OTEL', '1') + clearCursorWorkspaceMapCache() +}) + +afterEach(async () => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + clearCursorWorkspaceMapCache() + await rm(root, { recursive: true, force: true }) +}) + +describe('redirected editor data paths', () => { + it.each([ + ['win32', 'C:\\Users\\fixture', 'D:\\redirected-roaming', win32.join], + ['linux', '/home/fixture', '/mnt/redirected-config', posix.join], + ] as const)('uses the %s application-data override for every VS Code variant', (os, home, redirected, j) => { + vi.stubEnv(os === 'win32' ? 'APPDATA' : 'XDG_CONFIG_HOME', redirected) + for (const [getDirs, storage] of [ + [getVSCodeWorkspaceStorageDirs, 'workspaceStorage'], + [getVSCodeGlobalStorageDirs, 'globalStorage'], + ] as const) { + expect(getDirs(home, os)).toEqual(['Code', 'Code - Insiders', 'VSCodium'].map(editor => j(redirected, editor, 'User', storage))) + } + }) + + it.each([undefined, ''])('keeps platform defaults for absent or empty overrides (%s)', value => { + vi.stubEnv('APPDATA', value) + vi.stubEnv('XDG_CONFIG_HOME', value) + expect(getVSCodeWorkspaceStorageDirs('C:\\Users\\fixture', 'win32')[0]).toBe(win32.join('C:\\Users\\fixture', 'AppData', 'Roaming', 'Code', 'User', 'workspaceStorage')) + expect(getVSCodeGlobalStorageDirs('/home/fixture', 'linux')[0]).toBe('/home/fixture/.config/Code/User/globalStorage') + }) + + it('keeps macOS paths independent of APPDATA and XDG_CONFIG_HOME', () => { + expect(getVSCodeGlobalStorageDirs('/Users/fixture', 'darwin')).toEqual(['Code', 'Code - Insiders', 'VSCodium'].map(editor => posix.join('/Users/fixture', 'Library', 'Application Support', editor, 'User', 'globalStorage'))) + }) + + it.skipIf(process.platform === 'darwin')('discovers Copilot journals and watches both redirected storage folders', async () => { + const workspace = join(root, 'Code', 'User', 'workspaceStorage') + const global = join(root, 'Code', 'User', 'globalStorage') + const wsChats = join(workspace, 'hash', 'chatSessions') + const globalChats = join(global, 'emptyWindowChatSessions') + await mkdir(wsChats, { recursive: true }) + await mkdir(globalChats, { recursive: true }) + await writeFile(join(workspace, 'hash', 'workspace.json'), JSON.stringify({ folder: 'file:///work/redirected' })) + const journal = JSON.stringify({ kind: 0, v: { sessionId: 'redirected', requests: [] } }) + '\n' + const wsPath = join(wsChats, 'workspace.jsonl') + const globalPath = join(globalChats, 'empty.jsonl') + await writeFile(wsPath, journal) + await writeFile(globalPath, journal) + const provider = createCopilotProvider(join(root, 'no-cli'), undefined, undefined, join(root, 'no-jb'), join(root, 'no-store')) + expect((await provider.discoverSessions()).map(s => s.path).sort()).toEqual([wsPath, globalPath].sort()) + expect((await provider.probeRoots!()).map(r => r.path)).toEqual(expect.arrayContaining([workspace, global])) + }) + + it.skipIf(process.platform === 'darwin' || !isSqliteAvailable())('discovers the redirected Cursor database and its sibling workspace mapping', async () => { + const { DatabaseSync } = requireForTest('node:sqlite') as typeof import('node:sqlite') + const global = join(root, 'Cursor', 'User', 'globalStorage') + const workspace = join(root, 'Cursor', 'User', 'workspaceStorage', 'hash') + await mkdir(global, { recursive: true }) + await mkdir(workspace, { recursive: true }) + const dbPath = join(global, 'state.vscdb') + const globalDb = new DatabaseSync(dbPath) + globalDb.exec('CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT)') + globalDb.close() + const workspaceDb = new DatabaseSync(join(workspace, 'state.vscdb')) + workspaceDb.exec('CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT)') + workspaceDb.prepare('INSERT INTO ItemTable VALUES (?, ?)').run('composer.composerData', JSON.stringify({ allComposers: [{ composerId: 'redirected-composer' }] })) + workspaceDb.close() + await writeFile(join(workspace, 'workspace.json'), JSON.stringify({ folder: 'file:///work/redirected' })) + + const provider = createCursorProvider() + expect(await provider.probeRoots!()).toEqual([{ path: dbPath, label: 'db' }]) + expect((await provider.discoverSessions()).map(s => s.project)).toContain('-work-redirected') + }) + + it('keeps constructor storage overrides ahead of application-data defaults', async () => { + const workspace = join(root, 'explicit-ws') + const global = join(root, 'explicit-global') + const provider = createCopilotProvider(join(root, 'no-cli'), workspace, global, join(root, 'no-jb'), join(root, 'no-store')) + const roots = (await provider.probeRoots!()).map(r => r.path) + expect(roots).toEqual(expect.arrayContaining([workspace, global])) + expect(roots).not.toContain(join(root, 'Code', 'User', 'workspaceStorage')) + expect(await createCursorProvider(join(root, 'explicit.vscdb')).probeRoots!()).toEqual([{ path: join(root, 'explicit.vscdb'), label: 'db' }]) + }) + + it.skipIf(!isSqliteAvailable())('discovers OTel in a redirected Linux global-storage root', async () => { + vi.stubEnv('APPDATA', join(root, 'unused-windows-root')) + const { DatabaseSync } = requireForTest('node:sqlite') as typeof import('node:sqlite') + // posix.join can operate on this temporary Windows path too: Node's fs + // accepts its forward slashes, so Linux discovery is exercised on any host. + const global = getVSCodeGlobalStorageDirs(root, 'linux')[0]! + const otelDir = posix.join(global, 'github.copilot-chat') + const dbPath = posix.join(otelDir, 'agent-traces.db') + await mkdir(otelDir, { recursive: true }) + const db = new DatabaseSync(dbPath) + db.exec(` + CREATE TABLE spans (span_id TEXT PRIMARY KEY, trace_id TEXT, operation_name TEXT, start_time_ms INTEGER, response_model TEXT); + CREATE TABLE span_attributes (id INTEGER PRIMARY KEY, span_id TEXT, key TEXT, value TEXT); + INSERT INTO spans VALUES ('span', 'trace', 'chat', 1780157113020, 'gpt-4o'); + INSERT INTO span_attributes VALUES (1, 'span', 'gen_ai.conversation.id', 'redirected-otel'); + INSERT INTO span_attributes VALUES (2, 'span', 'gen_ai.usage.input_tokens', '100'); + INSERT INTO span_attributes VALUES (3, 'span', 'gen_ai.usage.output_tokens', '20'); + `) + db.close() + vi.spyOn(os, 'platform').mockReturnValue('linux') + vi.stubEnv('CODEBURN_COPILOT_DISABLE_OTEL', '') + const provider = createCopilotProvider(join(root, 'no-cli'), undefined, undefined, join(root, 'no-jb'), join(root, 'no-store')) + expect((await provider.discoverSessions()).map(s => s.path)).toContain(join(dbPath)) + expect((await provider.probeRoots!()).map(r => r.path)).toContain(join(otelDir)) + }) + + it.each(['APPDATA', 'XDG_CONFIG_HOME'])('invalidates Cursor caches on %s changes without discarding durable Copilot history', variable => { + const cursorBefore = computeEnvFingerprint('cursor') + const copilotBefore = computeEnvFingerprint('copilot') + vi.stubEnv(variable, join(root, 'moved')) + expect(computeEnvFingerprint('cursor')).not.toBe(cursorBefore) + expect(computeEnvFingerprint('copilot')).toBe(copilotBefore) + }) +}) diff --git a/tests/editor-discovery-cache.test.ts b/tests/editor-discovery-cache.test.ts new file mode 100644 index 00000000..12659b04 --- /dev/null +++ b/tests/editor-discovery-cache.test.ts @@ -0,0 +1,64 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { clearSessionCache, parseAllSessions } from '../src/parser.js' +import { currentTzKey, ensureCacheHydrated, toDateString } from '../src/daily-cache.js' +import { aggregateProjectsIntoDays } from '../src/day-aggregator.js' +import { calculateCost } from '../src/models.js' + +afterEach(() => { + clearSessionCache() + vi.unstubAllEnvs() +}) + +it.skipIf(process.platform === 'darwin')('backfills redirected editor history in a finalized v50 cache while retaining other providers', async () => { + const root = await mkdtemp(join(tmpdir(), 'editor-discovery-cache-')) + try { + const cache = join(root, 'cache') + vi.stubEnv('CODEBURN_CACHE_DIR', cache) + vi.stubEnv('APPDATA', root) + vi.stubEnv('XDG_CONFIG_HOME', root) + vi.stubEnv('CODEBURN_COPILOT_DISABLE_OTEL', '1') + vi.stubEnv('CODEBURN_COPILOT_SESSION_STATE_DIR', join(root, 'no-cli')) + vi.stubEnv('CODEBURN_COPILOT_SESSION_STORE_DB', join(root, 'no-store')) + vi.stubEnv('CODEBURN_COPILOT_JETBRAINS_DIR', join(root, 'no-jb')) + const chats = join(root, 'Code', 'User', 'globalStorage', 'emptyWindowChatSessions') + await mkdir(chats, { recursive: true }) + const timestamp = new Date(Date.now() - 4 * 86400000).toISOString() + const date = toDateString(new Date(timestamp)) + await writeFile(join(chats, 'redirected.jsonl'), JSON.stringify({ kind: 0, v: { + sessionId: 'redirected', creationDate: Date.parse(timestamp), requests: [{ + requestId: 'r', modelId: 'copilot/gpt-4o', completionTokens: 20, + result: { metadata: { promptTokens: 100 } }, + }], + } }) + '\n') + clearSessionCache() + const parse = () => parseAllSessions(undefined, 'copilot') + const fresh = await parse() + expect(aggregateProjectsIntoDays(fresh)[0]).toMatchObject({ date, calls: 1, inputTokens: 100, outputTokens: 20 }) + + const historical = structuredClone(fresh) + for (const project of historical) for (const session of project.sessions) for (const turn of session.turns) for (const call of turn.assistantCalls) { + call.provider = 'claude' + call.model = 'claude-sonnet-4-6' + call.usage.inputTokens = 50 + call.usage.outputTokens = 10 + call.costUSD = calculateCost(call.model, 50, 10, 0, 0, 0) + } + await mkdir(cache, { recursive: true }) + await writeFile(join(cache, 'daily-cache.v50.json'), JSON.stringify({ + version: 50, savingsConfigHash: '', tzKey: currentTzKey(), + lastComputedDate: toDateString(new Date(Date.now() - 86400000)), + days: aggregateProjectsIntoDays(historical), complete: true, watermarkTrusted: true, + })) + const hydrated = await ensureCacheHydrated(parse, aggregateProjectsIntoDays) + const day = hydrated.days.find(d => d.date === date)! + expect(day).toMatchObject({ calls: 2, inputTokens: 150, outputTokens: 30 }) + expect(day.providers.copilot).toMatchObject({ calls: 1, inputTokens: 100, outputTokens: 20 }) + expect(day.providers.claude).toMatchObject({ calls: 1, inputTokens: 50, outputTokens: 10 }) + } finally { + clearSessionCache() + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/tests/provider-env-declarations.test.ts b/tests/provider-env-declarations.test.ts index 36f337df..310b4cdd 100644 --- a/tests/provider-env-declarations.test.ts +++ b/tests/provider-env-declarations.test.ts @@ -38,7 +38,8 @@ const FILE_PROVIDERS: Record = { 'dsh.ts': ['dsh'], 'hermes.ts': ['hermes'], 'lingtai-tui.ts': ['lingtai-tui'], - // Its only literal read is CODEBURN_CURSOR_MAX_BUBBLES (cursor.ts:692). + // Application-data roots are read by the shared editor-data-dir helper; + // cursor.ts also reads CODEBURN_CURSOR_MAX_BUBBLES directly. 'cursor.ts': ['cursor'], // The ENV_DIR const (open-design.ts:10) resolves to CODEBURN_OPEN_DESIGN_DIR. 'open-design.ts': ['open-design'], @@ -106,7 +107,6 @@ const ALLOWLIST: Record = { 'copilot.ts:CODEBURN_COPILOT_GLOBAL_STORAGE_DIR': COPILOT_DEFERRED, 'copilot.ts:CODEBURN_COPILOT_DISABLE_OTEL': COPILOT_DEFERRED, 'copilot.ts:CODEBURN_COPILOT_SESSION_STORE_DB': COPILOT_STORE_DEFERRED, - 'copilot.ts:APPDATA': COPILOT_DEFERRED, 'copilot.ts:XDG_CONFIG_HOME': COPILOT_DEFERRED, 'copilot.ts:LOCALAPPDATA': COPILOT_DEFERRED, } diff --git a/tests/providers/copilot.test.ts b/tests/providers/copilot.test.ts index 66d156c5..155dde5e 100644 --- a/tests/providers/copilot.test.ts +++ b/tests/providers/copilot.test.ts @@ -1469,6 +1469,8 @@ describe('copilot provider - discoverSessions', () => { }) it('includes VSCodium workspaceStorage paths on all supported platforms', () => { + vi.stubEnv('APPDATA', undefined) + vi.stubEnv('XDG_CONFIG_HOME', undefined) expect(getVSCodeWorkspaceStorageDirs('/Users/test', 'darwin')).toContain( posix.join('/Users/test', 'Library', 'Application Support', 'VSCodium', 'User', 'workspaceStorage'), ) @@ -1481,6 +1483,8 @@ describe('copilot provider - discoverSessions', () => { }) it('includes VSCodium globalStorage paths on all supported platforms', () => { + vi.stubEnv('APPDATA', undefined) + vi.stubEnv('XDG_CONFIG_HOME', undefined) expect(getVSCodeGlobalStorageDirs('/Users/test', 'darwin')).toContain( posix.join('/Users/test', 'Library', 'Application Support', 'VSCodium', 'User', 'globalStorage'), ) diff --git a/tests/result-cache-suffix.test.ts b/tests/result-cache-suffix.test.ts index 4cf7ea97..0d024fea 100644 --- a/tests/result-cache-suffix.test.ts +++ b/tests/result-cache-suffix.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises' +import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from 'fs/promises' import { existsSync } from 'fs' import { tmpdir } from 'os' import { join } from 'path' @@ -173,6 +173,22 @@ describe('unsuffixed result caches coexist with mixed-version binaries', () => { expect(legacy.calls[0].model).toBe('old-binary') }) + it('does not reuse Cursor results for another database with identical size and timestamps', async () => { + const first = join(root, 'first.vscdb') + const second = join(root, 'second.vscdb') + await writeFile(first, 'first-db') + await writeFile(second, 'other-db') + const time = new Date('2026-05-01T00:00:00Z') + await utimes(first, time, time) + await utimes(second, time, time) + expect((await stat(first)).mtimeMs).toBe((await stat(second)).mtimeMs) + expect((await stat(first)).size).toBe((await stat(second)).size) + const floor = '2026-01-01T00:00:00.000Z' + await writeCachedResults(first, [call('cursor', 'first-database')], floor) + expect((await readCachedResults(first, floor))?.map(entry => entry.model)).toEqual(['first-database']) + expect(await readCachedResults(second, floor)).toBeNull() + }) + it('adopts a matching-version unsuffixed Cursor cache and ignores a mismatched one', async () => { const dbPath = join(root, 'state.vscdb') await writeFile(dbPath, 'cursor-db') @@ -182,6 +198,7 @@ describe('unsuffixed result caches coexist with mixed-version binaries', () => { await writeFile(join(root, CURSOR_LEGACY_CACHE_FILE), JSON.stringify({ version: CURSOR_CACHE_VERSION, + dbPath, dbMtimeMs: fp.mtimeMs, dbSizeBytes: fp.size, lookbackFloor: floor,