rewound 0.4.4 → 0.5.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.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Heavy users of coding agents accumulate gigabytes of session transcripts that ar
10
10
  - **History is perishable.** Claude Code deletes transcripts older than 30 days by default (`cleanupPeriodDays`, swept at startup) — your reasoning history evaporates.
11
11
  - **Agents can't remember.** Every new session rediscovers what a previous session already solved. Nobody serves the agent itself.
12
12
 
13
- rewound indexes every session transcript on your machine — Claude Code and OpenAI Codex CLI today, more harnesses next — into a local SQLite/FTS5 database and exposes it three ways: a CLI, an MCP server your agents can query directly, and a phone-friendly local web UI. Everything runs on your machine. Nothing leaves it.
13
+ rewound indexes every session transcript on your machine — Claude Code, OpenAI Codex CLI, and OpenCode today, more harnesses next — into a local SQLite/FTS5 database and exposes it three ways: a CLI, an MCP server your agents can query directly, and a phone-friendly local web UI. Everything runs on your machine. Nothing leaves it.
14
14
 
15
15
  ## 60-second demo
16
16
 
@@ -66,7 +66,7 @@ node dist/cli.js index # or: npm link, then `rewound index`
66
66
 
67
67
  </details>
68
68
 
69
- By default rewound reads `~/.claude/projects/**/*.jsonl` and Codex CLI sessions from `~/.codex/sessions` (read-only — it never modifies your transcripts) and writes its own database to `~/.rewound/rewound.db`. Override the DB path with `--db <path>` or `REWOUND_DB=<path>`.
69
+ By default rewound reads `~/.claude/projects/**/*.jsonl`, Codex CLI sessions from `~/.codex/sessions`, and OpenCode's session database from `~/.local/share/opencode` (read-only — it never modifies your transcripts, and OpenCode's shared SQLite DB is opened strictly read-only even if OpenCode is writing to it concurrently) and writes its own database to `~/.rewound/rewound.db`. Override roots with `--roots` / `--codex-roots` / `--opencode-roots`, and the DB path with `--db <path>` or `REWOUND_DB=<path>`.
70
70
 
71
71
  ### Multi-machine: your history follows you
72
72
 
@@ -164,7 +164,7 @@ Server-rendered with zero frontend build step, colorblind-safe palette (blue/ora
164
164
 
165
165
  ## Roadmap
166
166
 
167
- More harness adapters are next: Copilot CLI and OpenCode transcripts are already mapped (see repo issues/roadmap). Keyword-first search is deliberate for v0.x — it's fast, local, and predictable. Local hybrid/semantic search (vector index built with a local embedding model, no API keys, fused with FTS ranking) is planned once the keyword surface has proven itself; the gap it closes is vocabulary mismatch ("that time the port was already taken" vs `EADDRINUSE`).
167
+ More harness adapters are next: Copilot CLI is mapped (see repo issues/roadmap). Keyword-first search is deliberate for v0.x — it's fast, local, and predictable. Local hybrid/semantic search (vector index built with a local embedding model, no API keys, fused with FTS ranking) is planned once the keyword surface has proven itself; the gap it closes is vocabulary mismatch ("that time the port was already taken" vs `EADDRINUSE`).
168
168
 
169
169
  ## License
170
170
 
@@ -7,14 +7,42 @@ import path from "node:path";
7
7
  // trailing "\n" yet), the last fragment is torn — leave it unconsumed and
8
8
  // unparsed so the next incremental call re-reads it whole, rather than either
9
9
  // erroring on it or silently skipping past it.
10
- export function consumeCompleteLines(filePath, fromByte) {
10
+ // V8 caps a single string at ~512 MB (ERR_STRING_TOO_LONG), so decoding the
11
+ // whole consumed region in one toString() aborts on transcripts that grew past
12
+ // it even when every individual line is small (#2). Decode in newline-aligned
13
+ // chunks instead: cuts always land after a "\n" byte (0x0a never appears
14
+ // inside a multi-byte UTF-8 sequence), so no record and no character is ever
15
+ // split. A single line longer than the chunk is extended to its terminating
16
+ // newline rather than torn.
17
+ const DECODE_CHUNK_BYTES = 128 * 1024 * 1024;
18
+ export function consumeCompleteLines(filePath, fromByte, chunkBytes = DECODE_CHUNK_BYTES) {
11
19
  const buf = fs.readFileSync(filePath);
12
20
  const slice = buf.subarray(fromByte);
13
21
  const lastNewline = slice.lastIndexOf(0x0a); // "\n"
14
22
  const consumedSlice = lastNewline === -1 ? slice.subarray(0, 0) : slice.subarray(0, lastNewline + 1);
15
23
  const bytesConsumed = fromByte + consumedSlice.length;
16
- const text = consumedSlice.length > 0 ? consumedSlice.toString("utf8") : "";
17
- const lines = text.length > 0 ? text.split("\n") : [];
24
+ const lines = [];
25
+ let offset = 0;
26
+ while (offset < consumedSlice.length) {
27
+ let end = Math.min(offset + chunkBytes, consumedSlice.length);
28
+ if (end < consumedSlice.length) {
29
+ const nl = consumedSlice.lastIndexOf(0x0a, end - 1);
30
+ if (nl >= offset) {
31
+ end = nl + 1;
32
+ }
33
+ else {
34
+ // Single line longer than chunkBytes: consumedSlice always ends on a
35
+ // newline, so the forward scan is guaranteed to find one.
36
+ const next = consumedSlice.indexOf(0x0a, end);
37
+ end = next === -1 ? consumedSlice.length : next + 1;
38
+ }
39
+ }
40
+ for (const line of consumedSlice.subarray(offset, end).toString("utf8").split("\n")) {
41
+ if (line.length > 0)
42
+ lines.push(line); // callers skip blank lines anyway
43
+ }
44
+ offset = end;
45
+ }
18
46
  return { lines, bytesConsumed };
19
47
  }
20
48
  export function walkJsonlFiles(dir, found) {
@@ -0,0 +1,269 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import Database from "better-sqlite3";
4
+ // Storage/snapshot trees under a real OpenCode home can be large and there is
5
+ // no reason to walk them: the db always lives directly at <root>/opencode.db
6
+ // (checked first, below). This bound exists purely as a safety net against a
7
+ // pathologically deep or symlink-cyclic tree if a root is ever pointed
8
+ // somewhere unusual — depth alone bounds a cycle too, since every recursive
9
+ // call increments it regardless of whether the path repeats.
10
+ const MAX_DISCOVER_DEPTH = 8;
11
+ function walkForOpenCodeDb(entry, found, depth = 0) {
12
+ if (depth > MAX_DISCOVER_DEPTH)
13
+ return;
14
+ let stat;
15
+ try {
16
+ stat = fs.statSync(entry);
17
+ }
18
+ catch {
19
+ return;
20
+ }
21
+ if (stat.isFile()) {
22
+ if (path.basename(entry) === "opencode.db")
23
+ found.push(entry);
24
+ return;
25
+ }
26
+ if (!stat.isDirectory())
27
+ return;
28
+ let entries;
29
+ try {
30
+ entries = fs.readdirSync(entry, { withFileTypes: true });
31
+ }
32
+ catch {
33
+ return;
34
+ }
35
+ for (const e of entries) {
36
+ walkForOpenCodeDb(path.join(entry, e.name), found, depth + 1);
37
+ }
38
+ }
39
+ function tieKey(r) {
40
+ return `${r.kind}:${r.row_id}`;
41
+ }
42
+ export class OpenCodeAdapter {
43
+ id = "opencode";
44
+ cursorKind = "watermark";
45
+ discover(roots) {
46
+ const found = [];
47
+ for (const root of roots) {
48
+ // Fast path: the well-known, documented layout — skips walking
49
+ // storage/snapshot/log/tool-output entirely for the common case.
50
+ const wellKnown = path.join(root, "opencode.db");
51
+ let isWellKnownFile = false;
52
+ try {
53
+ isWellKnownFile = fs.statSync(wellKnown).isFile();
54
+ }
55
+ catch {
56
+ // doesn't exist — fall through to the bounded walk below
57
+ }
58
+ if (isWellKnownFile) {
59
+ found.push(wellKnown);
60
+ continue;
61
+ }
62
+ // root may itself be the db file (unusual, but supported), or the db
63
+ // could be nested somewhere under it — bounded recursive fallback.
64
+ walkForOpenCodeDb(root, found);
65
+ }
66
+ return found;
67
+ }
68
+ parseSince(dbPath, cursor) {
69
+ const persistedWatermark = cursor?.value ?? 0;
70
+ // Read-only, with a busy timeout: OpenCode may be actively writing (WAL
71
+ // mode) while we read. Never open read-write against another tool's DB.
72
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true, timeout: 5000 });
73
+ try {
74
+ // A restored/rolled-back source (e.g. an older backup copied back over
75
+ // opencode.db) can have a current max activity BEHIND our persisted
76
+ // cursor. Scanning "time_updated >= persistedWatermark" against that
77
+ // would then find nothing, forever — the byte-offset adapters have the
78
+ // analogous case (file shrank -> full reparse); here, reset to a fresh
79
+ // full scan instead.
80
+ const overallMax = db
81
+ .prepare(`SELECT MAX(x) as m FROM (
82
+ SELECT time_updated as x FROM message
83
+ UNION ALL SELECT time_updated FROM part
84
+ UNION ALL SELECT time_updated FROM session
85
+ )`)
86
+ .get();
87
+ const rolledBack = overallMax.m !== null && overallMax.m < persistedWatermark;
88
+ const watermark = rolledBack ? 0 : persistedWatermark;
89
+ const seenAtWatermark = rolledBack ? new Set() : new Set(cursor?.tieBreakIds ?? []);
90
+ // ONE combined, atomic read of every message/part/session row that
91
+ // could matter, tagged by kind — the next cursor AND which
92
+ // messages/sessions are touched are both derived purely from this same
93
+ // in-memory rowset below, never by issuing a second query against
94
+ // current DB state. An earlier version ran the touched-rows query and
95
+ // the next-cursor query separately; on a live WAL db (OpenCode may be
96
+ // writing while we read) a row committed between the two could be
97
+ // folded into the new cursor/tieBreakIds without ever having been in
98
+ // the touched set — silently skipped forever. A single statement
99
+ // closes that: there is no point after this call returns where a
100
+ // concurrent write could still affect what we derive from it.
101
+ const rows = db
102
+ .prepare(`SELECT 'm' as kind, id as row_id, id as msg_id, session_id, time_updated as ts FROM message WHERE time_updated >= ?
103
+ UNION ALL
104
+ SELECT 'p' as kind, id as row_id, message_id as msg_id, session_id, time_updated as ts FROM part WHERE time_updated >= ?
105
+ UNION ALL
106
+ SELECT 's' as kind, id as row_id, NULL as msg_id, id as session_id, time_updated as ts FROM session WHERE time_updated >= ?`)
107
+ .all(watermark, watermark, watermark);
108
+ if (rows.length === 0) {
109
+ return { sessions: [], cursor: { value: watermark, tieBreakIds: [...seenAtWatermark] } };
110
+ }
111
+ let nextValue = watermark;
112
+ for (const r of rows)
113
+ if (r.ts > nextValue)
114
+ nextValue = r.ts;
115
+ const nextTieBreakIds = rows.filter((r) => r.ts === nextValue).map(tieKey);
116
+ const nextCursor = { value: nextValue, tieBreakIds: nextTieBreakIds };
117
+ // A row is "new" if it's strictly newer than the watermark, or it ties
118
+ // the watermark but its own row id was never accounted for before —
119
+ // row-granular (not message-granular), so a new part landing at the
120
+ // same tied ms as an already-seen sibling row on the SAME message still
121
+ // counts as new (a message-level tie-break would wrongly suppress it).
122
+ const isNewRow = (r) => r.ts > watermark || (r.ts === watermark && !seenAtWatermark.has(tieKey(r)));
123
+ const touchedMessageIds = new Set();
124
+ const touchedSessionIds = new Set(); // sessions whose OWN row (title/etc) was touched
125
+ for (const r of rows) {
126
+ if (!isNewRow(r))
127
+ continue;
128
+ if (r.kind === "s")
129
+ touchedSessionIds.add(r.session_id);
130
+ else
131
+ touchedMessageIds.add(r.msg_id);
132
+ }
133
+ if (touchedMessageIds.size === 0 && touchedSessionIds.size === 0) {
134
+ return { sessions: [], cursor: nextCursor };
135
+ }
136
+ const getMessage = db.prepare("SELECT id, session_id, time_created, time_updated, data FROM message WHERE id = ?");
137
+ const getParts = db.prepare("SELECT id, time_created, time_updated, data FROM part WHERE message_id = ? ORDER BY time_created ASC, id ASC");
138
+ const getSessionRow = db.prepare("SELECT id, directory, title, parent_id FROM session WHERE id = ?");
139
+ const sessionRowCache = new Map();
140
+ const resolveSessionRow = (sessionId) => {
141
+ if (!sessionRowCache.has(sessionId)) {
142
+ sessionRowCache.set(sessionId, getSessionRow.get(sessionId));
143
+ }
144
+ return sessionRowCache.get(sessionId);
145
+ };
146
+ const bySessionMessages = new Map();
147
+ const bySessionParseErrors = new Map();
148
+ const emittedSessionIds = new Set();
149
+ for (const message_id of touchedMessageIds) {
150
+ const msgRow = getMessage.get(message_id);
151
+ if (!msgRow)
152
+ continue; // deleted between discover and parse
153
+ const sessionRow = resolveSessionRow(msgRow.session_id);
154
+ if (!sessionRow || sessionRow.parent_id)
155
+ continue; // gone, or a sub-session (v1 scope)
156
+ const bumpParseErrors = () => bySessionParseErrors.set(msgRow.session_id, (bySessionParseErrors.get(msgRow.session_id) ?? 0) + 1);
157
+ let data;
158
+ try {
159
+ data = JSON.parse(msgRow.data);
160
+ }
161
+ catch {
162
+ bumpParseErrors();
163
+ continue;
164
+ }
165
+ const role = data.role === "assistant" ? "assistant" : data.role === "user" ? "user" : undefined;
166
+ if (!role)
167
+ continue;
168
+ const proseParts = [];
169
+ const toolParts = [];
170
+ const tools = [];
171
+ for (const part of getParts.all(message_id)) {
172
+ let pd;
173
+ try {
174
+ pd = JSON.parse(part.data);
175
+ }
176
+ catch {
177
+ bumpParseErrors();
178
+ continue;
179
+ }
180
+ if (pd.type === "text") {
181
+ if (typeof pd.text === "string" && pd.text)
182
+ proseParts.push(pd.text);
183
+ }
184
+ else if (pd.type === "tool") {
185
+ if (typeof pd.tool === "string")
186
+ tools.push(pd.tool);
187
+ const state = pd.state;
188
+ const output = state?.output;
189
+ const error = state?.error;
190
+ // A failed tool call reports its error in state.error, not state.output
191
+ // (confirmed mutually exclusive on the real corpus) — without this, a
192
+ // failed command's actual error text never enters the index at all.
193
+ if (typeof output === "string" && output)
194
+ toolParts.push(output);
195
+ else if (typeof error === "string" && error)
196
+ toolParts.push(error);
197
+ }
198
+ else if (pd.type === "reasoning") {
199
+ if (typeof pd.text === "string" && pd.text)
200
+ toolParts.push(pd.text);
201
+ }
202
+ // step-start / step-finish / patch / compaction: no searchable content, v1 skip.
203
+ }
204
+ const normMsg = {
205
+ uuid: msgRow.id,
206
+ role,
207
+ ts: new Date(msgRow.time_created).toISOString(),
208
+ text: proseParts.join("\n\n"),
209
+ toolText: toolParts.length > 0 ? toolParts.join("\n\n") : undefined,
210
+ tools,
211
+ model: role === "assistant" && typeof data.modelID === "string" ? data.modelID : undefined,
212
+ isSidechain: false,
213
+ };
214
+ if (!bySessionMessages.has(msgRow.session_id))
215
+ bySessionMessages.set(msgRow.session_id, []);
216
+ bySessionMessages.get(msgRow.session_id).push(normMsg);
217
+ }
218
+ const sessions = [];
219
+ for (const [sessionId, messages] of bySessionMessages) {
220
+ messages.sort((a, b) => a.ts.localeCompare(b.ts));
221
+ const meta = resolveSessionRow(sessionId);
222
+ sessions.push({
223
+ id: sessionId,
224
+ source: "opencode",
225
+ projectDir: meta.directory,
226
+ projectDirSource: "cwd",
227
+ filePath: dbPath,
228
+ title: meta.title,
229
+ startedAt: messages[0]?.ts,
230
+ endedAt: messages[messages.length - 1]?.ts,
231
+ messages,
232
+ parseErrors: bySessionParseErrors.get(sessionId) ?? 0,
233
+ bytesConsumed: 0, // unused: watermark-cursor sources resume via parseSince's returned cursor, not a byte offset
234
+ });
235
+ emittedSessionIds.add(sessionId);
236
+ }
237
+ // Sessions touched only via their own row (e.g. an AI-generated title
238
+ // that lands after the last message) get an empty-messages entry so
239
+ // the title/directory refresh still reaches upsertSessionMessages —
240
+ // and any session whose only touched message this round was malformed
241
+ // (parse error recorded, but never added to bySessionMessages) gets one
242
+ // too, so that error isn't silently dropped from the output entirely.
243
+ const needsEmptyEntry = new Set([...touchedSessionIds, ...bySessionParseErrors.keys()]);
244
+ for (const sessionId of needsEmptyEntry) {
245
+ if (emittedSessionIds.has(sessionId))
246
+ continue;
247
+ const sessionRow = resolveSessionRow(sessionId);
248
+ if (!sessionRow || sessionRow.parent_id)
249
+ continue; // gone, or a sub-session (v1 scope)
250
+ sessions.push({
251
+ id: sessionId,
252
+ source: "opencode",
253
+ projectDir: sessionRow.directory,
254
+ projectDirSource: "cwd",
255
+ filePath: dbPath,
256
+ title: sessionRow.title,
257
+ messages: [],
258
+ parseErrors: bySessionParseErrors.get(sessionId) ?? 0,
259
+ bytesConsumed: 0,
260
+ });
261
+ emittedSessionIds.add(sessionId);
262
+ }
263
+ return { sessions, cursor: nextCursor };
264
+ }
265
+ finally {
266
+ db.close();
267
+ }
268
+ }
269
+ }
package/dist/cli.js CHANGED
@@ -7,7 +7,8 @@ import { fileURLToPath } from "node:url";
7
7
  import { openDb, resolveDbPath, getSessionByIdOrPrefix, getMessagesForSession, listSessions, getStats, getNewestMessageTs, parseJsonStringArray, } from "./db.js";
8
8
  import { ClaudeCodeAdapter } from "./adapters/claude-code.js";
9
9
  import { CodexAdapter } from "./adapters/codex.js";
10
- import { indexAll } from "./indexer.js";
10
+ import { OpenCodeAdapter } from "./adapters/opencode.js";
11
+ import { indexAll, indexAllWatermark } from "./indexer.js";
11
12
  import { search, collapseSnippetWhitespace, resumeCommand } from "./search.js";
12
13
  import { mergeDb, syncDir, sanitizeHostName } from "./sync.js";
13
14
  import { loadConfig, saveConfig } from "./config.js";
@@ -16,6 +17,7 @@ import { startMcpServer } from "./mcp.js";
16
17
  import { buildServer } from "./server.js";
17
18
  const DEFAULT_ROOTS = [path.join(os.homedir(), ".claude", "projects")];
18
19
  const DEFAULT_CODEX_ROOTS = [path.join(os.homedir(), ".codex", "sessions")];
20
+ const DEFAULT_OPENCODE_ROOTS = [path.join(os.homedir(), ".local", "share", "opencode")];
19
21
  export function getVersion() {
20
22
  // ../package.json resolves correctly from both src/ (tests via tsx) and dist/.
21
23
  const pkgPath = fileURLToPath(new URL("../package.json", import.meta.url));
@@ -39,16 +41,19 @@ export function runIndex(opts, log = defaultLog) {
39
41
  const db = openDb(resolveDbPath(opts.db));
40
42
  const claudeRoots = opts.roots && opts.roots.length > 0 ? opts.roots : DEFAULT_ROOTS;
41
43
  const codexRoots = opts.codexRoots && opts.codexRoots.length > 0 ? opts.codexRoots : DEFAULT_CODEX_ROOTS;
44
+ const opencodeRoots = opts.opencodeRoots && opts.opencodeRoots.length > 0 ? opts.opencodeRoots : DEFAULT_OPENCODE_ROOTS;
42
45
  const a = indexAll(db, new ClaudeCodeAdapter(), claudeRoots);
43
46
  const b = indexAll(db, new CodexAdapter(), codexRoots);
47
+ const c = indexAllWatermark(db, new OpenCodeAdapter(), opencodeRoots);
44
48
  db.close();
45
49
  const stats = {
46
- filesScanned: a.filesScanned + b.filesScanned,
47
- filesNew: a.filesNew + b.filesNew,
48
- filesUpdated: a.filesUpdated + b.filesUpdated,
49
- messagesIndexed: a.messagesIndexed + b.messagesIndexed,
50
- parseErrors: a.parseErrors + b.parseErrors,
51
- elapsedMs: a.elapsedMs + b.elapsedMs,
50
+ filesScanned: a.filesScanned + b.filesScanned + c.filesScanned,
51
+ filesNew: a.filesNew + b.filesNew + c.filesNew,
52
+ filesUpdated: a.filesUpdated + b.filesUpdated + c.filesUpdated,
53
+ messagesIndexed: a.messagesIndexed + b.messagesIndexed + c.messagesIndexed,
54
+ parseErrors: a.parseErrors + b.parseErrors + c.parseErrors,
55
+ skippedFiles: [...a.skippedFiles, ...b.skippedFiles, ...c.skippedFiles],
56
+ elapsedMs: a.elapsedMs + b.elapsedMs + c.elapsedMs,
52
57
  };
53
58
  if (opts.json) {
54
59
  log(JSON.stringify(stats));
@@ -57,6 +62,11 @@ export function runIndex(opts, log = defaultLog) {
57
62
  log(`files scanned: ${stats.filesScanned} new: ${stats.filesNew} updated: ${stats.filesUpdated}`);
58
63
  log(`messages indexed: ${stats.messagesIndexed} parse errors: ${stats.parseErrors}`);
59
64
  log(`elapsed: ${stats.elapsedMs}ms`);
65
+ // A skipped file contributed nothing this run (#2) — name it, loudly, so a
66
+ // pathological transcript reads as "this file was skipped", never as
67
+ // "indexing is broken".
68
+ for (const skipped of stats.skippedFiles)
69
+ log(`skipped (will retry next run): ${skipped}`);
60
70
  if (stats.filesScanned === 0) {
61
71
  log("");
62
72
  log("no transcript files found. roots scanned:");
@@ -64,7 +74,9 @@ export function runIndex(opts, log = defaultLog) {
64
74
  log(` ${r} (Claude Code)`);
65
75
  for (const r of codexRoots)
66
76
  log(` ${r} (Codex CLI)`);
67
- log("transcripts elsewhere? point rewound at them with --roots / --codex-roots");
77
+ for (const r of opencodeRoots)
78
+ log(` ${r} (OpenCode)`);
79
+ log("transcripts elsewhere? point rewound at them with --roots / --codex-roots / --opencode-roots");
68
80
  }
69
81
  }
70
82
  export function runSearch(query, opts, log = defaultLog) {
@@ -260,9 +272,10 @@ export function buildProgram() {
260
272
  .version(getVersion());
261
273
  program
262
274
  .command("index")
263
- .description("scan agent transcripts (Claude Code + Codex CLI) into the local search index")
275
+ .description("scan agent transcripts (Claude Code + Codex CLI + OpenCode) into the local search index")
264
276
  .option("--roots <dirs...>", "Claude Code root directories to scan")
265
277
  .option("--codex-roots <dirs...>", "Codex CLI session roots (default: ~/.codex/sessions)")
278
+ .option("--opencode-roots <dirs...>", "OpenCode session DB roots (default: ~/.local/share/opencode)")
266
279
  .option("--db <path>", "database path")
267
280
  .option("--json", "output JSON")
268
281
  .action((opts) => runIndex(opts));
package/dist/db.js CHANGED
@@ -38,13 +38,24 @@ CREATE TRIGGER IF NOT EXISTS messages_au AFTER UPDATE ON messages BEGIN
38
38
  INSERT INTO messages_fts(messages_fts, rowid, text, tool_text) VALUES('delete', old.id, old.text, old.tool_text);
39
39
  INSERT INTO messages_fts(rowid, text, tool_text) VALUES (new.id, new.text, new.tool_text);
40
40
  END;
41
+ CREATE TABLE IF NOT EXISTS sources (
42
+ path TEXT PRIMARY KEY, adapter_id TEXT NOT NULL,
43
+ cursor_kind TEXT NOT NULL, cursor_value INTEGER NOT NULL,
44
+ cursor_tie_ids TEXT NOT NULL DEFAULT '[]'
45
+ );
41
46
  `;
42
- export const CURRENT_SCHEMA_VERSION = 2;
47
+ export const CURRENT_SCHEMA_VERSION = 3;
43
48
  // bm25 column weights: a match in prose (typed user text, assistant text) is
44
49
  // worth 3x a match in tool output. Tool dumps stay searchable — error strings
45
50
  // often exist ONLY there — they just stop outranking a human sentence.
46
51
  export const PROSE_BM25_WEIGHT = 3.0;
47
52
  export const TOOL_BM25_WEIGHT = 1.0;
53
+ // v2 → v3: adds the `sources` table (per-source incremental cursor for
54
+ // watermark-cursor adapters, e.g. OpenCode's shared SQLite DB — see
55
+ // getSourceCursor/upsertSourceCursor below). Purely additive: CREATE TABLE IF
56
+ // NOT EXISTS in SCHEMA_SQL already covers both fresh and existing v2 DBs, so
57
+ // there is no migrateToV3 — bumping CURRENT_SCHEMA_VERSION alone is enough for
58
+ // openDb's existing "version < CURRENT_SCHEMA_VERSION" branch to stamp it.
48
59
  // v1 (0.1.0) → v2: messages gains tool_text; FTS becomes two weighted columns.
49
60
  // Migrates IN PLACE from the content table — never by reparsing source files,
50
61
  // because archived sessions' transcripts may already be deleted. Legacy rows
@@ -130,6 +141,28 @@ export function upsertFileRecord(db, rec) {
130
141
  mtime_ms = excluded.mtime_ms,
131
142
  byte_offset = excluded.byte_offset`).run(rec);
132
143
  }
144
+ // Per-source cursor for watermark-cursor adapters (see WatermarkSourceAdapter
145
+ // in types.ts) — analogous to the files table above, but keyed by source path
146
+ // alone since one source holds many sessions, not one session per path.
147
+ export function getSourceCursor(db, sourcePath) {
148
+ const row = db.prepare("SELECT cursor_kind, cursor_value, cursor_tie_ids FROM sources WHERE path = ?").get(sourcePath);
149
+ if (!row)
150
+ return undefined;
151
+ if (row.cursor_kind === "watermark") {
152
+ return { kind: "watermark", value: row.cursor_value, tieBreakIds: parseJsonStringArray(row.cursor_tie_ids) };
153
+ }
154
+ return { kind: row.cursor_kind, value: row.cursor_value };
155
+ }
156
+ export function upsertSourceCursor(db, sourcePath, adapterId, cursor) {
157
+ const tieIds = cursor.kind === "watermark" ? cursor.tieBreakIds : [];
158
+ db.prepare(`INSERT INTO sources (path, adapter_id, cursor_kind, cursor_value, cursor_tie_ids)
159
+ VALUES (@path, @adapterId, @kind, @value, @tieIds)
160
+ ON CONFLICT(path) DO UPDATE SET
161
+ adapter_id = excluded.adapter_id,
162
+ cursor_kind = excluded.cursor_kind,
163
+ cursor_value = excluded.cursor_value,
164
+ cursor_tie_ids = excluded.cursor_tie_ids`).run({ path: sourcePath, adapterId, kind: cursor.kind, value: cursor.value, tieIds: JSON.stringify(tieIds) });
165
+ }
133
166
  export function listTrackedFiles(db) {
134
167
  const rows = db.prepare("SELECT path, session_id as sessionId FROM files").all();
135
168
  return rows;
@@ -177,6 +210,15 @@ export function upsertSessionMessages(db, session, opts) {
177
210
  if (opts.mode === "replace") {
178
211
  deleteSessionMessages(db, session.id);
179
212
  }
213
+ else if (opts.mode === "upsert") {
214
+ // Watermark-cursor sources re-emit a message when it changes in place
215
+ // (e.g. a new part streamed in), not only when a new one is created.
216
+ // Delete any prior row for the same uuid first so the FTS triggers see
217
+ // a delete+reinsert rather than a second row for the same message.
218
+ const deleteByUuid = db.prepare("DELETE FROM messages WHERE session_id = ? AND uuid = ?");
219
+ for (const m of session.messages)
220
+ deleteByUuid.run(session.id, m.uuid);
221
+ }
180
222
  const insertMessage = db.prepare(`INSERT INTO messages (session_id, uuid, role, ts, text, tools, model, is_sidechain, tool_text)
181
223
  VALUES (@sessionId, @uuid, @role, @ts, @text, @tools, @model, @isSidechain, @toolText)`);
182
224
  for (const m of session.messages) {
@@ -192,17 +234,14 @@ export function upsertSessionMessages(db, session, opts) {
192
234
  isSidechain: m.isSidechain ? 1 : 0,
193
235
  });
194
236
  }
195
- const existing = opts.mode === "append" ? getSession(db, session.id) : undefined;
237
+ const existing = opts.mode === "replace" ? undefined : getSession(db, session.id);
196
238
  // A fallback-derived projectDir (naive dash→slash dir-name decode) must never
197
239
  // clobber a stored value: incremental append chunks with no cwd-bearing lines
198
240
  // (e.g. session-end meta records) would otherwise permanently mangle hyphenated
199
241
  // project names ("/home/dev/my-app" → "/home/dev/my/app"). cwd-derived always wins.
200
242
  const projectDir = session.projectDirSource === "cwd" ? session.projectDir : existing?.projectDir ?? session.projectDir;
201
- const modelsSeen = new Set(existing?.models ?? []);
202
243
  let costDelta = 0;
203
244
  for (const m of session.messages) {
204
- if (m.model)
205
- modelsSeen.add(m.model);
206
245
  if (m.usage)
207
246
  costDelta += estimateCostUsd(m.model, m.usage);
208
247
  }
@@ -221,25 +260,69 @@ export function upsertSessionMessages(db, session, opts) {
221
260
  usageSums.cacheRead += session.usageDelta.cacheRead;
222
261
  usageSums.cacheWrite += session.usageDelta.cacheWrite;
223
262
  }
224
- const messageCount = (existing?.messageCount ?? 0) + session.messages.length;
263
+ // usageSums/costDelta stay additive even in upsert mode: watermark-cursor
264
+ // adapters (OpenCode) don't map per-message usage in v1, so this is always
265
+ // a zero delta for them. A future watermark adapter that DOES map usage
266
+ // would need the same ground-truth treatment as messageCount/models below —
267
+ // but usage isn't persisted per-message row, so there's nothing to recompute
268
+ // from; flagging here rather than solving for a case that doesn't exist yet.
225
269
  const inputTokens = (existing?.inputTokens ?? 0) + usageSums.input;
226
270
  const outputTokens = (existing?.outputTokens ?? 0) + usageSums.output;
227
271
  const cacheReadTokens = (existing?.cacheReadTokens ?? 0) + usageSums.cacheRead;
228
272
  const cacheWriteTokens = (existing?.cacheWriteTokens ?? 0) + usageSums.cacheWrite;
229
273
  const estCostUsd = (existing?.estCostUsd ?? 0) + costDelta;
274
+ // Same known limitation as usage above: parse_errors also stays additive
275
+ // in upsert mode. Unlike message_count, it isn't stored per-message, so a
276
+ // message that keeps re-touching the same malformed sibling row (e.g. one
277
+ // permanently-bad part on an otherwise-live message) would drift upward
278
+ // rather than reflect a true current count. No per-run CLI/web/MCP surface
279
+ // reads this stored column today (the CLI's own "parse errors: N" comes
280
+ // from the current run's fresh IndexStats, not this field) — low impact,
281
+ // but worth knowing if that ever changes.
230
282
  const parseErrors = (existing?.parseErrors ?? 0) + session.parseErrors;
231
283
  const title = session.title ?? existing?.title;
232
284
  const gitBranch = session.gitBranch ?? existing?.gitBranch;
233
- const startedAt = existing?.startedAt && session.startedAt
234
- ? existing.startedAt < session.startedAt
235
- ? existing.startedAt
236
- : session.startedAt
237
- : session.startedAt ?? existing?.startedAt;
238
- const endedAt = existing?.endedAt && session.endedAt
239
- ? existing.endedAt > session.endedAt
240
- ? existing.endedAt
241
- : session.endedAt
242
- : session.endedAt ?? existing?.endedAt;
285
+ // A message can REPLACE an already-indexed one under "upsert" (same uuid,
286
+ // revised content) rather than only ever being net-new, so message_count/
287
+ // models/started_at/ended_at are recomputed from the messages table itself
288
+ // (ground truth, post delete+reinsert) instead of adding this batch's size
289
+ // on top of the stored aggregate — the append-mode delta math below would
290
+ // silently double-count a replaced message.
291
+ let messageCount;
292
+ let models;
293
+ let startedAt;
294
+ let endedAt;
295
+ if (opts.mode === "upsert") {
296
+ const agg = db
297
+ .prepare("SELECT COUNT(*) as cnt, MIN(ts) as minTs, MAX(ts) as maxTs FROM messages WHERE session_id = ?")
298
+ .get(session.id);
299
+ messageCount = agg.cnt;
300
+ startedAt = agg.minTs ?? undefined;
301
+ endedAt = agg.maxTs ?? undefined;
302
+ const modelRows = db
303
+ .prepare("SELECT DISTINCT model FROM messages WHERE session_id = ? AND model IS NOT NULL")
304
+ .all(session.id);
305
+ models = new Set(modelRows.map((r) => r.model));
306
+ }
307
+ else {
308
+ messageCount = (existing?.messageCount ?? 0) + session.messages.length;
309
+ models = new Set(existing?.models ?? []);
310
+ for (const m of session.messages)
311
+ if (m.model)
312
+ models.add(m.model);
313
+ startedAt =
314
+ existing?.startedAt && session.startedAt
315
+ ? existing.startedAt < session.startedAt
316
+ ? existing.startedAt
317
+ : session.startedAt
318
+ : session.startedAt ?? existing?.startedAt;
319
+ endedAt =
320
+ existing?.endedAt && session.endedAt
321
+ ? existing.endedAt > session.endedAt
322
+ ? existing.endedAt
323
+ : session.endedAt
324
+ : session.endedAt ?? existing?.endedAt;
325
+ }
243
326
  db.prepare(`INSERT INTO sessions (
244
327
  id, source, project_dir, file_path, title, git_branch, started_at, ended_at,
245
328
  message_count, models, input_tokens, output_tokens, cache_read_tokens,
@@ -274,7 +357,7 @@ export function upsertSessionMessages(db, session, opts) {
274
357
  startedAt: startedAt ?? null,
275
358
  endedAt: endedAt ?? null,
276
359
  messageCount,
277
- models: JSON.stringify(Array.from(modelsSeen)),
360
+ models: JSON.stringify(Array.from(models)),
278
361
  inputTokens,
279
362
  outputTokens,
280
363
  cacheReadTokens,
package/dist/indexer.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import fs from "node:fs";
2
- import { getFileRecord, upsertFileRecord, upsertSessionMessages, markSessionArchived, listTrackedFiles, getSession, } from "./db.js";
2
+ import { getFileRecord, upsertFileRecord, upsertSessionMessages, markSessionArchived, listTrackedFiles, getSession, getSourceCursor, upsertSourceCursor, } from "./db.js";
3
3
  // byteOffset/size must come from what adapter.parse() actually consumed
4
4
  // (session.bytesConsumed), never from an independent fs.stat. adapter.parse()
5
5
  // does its own fs.readFileSync internally; a stat taken by the caller — before
@@ -74,8 +74,19 @@ export function indexAll(db, adapter, roots) {
74
74
  let filesUpdated = 0;
75
75
  let messagesIndexed = 0;
76
76
  let parseErrors = 0;
77
+ const skippedFiles = [];
77
78
  for (const filePath of discovered) {
78
- const result = indexOneFile(db, adapter, filePath);
79
+ // #2: one pathological file (oversized single line, unreadable, vanished
80
+ // mid-scan) must not abort the whole run. No file record is written for a
81
+ // skipped file, so a later run retries it instead of skipping forever.
82
+ let result;
83
+ try {
84
+ result = indexOneFile(db, adapter, filePath);
85
+ }
86
+ catch (err) {
87
+ skippedFiles.push(`${filePath}: ${err instanceof Error ? err.message : String(err)}`);
88
+ continue;
89
+ }
79
90
  if (result.status === "new")
80
91
  filesNew++;
81
92
  else if (result.status === "updated")
@@ -95,6 +106,67 @@ export function indexAll(db, adapter, roots) {
95
106
  filesUpdated,
96
107
  messagesIndexed,
97
108
  parseErrors,
109
+ skippedFiles,
110
+ elapsedMs: Date.now() - start,
111
+ };
112
+ }
113
+ // Counterpart to indexAll() for watermark-cursor sources (see
114
+ // WatermarkSourceAdapter in types.ts): one source can hold many sessions and
115
+ // rows update in place, so tracking is per-source-path (the `sources` table)
116
+ // rather than per-file-per-session (the `files` table), and messages are
117
+ // upserted by uuid rather than appended. IndexStats' filesScanned/filesNew/
118
+ // filesUpdated fields are reused here for "sources" — same shape, no reason
119
+ // for a parallel stats type.
120
+ export function indexAllWatermark(db, adapter, roots) {
121
+ const start = Date.now();
122
+ const discovered = adapter.discover(roots);
123
+ let sourcesNew = 0;
124
+ let sourcesUpdated = 0;
125
+ let messagesIndexed = 0;
126
+ let parseErrors = 0;
127
+ const skippedFiles = [];
128
+ for (const sourcePath of discovered) {
129
+ const existing = getSourceCursor(db, sourcePath);
130
+ const existingCursor = existing?.kind === "watermark" ? { value: existing.value, tieBreakIds: existing.tieBreakIds } : undefined;
131
+ // A single corrupt, vanished, or lock-timed-out source must not abort the
132
+ // whole run — the Claude Code/Codex passes ahead of this one in cli.ts's
133
+ // runIndex already committed, and other sources in `discovered` still
134
+ // deserve a chance. Report it as skipped and move on, leaving its cursor
135
+ // untouched (we don't know what, if anything, it actually scanned).
136
+ let result;
137
+ try {
138
+ result = adapter.parseSince(sourcePath, existingCursor);
139
+ }
140
+ catch (err) {
141
+ skippedFiles.push(`${sourcePath}: ${err instanceof Error ? err.message : String(err)}`);
142
+ continue;
143
+ }
144
+ const { sessions, cursor } = result;
145
+ for (const session of sessions) {
146
+ upsertSessionMessages(db, session, { mode: "upsert" });
147
+ messagesIndexed += session.messages.length;
148
+ parseErrors += session.parseErrors;
149
+ }
150
+ // Persisted even when nothing was indexed this run: the cursor tracks
151
+ // everything parseSince scanned, not just what got upserted, so a
152
+ // no-op run doesn't leave the source stuck re-scanning the same rows.
153
+ upsertSourceCursor(db, sourcePath, adapter.id, {
154
+ kind: "watermark",
155
+ value: cursor.value,
156
+ tieBreakIds: cursor.tieBreakIds,
157
+ });
158
+ if (!existing)
159
+ sourcesNew++;
160
+ else if (sessions.length > 0)
161
+ sourcesUpdated++;
162
+ }
163
+ return {
164
+ filesScanned: discovered.length,
165
+ filesNew: sourcesNew,
166
+ filesUpdated: sourcesUpdated,
167
+ messagesIndexed,
168
+ parseErrors,
169
+ skippedFiles,
98
170
  elapsedMs: Date.now() - start,
99
171
  };
100
172
  }
package/dist/search.js CHANGED
@@ -3,6 +3,8 @@ import { searchMessagesRaw } from "./db.js";
3
3
  export function resumeCommand(source, sessionId) {
4
4
  if (source === "codex")
5
5
  return `codex resume ${sessionId}`;
6
+ if (source === "opencode")
7
+ return `opencode --session ${sessionId}`;
6
8
  return `claude --resume ${sessionId}`;
7
9
  }
8
10
  // Snippets lifted from code/tool dumps carry embedded newlines, tabs and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rewound",
3
- "version": "0.4.4",
3
+ "version": "0.5.1",
4
4
  "description": "Grep for everything your AI coding agents ever did. Local SQLite/FTS5 search over Claude Code session transcripts: CLI, MCP server, and web UI.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "David Erner",