diff --git a/README.md b/README.md index 79bb90b..db1335d 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,10 @@ both, so rows can add up to more than the total. With `--breakdown`, a **Per Session** column gives each tool / skill / command / agent count divided by the row's sessions. +Every period report, `session` included, ends with a **Skills** table: every +skill used in the range, by model and by user, with estimated tokens and cost, +as in the summary. `--top` limits the breakdown sub-rows, not this list. + The `session` report names each session by its title (the first 8 characters of its id when it has none), cut to at most 35 characters with `…` in every display format. JSON keeps the full title. @@ -124,8 +128,11 @@ your sessions as the unit. Each session lands in the first phase that fits: The report opens with a short written assessment, then shows the cohorts (as cards in HTML) with PRs, edits, tool calls per prompt, tokens and cost per -session; the phase mix per week; how many sessions use each capability -(skills, subagents, background agents, worktrees, MCP, web, PRs); and usage by +session and the share of each cohort that used plan mode and auto-approve (Claude +Code's auto mode or Copilot's autopilot, which run without asking per step; not +Cursor's Auto model setting, and Cursor doesn't log auto-run); the phase mix per +week, with the share of sessions in plan mode and auto-approve; how many sessions use each capability +(plan mode, auto-approve, skills, subagents, background agents, worktrees, MCP, web, PRs); and usage by surface (CLI, desktop, IDE, SDK, and the Copilot and Cursor surfaces with `--source`). PRs are the `pr-link` entries Claude Code records when it creates a PR; prompts exclude agent-to-agent messages and @@ -253,7 +260,12 @@ How the Copilot logs map onto the reports: own events. Hooks are named by event (`PreToolUse`), since Copilot doesn't log the command. **Pull requests** are the PR links in the output of `gh pr create` or a `create_pull_request` MCP call. -- Installed plugins are listed for Claude Code only. +- **Installed plugins** come from `installedPlugins` in + `~/.copilot/config.json`, with the enabled state from `enabledPlugins` in + `settings.json`. A plugin's skills count whether Copilot logs them as + `plugin:skill` or by the skill's own name. Copilot logs hooks by event, + so plugin hook runs stay 0. With `--source all` the table gets a + **Product** column. **Recommendations** run the same checks as for Claude Code. Their advice names Copilot's own levers: `.github/copilot-instructions.md` / `AGENTS.md`, @@ -320,10 +332,33 @@ How the transcripts map onto the reports: A read made only to look at or edit a skill counts as a use too. - **Recommendations:** without tokens, only the workflow checks can fire: coding step by step, and skills. -- **Not available:** tokens, cost, models, context size, hooks, compactions, - subagents and pull requests. The transcripts don't record tool results, so - no PR links either. IDE chats from before Cursor wrote transcripts are - kept only in the editor's database and aren't read. +- **Subagents:** launches are counted (with their type, and whether they ran + in the background), but a subagent's own work isn't in the transcript. +- **Not available:** tokens, cost, models that answered, context size, hooks, + compactions and pull requests. The transcripts don't record tool results, + so no PR links either. + +**Cursor's database.** The editor also keeps its chats in a SQLite database, +`state.vscdb` in Cursor's user folder (`%APPDATA%\Cursor\User` on Windows, +`~/Library/Application Support/Cursor/User` on macOS, `~/.config/Cursor/User` +on Linux; `CURSOR_USER_DIR` overrides it). ccreports reads it read-only, and +only metadata, never chat text or tool results: + +- **Model you picked and mode,** for every chat in it. `"default"` is + Cursor's **Auto** model setting. The adoption report's Agent adoption + table gets an **Auto model** row, as a share of the sessions that log a + model choice (the CLI's don't). Mode (`agent`, `chat` for Ask, `plan`) + counts toward plan mode. +- **Chats without a transcript,** such as editor chats from before Cursor + wrote transcripts. They count from the database: prompts, and tool calls + under Cursor's internal names (`write`, `search_replace`, + `run_terminal_cmd`, …), timed per message. Their project is the + workspace folder the chat belongs to. Drafts never sent are skipped. +- Token counts in the database are left out: Cursor fills them in for too + few messages to add up. + +Reading it needs Node 22.13 or later (`node:sqlite`). On older Node, +ccreports skips the database and says so. ## What is counted diff --git a/bin/ccreports.mjs b/bin/ccreports.mjs index 3a94e95..9a427e1 100644 --- a/bin/ccreports.mjs +++ b/bin/ccreports.mjs @@ -6,6 +6,7 @@ import { parseArgs } from 'node:util'; import { loadRecords, defaultProjectDirs } from '../src/loader.mjs'; import { loadCopilotRecords, defaultCopilotDirs, mergeData } from '../src/copilot.mjs'; import { loadCursorRecords, defaultCursorDirs } from '../src/cursor.mjs'; +import { defaultCursorUserDirs } from '../src/cursor-state.mjs'; import { aggregate, parseDateArg, toJSON, REPORTS } from '../src/aggregate.mjs'; import { buildPeriodReport, buildSummary } from '../src/report.mjs'; import { FORMATS, toTerminal, toMarkdown, toCsv, toHtml } from '../src/formats.mjs'; @@ -13,7 +14,7 @@ import { loadPricingTable, createPricer } from '../src/pricing.mjs'; import { buildAdoption, PHASES, AUTONOMY_THRESHOLD } from '../src/adoption.mjs'; import { buildRecommendations } from '../src/recommendations.mjs'; import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs'; -import { loadPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; +import { loadPlugins, loadCopilotPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; import { VERSION } from '../src/version.mjs'; const HELP = `ccreports - Claude Code (and GitHub Copilot, Cursor) tool, skill, slash-command and token usage @@ -155,7 +156,12 @@ const cursorDirs = opts['cursor-dir']?.length ? opts['cursor-dir'] : defaultCurs const wants = (src) => source === src || source === 'all'; const claudeData = wants('claude') ? await loadRecords({ dirs, includeSubagents }) : null; const copilotData = wants('copilot') ? await loadCopilotRecords({ dirs: copilotDirs, includeSubagents }) : null; -const cursorData = wants('cursor') ? await loadCursorRecords({ dirs: cursorDirs, includeSubagents }) : null; +const cursorData = wants('cursor') + ? await loadCursorRecords({ dirs: cursorDirs, userDirs: defaultCursorUserDirs(), includeSubagents }) + : null; +if (cursorData?.stateSkipped) { + console.error("ccreports: reading Cursor's database needs Node 22.13+; older chats and model choices are left out."); +} const loaded = [claudeData, copilotData, cursorData].filter(Boolean); const data = loaded.length > 1 ? mergeData(...loaded) : loaded[0]; if (data.files === 0) { @@ -195,8 +201,12 @@ if (showCost) { } // Installed plugins and what of each was used, in every report. -// (Claude Code plugins only.) -const plugins = claudeData ? pluginRows(await loadPlugins(dirs), result.totals, { project: opts.project }) : []; +// (Claude Code and GitHub Copilot; Cursor's installs aren't read.) +const installed = [ + ...(claudeData ? await loadPlugins(dirs) : []), + ...(copilotData ? await loadCopilotPlugins(copilotDirs) : []), +]; +const plugins = pluginRows(installed, result.totals, { project: opts.project }); // Only the terminal table hides columns to fit the screen. const compact = format === 'table' && (opts.compact || (toTTY && process.stdout.columns < 120)); diff --git a/src/adoption.mjs b/src/adoption.mjs index c99a32a..c971cd0 100644 --- a/src/adoption.mjs +++ b/src/adoption.mjs @@ -15,6 +15,8 @@ export const PHASES = [ // Tool calls per prompt you typed at which a session counts as agent-first. export const AUTONOMY_THRESHOLD = 10; const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']); +// Modes that run without asking per tool call: Claude Code's auto mode, Copilot's autopilot. +const AUTO_MODES = ['auto', 'autopilot']; const SURFACES = { cli: 'CLI', @@ -40,10 +42,14 @@ export function classify(s) { return 'assisted'; } -// Feature rows of the "Agent adoption" table: label and whether a session used it. +// Feature rows of the "Agent adoption" table: label, whether a session used it +// and, where only some sessions log it, which sessions the share is out of. const FEATURES = [ ['Code edits', (s) => s.edits > 0], ['Pull requests', (s) => s.prs > 0], + ['Plan mode', (s) => s.planMode], + ['Auto-approve', (s) => s.autoMode], + ['Auto model', (s) => s.autoModel, (s) => s.modelChoice != null], ['Skills', (s) => s.skills > 0], ['Subagents', (s) => s.subagentLaunches > 0], ['Background agents', (s) => s.backgroundAgents > 0], @@ -81,6 +87,11 @@ export function sessionStats(data, { since, until, project, timeZone, pricer } = surface: SURFACES[info?.entrypoint] ?? info?.entrypoint ?? 'unknown', prompts: info?.prompts.size ?? 0, prs: info?.prs.size ?? 0, + planMode: info?.modes?.has('plan') ?? false, + autoMode: AUTO_MODES.some((m) => info?.modes?.has(m)), + // The model picked for the session, where logged (Cursor's database); "default" is Cursor's Auto. + modelChoice: info?.modelChoice ?? null, + autoModel: info?.modelChoice === 'default', toolCalls: b.toolCalls, skills: b.skillCalls, subagentLaunches: b.subagentLaunches, @@ -115,7 +126,7 @@ const left = (title) => ({ title, align: 'left' }); const pct = (v) => `${Math.round(v * 100)}%`; /** Written assessment lines. */ -function assess(stats, byPhase) { +function assess(stats, byPhase, features) { if (!stats.length) return []; const lines = []; const ranked = PHASES.map((p) => ({ ...p, n: byPhase.get(p.key).length })).sort((a, b) => b.n - a.n); @@ -145,7 +156,7 @@ function assess(stats, byPhase) { lines.push(`PRs per session: ${parts.join(', ')}.`); } - const unused = FEATURES.filter(([, used]) => !stats.some(used)).map(([label]) => label.toLowerCase()); + const unused = features.filter(([, used]) => !stats.some(used)).map(([label]) => label.toLowerCase()); if (unused.length) lines.push(`Not used in this period: ${unused.join(', ')}.`); return lines; } @@ -156,6 +167,13 @@ export function buildAdoption(data, opts) { const stats = sessionStats(data, opts); const byPhase = new Map(PHASES.map((p) => [p.key, stats.filter((s) => s.phase === p.key)])); const sum = (list, f) => list.reduce((s, x) => s + f(x), 0); + // Cursor's logs don't record auto-run, so its reports leave auto mode out. + const logsAuto = opts.product !== 'Cursor'; + // Only Cursor logs the model you picked: the row shows when some session has it. + const logsModelChoice = stats.some((s) => s.modelChoice != null); + const features = FEATURES.filter( + ([label]) => (logsAuto || label !== 'Auto-approve') && (logsModelChoice || label !== 'Auto model'), + ).map(([label, ...rest]) => [label === 'Auto model' && opts.product !== 'Cursor' ? 'Auto model (Cursor)' : label, ...rest]); // Cohorts: one card per phase. // Column order matters for the HTML cards: title, subtitle, headline figure. @@ -168,6 +186,8 @@ export function buildAdoption(data, opts) { right('PRs'), right('Edits per session'), right('Median tool calls per prompt'), + right('Plan mode'), + ...(logsAuto ? [right('Auto-approve')] : []), ...(opts.tokens !== false ? [right('Tokens per session')] : []), ...(showCost ? [right('Cost per session')] : []), ]; @@ -187,6 +207,8 @@ export function buildAdoption(data, opts) { prs, average(sum(list, (s) => s.edits), list.length), m == null ? '' : average(m, 1), + share(list.filter((s) => s.planMode).length, list.length), + ...(logsAuto ? [share(list.filter((s) => s.autoMode).length, list.length)] : []), ...(opts.tokens !== false ? [list.length ? Math.round(sum(list, (s) => s.totalTokens) / list.length) : ''] : []), ...(showCost ? [list.length ? money(sum(list, (s) => s.costUSD) / list.length) : ''] : []), ], @@ -197,15 +219,24 @@ export function buildAdoption(data, opts) { const weekMap = new Map(); for (const s of stats) { const key = weekStart(s.firstActivity, timeZone); - const w = weekMap.get(key) ?? { key, total: 0, prs: 0, phases: Object.fromEntries(PHASES.map((p) => [p.key, 0])) }; + const w = weekMap.get(key) ?? { key, total: 0, prs: 0, plan: 0, auto: 0, phases: Object.fromEntries(PHASES.map((p) => [p.key, 0])) }; w.total += 1; w.prs += s.prs; + if (s.planMode) w.plan += 1; + if (s.autoMode) w.auto += 1; w.phases[s.phase] += 1; weekMap.set(key, w); } const weeks = [...weekMap.values()].sort((a, b) => (a.key < b.key ? -1 : 1)); const weekRows = weeks.map((w) => ({ - cells: [w.key, w.total, ...PHASES.map((p) => share(w.phases[p.key], w.total)), w.prs], + cells: [ + w.key, + w.total, + ...PHASES.map((p) => share(w.phases[p.key], w.total)), + share(w.plan, w.total), + ...(logsAuto ? [share(w.auto, w.total)] : []), + w.prs, + ], })); // Usage by surface. @@ -220,26 +251,33 @@ export function buildAdoption(data, opts) { .sort((a, b) => b[1].sessions - a[1].sessions) .map(([name, e]) => ({ cells: [name, e.sessions, share(e.sessions, stats.length), e.prs] })); - const featureRows = FEATURES.map(([label, used]) => { + const featureRows = features.map(([label, used, logged]) => { const n = stats.filter(used).length; - return { cells: [label, n, share(n, stats.length)] }; + return { cells: [label, n, share(n, logged ? stats.filter(logged).length : stats.length)] }; }); const range = opts.since || opts.until ? ` (${opts.since ?? '…'} → ${opts.until ?? 'today'})` : ''; return { title: `${opts.product ?? 'Claude Code'} adoption${range}`, - summary: assess(stats, byPhase), + summary: assess(stats, byPhase, features), sections: [ { title: 'Adoption cohorts', note: `sessions by how they used ${opts.product ?? 'Claude Code'}`, cards: true, columns: cohortColumns, rows: cohortRows }, { title: 'Phase mix per week', note: 'by the week a session started', - columns: [left('Week'), right('Sessions'), ...PHASES.map((p) => right(p.title)), right('PRs')], + columns: [ + left('Week'), + right('Sessions'), + ...PHASES.map((p) => right(p.title)), + right('Plan mode'), + ...(logsAuto ? [right('Auto-approve')] : []), + right('PRs'), + ], rows: weekRows, }, { title: 'Agent adoption', - note: 'share of sessions using each capability', + note: `share of sessions using each capability${logsModelChoice ? '; Auto model: of the sessions that log the model picked' : ''}`, columns: [left('Capability'), right('Sessions'), right('Share of sessions')], rows: featureRows, }, diff --git a/src/cursor-state.mjs b/src/cursor-state.mjs new file mode 100644 index 0000000..e28837b --- /dev/null +++ b/src/cursor-state.mjs @@ -0,0 +1,168 @@ +// Reads the Cursor editor's own database (/globalStorage/state.vscdb), +// which keeps chats the agent transcripts don't have (those from before Cursor +// wrote transcripts) and, for every chat, the model you picked and its mode. +// +// The database is SQLite, read with node:sqlite (Node 22.13+). On older Node it +// is skipped. Only metadata is read: per chat its mode, chosen model, title and +// workspace; per message its type, time and the name and command of a tool call. +// Chat text and tool results are never read out. Token counts are left out: +// Cursor fills them in for too few messages to add up. +// +// The format is undocumented, so every field access is defensive. + +import { existsSync } from 'node:fs'; +import { readdir, readFile } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +/** Cursor's user data directory (with globalStorage/ and workspaceStorage/), honoring CURSOR_USER_DIR. */ +export function defaultCursorUserDirs() { + if (process.env.CURSOR_USER_DIR) return [process.env.CURSOR_USER_DIR]; + const base = + process.platform === 'win32' + ? process.env.APPDATA || path.join(homedir(), 'AppData', 'Roaming') + : process.platform === 'darwin' + ? path.join(homedir(), 'Library', 'Application Support') + : process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config'); + return [path.join(base, 'Cursor', 'User')]; +} + +let sqlite; // the node:sqlite module, null when unavailable +/** node:sqlite without its ExperimentalWarning, or null on Node versions without it. */ +export async function loadSqlite() { + if (sqlite !== undefined) return sqlite; + const emit = process.emitWarning; + process.emitWarning = (warning, ...args) => { + const type = typeof args[0] === 'string' ? args[0] : args[0]?.type; + if (type === 'ExperimentalWarning' && /SQLite/i.test(String(warning?.message ?? warning))) return; + return emit.call(process, warning, ...args); + }; + try { + sqlite = await import('node:sqlite'); + } catch { + sqlite = null; + } finally { + process.emitWarning = emit; + } + return sqlite; +} + +const parse = (text) => { + try { + return JSON.parse(text); + } catch { + return null; + } +}; + +function open(file) { + if (!existsSync(file)) return null; + try { + return new sqlite.DatabaseSync(file, { readOnly: true }); + } catch { + return null; // locked or not a database + } +} + +/** "file:///z%3A/Sources/App" -> "z:\Sources\App" (a path on this platform). */ +function folderPath(uri) { + try { + const p = fileURLToPath(uri); + return /^[a-z]:/.test(p) ? p[0].toUpperCase() + p.slice(1) : p; + } catch { + return null; + } +} + +/** composerId -> project folder, from each workspace's own state.vscdb. */ +async function workspaceProjects(userDir) { + const out = new Map(); + const root = path.join(userDir, 'workspaceStorage'); + let dirs; + try { + dirs = await readdir(root); + } catch { + return out; + } + for (const dir of dirs) { + const workspace = parse(await readFile(path.join(root, dir, 'workspace.json'), 'utf8').catch(() => '')); + const project = workspace?.folder ? folderPath(workspace.folder) : '(no folder)'; + const db = open(path.join(root, dir, 'state.vscdb')); + if (!db) continue; + try { + const row = db.prepare("select value from ItemTable where key = 'composer.composerData'").get(); + for (const c of parse(row?.value)?.allComposers ?? []) if (c?.composerId) out.set(c.composerId, project); + } catch { + // no ItemTable + } finally { + db.close(); + } + } + return out; +} + +/** + * Chats in Cursor's database: composerId -> { title, mode, model, project, + * messages: [{ type: 'user' | 'assistant', timestamp, tool?: { name, command? } }] }, + * or null when node:sqlite is unavailable. Missing databases give an empty map. + */ +export async function readCursorState(userDirs) { + if (!userDirs.length) return new Map(); + if (!(await loadSqlite())) return null; + const chats = new Map(); + for (const userDir of userDirs) { + const db = open(path.join(userDir, 'globalStorage', 'state.vscdb')); + if (!db) continue; + const projects = await workspaceProjects(userDir); + try { + const rows = (prefix) => db.prepare('select key, value from cursorDiskKV where key like ?').all(`${prefix}%`); + for (const { key, value } of rows('composerData:')) { + const c = parse(value); + const id = key.slice('composerData:'.length); + if (!c) continue; + chats.set(id, { + title: c.name || null, + mode: c.unifiedMode ?? null, // agent, chat (Ask), plan, ... + model: c.modelConfig?.modelName ?? null, // "default" is Auto + project: projects.get(id) ?? null, + createdAt: typeof c.createdAt === 'number' ? new Date(c.createdAt).toISOString() : null, + order: (c.fullConversationHeadersOnly ?? []).map((h) => h?.bubbleId), + messages: new Map(), + }); + } + // Messages are stored as bubbleId::. + const select = db.prepare( + `select key, json_extract(value, '$.type') type, json_extract(value, '$.createdAt') createdAt, + json_extract(value, '$.toolFormerData.name') tool, json_extract(value, '$.toolFormerData.rawArgs') args + from cursorDiskKV where key like 'bubbleId:%'`, + ); + for (const r of select.all()) { + const [, composerId, bubbleId] = String(r.key).split(':'); + const chat = chats.get(composerId); + if (!chat || (r.type !== 1 && r.type !== 2)) continue; + const message = { type: r.type === 1 ? 'user' : 'assistant', timestamp: r.createdAt ?? null }; + if (r.tool) { + message.tool = { name: r.tool }; + const command = parse(r.args)?.command; + if (typeof command === 'string') message.tool.command = command; + } + chat.messages.set(bubbleId, message); + } + } catch { + // not the table layout this reader knows + } finally { + db.close(); + } + } + // Messages in conversation order; the ones not in the order list after, by time. + for (const chat of chats.values()) { + const ordered = chat.order.filter((id) => chat.messages.has(id)).map((id) => chat.messages.get(id)); + const listed = new Set(chat.order); + const rest = [...chat.messages].filter(([id]) => !listed.has(id)).map(([, m]) => m); + rest.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp))); + chat.messages = [...ordered, ...rest]; + delete chat.order; + } + return chats; +} diff --git a/src/cursor.mjs b/src/cursor.mjs index 23dbbca..6412503 100644 --- a/src/cursor.mjs +++ b/src/cursor.mjs @@ -16,6 +16,10 @@ // - Tools Cursor loads on demand are called through CallDynamicTool; they are // counted under their own name (MCP tools as mcp____). // +// Cursor's own database (src/cursor-state.mjs) adds, per chat, the model you +// picked and its mode, and the chats that have no transcript: those count +// from the database, with Cursor's internal tool names (write, read_file, ...). +// // The format is undocumented, so every field access is defensive. import { createReadStream, existsSync } from 'node:fs'; @@ -25,6 +29,7 @@ import { homedir } from 'node:os'; import path from 'node:path'; import { shellCommands } from './shell.mjs'; import { normalizeSkillName } from './loader.mjs'; +import { readCursorState } from './cursor-state.mjs'; const EDIT_TOOLS = new Set(['Write', 'Edit', 'StrReplace', 'MultiEdit', 'Delete', 'ApplyPatch', 'EditNotebook']); const WEB_TOOLS = new Set(['WebSearch', 'WebFetch']); @@ -35,6 +40,10 @@ const SHELL = process.platform === 'win32' ? 'PowerShell' : 'Bash'; // .claude/skills, .agents/skills, ... in a project or the home directory. A // SKILL.md elsewhere (a plugin's source, say) is read as a file, not used. const SKILL_FILE = /[\\/]\.[\w-]+[\\/]skills(?:-cursor)?[\\/]([^\\/]+)[\\/]SKILL\.md$/i; +// Tool names in Cursor's database, which differ from the transcripts'. +const DB_EDIT_TOOL = /^(write|search_replace|edit_file|delete_file|apply_patch|multi_edit)/; +const DB_WEB_TOOL = /^(web_search|fetch)/; +const DB_SHELL_TOOL = /^run_terminal/; const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; /** The Cursor config directory, honoring CURSOR_CONFIG_DIR. */ @@ -157,7 +166,11 @@ function toolName(c) { return !ns || ns === 'cursor' ? c.input.toolName : `mcp__${ns}__${c.input.toolName}`; } -export async function loadCursorRecords({ dirs = defaultCursorDirs(), includeSubagents = true } = {}) { +/** + * `userDirs`: Cursor's user data directories, for its database (see + * defaultCursorUserDirs in src/cursor-state.mjs); none by default. + */ +export async function loadCursorRecords({ dirs = defaultCursorDirs(), userDirs = [], includeSubagents = true } = {}) { const tools = []; const skills = []; const commands = []; @@ -260,10 +273,48 @@ export async function loadCursorRecords({ dirs = defaultCursorDirs(), includeSub } } + // Cursor's database: the chosen model and mode of every chat, and the chats without a transcript. + const state = await readCursorState(userDirs); + for (const [id, chat] of state ?? []) { + let info = sessions.get(id); + if (!info) { + const prompts = chat.messages.filter((m) => m.type === 'user'); + if (!prompts.length) continue; // a draft never sent + info = { entrypoint: 'cursor-ide', prompts: new Set(), prs: new Set(), compactions: new Set(), modes: new Set() }; + sessions.set(id, info); + fileCount += 1; + if (chat.title) titles.set(id, chat.title); + const project = chat.project ?? '(no folder)'; + let timestamp = chat.createdAt; + const base = () => ({ timestamp, sessionId: id, project, agent: null, source: 'cursor' }); + for (const m of chat.messages) { + timestamp = m.timestamp ?? timestamp; + if (!timestamp) continue; + if (m.type === 'user') { + info.prompts.add(info.prompts.size + 1); + events.push(base()); + continue; + } + if (!m.tool) continue; + const tool = { ...base(), name: m.tool.name }; + if (DB_EDIT_TOOL.test(m.tool.name)) tool.edit = true; + if (DB_WEB_TOOL.test(m.tool.name)) tool.web = true; + if (DB_SHELL_TOOL.test(m.tool.name) && m.tool.command) { + const names = shellCommands(m.tool.command, SHELL); + tool.shellCommands = SHELL === 'PowerShell' ? names.map(psName) : names; + } + tools.push(tool); + } + } + if (chat.mode) info.modes.add(chat.mode); + if (chat.model) info.modelChoice = chat.model; + } + return { sessions, charsPerToken: null, files: fileCount, + stateSkipped: state === null, // Node without node:sqlite usage: [], tools, skills, diff --git a/src/loader.mjs b/src/loader.mjs index a287188..b26abe8 100644 --- a/src/loader.mjs +++ b/src/loader.mjs @@ -99,10 +99,10 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent const commands = new Map(); // user-message uuid -> record const hooks = new Map(); // attachment uuid -> record const titles = new Map(); // sessionId -> ai title - // sessionId -> { entrypoint, prompts: Set, prs: Set, compactions: Set } (adoption / recommendations) + // sessionId -> { entrypoint, prompts: Set, prs: Set, compactions: Set, modes: Set } (adoption / recommendations) const sessions = new Map(); const sessionInfo = (id) => { - if (!sessions.has(id)) sessions.set(id, { entrypoint: null, prompts: new Set(), prs: new Set(), compactions: new Set() }); + if (!sessions.has(id)) sessions.set(id, { entrypoint: null, prompts: new Set(), prs: new Set(), compactions: new Set(), modes: new Set() }); return sessions.get(id); }; const sessionStart = new Map(); // sessionId -> { rank, timestamp, cwd } of its earliest record @@ -134,6 +134,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent !line.includes('"type":"user"') && !line.includes('"type":"ai-title"') && !line.includes('"type":"pr-link"') && + !line.includes('"type":"permission-mode"') && !line.includes('"subtype":"compact_boundary"') && !line.includes('"type":"hook_') ) { @@ -154,6 +155,10 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent if (d.sessionId && d.prUrl) sessionInfo(d.sessionId).prs.add(d.prUrl); continue; } + if (d.type === 'permission-mode') { + if (d.sessionId && d.permissionMode) sessionInfo(d.sessionId).modes.add(d.permissionMode); + continue; + } if (d.type === 'system') { if (d.subtype === 'compact_boundary') { attribution.compact(); @@ -250,6 +255,7 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent if (c.input?.run_in_background) tool.background = true; } if (c.input?.isolation === 'worktree' || c.name === 'EnterWorktree') tool.worktree = true; + if (!agent && (c.name === 'EnterPlanMode' || c.name === 'ExitPlanMode')) sessionInfo(base.sessionId).modes.add('plan'); if (SHELL_TOOLS.has(c.name) && typeof c.input?.command === 'string') { const names = shellCommands(c.input.command, c.name); tool.shellCommands = c.name === 'PowerShell' ? names.map(psName) : names; @@ -291,6 +297,8 @@ export async function loadRecords({ dirs = defaultProjectDirs(), includeSubagent } } if (!agent && d.entrypoint) sessionInfo(base.sessionId).entrypoint ??= d.entrypoint; + // The permission mode (default, plan, acceptEdits, auto, ...) the prompt was sent in. + if (!agent && d.permissionMode) sessionInfo(base.sessionId).modes.add(d.permissionMode); const match = COMMAND_RE.exec(text); if (match) { const name = '/' + normalizeSkillName(match[1]); diff --git a/src/plugins.mjs b/src/plugins.mjs index bd7cebb..2781181 100644 --- a/src/plugins.mjs +++ b/src/plugins.mjs @@ -1,8 +1,9 @@ -// Installed Claude Code plugins (/plugins/installed_plugins.json), +// Installed Claude Code plugins (/plugins/installed_plugins.json) +// and GitHub Copilot plugins (installedPlugins in ~/.copilot/config.json), // whether each is enabled (the enabledPlugins setting of its scope), and how // often the transcripts used what it provides. -import { readFile } from 'node:fs/promises'; +import { readFile, readdir } from 'node:fs/promises'; import path from 'node:path'; async function readJSON(file) { @@ -13,6 +14,15 @@ async function readJSON(file) { } } +/** JSON with whole-line // comments, as Copilot writes its config.json. */ +async function readJSONC(file) { + try { + return JSON.parse((await readFile(file, 'utf8')).replace(/^\s*\/\/.*$/gm, '')); + } catch { + return null; + } +} + /** The settings file that holds a scope's enabledPlugins. */ function settingsFile(root, install) { if (install.scope === 'user' || !install.projectPath) return path.join(root, 'settings.json'); @@ -24,9 +34,13 @@ function settingsFile(root, install) { async function hookCommands(installPath) { const commands = new Set(); if (!installPath) return commands; - const manifest = await readJSON(path.join(installPath, '.claude-plugin', 'plugin.json')); + // Claude Code reads .claude-plugin/plugin.json; Copilot also reads plugin.json at the root. + const manifests = [path.join(installPath, '.claude-plugin', 'plugin.json'), path.join(installPath, 'plugin.json')]; const files = [await readJSON(path.join(installPath, 'hooks', 'hooks.json'))]; - if (manifest?.hooks && typeof manifest.hooks === 'object') files.push(manifest); + for (const file of manifests) { + const manifest = await readJSON(file); + if (manifest?.hooks && typeof manifest.hooks === 'object') files.push(manifest); + } for (const file of files) { for (const groups of Object.values(file?.hooks ?? {})) { for (const group of Array.isArray(groups) ? groups : []) { @@ -72,6 +86,8 @@ export async function loadPlugins(dirs) { lastUpdated: install.lastUpdated ?? null, installPath: install.installPath ?? null, hookCommands: await hookCommands(install.installPath), + skillNames: new Set(), + product: 'Claude Code', }); } } @@ -79,6 +95,58 @@ export async function loadPlugins(dirs) { return plugins; } +/** Names of the skills a plugin ships: the folders in its manifest's skill paths (default skills/). */ +async function skillNames(installPath) { + const names = new Set(); + if (!installPath) return names; + const manifest = await readJSON(path.join(installPath, 'plugin.json')); + const dirs = [manifest?.skills ?? './skills/'].flat().filter((d) => typeof d === 'string'); + for (const dir of dirs) { + try { + for (const e of await readdir(path.join(installPath, dir), { withFileTypes: true })) if (e.isDirectory()) names.add(e.name); + } catch { + // No such folder. + } + } + return names; +} + +/** + * Installed GitHub Copilot plugins. `dirs` are the session-state directories; + * config.json (the installs) and settings.json (enabledPlugins) sit next to them. + */ +export async function loadCopilotPlugins(dirs) { + const roots = [...new Set(dirs.map((d) => path.dirname(path.resolve(d))))]; + const plugins = []; + for (const root of roots) { + const config = await readJSONC(path.join(root, 'config.json')); + const enabledPlugins = (await readJSONC(path.join(root, 'settings.json')))?.enabledPlugins ?? {}; + for (const install of Array.isArray(config?.installedPlugins) ? config.installedPlugins : []) { + if (!install?.name) continue; + const marketplace = install.marketplace ?? ''; + const id = marketplace ? `${install.name}@${marketplace}` : install.name; + const enabled = enabledPlugins[id] ?? install.enabled; + plugins.push({ + id, + name: install.name, + marketplace, + version: install.version ?? '', + scope: 'user', + projectPath: null, + enabled: typeof enabled === 'boolean' ? enabled : null, + installedAt: install.installed_at ?? null, + lastUpdated: install.installed_at ?? null, + installPath: install.cache_path ?? null, + hookCommands: await hookCommands(install.cache_path), + // Copilot may log a plugin's skill without the plugin prefix. + skillNames: await skillNames(install.cache_path), + product: 'GitHub Copilot', + }); + } + } + return plugins; +} + const sum = (map, match, valueOf = (v) => v) => [...map].reduce((n, [key, value]) => (match(key) ? n + valueOf(value) : n), 0); @@ -93,7 +161,7 @@ export function pluginUsage(plugin, totals) { [...plugin.hookCommands].flatMap((c) => [c, ...roots.map((r) => c.replaceAll('${CLAUDE_PLUGIN_ROOT}', r))]), ); const usage = { - skills: sum(totals.skills, (k) => k.startsWith(prefix), (s) => s.model + s.user), + skills: sum(totals.skills, (k) => k.startsWith(prefix) || plugin.skillNames?.has(k), (s) => s.model + s.user), commands: sum(totals.commands, (k) => k.replace(/^\//, '').startsWith(prefix)), agents: sum(totals.agents, (k) => k.startsWith(prefix), (a) => a.launches), // Claude Code names a plugin's MCP servers plugin__. @@ -114,4 +182,4 @@ export function pluginRows(plugins, totals, { project } = {}) { } /** JSON form of pluginRows. */ -export const pluginsJSON = (rows) => rows.map(({ hookCommands, installPath, ...p }) => p); +export const pluginsJSON = (rows) => rows.map(({ hookCommands, installPath, skillNames, ...p }) => p); diff --git a/src/recommendations.mjs b/src/recommendations.mjs index 21dc69a..542b5e9 100644 --- a/src/recommendations.mjs +++ b/src/recommendations.mjs @@ -81,7 +81,7 @@ const PRODUCTS = { 'model switch': 'Each model has its own cache: switching with `/model` mid-conversation re-reads the whole history. Pick the model at the start, or `/compact` before you switch.', }, autonomy: - 'Describe the whole task up front - goal, constraints and how to verify it - and let Claude run. Use plan mode for bigger changes, and turn workflows you repeat into skills.', + 'Describe the whole task up front - goal, constraints and how to verify it - and let Claude run. Use plan mode for bigger changes and auto mode to let Claude work without asking for each tool call, and turn workflows you repeat into skills.', parallel: 'Ask Claude to run independent tasks as parallel subagents: they run in the background while you keep working (`Ctrl+B` moves a long-running one there). When several agents change code at the same time, give each its own worktree: `isolation: worktree` in an agent\'s definition, or `claude -w ` for a whole session.', skills: @@ -390,10 +390,12 @@ export function recommend(data, opts = {}) { return v.length ? v[Math.floor(v.length / 2)] : 0; }; const agentic = coding.filter((s) => s.phase !== 'assisted'); - // Copilot logs the modes a session ran in. + // The loaders record the modes a session ran in; Cursor's logs have no auto-run. const modes = (mode) => coding.filter((s) => data.sessions.get(s.id)?.modes?.has(mode)).length; + const auto = { claude: ['auto mode', 'auto'], copilot: ['autopilot', 'autopilot'] }[opts.source ?? 'claude']; + const autoText = auto ? ` and ${auto[0]} in ${modes(auto[1])}` : ''; const modeText = data.sessions.get(coding[0].id)?.modes - ? ` Plan mode was used in ${modes('plan')} and autopilot in ${modes('autopilot')} of ${coding.length} coding sessions.` + ? ` Plan mode was used in ${modes('plan')}${autoText} of ${coding.length} coding sessions.` : ''; recs.push({ id: 'autonomy', diff --git a/src/report.mjs b/src/report.mjs index bf2f5a1..e14dc47 100644 --- a/src/report.mjs +++ b/src/report.mjs @@ -157,10 +157,13 @@ const PERIOD = { // their skills, commands, subagents, MCP servers and hooks were used. function pluginSection(plugins) { const yesNo = (v) => (v == null ? '' : v ? 'yes' : 'no'); + // A Product column only when the plugins come from more than one product. + const multi = new Set(plugins.map((p) => p.product)).size > 1; return { title: 'Installed plugins', note: 'usage is per plugin, across its installs', columns: [ + ...(multi ? [left('Product')] : []), left('Plugin'), left('Marketplace'), left('Version'), @@ -176,6 +179,7 @@ function pluginSection(plugins) { ], rows: plugins.map((p) => ({ cells: [ + ...(multi ? [p.product] : []), p.name, p.marketplace, p.version, @@ -193,6 +197,46 @@ function pluginSection(plugins) { }; } +// Estimated tokens and cost attributed to each tool / server / skill: input +// side (result in context + re-reads) and output (the input the model wrote). +function estimateColumns(opts) { + if (opts.tokens === false) return []; + return [ + right('Input (est.)'), + right('Output (est.)'), + right('Tokens (est.)'), + ...(opts.showCost ? [right('Cost (est.)')] : []), + right('Token share'), + ]; +} + +function estimateCells(usage, totals, opts) { + if (opts.tokens === false) return []; + const u = usage ?? { tokens: 0, outputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, costUSD: 0 }; + return [ + approx(u.cacheWriteTokens + u.cacheReadTokens), + approx(u.outputTokens), + approx(u.tokens), + ...(opts.showCost ? [money(u.costUSD, { approx: true })] : []), + share(u.tokens, totals.totalTokens), + ]; +} + +/** Every skill used, by who invoked it; `top` > 0 keeps the first rows. */ +function skillSection(totals, opts, top = 0) { + const entries = ranked(totals.skills, (s) => s.model + s.user); + if (!entries.length) return null; + const shown = top > 0 ? entries.slice(0, top) : entries; + return { + title: 'Skills', + note: shown.length < entries.length ? `top ${shown.length} of ${entries.length}` : undefined, + columns: [left('Skill'), right('By model'), right('By user'), right('Total'), ...estimateColumns(opts)], + rows: shown.map(([name, s]) => ({ + cells: [name, s.model, s.user, s.model + s.user, ...estimateCells(totals.skillTokens.get(name), totals, opts)], + })), + }; +} + export function buildPeriodReport(report, { buckets, totals }, opts) { const { breakdown, shell, top, timeZone } = opts; const hasSubRows = breakdown || shell; @@ -289,7 +333,10 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { return { title: `${opts.product ?? 'Claude Code'} ${PERIOD[report].name} usage${rangeText(opts)}`, - sections: [{ columns, rows }, ...(opts.plugins?.length ? [pluginSection(opts.plugins)] : [])], + // All skills: --top limits the per-row breakdown, not this list. + sections: [{ columns, rows }, skillSection(totals, opts), ...(opts.plugins?.length ? [pluginSection(opts.plugins)] : [])].filter( + Boolean, + ), }; } @@ -329,28 +376,8 @@ export function buildSummary({ totals }, opts) { const costCol = showCost ? [right('Cost (USD)')] : []; const costCell = (v) => (showCost ? [money(v)] : []); - // Estimated tokens and cost attributed to each tool / server / skill: input - // side (result in context + re-reads) and output (the input the model wrote). - const estCols = withTokens - ? [ - right('Input (est.)'), - right('Output (est.)'), - right('Tokens (est.)'), - ...(showCost ? [right('Cost (est.)')] : []), - right('Token share'), - ] - : []; - const estCells = (usage) => { - if (!withTokens) return []; - const u = usage ?? { tokens: 0, outputTokens: 0, cacheWriteTokens: 0, cacheReadTokens: 0, costUSD: 0 }; - return [ - approx(u.cacheWriteTokens + u.cacheReadTokens), - approx(u.outputTokens), - approx(u.tokens), - ...(showCost ? [money(u.costUSD, { approx: true })] : []), - share(u.tokens, totals.totalTokens), - ]; - }; + const estCols = estimateColumns(opts); + const estCells = (usage) => estimateCells(usage, totals, opts); section( 'Tools', @@ -366,12 +393,8 @@ export function buildSummary({ totals }, opts) { ([name, count]) => [name, count, ...estCells(totals.mcpServerTokens.get(name))], ); - section( - 'Skills', - [left('Skill'), right('By model'), right('By user'), right('Total'), ...estCols], - ranked(totals.skills, (s) => s.model + s.user), - ([name, s]) => [name, s.model, s.user, s.model + s.user, ...estCells(totals.skillTokens.get(name))], - ); + const skills = skillSection(totals, opts, top); + if (skills) sections.push(skills); // Programs run by Bash / PowerShell calls, grouped by purpose. Calls and // Share (of that tool's calls) count a call once per purpose. diff --git a/test/adoption.test.mjs b/test/adoption.test.mjs index 5166244..40586e4 100644 --- a/test/adoption.test.mjs +++ b/test/adoption.test.mjs @@ -41,7 +41,7 @@ function fixture() { cacheCreationTokens: 0, cacheReadTokens: 0, }); - const session = (entrypoint, prompts, prs = []) => ({ entrypoint, prompts: new Set(prompts), prs: new Set(prs) }); + const session = (entrypoint, prompts, prs = [], modes = []) => ({ entrypoint, prompts: new Set(prompts), prs: new Set(prs), modes: new Set(modes) }); return { usage: [u('chat', 1), u('assist', 2), u('agent', 3), u('multi', 4)], tools: [ @@ -57,8 +57,8 @@ function fixture() { sessions: new Map([ ['chat', session('cli', ['p1'])], ['assist', session('cli', ['p1', 'p2'], ['https://example.com/pr/1'])], - ['agent', session('claude-vscode', ['p1'], ['https://example.com/pr/2', 'https://example.com/pr/3'])], - ['multi', session('cli', ['p1'])], + ['agent', session('claude-vscode', ['p1'], ['https://example.com/pr/2', 'https://example.com/pr/3'], ['plan'])], + ['multi', session('cli', ['p1'], [], ['auto'])], ]), }; } @@ -75,11 +75,17 @@ test('buildAdoption: cohorts, weekly mix, capabilities, surfaces and summary', ( assert.equal(agentRow[0], 'Phase 2 · Agent-first'); assert.deepEqual(agentRow[2], { kind: 'avg', v: 2 }); // PRs per session assert.equal(agentRow[3], 1); // sessions + assert.deepEqual(agentRow[cohorts.columns.findIndex((c) => c.title === 'Plan mode')], { kind: 'pct', v: 1 }); assert.deepEqual(weekly.rows.map((r) => r.cells[0]), ['2026-09-28']); // Oct 1-4, 2026 is Thu-Sun of one week assert.equal(weekly.rows[0].cells[1], 4); + const weekCell = (title) => weekly.rows[0].cells[weekly.columns.findIndex((c) => c.title === title)]; + assert.deepEqual(weekCell('Plan mode'), { kind: 'pct', v: 0.25 }); + assert.deepEqual(weekCell('Auto-approve'), { kind: 'pct', v: 0.25 }); const used = Object.fromEntries(capabilities.rows.map((r) => [r.cells[0], r.cells[1]])); assert.equal(used['Background agents'], 1); assert.equal(used['Pull requests'], 2); + assert.equal(used['Plan mode'], 1); + assert.equal(used['Auto-approve'], 1); assert.deepEqual(surfaces.rows.map((r) => r.cells[0]), ['CLI', 'VS Code']); assert.ok(doc.summary.some((l) => l.startsWith('PRs per session: Assisted 1.00, Agent-first 2.00, Multi-agent 0.00'))); assert.ok(doc.summary.some((l) => l.includes('Not used in this period') && l.includes('worktrees'))); @@ -95,3 +101,15 @@ test('adoption renders as cards in HTML and as tables in Markdown', () => { assert.match(md, /^# Claude Code adoption\n\n- Most of your sessions/); assert.match(md, /## Adoption cohorts/); }); + +test('auto-approve counts auto mode and autopilot and is left out for Cursor', () => { + const data = fixture(); + data.sessions.get('agent').modes.add('autopilot'); + const copilot = buildAdoption(data, { timeZone: 'UTC', showCost: false, product: 'GitHub Copilot' }); + assert.deepEqual(copilot.stats.filter((s) => s.autoMode).map((s) => s.id).sort(), ['agent', 'multi']); + const cursor = buildAdoption(data, { timeZone: 'UTC', showCost: false, product: 'Cursor' }); + assert.ok(!cursor.sections[0].columns.some((c) => c.title === 'Auto-approve')); + assert.ok(!cursor.sections[1].columns.some((c) => c.title === 'Auto-approve')); + assert.equal(cursor.sections[1].columns.length, cursor.sections[1].rows[0].cells.length); + assert.ok(!cursor.sections[2].rows.some((r) => r.cells[0] === 'Auto-approve')); +}); diff --git a/test/ccreports.test.mjs b/test/ccreports.test.mjs index 2651be8..e57f16a 100644 --- a/test/ccreports.test.mjs +++ b/test/ccreports.test.mjs @@ -151,6 +151,11 @@ test('period report shows sessions and per-session averages on breakdown rows', assert.equal(plain.columns.some((c) => c.title === 'Per Session'), false); const session = buildPeriodReport('session', aggregate(data, { report: 'session' }), { breakdown: true }).sections[0]; assert.equal(session.columns.some((c) => c.title === 'Sessions' || c.title === 'Per Session'), false); + + // Every period report lists all skills used, whatever --top is. + const skills = buildPeriodReport('session', aggregate(data, { report: 'session' }), { top: 1 }).sections[1]; + assert.equal(skills.title, 'Skills'); + assert.deepEqual(skills.rows.map((r) => r.cells.slice(0, 4)), [['decide', 1, 0, 1], ['plan', 0, 1, 1]]); } finally { await rm(root, { recursive: true, force: true }); } @@ -330,3 +335,25 @@ test('session names are at most 35 characters in reports', async () => { const doc = buildPeriodReport('session', aggregate(data, { report: 'session' }), {}); assert.equal(doc.sections[0].rows[0].cells[0], 'A'.repeat(34) + '…'); }); + +test('records the permission modes a session ran in', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'ccreports-')); + try { + const proj = path.join(root, '-work-app'); + await mkdir(proj, { recursive: true }); + const lines = [ + { type: 'permission-mode', permissionMode: 'acceptEdits', sessionId: 's1' }, + { ...user('2026-10-01T10:00:00Z', 'u1', 'plan this'), permissionMode: 'plan' }, + { ...user('2026-10-01T10:00:00Z', 'u2', 'hi'), sessionId: 's2' }, + { ...assistant('2026-10-01T10:00:05Z', 'm1', 'r1', [{ type: 'tool_use', id: 't1', name: 'EnterPlanMode', input: {} }]), sessionId: 's2' }, + { ...user('2026-10-01T10:00:00Z', 'u3', 'hi'), sessionId: 's3' }, + ]; + await writeFile(path.join(proj, 's1.jsonl'), lines.map((l) => JSON.stringify(l)).join('\n') + '\n'); + const { sessions } = await loadRecords({ dirs: [root] }); + assert.deepEqual([...sessions.get('s1').modes].sort(), ['acceptEdits', 'plan']); + assert.deepEqual([...sessions.get('s2').modes], ['plan']); // entered by the model + assert.deepEqual([...sessions.get('s3').modes], []); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/test/cursor.test.mjs b/test/cursor.test.mjs index d8a562c..8aaa436 100644 --- a/test/cursor.test.mjs +++ b/test/cursor.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; +import { pathToFileURL } from 'node:url'; import { loadCursorRecords, parsePromptTime, decodeProjectDir } from '../src/cursor.mjs'; import { aggregate } from '../src/aggregate.mjs'; import { buildSummary } from '../src/report.mjs'; @@ -142,3 +143,81 @@ test('Cursor activity counts sessions without tokens, and reports drop token col await rm(root, { recursive: true, force: true }); } }); + +// Cursor's database: one chat that also has a transcript, one without, and a draft. +async function userDir() { + const { DatabaseSync } = await import('node:sqlite'); + const dir = await mkdtemp(path.join(tmpdir(), 'ccreports-cursor-user-')); + const project = path.join(dir, 'App'); + const ws = path.join(dir, 'workspaceStorage', 'abc'); + await mkdir(path.join(dir, 'globalStorage'), { recursive: true }); + await mkdir(ws, { recursive: true }); + await mkdir(project); + await writeFile(path.join(ws, 'workspace.json'), JSON.stringify({ folder: pathToFileURL(project).href })); + const wdb = new DatabaseSync(path.join(ws, 'state.vscdb')); + wdb.exec('create table ItemTable (key text, value text)'); + wdb.prepare('insert into ItemTable values (?, ?)').run('composer.composerData', JSON.stringify({ allComposers: [{ composerId: 'old-1' }] })); + wdb.close(); + + const db = new DatabaseSync(path.join(dir, 'globalStorage', 'state.vscdb')); + db.exec('create table cursorDiskKV (key text, value text)'); + const put = (key, value) => db.prepare('insert into cursorDiskKV values (?, ?)').run(key, JSON.stringify(value)); + put('composerData:ide-1', { unifiedMode: 'agent', modelConfig: { modelName: 'claude-4.5-opus-high-thinking' } }); + put('composerData:old-1', { + name: 'Fix the build', + unifiedMode: 'plan', + modelConfig: { modelName: 'default' }, + createdAt: Date.parse('2025-12-06T11:00:00Z'), + fullConversationHeadersOnly: [{ bubbleId: 'b1' }, { bubbleId: 'b2' }, { bubbleId: 'b3' }], + }); + put('composerData:draft', { unifiedMode: 'agent', modelConfig: { modelName: 'default' } }); + put('bubbleId:old-1:b3', { type: 2, createdAt: '2025-12-06T11:00:09Z', toolFormerData: { name: 'run_terminal_cmd', rawArgs: JSON.stringify({ command: 'git status' }) } }); + put('bubbleId:old-1:b1', { type: 1, createdAt: '2025-12-06T11:00:02Z', text: 'never read' }); + put('bubbleId:old-1:b2', { type: 2, createdAt: '2025-12-06T11:00:08Z', toolFormerData: { name: 'search_replace', rawArgs: '{}' } }); + db.close(); + return dir; +} + +test("Cursor's database adds model choice and mode, and chats without a transcript", async (t) => { + try { + await import('node:sqlite'); + } catch { + return t.skip('node:sqlite needs Node 22.13+'); + } + const root = await fixture(); + const dir = await userDir(); + try { + const data = await loadCursorRecords({ dirs: [root], userDirs: [dir] }); + assert.equal(data.stateSkipped, false); + assert.equal(data.files, 3); // two transcripts + one chat from the database; the draft is skipped + assert.equal(data.sessions.has('draft'), false); + + // A chat with a transcript keeps its activity and gains model choice and mode. + const ide = data.sessions.get('ide-1'); + assert.equal(ide.modelChoice, 'claude-4.5-opus-high-thinking'); + assert.deepEqual([...ide.modes], ['agent']); + + const old = data.sessions.get('old-1'); + assert.equal(old.entrypoint, 'cursor-ide'); + assert.equal(old.prompts.size, 1); + assert.equal(old.modelChoice, 'default'); + assert.deepEqual([...old.modes], ['plan']); + assert.equal(data.titles.get('old-1'), 'Fix the build'); + const tools = data.tools.filter((x) => x.sessionId === 'old-1'); + assert.deepEqual(tools.map((x) => [x.name, x.timestamp]), [ + ['search_replace', '2025-12-06T11:00:08Z'], + ['run_terminal_cmd', '2025-12-06T11:00:09Z'], + ]); + assert.equal(tools[0].edit, true); + assert.deepEqual(tools[1].shellCommands.map((c) => c.toLowerCase()), ['git']); + assert.equal(tools[0].project.toLowerCase(), path.join(dir, 'App').toLowerCase()); + + // Auto model: share of the sessions that log the model picked. + const stats = sessionStats(data, {}); + assert.deepEqual(stats.filter((s) => s.autoModel).map((s) => s.id), ['old-1']); + assert.equal(stats.filter((s) => s.modelChoice != null).length, 2); + } finally { + await rm(root, { recursive: true, force: true }); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/test/plugins.test.mjs b/test/plugins.test.mjs index 6d01615..14a5c87 100644 --- a/test/plugins.test.mjs +++ b/test/plugins.test.mjs @@ -3,7 +3,7 @@ import assert from 'node:assert/strict'; import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { loadPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; +import { loadPlugins, loadCopilotPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; import { buildSummary } from '../src/report.mjs'; import { toMarkdown } from '../src/formats.mjs'; @@ -79,3 +79,48 @@ test('no plugin config means no plugins', async () => { const root = await mkdtemp(path.join(tmpdir(), 'ccreports-plugins-')); assert.deepEqual(await loadPlugins([path.join(root, 'projects')]), []); }); + +test('GitHub Copilot plugins: installs, enabled state and skills used with or without prefix', async () => { + const root = await mkdtemp(path.join(tmpdir(), 'ccreports-plugins-')); + const cache = path.join(root, 'installed-plugins', 'market', 'dotnet'); + await mkdir(path.join(cache, 'skills', 'csharp-refactoring'), { recursive: true }); + await mkdir(path.join(root, 'session-state')); + await writeFile(path.join(cache, 'plugin.json'), JSON.stringify({ name: 'dotnet', skills: ['./skills/'] })); + await writeFile( + path.join(root, 'config.json'), + '// This file is managed automatically.\n' + + JSON.stringify({ + installedPlugins: [ + { name: 'dotnet', marketplace: 'market', version: '0.2.4', installed_at: '2026-10-01T11:57:20Z', cache_path: cache, enabled: true }, + { name: 'off', marketplace: 'market', version: '1.0.0', enabled: true }, + ], + }), + ); + await writeFile(path.join(root, 'settings.json'), JSON.stringify({ enabledPlugins: { 'off@market': false } })); + const plugins = await loadCopilotPlugins([path.join(root, 'session-state')]); + assert.deepEqual( + plugins.map((p) => [p.id, p.version, p.enabled, p.product]), + [ + ['dotnet@market', '0.2.4', true, 'GitHub Copilot'], + ['off@market', '1.0.0', false, 'GitHub Copilot'], // settings.json wins over config.json + ], + ); + + const totals = { + skills: new Map([['csharp-refactoring', { model: 1, user: 1 }], ['dotnet:setup', { model: 0, user: 1 }], ['plan', { model: 3, user: 0 }]]), + commands: new Map(), + agents: new Map(), + mcpServers: new Map(), + hooks: new Map(), + }; + const rows = pluginRows(plugins, totals); + assert.equal(rows[0].usage.skills, 3); + assert.equal(pluginsJSON(rows)[0].skillNames, undefined); + + // Plugins from two products get a Product column. + const claude = { ...rows[1], product: 'Claude Code' }; + const empty = { tools: new Map(), mcpServers: new Map(), skills: new Map(), commands: new Map(), hooks: new Map(), agents: new Map(), models: new Map(), sessions: new Set(), projects: new Set(), toolTokens: new Map(), mcpServerTokens: new Map(), skillTokens: new Map(), shellCategories: new Map() }; + const md = toMarkdown(buildSummary({ totals: empty }, { top: 15, showCost: false, plugins: [rows[0], claude] })); + assert.match(md, /\| Product \| Plugin \|/); + assert.match(md, /\| GitHub Copilot \| dotnet \| market \| 0\.2\.4 \|/); +});