@letsrebase/verify 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.claude/commands/rebase-verify.md +118 -0
  2. package/LICENSE +21 -0
  3. package/PRIVACY.md +113 -0
  4. package/README.md +210 -2
  5. package/SECURITY.md +33 -0
  6. package/bin/rebase-verify.mjs +700 -0
  7. package/package.json +38 -4
  8. package/share/practices.json +224 -0
  9. package/share/tech-labels.json +57 -0
  10. package/share/tech-lexicon.json +62 -0
  11. package/src/adapters/claude-code.mjs +225 -0
  12. package/src/adapters/codex.mjs +476 -0
  13. package/src/adapters/cursor.mjs +584 -0
  14. package/src/adapters/kimi.mjs +594 -0
  15. package/src/adapters/omp.mjs +59 -0
  16. package/src/adapters/opencode.mjs +439 -0
  17. package/src/adapters/pi.mjs +414 -0
  18. package/src/adapters/tool-vocab.mjs +15 -0
  19. package/src/agent-run.mjs +10 -0
  20. package/src/agentic-literacy.mjs +211 -0
  21. package/src/agents/acp.mjs +364 -0
  22. package/src/agents/json-answer.mjs +72 -0
  23. package/src/agents/registry.mjs +370 -0
  24. package/src/agents/run.mjs +131 -0
  25. package/src/ai-relationship.mjs +95 -0
  26. package/src/consistency.mjs +382 -0
  27. package/src/days.mjs +45 -0
  28. package/src/digest.mjs +501 -0
  29. package/src/distribution.mjs +54 -0
  30. package/src/enrich.mjs +118 -0
  31. package/src/fingerprint.mjs +134 -0
  32. package/src/forensics.mjs +178 -0
  33. package/src/groundedness.mjs +347 -0
  34. package/src/hub.mjs +136 -0
  35. package/src/intensity.mjs +132 -0
  36. package/src/live-status.mjs +79 -0
  37. package/src/practices-llm.mjs +90 -0
  38. package/src/practices-rules.mjs +295 -0
  39. package/src/practices-sample.mjs +111 -0
  40. package/src/practices.mjs +279 -0
  41. package/src/profile-llm.mjs +249 -0
  42. package/src/profile.mjs +497 -0
  43. package/src/redact.mjs +97 -0
  44. package/src/sources.mjs +91 -0
  45. package/src/submit.mjs +65 -0
  46. package/src/system-text.mjs +3 -0
  47. package/src/tech-usage.mjs +88 -0
  48. package/src/trajectory.mjs +264 -0
  49. package/src/wizard.mjs +411 -0
@@ -0,0 +1,584 @@
1
+ // cursor-agent adapter: reads Cursor's per-session SQLite blob-DAG
2
+ // (~/.cursor/chats/<32hex>/<session-uuid>/store.db, one db per session) and
3
+ // normalises it into the SAME session model claude-code.mjs, opencode.mjs,
4
+ // codex.mjs and pi.mjs produce, so every downstream lens (digest, agentic-
5
+ // literacy, forensics, fingerprint, intensity, distribution) keeps working
6
+ // unchanged. `cursor-agent -p`/`--print` is already recognised by digest.mjs's
7
+ // AGENT_LAUNCHER_RE — this adapter is pure log-reading, no digest changes.
8
+ //
9
+ // This is the most structurally involved adapter in the repo. Two things
10
+ // make it unlike anything else here:
11
+ //
12
+ // 1. Storage is a content-addressed BLOB DAG, not a log. `meta(key, value)`
13
+ // holds one row — value is HEX-ENCODED UTF-8 JSON — carrying the session
14
+ // id, a `latestRootBlobId` pointer, and (never stored downstream) a
15
+ // model-generated title. `blobs(id, data)` is content-addressed: id =
16
+ // sha256(data) hex. A blob is either a JSON message ({"role": ...},
17
+ // first byte 0x7B) or a small hand-rolled protobuf message (anything
18
+ // else). The ONLY thing we walk the protobuf for is the root blob
19
+ // pointed to by latestRootBlobId, and from it we take exactly three
20
+ // fields: field 1 (repeated 32-byte hashes, IN ORDER — this is the
21
+ // entire conversation ordering; there is no other index), field 9 (cwd,
22
+ // as a file:// URI), and field 26 (a last-updated epoch-ms varint).
23
+ // Every other field in the root message (workspace-file references,
24
+ // rule/tool metadata, timezone...) is structurally present but
25
+ // deliberately unread — the brief that drove this adapter verified
26
+ // those against a real session and none of them carry conversation
27
+ // content we need. The message blobs themselves are then walked in
28
+ // field-1 order and classified purely by their `role`.
29
+ //
30
+ // 2. The db is LIVE — cursor-agent keeps writing to it (WAL mode) for the
31
+ // lifetime of the session. Opening it directly, even read-only, races a
32
+ // concurrent writer and node:sqlite's read-only mode does not itself
33
+ // guarantee a consistent snapshot of a growing WAL file. So every read
34
+ // COPIES the trio (store.db, -wal, -shm — wal/shm may not exist, copy
35
+ // whatever is there) into a throwaway mkdtemp() dir first and only ever
36
+ // opens THAT copy, read-only, cleaning it up in a finally. This is the
37
+ // one adapter in the repo where "copy before read" is load-bearing, not
38
+ // just tidy. The residual risk a three-file, non-atomic copy can never
39
+ // fully close is a torn main-db copy (a checkpoint mid-copy leaves us
40
+ // with half-old/half-new pages); when that happens the copy degrades
41
+ // into the existing unreadableSessions/skip paths — DatabaseSync fails
42
+ // to open it outright, or per-message JSON.parse fails and the message
43
+ // is counted in files[].malformed — never a silent bad read.
44
+ //
45
+ // Privacy / exclusions, all deliberate:
46
+ // - meta.name (the model-generated conversation title) is NEVER stored —
47
+ // same precedent set for kimi's title/lastPrompt fields elsewhere in this
48
+ // repo. A title is a dense free-text summary of exactly what the human
49
+ // was doing; that's precisely the kind of thing this tool structurally
50
+ // avoids capturing.
51
+ // - Only `~/.cursor/chats/<hex>/<uuid>/store.db(+wal,+shm)` is ever opened.
52
+ // `~/.cursor/prompt_history.json` (raw global prompt history outside any
53
+ // session), `cli-config.json`, `projects/`, and any local sockets are
54
+ // never resolved or read — chats/ is the only subtree this adapter walks.
55
+ // - Tool call/result payloads follow the same structural-capture posture as
56
+ // every other adapter: Write's `contents`, StrReplace-style old/new text,
57
+ // and tool-result `result`/`experimental_content` bodies are never
58
+ // stored — only paths, truncated commands/queries, and byte counts.
59
+ // - Reasoning `text` is empty in every real blob observed; its `signature`
60
+ // (an opaque provider blob, not reasoning content) is reduced to a
61
+ // length, exactly like Claude Code's redacted-thinking signature and
62
+ // codex's encrypted_content.
63
+ //
64
+ // Timestamp honesty: cursor stores NO per-message timestamp. The only
65
+ // timestamps that exist are meta.createdAt (session creation) and the root
66
+ // blob's field 26 (last-updated), plus a human-readable
67
+ // "<timestamp>Saturday, Jul 18, 2026, 6:16 AM (UTC)</timestamp>" tag Cursor's
68
+ // own framework wrapper injects into EVERY <user_query> turn. We parse that
69
+ // tag (tolerantly — day-name and the "(UTC)" suffix aren't ISO) as the one
70
+ // real per-turn clock signal we have; every assistant/tool message in
71
+ // between inherits the most recent parsed user timestamp; the very first
72
+ // emitted message falls back to meta.createdAt. This means duration signals
73
+ // derived from cursor sessions are coarse — accurate to the user-turn
74
+ // granularity, not to individual assistant/tool steps — and that coarseness
75
+ // is a property of the source format, not a shortcut taken here.
76
+ //
77
+ // Usage: cursor persists NO per-message token usage anywhere in the blob DAG
78
+ // (grep-verified across every blob in a real session) — every message's
79
+ // `usage` is null, never invented from a context-budget snapshot.
80
+ //
81
+ // Version-gate warning: this is an UNDOCUMENTED internal format with no
82
+ // stability guarantee across cursor-agent releases (confirmed against
83
+ // v2026.07.16 on this machine). The adapter's only defense is shape-checking
84
+ // at every step — missing tables/rows/fields, malformed JSON, an unopenable
85
+ // copy, or an unrecognised protobuf wire type all degrade to "skip and
86
+ // count in stats", never throw.
87
+
88
+ import { readdirSync, readFileSync, existsSync, mkdtempSync, copyFileSync, rmSync } from "node:fs";
89
+ import { join } from "node:path";
90
+ import { homedir, tmpdir } from "node:os";
91
+ import { createHash } from "node:crypto";
92
+ import { createRequire } from "node:module";
93
+ import { redactText, countRedactions } from "../redact.mjs";
94
+ import { toPosix } from "./claude-code.mjs";
95
+ import { fallbackToolName } from "./tool-vocab.mjs";
96
+
97
+ const require = createRequire(import.meta.url);
98
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
99
+ const shortHash = (s) => sha256(s).slice(0, 8);
100
+ const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
101
+
102
+ // node:sqlite is experimental and only present on Node >= 22.5 (same gate as
103
+ // opencode.mjs). Unlike opencode there is no JSON fallback for cursor — the
104
+ // blob DAG has no other on-disk representation — so Node < 22.5 yields an
105
+ // EMPTY bundle with stats.backend: null, and the sources block discloses it.
106
+ function loadSqlite() {
107
+ try {
108
+ return require("node:sqlite");
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ // ── Default location ────────────────────────────────────────────────────────
115
+ // cursor-agent documents no env-var override for the chats root (unlike
116
+ // CODEX_HOME); ~/.cursor/chats is the only location observed. Only THIS
117
+ // subdirectory is ever walked — see the header comment for what's excluded.
118
+ export function defaultCursorRoot() {
119
+ return join(homedir(), ".cursor", "chats");
120
+ }
121
+
122
+ // ── Tool vocabulary: cursor → canonical (Claude Code) names ─────────────────
123
+ // Cursor's own toolName strings are already close to canonical (Read, Write,
124
+ // Grep, Glob, TodoWrite all pass through fallbackToolName unchanged) — only
125
+ // "Shell" needs an explicit rewrite to "Bash". "StrReplace" (cursor's
126
+ // string-replace edit tool, grep-confirmed in a real session's blob DAG) is
127
+ // mapped to "Edit" so it lands in digest.mjs's MUTATION set — unmapped it
128
+ // fell through fallbackToolName unchanged and cursor sessions editing files
129
+ // exclusively via StrReplace read as zero-mutation and got misclassified.
130
+ // Its path arg lives under the already-covered `path` key (confirmed against
131
+ // the real blob: keys are old_string/new_string/path — old_string/new_string
132
+ // are never read by buildToolUse's known-key list, see below). Anything not
133
+ // in this table (including tools not yet observed) falls through to the same
134
+ // shared fallback every other adapter uses.
135
+ const TOOL_MAP = { Shell: "Bash", StrReplace: "Edit" };
136
+ function mapTool(name) {
137
+ if (!name) return name;
138
+ if (TOOL_MAP[name]) return TOOL_MAP[name];
139
+ return fallbackToolName(name);
140
+ }
141
+
142
+ // tool-call args -> {path, cmd, q}, generic across tools (mirrors opencode's
143
+ // reduceParts): path/cmd/q are pulled from known-safe argument keys only.
144
+ // Write's `contents` and a StrReplace-style call's old_string/new_string are
145
+ // never read here, so they can never leak into the bundle no matter what
146
+ // unmapped tool names show up in future cursor-agent releases.
147
+ function buildToolUse(id, name, rawArgs) {
148
+ const args = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : {};
149
+ const mapped = mapTool(name);
150
+ const path = toPosix(redactText(String(args.path || args.file_path || args.filePath || "")));
151
+ const cmd = mapped === "Bash" ? redactText(String(args.command || "").slice(0, 240)) : "";
152
+ const q = redactText(String(args.pattern || args.glob_pattern || args.query || args.url || "").slice(0, 200));
153
+ return { id, name: mapped, path, cmd, q };
154
+ }
155
+
156
+ // A tool-result part's isError lives under providerOptions.cursor — checked
157
+ // first on the part itself, then (since real data shows it living there
158
+ // instead) on the enclosing message's own providerOptions. Absent either way
159
+ // defaults to false, same posture as every other adapter's isError guard.
160
+ function resultIsError(part, message) {
161
+ if (part && part.providerOptions && part.providerOptions.cursor && part.providerOptions.cursor.highLevelToolCallResult) {
162
+ if (part.providerOptions.cursor.highLevelToolCallResult.isError === true) return true;
163
+ }
164
+ if (message && message.providerOptions && message.providerOptions.cursor && message.providerOptions.cursor.highLevelToolCallResult) {
165
+ return message.providerOptions.cursor.highLevelToolCallResult.isError === true;
166
+ }
167
+ return false;
168
+ }
169
+
170
+ // ── Minimal hand-rolled protobuf walker (zero deps, per repo rule) ─────────
171
+ // Reads tag/value pairs from a buffer without any schema: fieldNo = tag >> 3,
172
+ // wireType = tag & 7. wt0 (varint) and wt2 (length-delimited bytes) are kept;
173
+ // wt5 (32-bit) and wt1 (64-bit) are skipped by their fixed width; any other
174
+ // wire type means we've lost sync (or hit a shape we don't understand) and we
175
+ // bail, returning whatever was parsed so far — callers treat a missing field
176
+ // as simply absent, never as an error. Varint values are accumulated with
177
+ // BigInt (a field like the epoch-ms timestamp routinely exceeds 2^32) and
178
+ // only narrowed to Number at the end.
179
+ function readVarint(buf, pos) {
180
+ let result = 0n;
181
+ let shift = 0n;
182
+ let i = pos;
183
+ while (i < buf.length) {
184
+ const byte = buf[i++];
185
+ result |= BigInt(byte & 0x7f) << shift;
186
+ if ((byte & 0x80) === 0) break;
187
+ shift += 7n;
188
+ if (shift > 70n) return { value: 0n, next: pos, ok: false }; // runaway varint: bail
189
+ }
190
+ return { value: result, next: i, ok: true };
191
+ }
192
+
193
+ export function pbFields(buf) {
194
+ const fields = new Map();
195
+ const push = (fieldNo, value) => {
196
+ if (!fields.has(fieldNo)) fields.set(fieldNo, []);
197
+ fields.get(fieldNo).push(value);
198
+ };
199
+ let i = 0;
200
+ while (i < buf.length) {
201
+ const tagRes = readVarint(buf, i);
202
+ if (!tagRes.ok || tagRes.next === i) break;
203
+ const tag = Number(tagRes.value);
204
+ i = tagRes.next;
205
+ const fieldNo = tag >>> 3;
206
+ const wireType = tag & 7;
207
+ if (wireType === 0) {
208
+ const v = readVarint(buf, i);
209
+ if (!v.ok) break;
210
+ i = v.next;
211
+ push(fieldNo, Number(v.value));
212
+ } else if (wireType === 2) {
213
+ const l = readVarint(buf, i);
214
+ if (!l.ok) break;
215
+ const len = Number(l.value);
216
+ if (len < 0 || l.next + len > buf.length) break; // malformed length: bail
217
+ push(fieldNo, buf.subarray(l.next, l.next + len));
218
+ i = l.next + len;
219
+ } else if (wireType === 5) {
220
+ i += 4;
221
+ } else if (wireType === 1) {
222
+ i += 8;
223
+ } else {
224
+ break; // unrecognised wire type: bail, return what was parsed
225
+ }
226
+ }
227
+ return fields;
228
+ }
229
+
230
+ // "<timestamp>Saturday, Jul 18, 2026, 6:16 AM (UTC)</timestamp>" -> ISO, or
231
+ // null when absent/unparseable. Tolerant: strips the leading day name (not
232
+ // part of any Date-parseable format) and turns the "(UTC)" suffix into a
233
+ // bare "UTC" the platform Date parser understands.
234
+ const TIMESTAMP_TAG_RE = /<timestamp>([^<]*)<\/timestamp>/;
235
+ function parseWrapperTimestamp(text) {
236
+ const m = TIMESTAMP_TAG_RE.exec(text);
237
+ if (!m) return null;
238
+ const cleaned = m[1].trim().replace(/^[A-Za-z]+,\s*/, "").replace(/\(UTC\)/, "UTC");
239
+ const ms = Date.parse(cleaned);
240
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
241
+ }
242
+
243
+ // "<user_query>\n...\n</user_query>" -> inner text, or null when the tag is
244
+ // absent from this block (a pure framework-wrapper block with no real query).
245
+ const USER_QUERY_RE = /<user_query>([\s\S]*?)<\/user_query>/;
246
+ function extractUserQuery(text) {
247
+ const m = USER_QUERY_RE.exec(text);
248
+ return m ? m[1].trim() : null;
249
+ }
250
+
251
+ // Two-level scan: <root>/<hex-dir>/<uuid-dir>/store.db. We do NOT validate
252
+ // the hex-dir name against md5(cwd) — the brief that drove this adapter
253
+ // confirmed real cwd comes from inside the db (root blob field 9), not from
254
+ // this directory name, so treating the name as anything but an opaque path
255
+ // segment would be relying on an assumption cursor-agent never promised to
256
+ // keep. Anything unreadable (permissions, a stray file where a dir is
257
+ // expected) is skipped rather than thrown — but every skip is COUNTED in
258
+ // acc.discoveryErrors so a root that silently yields zero sessions because
259
+ // readdir keeps failing is distinguishable from a root that legitimately has
260
+ // no sessions (see stats.discoveryErrors on the returned bundle).
261
+ function discoverSessions(root, acc) {
262
+ const out = [];
263
+ let level1;
264
+ try {
265
+ level1 = readdirSync(root, { withFileTypes: true });
266
+ } catch {
267
+ acc.discoveryErrors++;
268
+ return out;
269
+ }
270
+ for (const d1 of level1) {
271
+ if (!d1.isDirectory()) continue;
272
+ let level2;
273
+ try {
274
+ level2 = readdirSync(join(root, d1.name), { withFileTypes: true });
275
+ } catch {
276
+ acc.discoveryErrors++;
277
+ continue;
278
+ }
279
+ for (const d2 of level2) {
280
+ if (!d2.isDirectory()) continue;
281
+ const dbPath = join(root, d1.name, d2.name, "store.db");
282
+ if (existsSync(dbPath)) out.push({ hexDir: d1.name, uuidDir: d2.name, dbPath });
283
+ }
284
+ }
285
+ return out;
286
+ }
287
+
288
+ // Push one normalised message. usage is always null (see header comment —
289
+ // cursor persists no per-message token usage anywhere in the blob DAG).
290
+ function emit(session, acc, { role, ts, uuid, parentUuid, text, toolUses, toolResults, thinkingChars, signatureChars, model }) {
291
+ acc.redactionHits += countRedactions(text);
292
+ const textRedacted = redactText(text);
293
+ acc.redactedChars += text.length - textRedacted.length;
294
+ session.messages.push({
295
+ role,
296
+ ts,
297
+ uuid,
298
+ parentUuid,
299
+ model: model || null,
300
+ textRedacted,
301
+ textLen: text.length,
302
+ thinkingChars: thinkingChars || 0,
303
+ signatureChars: signatureChars || 0,
304
+ toolUses: toolUses || [],
305
+ toolResults: toolResults || [],
306
+ usage: null,
307
+ });
308
+ session.chain.push({ uuid, parentUuid, ts });
309
+ }
310
+
311
+ // Copy the trio, open the COPY read-only, reconstruct one session. Any
312
+ // failure anywhere in here (bad meta, missing/garbage root blob, an
313
+ // unopenable copy) propagates to the caller, which counts it in
314
+ // stats.unreadableSessions and moves on — this function never partially
315
+ // mutates caller state on failure.
316
+ function readSession(dbPath, hexDir, uuidDir, sqlite, acc) {
317
+ const tmpDir = mkdtempSync(join(tmpdir(), "cursor-"));
318
+ try {
319
+ const copiedDb = join(tmpDir, "store.db");
320
+ // Copy -wal/-shm BEFORE the main store.db, not after: a live writer can
321
+ // checkpoint (fold the WAL into the main file) between the two copies no
322
+ // matter which order we pick, so this can never be made fully atomic —
323
+ // but the two orderings fail differently. wal/shm first means the worst
324
+ // case is a WAL copy that's stale relative to the main file we copy next,
325
+ // yet still self-consistent (sqlite just re-applies frames the main copy
326
+ // may already reflect). Main first risks the opposite: a main file that
327
+ // gets checkpointed out from under a wal/shm copy taken afterward, which
328
+ // is a torn pairing, not merely a stale one.
329
+ for (const suffix of ["-wal", "-shm"]) {
330
+ const src = dbPath + suffix;
331
+ if (existsSync(src)) copyFileSync(src, copiedDb + suffix);
332
+ }
333
+ copyFileSync(dbPath, copiedDb);
334
+
335
+ const db = new sqlite.DatabaseSync(copiedDb, { readOnly: true });
336
+ try {
337
+ const metaRow = db.prepare("SELECT value FROM meta LIMIT 1").get();
338
+ if (!metaRow || typeof metaRow.value !== "string") throw new Error("cursor: no meta row");
339
+ const metaJson = JSON.parse(Buffer.from(metaRow.value, "hex").toString("utf8"));
340
+ const sessionId = metaJson.agentId;
341
+ if (!sessionId) throw new Error("cursor: meta missing agentId");
342
+ const createdAtIso = iso(metaJson.createdAt);
343
+ // meta.name is the model-generated conversation title — see header
344
+ // comment. It is read here only to confirm it exists, NEVER assigned
345
+ // to anything that ends up in the session object.
346
+
347
+ const blobStmt = db.prepare("SELECT data FROM blobs WHERE id = ?");
348
+ const rootHash = metaJson.latestRootBlobId;
349
+ if (!rootHash) throw new Error("cursor: meta missing latestRootBlobId");
350
+ const rootRow = blobStmt.get(rootHash);
351
+ if (!rootRow) throw new Error("cursor: root blob missing");
352
+ const rootBuf = Buffer.from(rootRow.data);
353
+ const rootFields = pbFields(rootBuf);
354
+
355
+ const msgHashes = (rootFields.get(1) || []).map((b) => Buffer.from(b));
356
+
357
+ let cwdRaw = "";
358
+ const cwdField = rootFields.get(9);
359
+ if (cwdField && cwdField[0]) {
360
+ const raw = Buffer.from(cwdField[0]).toString("utf8");
361
+ const stripped = raw.replace(/^file:\/\//, "");
362
+ try {
363
+ cwdRaw = decodeURIComponent(stripped);
364
+ } catch {
365
+ cwdRaw = stripped; // malformed % escape: keep the raw (still usable) path
366
+ }
367
+ }
368
+
369
+ const originatorField = rootFields.get(22);
370
+ const originator = originatorField && originatorField[0] ? Buffer.from(originatorField[0]).toString("utf8") : null;
371
+
372
+ const updatedField = rootFields.get(26);
373
+ const lastUpdatedIso = updatedField && Number.isFinite(updatedField[0]) ? iso(updatedField[0]) : null;
374
+
375
+ const session = {
376
+ source: "cursor",
377
+ sessionId,
378
+ projectLabel: cwdRaw ? `project-${shortHash(cwdRaw)}` : "project-unknown",
379
+ cwdRedacted: toPosix(redactText(cwdRaw)),
380
+ cwdRaw, // local-only; never sent in the bundle
381
+ gitBranch: null, // cursor does not record the branch in the fields we read
382
+ cliVersions: [], // no per-session app version lives in the fields this adapter reads
383
+ models: new Set(),
384
+ messages: [],
385
+ chain: [], // {uuid, parentUuid, ts}
386
+ firstTs: createdAtIso,
387
+ lastTs: null,
388
+ };
389
+
390
+ let currentTs = createdAtIso;
391
+ let prevUuid = null;
392
+ let emittedIdx = 0;
393
+ let malformed = 0;
394
+
395
+ for (const hashBuf of msgHashes) {
396
+ const row = blobStmt.get(hashBuf.toString("hex"));
397
+ if (!row) continue; // root references a blob this copy doesn't have: skip, don't throw
398
+ const raw = Buffer.from(row.data);
399
+ if (raw[0] !== 0x7b) continue; // not a JSON message blob (defensive; field 1 should only hold those)
400
+ let obj;
401
+ try {
402
+ obj = JSON.parse(raw.toString("utf8"));
403
+ } catch {
404
+ malformed++;
405
+ continue;
406
+ }
407
+ if (!obj || typeof obj !== "object") continue;
408
+
409
+ const role = obj.role;
410
+ if (role === "system") continue; // framework system prompt: drop entirely
411
+
412
+ if (role === "user") {
413
+ const content = obj.content;
414
+ if (typeof content === "string") continue; // framework-injected <user_info> turn: drop
415
+ if (!Array.isArray(content)) continue;
416
+ let text = "";
417
+ let parsedTs = null;
418
+ for (const block of content) {
419
+ if (!block || block.type !== "text" || typeof block.text !== "string") continue;
420
+ if (!parsedTs) {
421
+ const t = parseWrapperTimestamp(block.text);
422
+ if (t) parsedTs = t;
423
+ }
424
+ const q = extractUserQuery(block.text);
425
+ if (q !== null) text += q + "\n";
426
+ }
427
+ if (!text.trim()) continue; // every block was framework-wrapped (or none survived): drop the message
428
+ if (parsedTs) currentTs = parsedTs;
429
+ const uuid = `${sessionId}-m${emittedIdx}`;
430
+ const parentUuid = prevUuid;
431
+ emit(session, acc, { role: "user", ts: currentTs, uuid, parentUuid, text, toolUses: [], toolResults: [] });
432
+ prevUuid = uuid;
433
+ emittedIdx++;
434
+ continue;
435
+ }
436
+
437
+ if (role === "assistant") {
438
+ const content = Array.isArray(obj.content) ? obj.content : [];
439
+ let text = "";
440
+ let thinkingChars = 0;
441
+ let signatureChars = 0;
442
+ let model = null;
443
+ const toolUses = [];
444
+ for (const part of content) {
445
+ if (!part || typeof part !== "object") continue;
446
+ if (part.type === "reasoning") {
447
+ thinkingChars += (part.text || "").length;
448
+ signatureChars += (part.signature || "").length;
449
+ const m = part.providerOptions && part.providerOptions.cursor && part.providerOptions.cursor.modelName;
450
+ // Defensive redaction, same precedent as pi.mjs's model_change
451
+ // handling: pi's local-model ids turned out to carry
452
+ // filesystem paths. Cursor's modelName is a hosted gateway
453
+ // string today ("cursor-grok-4.5-high-fast"), but redactText
454
+ // is identity on strings with no path/secret shape, so this
455
+ // costs nothing and closes the same class of leak if that
456
+ // ever changes.
457
+ if (m) model = redactText(String(m));
458
+ } else if (part.type === "text") {
459
+ text += (part.text || "") + "\n";
460
+ } else if (part.type === "tool-call") {
461
+ toolUses.push(buildToolUse(part.toolCallId, part.toolName, part.args));
462
+ }
463
+ }
464
+ if (model) session.models.add(model);
465
+ const uuid = `${sessionId}-m${emittedIdx}`;
466
+ const parentUuid = prevUuid;
467
+ emit(session, acc, { role: "assistant", ts: currentTs, uuid, parentUuid, text, toolUses, toolResults: [], thinkingChars, signatureChars, model });
468
+ prevUuid = uuid;
469
+ emittedIdx++;
470
+ continue;
471
+ }
472
+
473
+ if (role === "tool") {
474
+ const content = Array.isArray(obj.content) ? obj.content : [];
475
+ const toolResults = [];
476
+ for (const part of content) {
477
+ if (!part || part.type !== "tool-result") continue;
478
+ toolResults.push({
479
+ forId: part.toolCallId,
480
+ isError: resultIsError(part, obj),
481
+ // Result content (part.result / experimental_content) is NEVER
482
+ // stored — only its serialized byte length, per the brief's
483
+ // exact rule.
484
+ bytes: JSON.stringify(part.result ?? "").length,
485
+ });
486
+ }
487
+ const uuid = `${sessionId}-m${emittedIdx}`;
488
+ const parentUuid = prevUuid;
489
+ emit(session, acc, { role: "tool", ts: currentTs, uuid, parentUuid, text: "", toolUses: [], toolResults });
490
+ prevUuid = uuid;
491
+ emittedIdx++;
492
+ continue;
493
+ }
494
+ // Any other role: unrecognised shape, skip without counting — forward-compat.
495
+ }
496
+
497
+ session.lastTs = lastUpdatedIso || (session.messages.length ? session.messages[session.messages.length - 1].ts : createdAtIso);
498
+
499
+ if (originator) acc.originatorCounts[originator] = (acc.originatorCounts[originator] || 0) + 1;
500
+
501
+ const dbBuf = readFileSync(copiedDb);
502
+ const file = {
503
+ relPath: `${hexDir}/${uuidDir}/store.db`,
504
+ sha256: sha256(dbBuf),
505
+ bytes: dbBuf.length,
506
+ lines: 0, // not line-oriented; malformed carries the JSON-blob parse-failure count instead
507
+ malformed,
508
+ cwdRaw: session.cwdRaw,
509
+ };
510
+
511
+ return { session: { ...session, models: [...session.models] }, file };
512
+ } finally {
513
+ // Cleanup must never turn a successful read into a thrown error — a
514
+ // close/rm failure here would otherwise supersede a pending `return`
515
+ // (finally-block semantics) and wrongly count a GOOD session as
516
+ // unreadable.
517
+ try {
518
+ db.close();
519
+ } catch {
520
+ // no-op
521
+ }
522
+ }
523
+ } finally {
524
+ try {
525
+ rmSync(tmpDir, { recursive: true, force: true });
526
+ } catch {
527
+ // no-op: best-effort temp-dir cleanup, never lets a successful read fail
528
+ }
529
+ }
530
+ }
531
+
532
+ const EMPTY = (root) => ({
533
+ source: "cursor",
534
+ root: root || null,
535
+ files: [],
536
+ sessions: [],
537
+ compactionSummaries: [], // cursor has no compaction-summary convention to mine
538
+ redaction: { hits: 0, charsRemoved: 0 },
539
+ stats: { unreadableSessions: 0, originatorCounts: {}, backend: null, discoveryErrors: 0 },
540
+ });
541
+
542
+ export function readCursor(root = defaultCursorRoot()) {
543
+ if (!root || !existsSync(root)) return EMPTY(root);
544
+
545
+ // Discovery is pure fs readdir, no sqlite involved — it runs (and its
546
+ // failures are disclosed via stats.discoveryErrors) even on Node < 22.5,
547
+ // where node:sqlite is unavailable and everything else below degrades to
548
+ // EMPTY. This is why the "root exists but readdir keeps failing" case is
549
+ // never silently indistinguishable from "root has zero sessions".
550
+ const acc = { redactionHits: 0, redactedChars: 0, unreadableSessions: 0, originatorCounts: {}, discoveryErrors: 0 };
551
+ const discovered = discoverSessions(root, acc);
552
+
553
+ const sqlite = loadSqlite();
554
+ if (!sqlite) {
555
+ // Node < 22.5: no JSON fallback exists for this format.
556
+ return { ...EMPTY(root), stats: { ...EMPTY(root).stats, discoveryErrors: acc.discoveryErrors } };
557
+ }
558
+
559
+ const sessions = [];
560
+ const files = [];
561
+
562
+ for (const { hexDir, uuidDir, dbPath } of discovered) {
563
+ try {
564
+ const { session, file } = readSession(dbPath, hexDir, uuidDir, sqlite, acc);
565
+ sessions.push(session);
566
+ files.push(file);
567
+ } catch {
568
+ // Bad meta, missing/garbage root blob, or an unopenable copy (e.g. a
569
+ // store.db that isn't a valid sqlite file): skip this session, disclose
570
+ // the count, never throw out of the adapter.
571
+ acc.unreadableSessions++;
572
+ }
573
+ }
574
+
575
+ return {
576
+ source: "cursor",
577
+ root,
578
+ files,
579
+ sessions,
580
+ compactionSummaries: [],
581
+ redaction: { hits: acc.redactionHits, charsRemoved: acc.redactedChars },
582
+ stats: { unreadableSessions: acc.unreadableSessions, originatorCounts: acc.originatorCounts, backend: "sqlite", discoveryErrors: acc.discoveryErrors },
583
+ };
584
+ }