rewound 0.4.3 → 0.5.0
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 +3 -3
- package/dist/adapters/codex.js +28 -2
- package/dist/adapters/opencode.js +269 -0
- package/dist/cli.js +16 -9
- package/dist/db.js +106 -17
- package/dist/indexer.js +59 -1
- package/dist/search.js +2 -0
- package/package.json +1 -1
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
|
|
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
|
|
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
|
|
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
|
|
package/dist/adapters/codex.js
CHANGED
|
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { consumeCompleteLines, walkJsonlFiles } from "./jsonl.js";
|
|
4
4
|
const ROLLOUT_RE = /rollout-.*\.jsonl$/;
|
|
5
|
+
const SCAFFOLDING_RE = /^\s*<(environment_context|user_instructions|permissions_context)\b/;
|
|
5
6
|
const UUID_RE = /([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\.jsonl$/;
|
|
6
7
|
function contentText(content) {
|
|
7
8
|
if (typeof content === "string")
|
|
@@ -40,6 +41,7 @@ export class CodexAdapter {
|
|
|
40
41
|
let startedAt;
|
|
41
42
|
let endedAt;
|
|
42
43
|
let parseErrors = 0;
|
|
44
|
+
let usageDelta;
|
|
43
45
|
const push = (m) => {
|
|
44
46
|
messages.push({ ...m, uuid: messageUuid(m.ts, m.role, m.text || m.toolText || ""), isSidechain: false });
|
|
45
47
|
if (m.ts) {
|
|
@@ -82,8 +84,26 @@ export class CodexAdapter {
|
|
|
82
84
|
model = p.model;
|
|
83
85
|
continue;
|
|
84
86
|
}
|
|
87
|
+
if (record.type === "event_msg") {
|
|
88
|
+
// token_count events carry per-turn usage in last_token_usage; the
|
|
89
|
+
// cumulative total_token_usage is deliberately ignored — summing
|
|
90
|
+
// per-turn deltas stays correct under incremental byte-offset parsing.
|
|
91
|
+
if (p.type === "token_count") {
|
|
92
|
+
const info = p.info;
|
|
93
|
+
const last = info?.last_token_usage;
|
|
94
|
+
if (last) {
|
|
95
|
+
const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
96
|
+
const cached = n(last.cached_input_tokens);
|
|
97
|
+
usageDelta ??= { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
98
|
+
usageDelta.input += Math.max(0, n(last.input_tokens) - cached);
|
|
99
|
+
usageDelta.output += n(last.output_tokens);
|
|
100
|
+
usageDelta.cacheRead += cached;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
85
105
|
if (record.type !== "response_item")
|
|
86
|
-
continue; // compacted,
|
|
106
|
+
continue; // compacted, drift: skip
|
|
87
107
|
const itemType = p.type;
|
|
88
108
|
if (itemType === "message") {
|
|
89
109
|
const role = p.role === "assistant" ? "assistant" : p.role === "user" ? "user" : undefined;
|
|
@@ -92,7 +112,12 @@ export class CodexAdapter {
|
|
|
92
112
|
const text = contentText(p.content);
|
|
93
113
|
if (!text)
|
|
94
114
|
continue;
|
|
95
|
-
|
|
115
|
+
if (role === "user" && SCAFFOLDING_RE.test(text)) {
|
|
116
|
+
push({ role, ts, text: "", toolText: text, tools: [] });
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
push({ role, ts, text, tools: [], model: role === "assistant" ? model : undefined });
|
|
120
|
+
}
|
|
96
121
|
}
|
|
97
122
|
else if (itemType === "reasoning") {
|
|
98
123
|
const text = [contentText(p.summary), contentText(p.content)].filter(Boolean).join("\n\n");
|
|
@@ -120,6 +145,7 @@ export class CodexAdapter {
|
|
|
120
145
|
startedAt,
|
|
121
146
|
endedAt,
|
|
122
147
|
messages,
|
|
148
|
+
usageDelta,
|
|
123
149
|
parseErrors,
|
|
124
150
|
bytesConsumed,
|
|
125
151
|
};
|
|
@@ -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 {
|
|
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,18 @@ 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
|
+
elapsedMs: a.elapsedMs + b.elapsedMs + c.elapsedMs,
|
|
52
56
|
};
|
|
53
57
|
if (opts.json) {
|
|
54
58
|
log(JSON.stringify(stats));
|
|
@@ -64,7 +68,9 @@ export function runIndex(opts, log = defaultLog) {
|
|
|
64
68
|
log(` ${r} (Claude Code)`);
|
|
65
69
|
for (const r of codexRoots)
|
|
66
70
|
log(` ${r} (Codex CLI)`);
|
|
67
|
-
|
|
71
|
+
for (const r of opencodeRoots)
|
|
72
|
+
log(` ${r} (OpenCode)`);
|
|
73
|
+
log("transcripts elsewhere? point rewound at them with --roots / --codex-roots / --opencode-roots");
|
|
68
74
|
}
|
|
69
75
|
}
|
|
70
76
|
export function runSearch(query, opts, log = defaultLog) {
|
|
@@ -260,9 +266,10 @@ export function buildProgram() {
|
|
|
260
266
|
.version(getVersion());
|
|
261
267
|
program
|
|
262
268
|
.command("index")
|
|
263
|
-
.description("scan agent transcripts (Claude Code + Codex CLI) into the local search index")
|
|
269
|
+
.description("scan agent transcripts (Claude Code + Codex CLI + OpenCode) into the local search index")
|
|
264
270
|
.option("--roots <dirs...>", "Claude Code root directories to scan")
|
|
265
271
|
.option("--codex-roots <dirs...>", "Codex CLI session roots (default: ~/.codex/sessions)")
|
|
272
|
+
.option("--opencode-roots <dirs...>", "OpenCode session DB roots (default: ~/.local/share/opencode)")
|
|
266
273
|
.option("--db <path>", "database path")
|
|
267
274
|
.option("--json", "output JSON")
|
|
268
275
|
.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 =
|
|
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 === "
|
|
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
|
}
|
|
@@ -215,25 +254,75 @@ export function upsertSessionMessages(db, session, opts) {
|
|
|
215
254
|
}
|
|
216
255
|
return acc;
|
|
217
256
|
}, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
218
|
-
|
|
257
|
+
if (session.usageDelta) {
|
|
258
|
+
usageSums.input += session.usageDelta.input;
|
|
259
|
+
usageSums.output += session.usageDelta.output;
|
|
260
|
+
usageSums.cacheRead += session.usageDelta.cacheRead;
|
|
261
|
+
usageSums.cacheWrite += session.usageDelta.cacheWrite;
|
|
262
|
+
}
|
|
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.
|
|
219
269
|
const inputTokens = (existing?.inputTokens ?? 0) + usageSums.input;
|
|
220
270
|
const outputTokens = (existing?.outputTokens ?? 0) + usageSums.output;
|
|
221
271
|
const cacheReadTokens = (existing?.cacheReadTokens ?? 0) + usageSums.cacheRead;
|
|
222
272
|
const cacheWriteTokens = (existing?.cacheWriteTokens ?? 0) + usageSums.cacheWrite;
|
|
223
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.
|
|
224
282
|
const parseErrors = (existing?.parseErrors ?? 0) + session.parseErrors;
|
|
225
283
|
const title = session.title ?? existing?.title;
|
|
226
284
|
const gitBranch = session.gitBranch ?? existing?.gitBranch;
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
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
|
+
}
|
|
237
326
|
db.prepare(`INSERT INTO sessions (
|
|
238
327
|
id, source, project_dir, file_path, title, git_branch, started_at, ended_at,
|
|
239
328
|
message_count, models, input_tokens, output_tokens, cache_read_tokens,
|
|
@@ -268,7 +357,7 @@ export function upsertSessionMessages(db, session, opts) {
|
|
|
268
357
|
startedAt: startedAt ?? null,
|
|
269
358
|
endedAt: endedAt ?? null,
|
|
270
359
|
messageCount,
|
|
271
|
-
models: JSON.stringify(Array.from(
|
|
360
|
+
models: JSON.stringify(Array.from(models)),
|
|
272
361
|
inputTokens,
|
|
273
362
|
outputTokens,
|
|
274
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
|
|
@@ -98,3 +98,61 @@ export function indexAll(db, adapter, roots) {
|
|
|
98
98
|
elapsedMs: Date.now() - start,
|
|
99
99
|
};
|
|
100
100
|
}
|
|
101
|
+
// Counterpart to indexAll() for watermark-cursor sources (see
|
|
102
|
+
// WatermarkSourceAdapter in types.ts): one source can hold many sessions and
|
|
103
|
+
// rows update in place, so tracking is per-source-path (the `sources` table)
|
|
104
|
+
// rather than per-file-per-session (the `files` table), and messages are
|
|
105
|
+
// upserted by uuid rather than appended. IndexStats' filesScanned/filesNew/
|
|
106
|
+
// filesUpdated fields are reused here for "sources" — same shape, no reason
|
|
107
|
+
// for a parallel stats type.
|
|
108
|
+
export function indexAllWatermark(db, adapter, roots) {
|
|
109
|
+
const start = Date.now();
|
|
110
|
+
const discovered = adapter.discover(roots);
|
|
111
|
+
let sourcesNew = 0;
|
|
112
|
+
let sourcesUpdated = 0;
|
|
113
|
+
let messagesIndexed = 0;
|
|
114
|
+
let parseErrors = 0;
|
|
115
|
+
for (const sourcePath of discovered) {
|
|
116
|
+
const existing = getSourceCursor(db, sourcePath);
|
|
117
|
+
const existingCursor = existing?.kind === "watermark" ? { value: existing.value, tieBreakIds: existing.tieBreakIds } : undefined;
|
|
118
|
+
// A single corrupt, vanished, or lock-timed-out source must not abort the
|
|
119
|
+
// whole run — the Claude Code/Codex passes ahead of this one in cli.ts's
|
|
120
|
+
// runIndex already committed, and other sources in `discovered` still
|
|
121
|
+
// deserve a chance. Count it as a parse error and move on, leaving its
|
|
122
|
+
// cursor untouched (we don't know what, if anything, it actually scanned).
|
|
123
|
+
let result;
|
|
124
|
+
try {
|
|
125
|
+
result = adapter.parseSince(sourcePath, existingCursor);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
parseErrors++;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const { sessions, cursor } = result;
|
|
132
|
+
for (const session of sessions) {
|
|
133
|
+
upsertSessionMessages(db, session, { mode: "upsert" });
|
|
134
|
+
messagesIndexed += session.messages.length;
|
|
135
|
+
parseErrors += session.parseErrors;
|
|
136
|
+
}
|
|
137
|
+
// Persisted even when nothing was indexed this run: the cursor tracks
|
|
138
|
+
// everything parseSince scanned, not just what got upserted, so a
|
|
139
|
+
// no-op run doesn't leave the source stuck re-scanning the same rows.
|
|
140
|
+
upsertSourceCursor(db, sourcePath, adapter.id, {
|
|
141
|
+
kind: "watermark",
|
|
142
|
+
value: cursor.value,
|
|
143
|
+
tieBreakIds: cursor.tieBreakIds,
|
|
144
|
+
});
|
|
145
|
+
if (!existing)
|
|
146
|
+
sourcesNew++;
|
|
147
|
+
else if (sessions.length > 0)
|
|
148
|
+
sourcesUpdated++;
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
filesScanned: discovered.length,
|
|
152
|
+
filesNew: sourcesNew,
|
|
153
|
+
filesUpdated: sourcesUpdated,
|
|
154
|
+
messagesIndexed,
|
|
155
|
+
parseErrors,
|
|
156
|
+
elapsedMs: Date.now() - start,
|
|
157
|
+
};
|
|
158
|
+
}
|
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.
|
|
3
|
+
"version": "0.5.0",
|
|
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",
|