@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.
- package/.claude/commands/rebase-verify.md +118 -0
- package/LICENSE +21 -0
- package/PRIVACY.md +113 -0
- package/README.md +210 -2
- package/SECURITY.md +33 -0
- package/bin/rebase-verify.mjs +700 -0
- package/package.json +38 -4
- package/share/practices.json +224 -0
- package/share/tech-labels.json +57 -0
- package/share/tech-lexicon.json +62 -0
- package/src/adapters/claude-code.mjs +225 -0
- package/src/adapters/codex.mjs +476 -0
- package/src/adapters/cursor.mjs +584 -0
- package/src/adapters/kimi.mjs +594 -0
- package/src/adapters/omp.mjs +59 -0
- package/src/adapters/opencode.mjs +439 -0
- package/src/adapters/pi.mjs +414 -0
- package/src/adapters/tool-vocab.mjs +15 -0
- package/src/agent-run.mjs +10 -0
- package/src/agentic-literacy.mjs +211 -0
- package/src/agents/acp.mjs +364 -0
- package/src/agents/json-answer.mjs +72 -0
- package/src/agents/registry.mjs +370 -0
- package/src/agents/run.mjs +131 -0
- package/src/ai-relationship.mjs +95 -0
- package/src/consistency.mjs +382 -0
- package/src/days.mjs +45 -0
- package/src/digest.mjs +501 -0
- package/src/distribution.mjs +54 -0
- package/src/enrich.mjs +118 -0
- package/src/fingerprint.mjs +134 -0
- package/src/forensics.mjs +178 -0
- package/src/groundedness.mjs +347 -0
- package/src/hub.mjs +136 -0
- package/src/intensity.mjs +132 -0
- package/src/live-status.mjs +79 -0
- package/src/practices-llm.mjs +90 -0
- package/src/practices-rules.mjs +295 -0
- package/src/practices-sample.mjs +111 -0
- package/src/practices.mjs +279 -0
- package/src/profile-llm.mjs +249 -0
- package/src/profile.mjs +497 -0
- package/src/redact.mjs +97 -0
- package/src/sources.mjs +91 -0
- package/src/submit.mjs +65 -0
- package/src/system-text.mjs +3 -0
- package/src/tech-usage.mjs +88 -0
- package/src/trajectory.mjs +264 -0
- package/src/wizard.mjs +411 -0
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// opencode adapter: reads opencode's logs and normalises them into the SAME
|
|
2
|
+
// session model that claude-code.mjs produces, so every downstream lens
|
|
3
|
+
// (digest, agentic-literacy, forensics, fingerprint, intensity, distribution)
|
|
4
|
+
// consumes it unchanged.
|
|
5
|
+
//
|
|
6
|
+
// Two storage backends, both supported:
|
|
7
|
+
// - sqlite (opencode.db): the authoritative, fuller store. Preferred when
|
|
8
|
+
// node:sqlite is available (Node >= 22.5). One indexed read instead of
|
|
9
|
+
// tens of thousands of file opens, and it retains more history than the
|
|
10
|
+
// JSON cache.
|
|
11
|
+
// - JSON files (storage/{session,message,part}/...): older/portable layout
|
|
12
|
+
// and the fallback when node:sqlite is missing.
|
|
13
|
+
//
|
|
14
|
+
// Either way the shape is identical: session/<id> with messages reconstructed
|
|
15
|
+
// by joining each message with its parts (text, reasoning, tool calls,
|
|
16
|
+
// step-finish token usage, compaction markers).
|
|
17
|
+
//
|
|
18
|
+
// Two translations make the shared model work:
|
|
19
|
+
// 1. Vocabulary — opencode tool names are lowercase ("edit","bash","task")
|
|
20
|
+
// and MCP tools are "server_tool"; mapped onto the canonical Claude names
|
|
21
|
+
// ("Edit","Bash","Task") and "mcp__server__tool" so the MUTATION/RESEARCH/
|
|
22
|
+
// DELEGATION sets and MCP classification just fire.
|
|
23
|
+
// 2. Timestamps — opencode stores epoch ms; converted to ISO at the boundary
|
|
24
|
+
// because downstream assumes ISO.
|
|
25
|
+
//
|
|
26
|
+
// Privacy: tool OUTPUTS and assistant ERROR blobs (URLs, headers, command
|
|
27
|
+
// output) are never stored — only byte counts, mirroring the Claude adapter.
|
|
28
|
+
// Reasoning text is reduced to a character count, never kept.
|
|
29
|
+
|
|
30
|
+
import { readdirSync, readFileSync, existsSync } from "node:fs";
|
|
31
|
+
import { join, dirname } from "node:path";
|
|
32
|
+
import { homedir } from "node:os";
|
|
33
|
+
import { createHash } from "node:crypto";
|
|
34
|
+
import { createRequire } from "node:module";
|
|
35
|
+
import { redactText, countRedactions } from "../redact.mjs";
|
|
36
|
+
import { toPosix } from "./claude-code.mjs";
|
|
37
|
+
import { fallbackToolName } from "./tool-vocab.mjs";
|
|
38
|
+
|
|
39
|
+
const require = createRequire(import.meta.url);
|
|
40
|
+
const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
|
|
41
|
+
const shortHash = (s) => sha256(s).slice(0, 8);
|
|
42
|
+
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
43
|
+
|
|
44
|
+
// node:sqlite is experimental and only present on Node >= 22.5. Load it lazily
|
|
45
|
+
// so the adapter still imports (and the JSON path still works) on Node 20.
|
|
46
|
+
function loadSqlite() {
|
|
47
|
+
try { return require("node:sqlite"); } catch { return null; }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── Default locations ───────────────────────────────────────────────────────
|
|
51
|
+
// opencode follows XDG even on Windows: ~/.local/share/opencode/{storage,opencode.db}.
|
|
52
|
+
export function defaultOpencodeRoot() {
|
|
53
|
+
const candidates = [
|
|
54
|
+
process.env.OPENCODE_DATA && join(process.env.OPENCODE_DATA, "storage"),
|
|
55
|
+
process.env.XDG_DATA_HOME && join(process.env.XDG_DATA_HOME, "opencode", "storage"),
|
|
56
|
+
join(homedir(), ".local", "share", "opencode", "storage"),
|
|
57
|
+
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "opencode", "storage"),
|
|
58
|
+
].filter(Boolean);
|
|
59
|
+
return candidates.find((p) => existsSync(p)) || null;
|
|
60
|
+
}
|
|
61
|
+
// The db sits beside the storage dir.
|
|
62
|
+
export function defaultOpencodeDb(root = defaultOpencodeRoot()) {
|
|
63
|
+
if (!root) return null;
|
|
64
|
+
const db = join(dirname(root), "opencode.db");
|
|
65
|
+
return existsSync(db) ? db : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ── Tool vocabulary: opencode → canonical (Claude Code) names ───────────────
|
|
69
|
+
const TOOL_MAP = {
|
|
70
|
+
bash: "Bash", read: "Read", edit: "Edit", write: "Write", patch: "Edit",
|
|
71
|
+
multiedit: "MultiEdit", glob: "Glob", grep: "Grep", list: "Read",
|
|
72
|
+
webfetch: "WebFetch", websearch: "WebSearch", todowrite: "TodoWrite",
|
|
73
|
+
todoread: "TodoRead", task: "Task", question: "AskUserQuestion",
|
|
74
|
+
};
|
|
75
|
+
function mapTool(name) {
|
|
76
|
+
if (!name) return name;
|
|
77
|
+
if (TOOL_MAP[name]) return TOOL_MAP[name];
|
|
78
|
+
// Anything else falls through to the fallback shared with every other
|
|
79
|
+
// adapter (see tool-vocab.mjs for why it's shared, not reimplemented here).
|
|
80
|
+
return fallbackToolName(name);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Reduce a message's parts into the shared content shape.
|
|
84
|
+
function reduceParts(parts) {
|
|
85
|
+
const toolUses = [];
|
|
86
|
+
const toolResults = [];
|
|
87
|
+
let text = "";
|
|
88
|
+
let thinkingChars = 0;
|
|
89
|
+
let isCompaction = false;
|
|
90
|
+
let tokens = null;
|
|
91
|
+
|
|
92
|
+
for (const b of parts) {
|
|
93
|
+
switch (b.type) {
|
|
94
|
+
case "text":
|
|
95
|
+
if (typeof b.text === "string") text += b.text + "\n";
|
|
96
|
+
break;
|
|
97
|
+
case "reasoning":
|
|
98
|
+
// Like Claude's redacted thinking: keep length as a depth proxy only.
|
|
99
|
+
thinkingChars += (b.text || "").length;
|
|
100
|
+
break;
|
|
101
|
+
case "tool": {
|
|
102
|
+
const inp = (b.state && b.state.input) || {};
|
|
103
|
+
const out = b.state && typeof b.state.output === "string" ? b.state.output.length : 0;
|
|
104
|
+
toolUses.push({
|
|
105
|
+
id: b.callID || b.id,
|
|
106
|
+
name: mapTool(b.tool),
|
|
107
|
+
path: toPosix(redactText(inp.filePath || inp.file_path || inp.path || "")),
|
|
108
|
+
cmd: b.tool === "bash" ? redactText(String(inp.command || "").slice(0, 240)) : "",
|
|
109
|
+
q: redactText(String(inp.query || inp.url || inp.pattern || "").slice(0, 200)),
|
|
110
|
+
});
|
|
111
|
+
toolResults.push({ forId: b.callID || b.id, isError: b.state && b.state.status === "error", bytes: out });
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
case "step-finish":
|
|
115
|
+
if (b.tokens) {
|
|
116
|
+
tokens ||= { input: 0, output: 0, cacheRead: 0, cacheCreate: 0 };
|
|
117
|
+
tokens.input += b.tokens.input || 0;
|
|
118
|
+
tokens.output += b.tokens.output || 0;
|
|
119
|
+
tokens.cacheRead += (b.tokens.cache && b.tokens.cache.read) || 0;
|
|
120
|
+
tokens.cacheCreate += (b.tokens.cache && b.tokens.cache.write) || 0;
|
|
121
|
+
}
|
|
122
|
+
break;
|
|
123
|
+
case "compaction":
|
|
124
|
+
isCompaction = true;
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return { text, thinkingChars, toolUses, toolResults, isCompaction, tokens };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Base session object from session info ({id, directory, parentID, version}).
|
|
132
|
+
function baseSession(info) {
|
|
133
|
+
const cwdRaw = info.directory || "";
|
|
134
|
+
return {
|
|
135
|
+
source: "opencode",
|
|
136
|
+
sessionId: info.id,
|
|
137
|
+
parentId: info.parentID || null,
|
|
138
|
+
projectLabel: cwdRaw ? `project-${shortHash(cwdRaw)}` : "project-unknown",
|
|
139
|
+
cwdRedacted: toPosix(redactText(cwdRaw)),
|
|
140
|
+
cwdRaw, // local-only; never sent in the bundle
|
|
141
|
+
gitBranch: null, // opencode does not record the branch
|
|
142
|
+
cliVersions: info.version ? [info.version] : [],
|
|
143
|
+
models: new Set(),
|
|
144
|
+
messages: [],
|
|
145
|
+
chain: [],
|
|
146
|
+
firstTs: null,
|
|
147
|
+
lastTs: null,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Fold one message (already parsed) + its parts into a session, updating the
|
|
152
|
+
// shared accumulators (redaction stats, compaction summaries).
|
|
153
|
+
function ingestMessage(session, m, parts, acc) {
|
|
154
|
+
if (!m || (m.role !== "user" && m.role !== "assistant")) return;
|
|
155
|
+
const { text, thinkingChars, toolUses, toolResults, isCompaction, tokens } = reduceParts(parts);
|
|
156
|
+
const ts = iso(m.time && m.time.created);
|
|
157
|
+
if (ts) {
|
|
158
|
+
// Store the ISO string, not the parsed epoch. Downstream lenses
|
|
159
|
+
// (intensity.mjs, trajectory.mjs) call Date.parse(s.firstTs) and
|
|
160
|
+
// expect an ISO string; epoch numbers coerce to "1748772000000" which
|
|
161
|
+
// is not a valid ISO date and yields NaN, silently dropping the session.
|
|
162
|
+
// ISO strings compare correctly lexicographically for the same format.
|
|
163
|
+
if (!session.firstTs || ts < session.firstTs) session.firstTs = ts;
|
|
164
|
+
if (!session.lastTs || ts > session.lastTs) session.lastTs = ts;
|
|
165
|
+
}
|
|
166
|
+
const providerID = m.providerID || (m.model && m.model.providerID);
|
|
167
|
+
const modelID = m.modelID || (m.model && m.model.modelID);
|
|
168
|
+
const model = providerID && modelID ? `${providerID}/${modelID}` : null;
|
|
169
|
+
if (model) session.models.add(model);
|
|
170
|
+
|
|
171
|
+
acc.redactionHits += countRedactions(text);
|
|
172
|
+
const textRedacted = redactText(text);
|
|
173
|
+
acc.redactedChars += text.length - textRedacted.length;
|
|
174
|
+
if (isCompaction && textRedacted.length > 200) acc.compactionSummaries.push(textRedacted.slice(0, 3000));
|
|
175
|
+
if (m.id) session.chain.push({ uuid: m.id, parentUuid: m.parentID ?? null, ts });
|
|
176
|
+
|
|
177
|
+
session.messages.push({
|
|
178
|
+
role: m.role,
|
|
179
|
+
ts,
|
|
180
|
+
uuid: m.id,
|
|
181
|
+
parentUuid: m.parentID ?? null,
|
|
182
|
+
model,
|
|
183
|
+
messageId: m.id,
|
|
184
|
+
requestId: null, // opencode has no per-request id
|
|
185
|
+
textRedacted,
|
|
186
|
+
textLen: text.length,
|
|
187
|
+
thinkingChars,
|
|
188
|
+
signatureChars: 0,
|
|
189
|
+
toolUses,
|
|
190
|
+
toolResults,
|
|
191
|
+
usage: tokens || (m.tokens ? {
|
|
192
|
+
input: m.tokens.input || 0,
|
|
193
|
+
output: m.tokens.output || 0,
|
|
194
|
+
cacheRead: (m.tokens.cache && m.tokens.cache.read) || 0,
|
|
195
|
+
cacheCreate: (m.tokens.cache && m.tokens.cache.write) || 0,
|
|
196
|
+
} : null),
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ── Within-opencode subagent rollup ────────────────────────────────────────
|
|
201
|
+
// opencode spawns subagents (the `task` tool) as CHILD sessions linked by
|
|
202
|
+
// parentID. Left alone they cluster as their own tiny "products", scattering
|
|
203
|
+
// the orchestration. Re-point each child to its root ancestor's working dir so
|
|
204
|
+
// the subagent work is attributed to the product that launched it. The
|
|
205
|
+
// delegation COUNT is already carried by the parent's mapped `Task` calls.
|
|
206
|
+
//
|
|
207
|
+
// Re-point ALL THREE project-identity fields together, not just cwdRedacted:
|
|
208
|
+
// digest clusters by cwdRedacted (repoKey) but fingerprint counts distinct
|
|
209
|
+
// projectLabel (= shortHash(cwdRaw)). If only cwdRedacted moves, the child
|
|
210
|
+
// folds into the parent product for the digest yet stays a separate project
|
|
211
|
+
// for the fingerprint — the two then disagree on the product count.
|
|
212
|
+
function applyRollup(sessions, byId) {
|
|
213
|
+
const ancestor = (s, seen = new Set()) => {
|
|
214
|
+
if (!s.parentId || seen.has(s.sessionId)) return s;
|
|
215
|
+
seen.add(s.sessionId);
|
|
216
|
+
const parent = byId.get(s.parentId);
|
|
217
|
+
return parent ? ancestor(parent, seen) : s;
|
|
218
|
+
};
|
|
219
|
+
let rolledUp = 0;
|
|
220
|
+
let orphaned = 0;
|
|
221
|
+
for (const s of sessions) {
|
|
222
|
+
if (!s.parentId) continue;
|
|
223
|
+
const anc = ancestor(s);
|
|
224
|
+
// Parent absent from the read set (a pruned/partial JSON cache can hold a
|
|
225
|
+
// subagent child without its root): ancestor() returns the child itself, so
|
|
226
|
+
// it can't roll up and stands as its own spurious "product", inflating the
|
|
227
|
+
// count. We can't attribute it without the parent, so disclose it in stats
|
|
228
|
+
// rather than let the over-count be silent.
|
|
229
|
+
if (anc === s) { orphaned++; continue; }
|
|
230
|
+
if (anc.cwdRedacted && anc.cwdRedacted !== s.cwdRedacted) {
|
|
231
|
+
s.cwdRedacted = anc.cwdRedacted;
|
|
232
|
+
s.cwdRaw = anc.cwdRaw;
|
|
233
|
+
s.projectLabel = anc.projectLabel;
|
|
234
|
+
rolledUp++;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return { rolledUp, orphaned };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function finalize(root, sessions, files, acc, rolledUp, backend, orphaned = 0) {
|
|
241
|
+
return {
|
|
242
|
+
source: "opencode",
|
|
243
|
+
root,
|
|
244
|
+
files,
|
|
245
|
+
sessions: sessions.map((s) => ({ ...s, models: [...s.models] })),
|
|
246
|
+
compactionSummaries: acc.compactionSummaries,
|
|
247
|
+
redaction: { hits: acc.redactionHits, charsRemoved: acc.redactedChars },
|
|
248
|
+
// backend records WHICH read path produced this bundle ("sqlite" = the full
|
|
249
|
+
// opencode.db, "json" = the partial JSON cache). It is the silent-fallback
|
|
250
|
+
// disclosure hook: the JSON cache can hold far fewer sessions than the db,
|
|
251
|
+
// so the user should see which one was read. summarizeSources surfaces it.
|
|
252
|
+
stats: { rolledUpSubagentSessions: rolledUp, orphanedSubagentSessions: orphaned, backend },
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const EMPTY = (root) => ({
|
|
257
|
+
source: "opencode", root: root || null, files: [], sessions: [],
|
|
258
|
+
compactionSummaries: [], redaction: { hits: 0, charsRemoved: 0 },
|
|
259
|
+
stats: { rolledUpSubagentSessions: 0, orphanedSubagentSessions: 0, backend: null },
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// ── Backend: sqlite (preferred) ─────────────────────────────────────────────
|
|
263
|
+
// Walks one session at a time via the indexed message/part lookups, so memory
|
|
264
|
+
// stays bounded (the db can be >1 GB once full tool outputs are stored) and the
|
|
265
|
+
// provenance hash is taken over the RAW row bytes without re-serialising.
|
|
266
|
+
export function readOpencodeDb(dbPath = defaultOpencodeDb()) {
|
|
267
|
+
if (!dbPath || !existsSync(dbPath)) return EMPTY(dbPath);
|
|
268
|
+
const sqlite = loadSqlite();
|
|
269
|
+
if (!sqlite) return EMPTY(dbPath);
|
|
270
|
+
|
|
271
|
+
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true });
|
|
272
|
+
try {
|
|
273
|
+
// ORDER BY id: without it SQLite returns rows in physical/rowid order, which
|
|
274
|
+
// is not stable across machines (or after VACUUM / row deletion). Session
|
|
275
|
+
// emission order feeds the digest's Map-insertion order, which is the
|
|
276
|
+
// tie-break for representative selection on equal-significance products — so
|
|
277
|
+
// an unordered read can reorder/reselect representatives machine-to-machine.
|
|
278
|
+
// The session table has no time_created column (unlike message/part), so id
|
|
279
|
+
// is the deterministic key. (bundleHash sorts file hashes, so the tamper hash
|
|
280
|
+
// was already safe; this fixes the candidate.json ordering/selection.)
|
|
281
|
+
const sessStmt = db.prepare("SELECT id, parent_id, directory, version FROM session ORDER BY id");
|
|
282
|
+
const mStmt = db.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created");
|
|
283
|
+
const pStmt = db.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY time_created");
|
|
284
|
+
|
|
285
|
+
const acc = { redactionHits: 0, redactedChars: 0, compactionSummaries: [] };
|
|
286
|
+
const sessions = [];
|
|
287
|
+
const byId = new Map();
|
|
288
|
+
const files = [];
|
|
289
|
+
|
|
290
|
+
for (const row of sessStmt.all()) {
|
|
291
|
+
const info = { id: row.id, parentID: row.parent_id || null, directory: row.directory || "", version: row.version || null };
|
|
292
|
+
const session = baseSession(info);
|
|
293
|
+
|
|
294
|
+
const h = createHash("sha256"); // provenance over raw row bytes
|
|
295
|
+
h.update(info.id + "\n" + info.directory);
|
|
296
|
+
let records = 0, malformed = 0, bytes = 0;
|
|
297
|
+
|
|
298
|
+
for (const mr of mStmt.all(info.id)) {
|
|
299
|
+
h.update(mr.data); bytes += mr.data.length;
|
|
300
|
+
let mObj; try { mObj = JSON.parse(mr.data); } catch { malformed++; continue; }
|
|
301
|
+
const m = { id: mr.id, ...mObj };
|
|
302
|
+
const parts = [];
|
|
303
|
+
for (const pr of pStmt.all(mr.id)) {
|
|
304
|
+
h.update(pr.data); bytes += pr.data.length;
|
|
305
|
+
try { parts.push(JSON.parse(pr.data)); } catch { malformed++; }
|
|
306
|
+
}
|
|
307
|
+
records += 1 + parts.length;
|
|
308
|
+
ingestMessage(session, m, parts, acc);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
files.push({ relPath: `opencode-db/session/${info.id}`, sha256: h.digest("hex"), bytes, lines: records, malformed, cwdRaw: session.cwdRaw });
|
|
312
|
+
byId.set(session.sessionId, session);
|
|
313
|
+
sessions.push(session);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const { rolledUp, orphaned } = applyRollup(sessions, byId);
|
|
317
|
+
return finalize(dbPath, sessions, files, acc, rolledUp, "sqlite", orphaned);
|
|
318
|
+
} finally {
|
|
319
|
+
db.close();
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ── Backend: JSON files (fallback) ──────────────────────────────────────────
|
|
324
|
+
const listJson = (dir) =>
|
|
325
|
+
existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(".json")).map((e) => join(dir, e.name)) : [];
|
|
326
|
+
|
|
327
|
+
export function readOpencodeJson(root = defaultOpencodeRoot()) {
|
|
328
|
+
if (!root || !existsSync(root)) return EMPTY(root);
|
|
329
|
+
const sessionDir = join(root, "session");
|
|
330
|
+
const messageDir = join(root, "message");
|
|
331
|
+
const partDir = join(root, "part");
|
|
332
|
+
|
|
333
|
+
const acc = { redactionHits: 0, redactedChars: 0, compactionSummaries: [] };
|
|
334
|
+
const sessions = [];
|
|
335
|
+
const byId = new Map();
|
|
336
|
+
const files = [];
|
|
337
|
+
|
|
338
|
+
const sessionFiles = [];
|
|
339
|
+
if (existsSync(sessionDir)) {
|
|
340
|
+
for (const e of readdirSync(sessionDir, { withFileTypes: true })) {
|
|
341
|
+
if (e.isDirectory()) sessionFiles.push(...listJson(join(sessionDir, e.name)));
|
|
342
|
+
else if (e.isFile() && e.name.endsWith(".json")) sessionFiles.push(join(sessionDir, e.name));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
for (const sf of sessionFiles) {
|
|
347
|
+
let info;
|
|
348
|
+
try { info = JSON.parse(readFileSync(sf, "utf8")); } catch { continue; }
|
|
349
|
+
if (!info || !info.id) continue;
|
|
350
|
+
|
|
351
|
+
const session = baseSession({ id: info.id, parentID: info.parentID || null, directory: info.directory || "", version: info.version || null });
|
|
352
|
+
const chunks = [readFileSync(sf)];
|
|
353
|
+
let records = 0;
|
|
354
|
+
let malformed = 0;
|
|
355
|
+
|
|
356
|
+
// Collect messages first, then ingest in CREATION-TIME order. The sqlite
|
|
357
|
+
// backend reads messages `ORDER BY time_created`; opencode message ids sort
|
|
358
|
+
// reverse-chronologically (descending-id scheme), so a bare filename sort
|
|
359
|
+
// feeds messages newest-first and the two backends reconstruct each session
|
|
360
|
+
// in OPPOSITE order — diverging compactionSummaries (sliced -6 into the
|
|
361
|
+
// narrative), concatenated text, and the per-file provenance bytes, all from
|
|
362
|
+
// nothing but the Node version (sqlite present >= 22.5 vs JSON fallback).
|
|
363
|
+
// Sort by m.time.created so the JSON path agrees with the db. Provenance is
|
|
364
|
+
// still hashed over `chunks` in filename order, so the per-file sha is
|
|
365
|
+
// unchanged. Parts carry no timestamp in the JSON layout, so their
|
|
366
|
+
// within-message order stays filename-sorted (only multi-text-part
|
|
367
|
+
// concatenation is order-sensitive there).
|
|
368
|
+
const msgs = [];
|
|
369
|
+
for (const mf of listJson(join(messageDir, info.id)).sort()) {
|
|
370
|
+
let m;
|
|
371
|
+
try { chunks.push(readFileSync(mf)); m = JSON.parse(readFileSync(mf, "utf8")); records++; }
|
|
372
|
+
catch { malformed++; continue; }
|
|
373
|
+
const parts = [];
|
|
374
|
+
for (const pf of listJson(join(partDir, m.id)).sort()) {
|
|
375
|
+
try { chunks.push(readFileSync(pf)); parts.push(JSON.parse(readFileSync(pf, "utf8"))); records++; }
|
|
376
|
+
catch { malformed++; }
|
|
377
|
+
}
|
|
378
|
+
msgs.push({ m, parts });
|
|
379
|
+
}
|
|
380
|
+
msgs.sort((a, b) => (a.m.time?.created ?? 0) - (b.m.time?.created ?? 0));
|
|
381
|
+
for (const { m, parts } of msgs) ingestMessage(session, m, parts, acc);
|
|
382
|
+
|
|
383
|
+
const buf = Buffer.concat(chunks);
|
|
384
|
+
files.push({ relPath: `opencode/session/${info.id}`, sha256: sha256(buf), bytes: buf.length, lines: records, malformed, cwdRaw: session.cwdRaw });
|
|
385
|
+
byId.set(session.sessionId, session);
|
|
386
|
+
sessions.push(session);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const { rolledUp, orphaned } = applyRollup(sessions, byId);
|
|
390
|
+
return finalize(root, sessions, files, acc, rolledUp, "json", orphaned);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ── Public entry: prefer the db, fall back to JSON ──────────────────────────
|
|
394
|
+
export function readOpencode(root = defaultOpencodeRoot()) {
|
|
395
|
+
const db = defaultOpencodeDb(root);
|
|
396
|
+
if (db && loadSqlite()) {
|
|
397
|
+
try {
|
|
398
|
+
const fromDb = readOpencodeDb(db);
|
|
399
|
+
if (fromDb.sessions.length) return fromDb;
|
|
400
|
+
} catch {
|
|
401
|
+
// Corrupt/locked db, or an unexpected schema — fall through to JSON.
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return readOpencodeJson(root);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Merge two parsed sources (e.g. Claude Code + opencode) into one bundle. The
|
|
408
|
+
// per-repo clustering downstream then unifies sessions of the same product
|
|
409
|
+
// across tools automatically. summarizeSources(parsed) on main reads the
|
|
410
|
+
// per-session source tag and groups them for the profile's sources block.
|
|
411
|
+
//
|
|
412
|
+
// We also carry a per-source `backends` map ({ source: "sqlite"|"json" }) out
|
|
413
|
+
// of the merge — the one piece of per-source stats the capture-level seam needs
|
|
414
|
+
// that can't be recovered from a session tag (which read path served a source).
|
|
415
|
+
// summarizeSources reads it to fill each source's `backend` field.
|
|
416
|
+
export function mergeSources(...parsedList) {
|
|
417
|
+
const sources = parsedList.filter(Boolean);
|
|
418
|
+
const backends = {};
|
|
419
|
+
for (const p of sources) {
|
|
420
|
+
if (p.source && p.stats?.backend) backends[p.source] = p.stats.backend;
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
source: sources.map((p) => p.source).join("+") || "none",
|
|
424
|
+
root: sources[0]?.root ?? null,
|
|
425
|
+
files: sources.flatMap((p) => p.files ?? []),
|
|
426
|
+
// Both shipped adapters stamp source per session; the merge seam
|
|
427
|
+
// re-guarantees it so every downstream consumer (digest fan-out, sources
|
|
428
|
+
// summary, forensics scoping) reads one contract even if a future adapter
|
|
429
|
+
// forgets to stamp.
|
|
430
|
+
sessions: sources.flatMap((p) =>
|
|
431
|
+
(p.sessions ?? []).map((s) => (s.source || !p.source ? s : { ...s, source: p.source }))),
|
|
432
|
+
compactionSummaries: sources.flatMap((p) => p.compactionSummaries ?? []),
|
|
433
|
+
redaction: {
|
|
434
|
+
hits: sources.reduce((n, p) => n + (p.redaction?.hits ?? 0), 0),
|
|
435
|
+
charsRemoved: sources.reduce((n, p) => n + (p.redaction?.charsRemoved ?? 0), 0),
|
|
436
|
+
},
|
|
437
|
+
backends,
|
|
438
|
+
};
|
|
439
|
+
}
|