codeburn/src/providers/opencode.ts
Resham Joshi 3dd1d1c793
feat(doctor): per-provider detection diagnostics (#685)
* feat(doctor): add per-provider detection diagnostics command

When a provider reports zero (or a number that looks wrong) there was no way
to see why: whether the tool is not installed, an env override points at the
wrong directory, the data dir is empty, or parsing failed. Users had to file
issues like "OpenCode does not work" with nothing to go on.

`codeburn doctor` closes that gap. For every provider (or one via --provider)
it shows the exact directories/dbs probed with any env override and whether the
path exists, how many session files were discovered, how many of a bounded
sample parsed cleanly, the cached file count and parser version, and a one-line
verdict: OK (n sessions), NOTHING FOUND with a concrete likely cause, or
ERRORS (n parse failures). Output is a human table by default or --json.

The collect logic is a pure function separated from rendering so tests exercise
it without a TTY. It runs fully offline and read-only (never writes caches or
config, and skips the one network provider's parse), and isolates each provider
in its own try/catch so a single thrower becomes an error row instead of
crashing the report. Providers expose their scan roots via an optional
probeRoots() so the exact paths are shown even when zero sessions are found,
reusing each provider's own path resolution rather than duplicating it.

* fix(doctor): make the inert promise actually true

Adversarial re-review reproduced two false guarantees. Cursor's parser
writes its results cache to disk before its first yield, so a doctor run
created ~/.cache/codeburn/cursor-results.json on a clean machine; the
collect pass now sets CODEBURN_SUPPRESS_CACHE_WRITES (restored after) and
the cursor writer honors it. Antigravity's parse probes for a live
language server (spawns ps and lsof, RPCs the IDE when found); doctor now
skips its parse sample the way network providers are skipped, keeping
discovery counts meaningful.

Also stop blaming CODEBURN_CACHE_DIR in NOTHING FOUND hints (it is our
cache location, not a discovery path) and correct the sample-cap comment:
the cap truncates yields, eager parsers still do whole-file work.
2026-07-16 10:38:08 -07:00

103 lines
4.2 KiB
TypeScript

import { join } from 'path'
import { homedir } from 'os'
import { getShortModelName } from '../models.js'
import { discoverSqliteSessions, createSqliteSessionParser, type SqliteProviderConfig } from './sqlite-session-parser.js'
import { discoverOpenCodeFileSessions, createOpenCodeFileSessionParser } from './opencode-file-parser.js'
import type { Provider, ProbeRoot, SessionSource, SessionParser } from './types.js'
const toolNameMap: Record<string, string> = {
bash: 'Bash',
read: 'Read',
edit: 'Edit',
write: 'Write',
glob: 'Glob',
grep: 'Grep',
task: 'Agent',
fetch: 'WebFetch',
search: 'WebSearch',
todo: 'TodoWrite',
skill: 'Skill',
patch: 'Patch',
}
function getDataDir(dataDir?: string): string {
// Test seam: createOpenCodeProvider(tmpDir) points at a base dir that still
// gets the 'opencode' subdirectory appended, preserving existing fixtures
// (tmpDir/opencode/opencode*.db and tmpDir/opencode/storage/...).
if (dataDir) return join(dataDir, 'opencode')
// Production override for OpenCode-compatible forks/renames (e.g. MiMoCode at
// ~/.local/share/mimocode). This is the EXACT data directory — no 'opencode'
// suffix — so a fork writing <dir>/<prefix>*.db or <dir>/storage/... is found
// instead of silently yielding zero sessions. (issue #617)
const override = process.env['OPENCODE_DATA_DIR']
if (override) return override
// Default: $XDG_DATA_HOME/opencode or ~/.local/share/opencode.
const base = process.env['XDG_DATA_HOME'] ?? join(homedir(), '.local', 'share')
return join(base, 'opencode')
}
function getSqliteConfig(dataDir?: string): SqliteProviderConfig {
return {
providerName: 'opencode',
displayName: 'OpenCode',
dbDir: getDataDir(dataDir),
// Truthy check (not `??`): an empty-string `OPENCODE_DB_PREFIX` must fall
// back to 'opencode'. With `??`, '' survives as the prefix and
// `discoverSqliteSessions` matches every '*.db' file (filename.startsWith('')
// is always true), sweeping unrelated DBs into discovery. Aligns with
// `OPENCODE_DATA_DIR`'s truthy handling above, and makes behavior identical
// for unset vs empty — which matches the env fingerprint, since
// `computeEnvFingerprint` collapses both to 'OPENCODE_DB_PREFIX='. (issue #617)
dbFilePrefix: process.env['OPENCODE_DB_PREFIX'] || 'opencode',
}
}
export function createOpenCodeProvider(dataDir?: string): Provider {
const sqliteConfig = getSqliteConfig(dataDir)
const resolvedDataDir = getDataDir(dataDir)
return {
name: 'opencode',
displayName: 'OpenCode',
modelDisplayName(model: string): string {
const stripped = model.replace(/^[^/]+\//, '')
return getShortModelName(stripped)
},
toolDisplayName(rawTool: string): string {
return toolNameMap[rawTool] ?? rawTool
},
// OpenCode migrated from file-based JSON (storage/session/*.json) to a
// SQLite DB (opencode.db). After an in-place upgrade, legacy JSON files
// remain on disk while all new data flows into the SQLite DB. Merge both
// sources so migrated installs keep reporting legacy sessions AND pick up
// current SQLite data. Dedup is handled per-message in createSessionParser
// via seenKeys (keyed by `${provider}:${sessionId}:${messageId}`).
// Both the legacy JSON store (storage/session/*.json) and the SQLite DB
// (opencode*.db) live under this one data dir, resolved via OPENCODE_DATA_DIR
// or XDG_DATA_HOME the same way discoverSessions does.
async probeRoots(): Promise<ProbeRoot[]> {
return [{ path: resolvedDataDir, label: 'data' }]
},
async discoverSessions(): Promise<SessionSource[]> {
const fileSessions = await discoverOpenCodeFileSessions(resolvedDataDir, 'opencode')
const sqliteSessions = await discoverSqliteSessions(sqliteConfig)
return [...fileSessions, ...sqliteSessions]
},
createSessionParser(source: SessionSource, seenKeys: Set<string>): SessionParser {
if (source.path.endsWith('.json')) {
return createOpenCodeFileSessionParser(source, seenKeys, resolvedDataDir, 'opencode')
}
return createSqliteSessionParser(source, seenKeys, sqliteConfig)
},
}
}
export const opencode = createOpenCodeProvider()