From 972744560693fb899dfe849414a225389f718da6 Mon Sep 17 00:00:00 2001 From: Peter Bons Date: Tue, 27 Oct 2026 15:29:39 +0100 Subject: [PATCH] Report Cursor activity with --source cursor A new loader (src/cursor.mjs) reads Cursor's agent transcripts (~/.cursor/projects//agent-transcripts//.jsonl), written by both the Cursor CLI and the agent in the Cursor editor. --source all now covers Claude Code, GitHub Copilot and Cursor. Cursor keeps token usage on its servers, so its sessions count in activity only: sessions, prompts, tools, skills, slash commands and adoption. - Activity records (one per prompt) count sessions that have no tokens. - Reports on data without any token usage leave out the token, cost, context, request and model columns instead of showing zeros. - Skills you invoke come from the skill block Cursor attaches to your message; skills the agent uses are reads of a SKILL.md in a skills folder Cursor loads from (.cursor/skills, .claude/skills, ...). - Each record gets the time of the prompt that started its turn; the project comes from the CLI's session metadata or the decoded folder name. - Recommendations get a Cursor profile; without tokens only the workflow checks (step-by-step coding, skills) can fire. - Adoption labels the Cursor CLI and editor, and outside Claude-only reports the phase descriptions say "the agent" instead of "Claude". Co-Authored-By: Claude Opus 5.5 --- README.md | 52 +++++++- bin/ccreports.mjs | 41 ++++-- skills/report/SKILL.md | 11 +- src/adoption.mjs | 10 +- src/aggregate.mjs | 3 + src/copilot.mjs | 3 +- src/cursor.mjs | 275 ++++++++++++++++++++++++++++++++++++++++ src/recommendations.mjs | 28 +++- src/report.mjs | 107 +++++++++------- test/cursor.test.mjs | 144 +++++++++++++++++++++ 10 files changed, 608 insertions(+), 66 deletions(-) create mode 100644 src/cursor.mjs create mode 100644 test/cursor.test.mjs diff --git a/README.md b/README.md index aadfdb0..ac94c6e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ccreports -Reports Claude Code (and [GitHub Copilot](#github-copilot)) **tool calls, skills, slash commands, subagents, token usage and cost** from +Reports Claude Code (and [GitHub Copilot](#github-copilot) and [Cursor](#cursor)) **tool calls, skills, slash commands, subagents, token usage and cost** from the local session transcripts in `~/.claude/projects`. Inspired by [ccusage](https://github.com/ccusage/ccusage), which covers tokens and cost; ccreports adds what you actually *did* with those tokens. @@ -199,8 +199,9 @@ byte order mark so Excel shows non-ASCII characters correctly. | `--no-subagents` | Exclude subagent transcripts | | `--compact` | Hide cache token columns (automatic below 120 columns) | | `--dir ` | Projects directory (repeatable). Default: `CLAUDE_CONFIG_DIR` (comma-separated) or `~/.claude` / `~/.config/claude` | -| `--source ` | `claude` (default), `copilot` or `all` - see [GitHub Copilot](#github-copilot) | +| `--source ` | `claude` (default), `copilot`, `cursor` or `all` - see [GitHub Copilot](#github-copilot) and [Cursor](#cursor) | | `--copilot-dir ` | Copilot session-state directory (repeatable). Default: `COPILOT_HOME` or `~/.copilot`, then `session-state` | +| `--cursor-dir ` | Cursor config directory (repeatable). Default: `CURSOR_CONFIG_DIR` or `~/.cursor` | | `-v, --version` | Print the ccreports version. Reports name it too: in the HTML header line, as a footer in table and Markdown output, and as `ccreportsVersion` in JSON | ### GitHub Copilot @@ -265,6 +266,53 @@ checks work differently for Copilot: With `--source all`, each product gets its own recommendations, weighed against its own cost, and in JSON every recommendation has a `source`. +### Cursor + +`--source cursor` reports Cursor, from the agent transcripts in +`~/.cursor/projects//agent-transcripts//.jsonl`. Both the +Cursor CLI and the agent in the Cursor editor write them. `--source all` +adds Cursor to Claude Code and GitHub Copilot. + +```sh +node bin/ccreports.mjs --source cursor # summary +node bin/ccreports.mjs session --source cursor +node bin/ccreports.mjs adoption --source cursor +``` + +**Activity only.** Cursor keeps token usage on its servers. Its local logs +have no tokens, models or cost, so Cursor reports leave out those columns. +In `--source all` reports, Cursor sessions count in sessions, tools, skills +and adoption, but add nothing to tokens and cost. + +How the transcripts map onto the reports: + +- **Sessions and prompts:** one transcript per session. A prompt is a + message with a ``. Cursor's own session metadata + (`~/.cursor/chats/…/meta.json`) marks a session as CLI and gives its title + and working directory. Sessions without it come from the editor. +- **Time:** lines have no timestamps. Recent prompts carry one, and every + record gets the time of the prompt that started its turn. Older transcripts + without any use the file's modification time. +- **Project:** the working directory from the CLI's metadata. Otherwise the + transcript's folder name (`Z-Sources-My-App`), decoded against the folders + that exist on disk. `(no folder)` is the editor without an open folder. +- **Tools** keep Cursor's names (`Read`, `Shell`, `Write`, …). Tools called + through `CallDynamicTool` count under their own name; those outside + Cursor's namespace count as MCP tools (`mcp____`). `-x` + breaks down `Shell` commands. Edits are `Write`, `Edit`, `StrReplace`, + `MultiEdit` and `Delete`. `SwitchMode` and `CreatePlan` mark plan mode. +- **Skills you invoke** come from the skill block Cursor attaches to your + message (`/github` in the CLI, or picked in the editor). **Skills the + agent uses** are `Read` calls on a `SKILL.md` in a skills folder Cursor + loads from, such as `.cursor/skills`, `.claude/skills` or `.agents/skills`. + 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. + ## What is counted - **Tokens** – `usage` from each assistant message, deduplicated per diff --git a/bin/ccreports.mjs b/bin/ccreports.mjs index 1ec6775..3a94e95 100644 --- a/bin/ccreports.mjs +++ b/bin/ccreports.mjs @@ -5,6 +5,7 @@ import path from 'node:path'; 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 { 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'; @@ -15,7 +16,7 @@ import { openFile, FORMAT_EXTENSIONS } from '../src/open.mjs'; import { loadPlugins, pluginRows, pluginsJSON } from '../src/plugins.mjs'; import { VERSION } from '../src/version.mjs'; -const HELP = `ccreports - Claude Code (and GitHub Copilot) tool, skill, slash-command and token usage +const HELP = `ccreports - Claude Code (and GitHub Copilot, Cursor) tool, skill, slash-command and token usage Usage: ccreports [report] [options] @@ -31,7 +32,8 @@ Reports: recommendations Best-practice recommendations based on your usage, with the cost at stake Options: - --source claude (default), copilot (GitHub Copilot CLI / VS Code agent) or all + --source claude (default), copilot (GitHub Copilot CLI / VS Code agent), + cursor (Cursor CLI / editor agent; activity only, no tokens) or all -s, --since Include from this date (YYYYMMDD or YYYY-MM-DD) -u, --until Include up to and including this date -p, --project Only projects whose path contains (case-insensitive) @@ -54,6 +56,7 @@ Options: --no-color Disable colors (also honors NO_COLOR) --dir Projects directory to scan (repeatable; default from CLAUDE_CONFIG_DIR or ~/.claude) --copilot-dir Copilot session-state directory (repeatable; default from COPILOT_HOME or ~/.copilot) + --cursor-dir Cursor config directory (repeatable; default from CURSOR_CONFIG_DIR or ~/.cursor) -v, --version Show the ccreports version -h, --help Show this help `; @@ -91,6 +94,7 @@ try { dir: { type: 'string', multiple: true }, source: { type: 'string' }, 'copilot-dir': { type: 'string', multiple: true }, + 'cursor-dir': { type: 'string', multiple: true }, version: { type: 'boolean', short: 'v' }, help: { type: 'boolean', short: 'h' }, }, @@ -114,7 +118,7 @@ if (!REPORTS.includes(report)) fail(`unknown report "${report}". Expected one of if (positionals.length > 1) fail(`unexpected argument "${positionals[1]}"`); if (opts.order && !['asc', 'desc'].includes(opts.order)) fail('--order must be asc or desc'); const source = (opts.source ?? 'claude').toLowerCase(); -if (!['claude', 'copilot', 'all'].includes(source)) fail('--source must be claude, copilot or all'); +if (!['claude', 'copilot', 'cursor', 'all'].includes(source)) fail('--source must be claude, copilot, cursor or all'); let format = opts.json ? 'json' : (opts.format ?? 'table').toLowerCase(); if (format === 'md') format = 'markdown'; @@ -147,16 +151,30 @@ const toTTY = !opts.output && !opts.open && process.stdout.isTTY; const includeSubagents = !opts['no-subagents']; const dirs = opts.dir?.length ? opts.dir : defaultProjectDirs(); const copilotDirs = opts['copilot-dir']?.length ? opts['copilot-dir'] : defaultCopilotDirs(); -const claudeData = source !== 'copilot' ? await loadRecords({ dirs, includeSubagents }) : null; -const copilotData = source !== 'claude' ? await loadCopilotRecords({ dirs: copilotDirs, includeSubagents }) : null; -const data = claudeData && copilotData ? mergeData(claudeData, copilotData) : claudeData ?? copilotData; +const cursorDirs = opts['cursor-dir']?.length ? opts['cursor-dir'] : defaultCursorDirs(); +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 loaded = [claudeData, copilotData, cursorData].filter(Boolean); +const data = loaded.length > 1 ? mergeData(...loaded) : loaded[0]; if (data.files === 0) { - const scanned = [...(claudeData ? dirs : []), ...(copilotData ? copilotDirs : [])]; - fail(`no ${source === 'copilot' ? 'sessions' : 'transcripts'} found in: ${scanned.join(', ')}`); + const scanned = [...(claudeData ? dirs : []), ...(copilotData ? copilotDirs : []), ...(cursorData ? cursorDirs : [])]; + fail(`no ${source === 'claude' ? 'transcripts' : 'sessions'} found in: ${scanned.join(', ')}`); } -const product = { claude: 'Claude Code', copilot: 'GitHub Copilot', all: 'Claude Code and GitHub Copilot' }[source]; +const product = { + claude: 'Claude Code', + copilot: 'GitHub Copilot', + cursor: 'Cursor', + all: 'Claude Code, GitHub Copilot and Cursor', +}[source]; -const showCost = !opts['no-cost']; +// Cursor logs no token usage: its own reports leave out cost, and combined +// ones count its sessions in activity only. +const showCost = !opts['no-cost'] && source !== 'cursor'; +if (source === 'all' && cursorData?.files) { + console.error('ccreports: Cursor logs no token usage; its sessions count in activity (prompts, tools, skills) only.'); +} let pricer, pricingSource; if (showCost) { const pricing = await loadPricingTable({ offline: opts.offline }); @@ -195,6 +213,8 @@ const docOpts = { pricer, plugins, product, + // No token usage at all (Cursor alone): reports leave out the token columns. + tokens: data.usage.length > 0, }; // The adoption assessment and recommendations: their own reports, or appended @@ -207,6 +227,7 @@ if (report === 'recommendations' || opts.recommendations) { const parts = [ ['claude', claudeData], ['copilot', copilotData], + ['cursor', cursorData], ] .filter(([, d]) => d?.files) .map(([src, d]) => ({ src, doc: buildRecommendations(d, { ...docOpts, source: src }) })); diff --git a/skills/report/SKILL.md b/skills/report/SKILL.md index dc905de..87a859a 100644 --- a/skills/report/SKILL.md +++ b/skills/report/SKILL.md @@ -1,6 +1,6 @@ --- name: report -description: Report the user's own Claude Code usage from their local session logs (~/.claude/projects), and their GitHub Copilot CLI / VS Code agent usage (~/.copilot/session-state) - tokens and estimated API cost, tool / skill / slash-command / hook / subagent counts and the tokens each consumed, context size, sessions, an adoption assessment (chat, assisted, agent-first, multi-agent) and best-practice recommendations backed by their data. Use when the user asks how much they used or spent, which tools or skills they use most, what consumes their tokens, how their usage trends per day/week/month/project/session, how far they have adopted agentic workflows, how to use Claude Code or Copilot more effectively or cheaply, how their Claude Code and Copilot usage compare, or wants such a report as a table, Markdown, CSV, JSON or HTML page. +description: Report the user's own Claude Code usage from their local session logs (~/.claude/projects), their GitHub Copilot CLI / VS Code agent usage (~/.copilot/session-state), and their Cursor CLI / editor agent activity (~/.cursor/projects) - tokens and estimated API cost, tool / skill / slash-command / hook / subagent counts and the tokens each consumed, context size, sessions, an adoption assessment (chat, assisted, agent-first, multi-agent) and best-practice recommendations backed by their data. Use when the user asks how much they used or spent, which tools or skills they use most, what consumes their tokens, how their usage trends per day/week/month/project/session, how far they have adopted agentic workflows, how to use Claude Code, Copilot or Cursor more effectively or cheaply, how their usage of these tools compares, or wants such a report as a table, Markdown, CSV, JSON or HTML page. argument-hint: "[summary|daily|weekly|monthly|session|project|adoption|recommendations] [options]" --- @@ -33,7 +33,8 @@ the request: | an adoption / maturity assessment | `adoption`, or `-a` to add it to another report | | advice: how to use Claude Code better or cheaper | `recommendations`, or `-r` to add it to another report | | the same for GitHub Copilot (CLI or VS Code agent) | any of the above with `--source copilot` | -| Claude Code and Copilot together, or compared | any of the above with `--source all` (recommendations get a section per product) | +| the same for Cursor (CLI or editor agent; activity only, no tokens or cost) | any of the above with `--source cursor` | +| Claude Code, Copilot and Cursor together, or compared | any of the above with `--source all` (recommendations get a section per product) | Useful options: `-s/--since` and `-u/--until` (`YYYYMMDD`), `-p/--project `, `-n/--top `, `--compact`, `--no-cost`, `-f/--format table|json|csv|markdown|html`, @@ -65,7 +66,7 @@ of every table. Keep these caveats in mind and mention them when relevant: - The adoption phases are per session, from the user's own logs; PRs are those Claude Code created. -With `--source copilot` or `all`, also keep in mind: +With `--source copilot`, `cursor` or `all`, also keep in mind: - Copilot cost is what it billed in AI credits (1 AIU = $0.01); where nothing was billed, Claude models are priced at API rates and other models (GPT, @@ -75,3 +76,7 @@ With `--source copilot` or `all`, also keep in mind: shut down cleanly have no token counts. - Copilot's tokens per tool are rougher than Claude Code's: they are scaled down to at most what each session sent. +- Cursor keeps token usage on its servers: Cursor reports show activity only + (sessions, prompts, tools, skills, commands, adoption), and add nothing to + tokens or cost in combined reports. Skills the agent picks itself are + inferred from it reading a SKILL.md. diff --git a/src/adoption.mjs b/src/adoption.mjs index e4877db..c99a32a 100644 --- a/src/adoption.mjs +++ b/src/adoption.mjs @@ -27,6 +27,8 @@ const SURFACES = { remote: 'Web', 'copilot-cli': 'Copilot CLI', 'copilot-vscode': 'Copilot in VS Code', + 'cursor-cli': 'Cursor CLI', + 'cursor-ide': 'Cursor editor', }; /** Places one session's stats in a phase (first matching rule wins). */ @@ -166,9 +168,11 @@ export function buildAdoption(data, opts) { right('PRs'), right('Edits per session'), right('Median tool calls per prompt'), - right('Tokens per session'), + ...(opts.tokens !== false ? [right('Tokens per session')] : []), ...(showCost ? [right('Cost per session')] : []), ]; + // The phase descriptions name Claude; other products' reports say "the agent". + const agentName = (opts.product ?? 'Claude Code') === 'Claude Code' ? 'Claude' : 'The agent'; const cohortRows = PHASES.map((p) => { const list = byPhase.get(p.key); const prs = sum(list, (s) => s.prs); @@ -176,14 +180,14 @@ export function buildAdoption(data, opts) { return { cells: [ p.title, - p.description, + p.description.replace(/^Claude\b/, agentName), average(prs, list.length), list.length, share(list.length, stats.length), prs, average(sum(list, (s) => s.edits), list.length), m == null ? '' : average(m, 1), - list.length ? Math.round(sum(list, (s) => s.totalTokens) / 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) : ''] : []), ], }; diff --git a/src/aggregate.mjs b/src/aggregate.mjs index 7045b7e..07f9263 100644 --- a/src/aggregate.mjs +++ b/src/aggregate.mjs @@ -299,6 +299,9 @@ export function aggregate(data, { report = 'summary', since, until, project, tim } } + // Activity without tokens (Cursor's prompts): counts the session and its time only. + for (const rec of data.events ?? []) accept(rec); + for (const rec of data.hooks ?? []) { for (const b of accept(rec) ?? []) { const h = b.hooks.get(rec.command) ?? { events: new Set(), runs: 0, errors: 0, blocked: 0, durationMs: 0, contextTokens: 0 }; diff --git a/src/copilot.mjs b/src/copilot.mjs index 9c6d19c..d99efa5 100644 --- a/src/copilot.mjs +++ b/src/copilot.mjs @@ -424,10 +424,11 @@ export function mergeData(...parts) { skills: [...first.skills], commands: [...first.commands], hooks: [...first.hooks], + events: [...(first.events ?? [])], }; for (const p of rest) { out.files += p.files; - for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks']) out[k].push(...p[k]); + for (const k of ['usage', 'tools', 'skills', 'commands', 'hooks', 'events']) out[k].push(...(p[k] ?? [])); for (const [k, v] of p.sessions) out.sessions.set(k, v); for (const [k, v] of p.titles) out.titles.set(k, v); } diff --git a/src/cursor.mjs b/src/cursor.mjs new file mode 100644 index 0000000..23dbbca --- /dev/null +++ b/src/cursor.mjs @@ -0,0 +1,275 @@ +// Reads Cursor's agent transcripts (~/.cursor/projects//agent-transcripts//.jsonl), +// written by both the Cursor CLI and the agent in the Cursor editor, and +// returns the same normalized records as loadRecords() in src/loader.mjs. +// +// Cursor keeps token usage on its servers, so these logs have no usage, model +// or cost: Cursor sessions count in activity (prompts, tools, skills, commands, +// adoption) only. Other differences from Claude Code's transcripts: +// - Lines carry no timestamps; prompts do (in a tag) in recent +// versions. Every record gets the time of the prompt that started its turn, +// or the transcript's modification time when the prompt has none. +// - The project folder name is the working directory with every separator +// turned into "-"; it is decoded against the folders that exist, or taken +// from the CLI's own session metadata (~/.cursor/chats///meta.json). +// - A skill you invoke arrives as a block in your +// message; a skill the agent picks itself is a Read of its SKILL.md. +// - Tools Cursor loads on demand are called through CallDynamicTool; they are +// counted under their own name (MCP tools as mcp____). +// +// The format is undocumented, so every field access is defensive. + +import { createReadStream, existsSync } from 'node:fs'; +import { readdir, readFile, stat } from 'node:fs/promises'; +import { createInterface } from 'node:readline'; +import { homedir } from 'node:os'; +import path from 'node:path'; +import { shellCommands } from './shell.mjs'; +import { normalizeSkillName } from './loader.mjs'; + +const EDIT_TOOLS = new Set(['Write', 'Edit', 'StrReplace', 'MultiEdit', 'Delete', 'ApplyPatch', 'EditNotebook']); +const WEB_TOOLS = new Set(['WebSearch', 'WebFetch']); +const AGENT_TOOLS = new Set(['Task', 'Agent']); +// Cursor's Shell tool runs the platform's shell. +const SHELL = process.platform === 'win32' ? 'PowerShell' : 'Bash'; +// A skill folder Cursor loads from: .cursor/skills, .cursor/skills-cursor (built in), +// .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; +const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/** The Cursor config directory, honoring CURSOR_CONFIG_DIR. */ +export function defaultCursorDirs() { + return [process.env.CURSOR_CONFIG_DIR || path.join(homedir(), '.cursor')]; +} + +/** "Tuesday, Oct 27, 2026, 2:44 PM (UTC+1)" -> ISO timestamp, or null. */ +export function parsePromptTime(text) { + const m = /([A-Z][a-z]{2}) (\d{1,2}), (\d{4}), (\d{1,2}):(\d{2}) (AM|PM)(?: \(UTC([+-]\d{1,2})(?::?(\d{2}))?\))?/.exec( + String(text ?? ''), + ); + if (!m) return null; + const month = MONTHS.indexOf(m[1]); + if (month < 0) return null; + let hour = Number(m[4]) % 12; + if (m[6] === 'PM') hour += 12; + const offset = m[7] ? Number(m[7]) * 60 + Math.sign(Number(m[7]) || 1) * Number(m[8] ?? 0) : 0; + const utc = Date.UTC(Number(m[3]), month, Number(m[2]), hour, Number(m[5])) - offset * 60_000; + return new Date(utc).toISOString(); +} + +/** + * "Z-Sources-Ibis-Calculeren-Shared" -> "Z:\Sources\Ibis.Calculeren.Shared" when + * that folder exists: each "-" is a separator, or part of a name (as "-", "." + * or " "). Falls back to the folder name. + */ +export function decodeProjectDir(name, exists = existsSync) { + if (name === 'empty-window') return '(no folder)'; + const m = /^([A-Za-z])-(.*)$/.exec(name); + const [root, rest] = m ? [`${m[1].toUpperCase()}:\\`, m[2]] : ['/', name]; + const sep = m ? '\\' : '/'; + const parts = rest.split('-').filter(Boolean); + // Depth-first over how the parts join up, checking each folder exists. + const walk = (dir, i) => { + if (i === parts.length) return dir; + for (let j = parts.length; j > i; j--) { + for (const glue of ['-', '.', ' ']) { + const seg = parts.slice(i, j).join(glue); + const next = dir.endsWith(sep) ? dir + seg : dir + sep + seg; + if (exists(next)) { + const found = walk(next, j); + if (found) return found; + } + if (j - i === 1) break; // one part: no glue to vary + } + } + return null; + }; + return walk(root, 0) ?? name; +} + +/** CLI sessions: id -> { cwd, title } from ~/.cursor/chats///meta.json. */ +async function readCliSessions(root) { + const out = new Map(); + let hashes; + try { + hashes = await readdir(path.join(root, 'chats')); + } catch { + return out; + } + for (const hash of hashes) { + let ids; + try { + ids = await readdir(path.join(root, 'chats', hash)); + } catch { + continue; + } + for (const id of ids) { + try { + const meta = JSON.parse(await readFile(path.join(root, 'chats', hash, id, 'meta.json'), 'utf8')); + out.set(id, { cwd: meta.cwd ?? null, title: meta.title ?? null }); + } catch { + out.set(id, { cwd: null, title: null }); + } + } + } + return out; +} + +async function listTranscripts(root) { + const files = []; + let projects; + try { + projects = await readdir(path.join(root, 'projects'), { withFileTypes: true }); + } catch { + return files; + } + for (const p of projects) { + if (!p.isDirectory()) continue; + const dir = path.join(root, 'projects', p.name, 'agent-transcripts'); + let ids; + try { + ids = await readdir(dir); + } catch { + continue; + } + for (const id of ids) { + const file = path.join(dir, id, `${id}.jsonl`); + try { + files.push({ id, projectDir: p.name, file, mtime: (await stat(file)).mtime.toISOString() }); + } catch { + // a folder without its transcript + } + } + } + return files; +} + +const textOf = (content) => + (Array.isArray(content) ? content : []) + .filter((c) => c?.type === 'text' && typeof c.text === 'string') + .map((c) => c.text) + .join('\n'); + +/** A dynamic tool call counts under the tool it calls. */ +function toolName(c) { + if (c.name !== 'CallDynamicTool' || !c.input?.toolName) return c.name; + const ns = c.input.namespace; + return !ns || ns === 'cursor' ? c.input.toolName : `mcp__${ns}__${c.input.toolName}`; +} + +export async function loadCursorRecords({ dirs = defaultCursorDirs(), includeSubagents = true } = {}) { + const tools = []; + const skills = []; + const commands = []; + const events = []; // one per prompt: activity without tokens + const titles = new Map(); + const sessions = new Map(); + const psNames = new Map(); + const psName = (name) => { + if (!psNames.has(name.toLowerCase())) psNames.set(name.toLowerCase(), name); + return psNames.get(name.toLowerCase()); + }; + const decoded = new Map(); // project folder name -> path + let fileCount = 0; + + for (const root of dirs) { + const cli = await readCliSessions(root); + for (const { id, projectDir, file, mtime } of await listTranscripts(root)) { + fileCount += 1; + const meta = cli.get(id); + if (!decoded.has(projectDir)) decoded.set(projectDir, decodeProjectDir(projectDir)); + const project = meta?.cwd || decoded.get(projectDir); + if (meta?.title) titles.set(id, meta.title); + const info = { + entrypoint: meta ? 'cursor-cli' : 'cursor-ide', + prompts: new Set(), + prs: new Set(), + compactions: new Set(), + modes: new Set(), + }; + sessions.set(id, info); + + let timestamp = null; // of the current turn's prompt + let turn = 0; + let pendingCommand = null; // a /command typed this turn, waiting for its skill read + const base = () => ({ timestamp: timestamp ?? mtime, sessionId: id, project, agent: null, source: 'cursor' }); + + const rl = createInterface({ input: createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity }); + for await (const line of rl) { + let d; + try { + d = JSON.parse(line); + } catch { + continue; + } + const content = d.message?.content; + + if (d.role === 'user') { + const text = textOf(content); + const query = /\s*([\s\S]*?)\s*<\/user_query>/.exec(text); + if (!query) continue; // not something the user typed + turn += 1; + timestamp = parsePromptTime(/([^<]+)<\/timestamp>/.exec(text)?.[1]) ?? timestamp; + info.prompts.add(turn); + events.push(base()); + pendingCommand = null; + const cmd = /^\/([\w:.-]+)/.exec(query[1]); + if (cmd) { + const name = '/' + normalizeSkillName(cmd[1]); + commands.push({ ...base(), name }); + pendingCommand = name; + } + // Skills the user attached (typed as /name or picked in the editor). + const attached = /([\s\S]*?)<\/manually_attached_skills>/.exec(text)?.[1] ?? ''; + for (const m of attached.matchAll(/^Skill Name:\s*(.+?)\s*$/gm)) { + skills.push({ ...base(), name: normalizeSkillName(m[1]), source: 'user' }); + pendingCommand = null; // its content is attached: no read follows + } + continue; + } + + if (d.role !== 'assistant') continue; + for (const c of Array.isArray(content) ? content : []) { + if (c?.type !== 'tool_use' || !c.name) continue; + const name = toolName(c); + const input = (c.name === 'CallDynamicTool' ? c.input?.arguments : c.input) ?? {}; + const tool = { ...base(), name }; + if (AGENT_TOOLS.has(name)) { + if (!includeSubagents) continue; + tool.subagentType = input.subagent_type || input.subagentType || 'general-purpose'; + if (input.run_in_background || input.background) tool.background = true; + } + if (EDIT_TOOLS.has(name)) tool.edit = true; + if (WEB_TOOLS.has(name)) tool.web = true; + if (name === 'Shell' && typeof input.command === 'string') { + const names = shellCommands(input.command, SHELL); + tool.shellCommands = SHELL === 'PowerShell' ? names.map(psName) : names; + } + if (name === 'SwitchMode' && input.target_mode_id) info.modes.add(input.target_mode_id); + if (name === 'CreatePlan') info.modes.add('plan'); + tools.push(tool); + // The agent loads a skill by reading its SKILL.md. + const skill = name === 'Read' && SKILL_FILE.exec(String(input.path ?? ''))?.[1]; + if (skill) { + const byUser = pendingCommand === `/${skill}`; + skills.push({ ...base(), name: normalizeSkillName(skill), source: byUser ? 'user' : 'model' }); + if (byUser) pendingCommand = null; + } + } + } + } + } + + return { + sessions, + charsPerToken: null, + files: fileCount, + usage: [], + tools, + skills, + commands, + hooks: [], + events, + titles, + }; +} diff --git a/src/recommendations.mjs b/src/recommendations.mjs index cb03784..21dc69a 100644 --- a/src/recommendations.mjs +++ b/src/recommendations.mjs @@ -122,6 +122,29 @@ const PRODUCTS = { 'A failing hook gives none of the protection it was added for, and a failing `preToolUse` hook also denies the tool call. Use absolute paths so hooks still resolve when Copilot works in a subfolder, check that the interpreter (python, node) is on PATH, and remove stale ones from the configuration that defines them.', }, }, + // Cursor's logs have no tokens, so only the workflow checks (autonomy, skills) can fire. + cursor: { + name: 'Cursor', + explorationTools: new Set(['Read', 'Grep', 'Glob', 'LS']), + toolAdvice: {}, + defaultToolAdvice: '', + subagentTokens: false, + subagentModel: false, + worktrees: false, + parallel: false, // Cursor's logs show no subagent launches to measure + advice: { + longContext: '', + delegate: '', + compaction: '', + cache: {}, + autonomy: + 'Describe the whole task up front - goal, constraints and how to verify it - and let the agent run. Use Plan mode for bigger changes, so you agree on the plan once instead of steering each step, and turn workflows you repeat into skills.', + parallel: '', + skills: + 'Capture the instructions you keep repeating (how to test, release, review or plan in this repo) as a skill (`.cursor/skills//SKILL.md`, or `~/.cursor/skills` for all your projects), so the agent follows them every time without you typing them out.', + hooks: '', + }, + }, }; const fmt = (n) => Math.round(n).toLocaleString('en-US'); @@ -185,7 +208,8 @@ export function recommend(data, opts = {}) { const p = PRODUCTS[opts.source ?? 'claude']; const inRange = recordFilter(opts); const usage = data.usage.filter(inRange); - if (!usage.length) return []; + // Activity without tokens (Cursor) still feeds the workflow checks. + if (!usage.length && !(data.events ?? []).some(inRange)) return []; const { totals } = aggregate(data, { ...opts, report: 'summary' }); const stats = sessionStats(data, opts); // GitHub Copilot records carry their billed cost. @@ -386,7 +410,7 @@ export function recommend(data, opts = {}) { const share = (f) => stats.filter(f).length / stats.length; const background = share((s) => s.backgroundAgents > 0); const worktrees = share((s) => s.worktrees > 0); - if (background < 0.1 && (!p.worktrees || worktrees < 0.1)) { + if (p.parallel !== false && background < 0.1 && (!p.worktrees || worktrees < 0.1)) { recs.push({ id: 'parallel', title: 'Run independent work in parallel', diff --git a/src/report.mjs b/src/report.mjs index 4857dae..2cd3848 100644 --- a/src/report.mjs +++ b/src/report.mjs @@ -52,7 +52,11 @@ const localTime = (timestamp, timeZone) => minute: '2-digit', }).format(new Date(timestamp)); -function tokenColumns({ compact, showCost }) { +// `tokens: false` (activity-only data, such as Cursor's) leaves out every token, +// cost, context and request column. + +function tokenColumns({ compact, showCost, tokens }) { + if (tokens === false) return []; const cols = compact ? [right('Input'), right('Output'), right('Total Tokens')] : [right('Input'), right('Output'), right('Cache Create'), right('Cache Read'), right('Total Tokens')]; @@ -90,7 +94,8 @@ function exact(a) { }; } -function subTokenCells(u, { compact, showCost }) { +function subTokenCells(u, { compact, showCost, tokens }) { + if (tokens === false) return []; const cells = !u ? (compact ? ['', '', ''] : ['', '', '', '', '']) : compact @@ -100,7 +105,8 @@ function subTokenCells(u, { compact, showCost }) { return cells; } -function tokenCells(b, { compact, showCost }) { +function tokenCells(b, { compact, showCost, tokens }) { + if (tokens === false) return []; const cells = compact ? [b.inputTokens, b.outputTokens, b.totalTokens] : [b.inputTokens, b.outputTokens, b.cacheCreationTokens, b.cacheReadTokens, b.totalTokens]; @@ -193,16 +199,20 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { // sense for the other reports. Per Session is filled on breakdown sub-rows. const sessionColumns = isSession ? [] : [right('Sessions'), ...(hasSubRows ? [right('Per Session')] : [])]; const sessionCells = (b) => (isSession ? [] : [b.sessions.size, ...(hasSubRows ? [''] : [])]); + const withTokens = opts.tokens !== false; + const contextCols = withTokens ? contextColumns(isSession) : []; const columns = [ ...lead, - left('Models', 28), + ...(withTokens ? [left('Models', 28)] : []), ...tokenColumns(opts), - ...contextColumns(isSession), + ...contextCols, ...sessionColumns, ...COUNT_COLUMNS, ]; const blankLead = lead.map(() => ''); - const emptyContext = contextColumns(isSession).map(() => ''); + const emptyContext = contextCols.map(() => ''); + const modelCell = (text) => (withTokens ? [text] : []); + const contextOf = (b) => (withTokens ? contextCells(b, isSession) : []); // Sub-row: label in the first column, the item's tokens and cost under Total // Tokens / Cost, its count under Tools / Skills / Cmds / Agents, and the count @@ -214,7 +224,7 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { subLead[0] = label; const perSession = isSession ? [] : ['', average(count, b.sessions.size)]; return { - cells: [...subLead, '', ...subTokenCells(usage, opts), ...emptyContext, ...perSession, ...counts], + cells: [...subLead, ...modelCell(''), ...subTokenCells(usage, opts), ...emptyContext, ...perSession, ...counts], style: 'sub', }; }; @@ -228,9 +238,9 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { rows.push({ cells: [ ...leadCells, - models.join(', '), + ...modelCell(models.join(', ')), ...tokenCells(b, opts), - ...contextCells(b, isSession), + ...contextOf(b), ...sessionCells(b), ...countCells(b), ], @@ -263,9 +273,9 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { rows.push({ cells: [ ...totalLead, - '', + ...modelCell(''), ...tokenCells(totals, opts), - ...contextCells(totals, isSession), + ...contextOf(totals), ...sessionCells(totals), ...countCells(totals), ], @@ -281,12 +291,12 @@ export function buildPeriodReport(report, { buckets, totals }, opts) { /** Summary: totals plus ranked tool / MCP / skill / command / subagent / model tables. */ export function buildSummary({ totals }, opts) { const { top, showCost } = opts; + const withTokens = opts.tokens !== false; const sections = [ { columns: [ ...tokenColumns(opts), - ...contextColumns(false), - right('Requests'), + ...(withTokens ? [...contextColumns(false), right('Requests')] : []), right('Sessions'), right('Projects'), ...COUNT_COLUMNS, @@ -295,8 +305,7 @@ export function buildSummary({ totals }, opts) { { cells: [ ...tokenCells(totals, opts), - ...contextCells(totals, false), - totals.requests, + ...(withTokens ? [...contextCells(totals, false), totals.requests] : []), totals.sessions.size, totals.projects.size, ...countCells(totals), @@ -317,14 +326,17 @@ export function buildSummary({ totals }, opts) { // 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 = [ - right('Input (est.)'), - right('Output (est.)'), - right('Tokens (est.)'), - ...(showCost ? [right('Cost (est.)')] : []), - right('Token share'), - ]; + 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), @@ -426,29 +438,34 @@ export function buildSummary({ totals }, opts) { if (totals.subagentLaunches > 0 || [...totals.agents.keys()].some((k) => k !== MAIN_AGENT)) { section( 'Subagents', - [ - left('Type'), - right('Launches'), - right('Requests'), - right('Tool calls'), - right('Input'), - right('Output'), - right('Total Tokens'), - ...costCol, - right('Token share'), - ], - ranked(totals.agents, (a) => a.totalTokens), - ([name, a]) => [ - name, - name === MAIN_AGENT ? '' : a.launches, - a.requests, - a.toolCalls, - a.inputTokens + a.cacheCreationTokens + a.cacheReadTokens, - a.outputTokens, - a.totalTokens, - ...costCell(a.costUSD), - share(a.totalTokens, totals.totalTokens), - ], + withTokens + ? [ + left('Type'), + right('Launches'), + right('Requests'), + right('Tool calls'), + right('Input'), + right('Output'), + right('Total Tokens'), + ...costCol, + right('Token share'), + ] + : [left('Type'), right('Launches'), right('Tool calls')], + ranked(totals.agents, (a) => (withTokens ? a.totalTokens : a.launches)), + ([name, a]) => + withTokens + ? [ + name, + name === MAIN_AGENT ? '' : a.launches, + a.requests, + a.toolCalls, + a.inputTokens + a.cacheCreationTokens + a.cacheReadTokens, + a.outputTokens, + a.totalTokens, + ...costCell(a.costUSD), + share(a.totalTokens, totals.totalTokens), + ] + : [name, name === MAIN_AGENT ? '' : a.launches, a.toolCalls], ); } diff --git a/test/cursor.test.mjs b/test/cursor.test.mjs new file mode 100644 index 0000000..d8a562c --- /dev/null +++ b/test/cursor.test.mjs @@ -0,0 +1,144 @@ +import { test } from 'node:test'; +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 { loadCursorRecords, parsePromptTime, decodeProjectDir } from '../src/cursor.mjs'; +import { aggregate } from '../src/aggregate.mjs'; +import { buildSummary } from '../src/report.mjs'; +import { sessionStats } from '../src/adoption.mjs'; + +test('parsePromptTime reads Cursor prompt timestamps with their UTC offset', () => { + assert.equal(parsePromptTime('Tuesday, Oct 27, 2026, 2:44 PM (UTC+1)'), '2026-10-27T13:44:00.000Z'); + assert.equal(parsePromptTime('Monday, Jan 5, 2026, 12:05 AM (UTC-5)'), '2026-01-05T05:05:00.000Z'); + assert.equal(parsePromptTime('Friday, Mar 6, 2026, 9:30 AM'), '2026-03-06T09:30:00.000Z'); + assert.equal(parsePromptTime('no time here'), null); +}); + +test('decodeProjectDir picks the separators that match existing folders', () => { + const existing = new Set(['Z:\\Sources', 'Z:\\Sources\\Ibis.Calculeren.Shared', 'C:\\Users', 'C:\\Users\\PeterBons']); + const exists = (p) => existing.has(p); + assert.equal(decodeProjectDir('Z-Sources-Ibis-Calculeren-Shared', exists), 'Z:\\Sources\\Ibis.Calculeren.Shared'); + assert.equal(decodeProjectDir('C-Users-PeterBons', exists), 'C:\\Users\\PeterBons'); + assert.equal(decodeProjectDir('empty-window', exists), '(no folder)'); + assert.equal(decodeProjectDir('Q-gone-away', exists), 'Q-gone-away'); +}); + +const user = (text) => ({ role: 'user', message: { content: [{ type: 'text', text } ] } }); +const assistant = (...content) => ({ role: 'assistant', message: { content } }); +const use = (name, input) => ({ type: 'tool_use', name, input }); + +// Recent format: timestamps, a skill attached with /github, dynamic tools. +const recent = [ + user('Tuesday, Oct 27, 2026, 2:44 PM (UTC+1)\n\nplan a page\n'), + assistant( + { type: 'text', text: 'Planning.' }, + use('CallDynamicTool', { namespace: 'cursor', toolName: 'SwitchMode', arguments: { target_mode_id: 'plan' } }), + use('Read', { path: 'C:\\Users\\me\\.cursor\\skills\\browseros-neo\\SKILL.md' }), + use('Read', { path: 'Z:\\Sources\\ccreports\\skills\\report\\SKILL.md' }), // a plugin's source, not a skill in use + use('Shell', { command: 'git status; gh pr list' }), + use('Write', { path: 'z:\\temp\\index.html', contents: '

hi

' }), + use('CallDynamicTool', { namespace: 'github', toolName: 'search_code', arguments: {} }), + ), + { type: 'turn_ended', status: 'success' }, + user( + '\nSkill Name: github\nPath: C:\\Users\\me\\.claude\\skills\\github\\SKILL.md\nSKILL.md content:\n...\n\nTuesday, Oct 27, 2026, 2:50 PM (UTC+1)\n\n/github\n', + ), + assistant(use('Shell', { command: 'gh auth status' })), +]; + +// Older format: no timestamps, a /command whose skill the agent then reads. +const older = [ + user('\n/create-a-text-file\n'), + assistant(use('Read', { path: 'Z:\\Sources\\Test\\.claude\\skills\\create-a-text-file\\SKILL.md' })), + user('not a prompt: no user_query tag'), +]; + +async function fixture() { + const root = await mkdtemp(path.join(tmpdir(), 'ccreports-cursor-')); + const transcript = async (project, id, lines) => { + const dir = path.join(root, 'projects', project, 'agent-transcripts', id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, `${id}.jsonl`), lines.map((l) => JSON.stringify(l)).join('\n') + '\nnot json\n'); + }; + await transcript('C-Users-me', 'cli-1', recent); + await transcript('empty-window', 'ide-1', older); + // The CLI keeps its own metadata per session; the editor doesn't. + await mkdir(path.join(root, 'chats', 'hash', 'cli-1'), { recursive: true }); + await writeFile( + path.join(root, 'chats', 'hash', 'cli-1', 'meta.json'), + JSON.stringify({ cwd: 'C:\\Users\\me', title: 'Page Plan' }), + ); + return root; +} + +test('loadCursorRecords reads prompts, tools, skills and commands from agent transcripts', async () => { + const root = await fixture(); + try { + const data = await loadCursorRecords({ dirs: [root] }); + assert.equal(data.files, 2); + assert.equal(data.usage.length, 0); + assert.equal(data.titles.get('cli-1'), 'Page Plan'); + + const cli = data.sessions.get('cli-1'); + assert.equal(cli.entrypoint, 'cursor-cli'); + assert.equal(cli.prompts.size, 2); + assert.deepEqual([...cli.modes], ['plan']); + assert.equal(data.sessions.get('ide-1').entrypoint, 'cursor-ide'); + assert.equal(data.sessions.get('ide-1').prompts.size, 1); + + const names = data.tools.filter((t) => t.sessionId === 'cli-1').map((t) => t.name); + assert.deepEqual(names, ['SwitchMode', 'Read', 'Read', 'Shell', 'Write', 'mcp__github__search_code', 'Shell']); + const shell = data.tools.find((t) => t.name === 'Shell'); + assert.deepEqual(shell.shellCommands.map((c) => c.toLowerCase()), ['git', 'gh']); + assert.equal(data.tools.find((t) => t.name === 'Write').edit, true); + + // Each record has the time of the prompt that started its turn. + assert.equal(data.tools.find((t) => t.name === 'Write').timestamp, '2026-10-27T13:44:00.000Z'); + assert.equal(data.tools.at(-2).timestamp, '2026-10-27T13:50:00.000Z'); + assert.equal(data.tools.at(-2).project, 'C:\\Users\\me'); + + assert.deepEqual( + data.skills.map((s) => [s.sessionId, s.name, s.source]).sort(), + [ + ['cli-1', 'browseros-neo', 'model'], + ['cli-1', 'github', 'user'], + ['ide-1', 'create-a-text-file', 'user'], + ], + ); + assert.deepEqual(data.commands.map((c) => c.name).sort(), ['/create-a-text-file', '/github']); + assert.equal(data.events.length, 3); // one per prompt + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('Cursor activity counts sessions without tokens, and reports drop token columns', async () => { + const root = await fixture(); + try { + const data = await loadCursorRecords({ dirs: [root] }); + const result = aggregate(data, {}); + assert.equal(result.totals.sessions.size, 2); + assert.equal(result.totals.totalTokens, 0); + + const doc = buildSummary(result, { top: 15, showCost: false, tokens: false, product: 'Cursor' }); + assert.equal(doc.title, 'Cursor usage summary'); + assert.deepEqual( + doc.sections[0].columns.map((c) => c.title), + ['Sessions', 'Projects', 'Tools', 'Skills', 'Cmds', 'Agents'], + ); + const tools = doc.sections.find((s) => s.title === 'Tools'); + assert.deepEqual(tools.columns.map((c) => c.title), ['Tool', 'Calls', 'Share']); + + const stats = sessionStats(data, {}); + assert.deepEqual( + stats.map((s) => [s.id, s.surface, s.edits]).sort(), + [ + ['cli-1', 'Cursor CLI', 1], + ['ide-1', 'Cursor editor', 0], + ], + ); + } finally { + await rm(root, { recursive: true, force: true }); + } +});