nlm-memory 0.5.0 → 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.
Files changed (247) hide show
  1. package/README.md +72 -34
  2. package/dist/cli/nlm.js +2 -1
  3. package/dist/cli/nlm.js.map +1 -1
  4. package/dist/http/app.js +2 -1
  5. package/dist/http/app.js.map +1 -1
  6. package/dist/mcp/server.js +20 -1
  7. package/dist/mcp/server.js.map +1 -1
  8. package/dist/ui/assets/{index-C8cpwbYJ.css → index-Beo8psd-.css} +1 -1
  9. package/dist/ui/assets/{index-CB50QnL-.js → index-CSPTTeeM.js} +8 -8
  10. package/dist/ui/index.html +2 -2
  11. package/package.json +26 -1
  12. package/.agents/plugins/marketplace.json +0 -20
  13. package/.github/workflows/ci.yml +0 -30
  14. package/docs/methodology/re-derivation-rate.md +0 -112
  15. package/docs/methodology/useful-hit-rate.md +0 -79
  16. package/docs/plans/2026-05-20-fts5-lexical-recall.md +0 -1088
  17. package/docs/plans/2026-05-20-recall-daemon-wedge-fix.md +0 -662
  18. package/docs/plans/2026-05-20-recall-hook-design.md +0 -131
  19. package/docs/plans/2026-05-20-recall-hook-implementation.md +0 -1222
  20. package/docs/plans/desktop-product.md +0 -69
  21. package/docs/plans/factstore-design.md +0 -236
  22. package/logs/CHANGELOG/CHANGELOG-2026.md +0 -1575
  23. package/logs/CHANGELOG/CHANGELOG.md +0 -209
  24. package/migrations/000_initial_schema.sql +0 -174
  25. package/migrations/001_entity_type_rename.sql +0 -17
  26. package/migrations/002_adapter_state_extend.sql +0 -12
  27. package/migrations/003_session_embeddings.sql +0 -11
  28. package/migrations/004_facts.sql +0 -46
  29. package/migrations/005_sources.sql +0 -31
  30. package/migrations/006_providers.sql +0 -33
  31. package/migrations/007_source_tokens.sql +0 -17
  32. package/migrations/008_fts_rebuild.sql +0 -9
  33. package/migrations/009_session_embedding_chunks.sql +0 -46
  34. package/migrations/010_sources_opencode.sql +0 -30
  35. package/migrations/011_sources_hermes_agent.sql +0 -30
  36. package/migrations/012_sources_aider.sql +0 -30
  37. package/migrations/013_adapter_state_failure_count.sql +0 -12
  38. package/migrations/014_sources_cursor.sql +0 -30
  39. package/migrations/015_sources_windsurf.sql +0 -30
  40. package/plugin-hermes-agent/README.md +0 -49
  41. package/plugin-hermes-agent/__init__.py +0 -75
  42. package/plugin-hermes-agent/plugin.yaml +0 -15
  43. package/scripts/backfill-citations.mjs +0 -0
  44. package/scripts/build-codex-plugin.mjs +0 -61
  45. package/scripts/deepseek-probe.mjs +0 -67
  46. package/scripts/extract-triples.mjs +0 -207
  47. package/scripts/longmemeval/embedding-cache.ts +0 -77
  48. package/scripts/longmemeval/fetch-dataset.sh +0 -25
  49. package/scripts/longmemeval/run-harness.ts +0 -315
  50. package/scripts/longmemeval/scorer.ts +0 -99
  51. package/scripts/longmemeval/tsconfig.json +0 -9
  52. package/scripts/longmemeval/types.ts +0 -35
  53. package/scripts/nlm-daily-digest.py +0 -239
  54. package/scripts/nlm-daily-digest.sh +0 -28
  55. package/src/cli/classify-parity.ts +0 -257
  56. package/src/cli/launchctl-helpers.ts +0 -49
  57. package/src/cli/nlm.ts +0 -1078
  58. package/src/core/actions/actions-log.ts +0 -118
  59. package/src/core/actions/overlay.ts +0 -117
  60. package/src/core/adapters/aider.ts +0 -205
  61. package/src/core/adapters/claude-code.ts +0 -293
  62. package/src/core/adapters/common.ts +0 -54
  63. package/src/core/adapters/cursor.ts +0 -486
  64. package/src/core/adapters/from-source.ts +0 -67
  65. package/src/core/adapters/hermes-agent.ts +0 -240
  66. package/src/core/adapters/hermes.ts +0 -277
  67. package/src/core/adapters/jsonl-generic.ts +0 -208
  68. package/src/core/adapters/opencode.ts +0 -281
  69. package/src/core/adapters/pi.ts +0 -264
  70. package/src/core/adapters/windsurf.ts +0 -386
  71. package/src/core/classifier/prompt.ts +0 -200
  72. package/src/core/dataset/build-dataset.ts +0 -463
  73. package/src/core/embedding/chunk-body.ts +0 -76
  74. package/src/core/embedding/embed-backfill.ts +0 -210
  75. package/src/core/embedding/embed-normalize.ts +0 -135
  76. package/src/core/facts/backfill-facts.ts +0 -254
  77. package/src/core/facts/extract-facts.ts +0 -50
  78. package/src/core/hook/citation-detect.ts +0 -124
  79. package/src/core/hook/cite-memo.ts +0 -68
  80. package/src/core/hook/claude-settings.ts +0 -187
  81. package/src/core/hook/gate.ts +0 -25
  82. package/src/core/hook/hook-log.ts +0 -41
  83. package/src/core/hook/memo-sweep.ts +0 -164
  84. package/src/core/hook/memo.ts +0 -67
  85. package/src/core/hook/pointer-block.ts +0 -26
  86. package/src/core/hook/select.ts +0 -32
  87. package/src/core/hook/transcript.ts +0 -121
  88. package/src/core/ingest/ingest-session.ts +0 -111
  89. package/src/core/providers/provider-models.ts +0 -100
  90. package/src/core/providers/provider-registry.ts +0 -196
  91. package/src/core/recall/citation-log.ts +0 -108
  92. package/src/core/recall/filter.ts +0 -27
  93. package/src/core/recall/index.ts +0 -6
  94. package/src/core/recall/match-fields.ts +0 -40
  95. package/src/core/recall/query-log.ts +0 -149
  96. package/src/core/recall/query-shape.ts +0 -66
  97. package/src/core/recall/recall-service.ts +0 -320
  98. package/src/core/recall/recent-log.ts +0 -59
  99. package/src/core/recall/tokenize.ts +0 -18
  100. package/src/core/recall/useful-scan.ts +0 -336
  101. package/src/core/recall-facts/fact-query-log.ts +0 -150
  102. package/src/core/recall-facts/fact-recall-service.ts +0 -327
  103. package/src/core/scheduler/scan-once.ts +0 -142
  104. package/src/core/scheduler/scheduler.ts +0 -225
  105. package/src/core/sources/source-registry.ts +0 -278
  106. package/src/core/storage/db-restore.ts +0 -133
  107. package/src/core/storage/live-status.ts +0 -45
  108. package/src/core/storage/migrate.ts +0 -72
  109. package/src/core/storage/sqlite-fact-store.ts +0 -304
  110. package/src/core/storage/sqlite-session-store.ts +0 -810
  111. package/src/hook/hook-auth.ts +0 -18
  112. package/src/hook/prompt-recall-hook.ts +0 -180
  113. package/src/hook/session-end-hook.ts +0 -81
  114. package/src/hook/session-start-hook.ts +0 -168
  115. package/src/hook/stop-hook.ts +0 -239
  116. package/src/http/app.ts +0 -1215
  117. package/src/install/claude-code.ts +0 -128
  118. package/src/install/codex.ts +0 -367
  119. package/src/install/cursor.ts +0 -68
  120. package/src/install/hermes-agent.ts +0 -76
  121. package/src/install/hermes.ts +0 -78
  122. package/src/install/nlm-dir-perms.ts +0 -55
  123. package/src/install/ollama.ts +0 -284
  124. package/src/install/setup.ts +0 -489
  125. package/src/install/windsurf.ts +0 -68
  126. package/src/llm/classifier-box.ts +0 -64
  127. package/src/llm/deepseek-client.ts +0 -150
  128. package/src/llm/env-autoload.ts +0 -55
  129. package/src/llm/ollama-client.ts +0 -189
  130. package/src/mcp/server.ts +0 -534
  131. package/src/ports/fact-store.ts +0 -102
  132. package/src/ports/llm-client.ts +0 -52
  133. package/src/ports/logger.ts +0 -16
  134. package/src/ports/session-store.ts +0 -45
  135. package/src/ports/transcript-adapter.ts +0 -55
  136. package/src/shared/types.ts +0 -149
  137. package/src/ui/App.tsx +0 -58
  138. package/src/ui/components/PromoteOpenButton.tsx +0 -65
  139. package/src/ui/components/SessionDrawer.tsx +0 -199
  140. package/src/ui/components/SideNav.tsx +0 -162
  141. package/src/ui/components/Skeleton.tsx +0 -107
  142. package/src/ui/index.html +0 -13
  143. package/src/ui/lib/actions.ts +0 -30
  144. package/src/ui/lib/api.ts +0 -92
  145. package/src/ui/lib/dataset.ts +0 -141
  146. package/src/ui/lib/registries.ts +0 -155
  147. package/src/ui/lib/view-settings.ts +0 -41
  148. package/src/ui/main.tsx +0 -15
  149. package/src/ui/pages/Live.tsx +0 -229
  150. package/src/ui/pages/Pulse.tsx +0 -415
  151. package/src/ui/pages/Recall.tsx +0 -190
  152. package/src/ui/pages/River.tsx +0 -354
  153. package/src/ui/pages/Search.tsx +0 -386
  154. package/src/ui/pages/Stub.tsx +0 -9
  155. package/src/ui/pages/Thread.tsx +0 -473
  156. package/src/ui/pages/settings/Classifier.tsx +0 -227
  157. package/src/ui/pages/settings/Data.tsx +0 -190
  158. package/src/ui/pages/settings/Index.tsx +0 -65
  159. package/src/ui/pages/settings/Labels.tsx +0 -224
  160. package/src/ui/pages/settings/Providers.tsx +0 -305
  161. package/src/ui/pages/settings/SettingsSubnav.tsx +0 -28
  162. package/src/ui/pages/settings/Sources.tsx +0 -326
  163. package/src/ui/pages/settings/Views.tsx +0 -96
  164. package/src/ui/styles.css +0 -1890
  165. package/src/ui/tsconfig.json +0 -21
  166. package/src/ui/vite.config.ts +0 -19
  167. package/tests/fixtures/claude_code/short_session.jsonl +0 -2
  168. package/tests/fixtures/claude_code/standard_iso.jsonl +0 -4
  169. package/tests/fixtures/claude_code/tool_heavy.jsonl +0 -8
  170. package/tests/fixtures/claude_code/with_subagent.jsonl +0 -7
  171. package/tests/fixtures/facts.ts +0 -17
  172. package/tests/fixtures/golden-corpus.ts +0 -85
  173. package/tests/fixtures/hermes/paired_request_dump.json +0 -24
  174. package/tests/fixtures/hermes/paired_session.json +0 -23
  175. package/tests/fixtures/hermes/request_dump.json +0 -28
  176. package/tests/fixtures/hermes/session_iso.json +0 -38
  177. package/tests/fixtures/hermes/session_unix.json +0 -38
  178. package/tests/fixtures/hermes/system_only.json +0 -18
  179. package/tests/fixtures/pi/error-connection-abort.jsonl +0 -8
  180. package/tests/fixtures/pi/short-successful.jsonl +0 -5
  181. package/tests/fixtures/pi/with-custom-message.jsonl +0 -6
  182. package/tests/fixtures/sessions.ts +0 -22
  183. package/tests/integration/backfill-facts.test.ts +0 -362
  184. package/tests/integration/citation-explicit.test.ts +0 -111
  185. package/tests/integration/cite-event.test.ts +0 -169
  186. package/tests/integration/cite-memo.test.ts +0 -87
  187. package/tests/integration/db-restore.test.ts +0 -153
  188. package/tests/integration/embed-backfill.test.ts +0 -176
  189. package/tests/integration/fact-supersedence.test.ts +0 -313
  190. package/tests/integration/fts-index.test.ts +0 -60
  191. package/tests/integration/getbyids-sqlite.test.ts +0 -100
  192. package/tests/integration/hermes-agent-hooks.test.ts +0 -248
  193. package/tests/integration/hook-claude-settings.test.ts +0 -218
  194. package/tests/integration/hook-log.test.ts +0 -54
  195. package/tests/integration/hook-memo.test.ts +0 -68
  196. package/tests/integration/hook-pre-compact.test.ts +0 -105
  197. package/tests/integration/hook-subagent-start.test.ts +0 -102
  198. package/tests/integration/http.test.ts +0 -401
  199. package/tests/integration/keyword-search-fts.test.ts +0 -66
  200. package/tests/integration/mcp-recall-logging.test.ts +0 -88
  201. package/tests/integration/mcp.test.ts +0 -260
  202. package/tests/integration/memo-sweep.test.ts +0 -91
  203. package/tests/integration/prompt-recall-hook.test.ts +0 -88
  204. package/tests/integration/provider-registry.test.ts +0 -107
  205. package/tests/integration/recall-golden.test.ts +0 -59
  206. package/tests/integration/recall-sqlite.test.ts +0 -169
  207. package/tests/integration/scheduler.test.ts +0 -391
  208. package/tests/integration/session-end-hook.test.ts +0 -48
  209. package/tests/integration/session-start-hook.test.ts +0 -126
  210. package/tests/integration/source-registry.test.ts +0 -122
  211. package/tests/integration/sqlite-fact-store.test.ts +0 -346
  212. package/tests/integration/stop-hook.test.ts +0 -560
  213. package/tests/integration/wal-checkpoint.test.ts +0 -49
  214. package/tests/unit/cli/launchctl-helpers.test.ts +0 -60
  215. package/tests/unit/core/adapters/aider.test.ts +0 -230
  216. package/tests/unit/core/adapters/claude-code.test.ts +0 -118
  217. package/tests/unit/core/adapters/cursor.test.ts +0 -485
  218. package/tests/unit/core/adapters/hermes-agent.test.ts +0 -329
  219. package/tests/unit/core/adapters/hermes.test.ts +0 -81
  220. package/tests/unit/core/adapters/jsonl-generic.test.ts +0 -142
  221. package/tests/unit/core/adapters/opencode.test.ts +0 -354
  222. package/tests/unit/core/adapters/pi.test.ts +0 -110
  223. package/tests/unit/core/adapters/windsurf.test.ts +0 -416
  224. package/tests/unit/core/classifier/prompt.test.ts +0 -126
  225. package/tests/unit/core/embedding/chunk-body.test.ts +0 -100
  226. package/tests/unit/core/facts/extract-facts.test.ts +0 -117
  227. package/tests/unit/core/filter.test.ts +0 -40
  228. package/tests/unit/core/hook/citation-detect-cite-session.test.ts +0 -96
  229. package/tests/unit/core/hook/citation-detect.test.ts +0 -124
  230. package/tests/unit/core/hook/gate.test.ts +0 -29
  231. package/tests/unit/core/hook/pointer-block.test.ts +0 -22
  232. package/tests/unit/core/hook/select.test.ts +0 -66
  233. package/tests/unit/core/match-fields.test.ts +0 -39
  234. package/tests/unit/core/mcp-cite-session.test.ts +0 -51
  235. package/tests/unit/core/providers/provider-models.test.ts +0 -101
  236. package/tests/unit/core/query-shape.test.ts +0 -92
  237. package/tests/unit/core/recall-facts/fact-recall-service.test.ts +0 -258
  238. package/tests/unit/core/recall-service.test.ts +0 -200
  239. package/tests/unit/core/storage/live-status.test.ts +0 -54
  240. package/tests/unit/core/tokenize.test.ts +0 -32
  241. package/tests/unit/core/useful-scan.test.ts +0 -537
  242. package/tests/unit/llm/embed.test.ts +0 -93
  243. package/tests/unit/llm/ollama-client.test.ts +0 -124
  244. package/tests/unit/scripts/longmemeval-scorer.test.ts +0 -114
  245. package/tsconfig.json +0 -31
  246. package/tsconfig.test.json +0 -11
  247. package/vitest.config.ts +0 -22
@@ -1,264 +0,0 @@
1
- /**
2
- * Pi adapter.
3
- *
4
- * Reads ~/.pi/agent/sessions/<cwd-slug>/<timestamp>_<uuid>.jsonl. Pi writes
5
- * session files even when a run aborts — those still ingest, but the adapter
6
- * flags them via the `gitBranch: "aborted"` sentinel (SessionChunk has no
7
- * status field; storage layer decodes the sentinel later).
8
- *
9
- * File shape (v3, confirmed 2026-05-18): one JSON object per line. Five
10
- * event types: session, model_change, thinking_level_change, message,
11
- * custom_message. Only `message` produces turns; the rest are configuration
12
- * or extension-injected (custom_message must be excluded).
13
- *
14
- * Discovery is recursive (`<sessions>/<cwd-slug>/<file>.jsonl`).
15
- * $PI_SESSIONS_PATH overrides the default path.
16
- */
17
-
18
- import { promises as fs, existsSync, statSync } from "node:fs";
19
- import { extname, join } from "node:path";
20
- import { homedir } from "node:os";
21
- import type {
22
- DetectionResult,
23
- DiscoverOptions,
24
- SessionChunk,
25
- TranscriptAdapter,
26
- } from "@ports/transcript-adapter.js";
27
- import {
28
- durationMinutes,
29
- normalizeTimestamp,
30
- safeSessionId,
31
- } from "./common.js";
32
-
33
- const TOOL_RESULT_PREVIEW_CHARS = 240;
34
-
35
- export interface PiAdapterOptions {
36
- readonly sessionsPath?: string;
37
- readonly idleMinutes?: number;
38
- }
39
-
40
- interface Turn {
41
- readonly role: "user" | "assistant";
42
- readonly text: string;
43
- readonly timestamp: string;
44
- }
45
-
46
- function defaultSessionsPath(): string {
47
- return (
48
- process.env["PI_SESSIONS_PATH"] ??
49
- join(homedir(), ".pi", "agent", "sessions")
50
- );
51
- }
52
-
53
- export class PiAdapter implements TranscriptAdapter {
54
- readonly name = "pi";
55
- readonly runtimeVersion = "pi/1.0";
56
- readonly transcriptKind = "pi-jsonl";
57
-
58
- private readonly sessionsPath: string;
59
- readonly idleMinutes: number;
60
-
61
- constructor(opts: PiAdapterOptions = {}) {
62
- this.sessionsPath = opts.sessionsPath ?? defaultSessionsPath();
63
- this.idleMinutes = opts.idleMinutes ?? 15;
64
- }
65
-
66
- detect(): DetectionResult {
67
- const p = defaultSessionsPath();
68
- if (existsSync(p) && statSync(p).isDirectory()) {
69
- return { adapterName: this.name, enabled: true, path: p, hint: null };
70
- }
71
- return {
72
- adapterName: this.name,
73
- enabled: false,
74
- path: null,
75
- hint: "Pi not detected — ~/.pi/agent/sessions/ missing.",
76
- };
77
- }
78
-
79
- async discover(options: DiscoverOptions = {}): Promise<ReadonlyArray<string>> {
80
- if (!existsSync(this.sessionsPath)) return [];
81
-
82
- const found: { mtime: number; path: string }[] = [];
83
- await walk(this.sessionsPath, async (full, st) => {
84
- if (st.size === 0) return;
85
- if (extname(full) !== ".jsonl") return;
86
- if (options.since && st.mtime < options.since) return;
87
- found.push({ mtime: st.mtimeMs, path: full });
88
- });
89
- found.sort((a, b) => a.mtime - b.mtime);
90
- return found.map((f) => f.path);
91
- }
92
-
93
- async parseSession(path: string): Promise<SessionChunk | null> {
94
- let raw: string;
95
- try {
96
- raw = await fs.readFile(path, "utf8");
97
- } catch {
98
- return null;
99
- }
100
-
101
- const turns: Turn[] = [];
102
- let sessionId = "";
103
- let projectDir = "";
104
- let startedAt = "";
105
- let endedAt = "";
106
- let totalBytes = 0;
107
- let allAssistantErrors = true;
108
-
109
- for (const line of raw.split("\n")) {
110
- totalBytes += Buffer.byteLength(line, "utf8") + 1;
111
- const trimmed = line.trim();
112
- if (!trimmed) continue;
113
-
114
- let evt: Record<string, unknown>;
115
- try {
116
- evt = JSON.parse(trimmed) as Record<string, unknown>;
117
- } catch {
118
- continue;
119
- }
120
-
121
- const evtType = evt["type"];
122
-
123
- if (evtType === "session") {
124
- if (typeof evt["id"] === "string") sessionId = evt["id"];
125
- if (typeof evt["cwd"] === "string") projectDir = evt["cwd"];
126
- continue;
127
- }
128
- if (
129
- evtType === "model_change" ||
130
- evtType === "thinking_level_change" ||
131
- evtType === "custom_message"
132
- ) {
133
- continue;
134
- }
135
- if (evtType !== "message") continue;
136
-
137
- const msg = isRecord(evt["message"]) ? (evt["message"] as Record<string, unknown>) : {};
138
- const role = msg["role"];
139
- if (role !== "user" && role !== "assistant") continue;
140
-
141
- const innerTs = msg["timestamp"];
142
- const outerTs = evt["timestamp"];
143
- const ts = innerTs
144
- ? normalizeTimestamp(innerTs)
145
- : normalizeTimestamp(outerTs);
146
- if (ts) {
147
- if (!startedAt) startedAt = ts;
148
- endedAt = ts;
149
- }
150
-
151
- const text = extractPiText(msg["content"]);
152
-
153
- if (role === "assistant") {
154
- const stop = typeof msg["stopReason"] === "string" ? msg["stopReason"] : "";
155
- if (stop !== "error") allAssistantErrors = false;
156
- if (!text.trim()) continue; // error turns have empty content
157
- } else if (!text.trim()) {
158
- continue;
159
- }
160
-
161
- turns.push({ role, text, timestamp: ts });
162
- }
163
-
164
- if (turns.length === 0) return null;
165
-
166
- const hasUser = turns.some((t) => t.role === "user");
167
- const hasSuccessfulAssistant = turns.some((t) => t.role === "assistant");
168
- const isAborted =
169
- hasUser && (!hasSuccessfulAssistant || allAssistantErrors);
170
-
171
- const transcript = turns.map((t) => `[${t.role}] ${t.text}`).join("\n\n");
172
- const duration = durationMinutes(startedAt, endedAt);
173
- const label = provisionalLabel(turns);
174
- const rawId = sessionId || path.split("/").pop()!.replace(".jsonl", "");
175
-
176
- return {
177
- id: safeSessionId("pi", rawId),
178
- runtime: this.runtimeVersion,
179
- runtimeSessionId: rawId,
180
- sourcePath: path,
181
- startedAt,
182
- endedAt,
183
- durationMin: duration,
184
- turnCount: turns.length,
185
- byteRange: [0, totalBytes],
186
- projectDir,
187
- gitBranch: isAborted ? "aborted" : "",
188
- text: transcript,
189
- label,
190
- };
191
- }
192
- }
193
-
194
- // ── helpers ──────────────────────────────────────────────────────────────
195
-
196
- function isRecord(v: unknown): v is Record<string, unknown> {
197
- return !!v && typeof v === "object" && !Array.isArray(v);
198
- }
199
-
200
- async function walk(
201
- dir: string,
202
- onFile: (path: string, st: import("node:fs").Stats) => Promise<void>,
203
- ): Promise<void> {
204
- let entries;
205
- try {
206
- entries = await fs.readdir(dir, { withFileTypes: true });
207
- } catch {
208
- return;
209
- }
210
- for (const ent of entries) {
211
- const full = join(dir, ent.name);
212
- if (ent.isDirectory()) {
213
- await walk(full, onFile);
214
- } else if (ent.isFile()) {
215
- try {
216
- const st = await fs.stat(full);
217
- await onFile(full, st);
218
- } catch {
219
- continue;
220
- }
221
- }
222
- }
223
- }
224
-
225
- function extractPiText(content: unknown): string {
226
- if (typeof content === "string") return content.trim();
227
- if (!Array.isArray(content)) return "";
228
-
229
- const parts: string[] = [];
230
- for (const block of content) {
231
- if (!isRecord(block)) continue;
232
- const btype = block["type"];
233
- if (btype === "text") {
234
- const t = block["text"];
235
- if (typeof t === "string" && t.trim()) parts.push(t.trim());
236
- } else if (btype === "tool_use") {
237
- const name = typeof block["name"] === "string" ? block["name"] : "tool";
238
- parts.push(`[tool_use: ${name}]`);
239
- } else if (btype === "tool_result") {
240
- let res = block["content"];
241
- if (Array.isArray(res)) {
242
- res = res
243
- .filter(isRecord)
244
- .map((b) => (typeof b["text"] === "string" ? (b["text"] as string) : ""))
245
- .join("\n");
246
- }
247
- if (typeof res === "string" && res) {
248
- const preview = res.slice(0, TOOL_RESULT_PREVIEW_CHARS);
249
- const ellipsis = res.length > TOOL_RESULT_PREVIEW_CHARS ? "..." : "";
250
- parts.push(`[tool_result: ${preview}${ellipsis}]`);
251
- }
252
- }
253
- }
254
- return parts.filter((p) => p).join("\n");
255
- }
256
-
257
- function provisionalLabel(turns: ReadonlyArray<Turn>): string {
258
- for (const t of turns) {
259
- if (t.role !== "user") continue;
260
- const firstLine = t.text.split("\n", 1)[0]?.trim();
261
- if (firstLine) return firstLine.slice(0, 80);
262
- }
263
- return "Untitled session";
264
- }
@@ -1,386 +0,0 @@
1
- /**
2
- * WindsurfAdapter — reads Windsurf (Codeium Cascade) sessions.
3
- *
4
- * ## Storage locations (macOS; Linux uses ~/.config/)
5
- *
6
- * Workspace DBs ~/Library/Application Support/Windsurf/User/workspaceStorage/<hash>/state.vscdb
7
- * Table: ItemTable
8
- * Key: workbench.panel.aichat.view.aichat.chatdata — chat tabs
9
- * Bubble role: type 'user' → user, type 'ai' → assistant
10
- *
11
- * Global DB ~/Library/Application Support/Windsurf/User/globalStorage/state.vscdb
12
- * Table: cursorDiskKV (if present) — composerData:*, agentData:*, flowData:*
13
- * Table: ItemTable (fallback) — keys matching %agent%, %flow%, %cascade%
14
- * Conversation format: type 1/2 (user/assistant) or role: user/assistant
15
- *
16
- * ## Session ID prefixes
17
- *
18
- * ws_ — workspace chat tab (ItemTable chatdata)
19
- * wsg_ — global DB agent/flow session (cursorDiskKV or ItemTable)
20
- *
21
- * ## pathOrUrl in source registry
22
- * Path to the Windsurf User directory. The adapter discovers:
23
- * <userDir>/workspaceStorage/<hash>/state.vscdb (workspace)
24
- * <userDir>/globalStorage/state.vscdb (global)
25
- *
26
- * Env override: NLM_WINDSURF_USER_DIR
27
- */
28
-
29
- import { existsSync, readdirSync } from "node:fs";
30
- import { homedir } from "node:os";
31
- import { join } from "node:path";
32
- import Database from "better-sqlite3";
33
- import type {
34
- DetectionResult,
35
- DiscoverOptions,
36
- SessionChunk,
37
- TranscriptAdapter,
38
- } from "@ports/transcript-adapter.js";
39
- import { durationMinutes, normalizeTimestamp, safeSessionId } from "./common.js";
40
-
41
- export interface WindsurfAdapterOptions {
42
- readonly userDir?: string;
43
- }
44
-
45
- // ── Types ─────────────────────────────────────────────────────────────────────
46
-
47
- interface ItemTableRow {
48
- readonly key: string;
49
- readonly value: string | null;
50
- }
51
-
52
- interface KVRow {
53
- readonly key: string;
54
- readonly value: string | null;
55
- }
56
-
57
- interface ChatTab {
58
- readonly tabId?: string;
59
- readonly chatTitle?: string;
60
- readonly lastSendTime?: number;
61
- readonly bubbles?: ChatBubble[];
62
- }
63
-
64
- interface ChatBubble {
65
- readonly type?: "user" | "ai" | string;
66
- readonly text?: string;
67
- readonly rawText?: string;
68
- }
69
-
70
- interface AgentComposer {
71
- readonly composerId?: string;
72
- readonly name?: string;
73
- readonly createdAt?: unknown;
74
- readonly lastUpdatedAt?: unknown;
75
- readonly conversation?: AgentBubble[];
76
- readonly status?: string;
77
- }
78
-
79
- interface AgentBubble {
80
- readonly type?: number | string;
81
- readonly role?: string;
82
- readonly text?: string;
83
- }
84
-
85
- type Turn = { role: "user" | "assistant"; text: string };
86
-
87
- const CHAT_KEY = "workbench.panel.aichat.view.aichat.chatdata";
88
-
89
- // ── Path helpers ──────────────────────────────────────────────────────────────
90
-
91
- export function defaultUserDir(): string {
92
- if (process.env["NLM_WINDSURF_USER_DIR"]) return process.env["NLM_WINDSURF_USER_DIR"];
93
- const home = homedir();
94
- if (process.platform === "darwin") {
95
- return join(home, "Library/Application Support/Windsurf/User");
96
- }
97
- return join(home, ".config/Windsurf/User");
98
- }
99
-
100
- function workspaceStorageDir(userDir: string): string {
101
- return join(userDir, "workspaceStorage");
102
- }
103
-
104
- function globalDbPath(userDir: string): string {
105
- return join(userDir, "globalStorage", "state.vscdb");
106
- }
107
-
108
- function listWorkspaceDbs(userDir: string): string[] {
109
- const wsDir = workspaceStorageDir(userDir);
110
- if (!existsSync(wsDir)) return [];
111
- try {
112
- return readdirSync(wsDir, { withFileTypes: true })
113
- .filter((e) => e.isDirectory())
114
- .map((e) => join(wsDir, e.name, "state.vscdb"))
115
- .filter((p) => existsSync(p));
116
- } catch {
117
- return [];
118
- }
119
- }
120
-
121
- // ── Turn extraction ───────────────────────────────────────────────────────────
122
-
123
- function extractChatTurns(bubbles: ChatBubble[]): Turn[] {
124
- const turns: Turn[] = [];
125
- for (const b of bubbles) {
126
- const text = (b.rawText ?? b.text ?? "").trim();
127
- if (!text) continue;
128
- turns.push({ role: b.type === "user" ? "user" : "assistant", text });
129
- }
130
- return turns;
131
- }
132
-
133
- function extractAgentTurns(bubbles: AgentBubble[]): Turn[] {
134
- const turns: Turn[] = [];
135
- for (const b of bubbles) {
136
- const text = (b.text ?? "").trim();
137
- if (!text) continue;
138
- // Accept numeric type (1/2) or string role
139
- const isUser = b.type === 1 || b.role === "user";
140
- const isAssistant = b.type === 2 || b.role === "assistant";
141
- if (!isUser && !isAssistant) continue;
142
- turns.push({ role: isUser ? "user" : "assistant", text });
143
- }
144
- return turns;
145
- }
146
-
147
- function provisionalLabel(turns: ReadonlyArray<Turn>): string {
148
- for (const t of turns) {
149
- if (t.role !== "user") continue;
150
- const first = t.text.split("\n", 1)[0]?.trim();
151
- if (first) return first.slice(0, 80);
152
- }
153
- return "Untitled session";
154
- }
155
-
156
- function buildChunk(
157
- id: string,
158
- runtimeSessionId: string,
159
- sourcePath: string,
160
- turns: Turn[],
161
- startedAt: string,
162
- endedAt: string,
163
- label: string,
164
- ): SessionChunk {
165
- const text = turns.map((t) => `${t.role}: ${t.text}`).join("\n\n");
166
- return {
167
- id,
168
- runtime: "windsurf/1.0",
169
- runtimeSessionId,
170
- sourcePath,
171
- startedAt,
172
- endedAt,
173
- durationMin: durationMinutes(startedAt, endedAt),
174
- turnCount: turns.length,
175
- byteRange: [0, Buffer.byteLength(text, "utf8")],
176
- projectDir: "",
177
- gitBranch: "",
178
- text,
179
- label,
180
- };
181
- }
182
-
183
- // ── Workspace chat helpers ────────────────────────────────────────────────────
184
-
185
- function parseTabsFromDb(dbPath: string): ChatTab[] {
186
- let db: Database.Database | undefined;
187
- try {
188
- db = new Database(dbPath, { readonly: true });
189
- const row = db
190
- .prepare<[string], ItemTableRow>(`SELECT key, value FROM ItemTable WHERE key = ?`)
191
- .get(CHAT_KEY);
192
- if (!row?.value) return [];
193
- const data = JSON.parse(row.value) as { tabs?: ChatTab[] };
194
- return Array.isArray(data.tabs) ? data.tabs : [];
195
- } catch {
196
- return [];
197
- } finally {
198
- db?.close();
199
- }
200
- }
201
-
202
- // ── Global DB helpers ─────────────────────────────────────────────────────────
203
-
204
- interface GlobalSession {
205
- readonly id: string; // raw composerId/session key
206
- readonly meta: AgentComposer;
207
- readonly dbPath: string;
208
- }
209
-
210
- function parseGlobalSessions(globalPath: string): GlobalSession[] {
211
- if (!existsSync(globalPath)) return [];
212
- let db: Database.Database | undefined;
213
- const results: GlobalSession[] = [];
214
- try {
215
- db = new Database(globalPath, { readonly: true });
216
- const tables = db
217
- .prepare<[], { name: string }>(`SELECT name FROM sqlite_master WHERE type='table'`)
218
- .all()
219
- .map((r) => r.name);
220
-
221
- if (tables.includes("cursorDiskKV")) {
222
- const rows = db
223
- .prepare<[], KVRow>(
224
- `SELECT key, value FROM cursorDiskKV
225
- WHERE key LIKE 'composerData:%' OR key LIKE 'agentData:%' OR key LIKE 'flowData:%'
226
- ORDER BY rowid ASC`,
227
- )
228
- .all();
229
- for (const row of rows) {
230
- if (!row.value) continue;
231
- try {
232
- const meta = JSON.parse(row.value) as AgentComposer;
233
- const rawId = meta.composerId ?? row.key.split(":").slice(1).join(":");
234
- if (rawId) results.push({ id: rawId, meta, dbPath: globalPath });
235
- } catch { /* skip */ }
236
- }
237
- } else if (tables.includes("ItemTable")) {
238
- // Fallback: probe for agent/flow/cascade keys
239
- const rows = db
240
- .prepare<[], ItemTableRow>(
241
- `SELECT key, value FROM ItemTable
242
- WHERE key LIKE '%agent%' OR key LIKE '%flow%' OR key LIKE '%cascade%'`,
243
- )
244
- .all();
245
- for (const row of rows) {
246
- if (!row.value) continue;
247
- try {
248
- const data = JSON.parse(row.value);
249
- if (typeof data !== "object" || !data) continue;
250
- // Accept any object with a conversation array
251
- const conv = (data as AgentComposer).conversation;
252
- if (!Array.isArray(conv) || conv.length === 0) continue;
253
- const id = (data as AgentComposer).composerId ?? row.key;
254
- results.push({ id, meta: data as AgentComposer, dbPath: globalPath });
255
- } catch { /* skip */ }
256
- }
257
- }
258
- } catch { /* inaccessible */ } finally {
259
- db?.close();
260
- }
261
- return results;
262
- }
263
-
264
- // ── Adapter ───────────────────────────────────────────────────────────────────
265
-
266
- export class WindsurfAdapter implements TranscriptAdapter {
267
- readonly name = "windsurf";
268
- readonly runtimeVersion = "windsurf/1.0";
269
- readonly transcriptKind = "windsurf-sqlite";
270
-
271
- private readonly userDir: string;
272
-
273
- constructor(opts: WindsurfAdapterOptions = {}) {
274
- this.userDir = opts.userDir ?? defaultUserDir();
275
- }
276
-
277
- detect(): DetectionResult {
278
- if (existsSync(this.userDir)) {
279
- return { adapterName: this.name, enabled: true, path: this.userDir, hint: null };
280
- }
281
- return {
282
- adapterName: this.name,
283
- enabled: false,
284
- path: null,
285
- hint: "Windsurf User directory not found — install Windsurf or set NLM_WINDSURF_USER_DIR.",
286
- };
287
- }
288
-
289
- async discover(options?: DiscoverOptions): Promise<ReadonlyArray<string>> {
290
- const seen = new Set<string>();
291
- const ids: string[] = [];
292
- const add = (id: string) => { if (!seen.has(id)) { seen.add(id); ids.push(id); } };
293
- const cutoff = options?.since?.getTime();
294
-
295
- // ── Workspace chat tabs ───────────────────────────────────────────────
296
- for (const dbPath of listWorkspaceDbs(this.userDir)) {
297
- for (const tab of parseTabsFromDb(dbPath)) {
298
- if (!tab.tabId) continue;
299
- if (!(tab.bubbles && tab.bubbles.length > 0)) continue;
300
- if (cutoff !== undefined) {
301
- const ts = tab.lastSendTime;
302
- // Only skip when we have a real non-zero timestamp older than the cutoff.
303
- // Missing (undefined) or zero timestamps are treated as "unknown age" — include.
304
- if (ts !== undefined && ts > 0 && ts < cutoff) continue;
305
- }
306
- add(`ws_${tab.tabId}`);
307
- }
308
- }
309
-
310
- // ── Global agent/flow sessions ────────────────────────────────────────
311
- for (const gs of parseGlobalSessions(globalDbPath(this.userDir))) {
312
- if (cutoff !== undefined) {
313
- const ts = gs.meta.lastUpdatedAt ?? gs.meta.createdAt;
314
- if (ts !== undefined && ts !== null) {
315
- const normalized = normalizeTimestamp(ts);
316
- if (normalized && Date.parse(normalized) < cutoff) continue;
317
- }
318
- }
319
- add(`wsg_${gs.id}`);
320
- }
321
-
322
- return ids;
323
- }
324
-
325
- async parseSession(id: string): Promise<SessionChunk | null> {
326
- if (id.startsWith("wsg_")) {
327
- return this._parseGlobalSession(id.slice("wsg_".length));
328
- }
329
- // ws_ prefix or legacy plain tabId
330
- const tabId = id.startsWith("ws_") ? id.slice("ws_".length) : id;
331
- return this._parseWorkspaceChatTab(tabId);
332
- }
333
-
334
- private _parseWorkspaceChatTab(tabId: string): SessionChunk | null {
335
- for (const dbPath of listWorkspaceDbs(this.userDir)) {
336
- const tabs = parseTabsFromDb(dbPath);
337
- const tab = tabs.find((t) => t.tabId === tabId);
338
- if (!tab) continue;
339
-
340
- const turns = extractChatTurns(tab.bubbles ?? []);
341
- if (turns.length === 0) return null;
342
-
343
- const endedAtMs = tab.lastSendTime ?? 0;
344
- const endedAt = endedAtMs > 0 ? new Date(endedAtMs).toISOString() : "";
345
- const label = tab.chatTitle?.trim()
346
- ? tab.chatTitle.trim().slice(0, 80)
347
- : provisionalLabel(turns);
348
-
349
- return buildChunk(
350
- safeSessionId("ws", tabId),
351
- tabId,
352
- `${dbPath}::${tabId}`,
353
- turns,
354
- endedAt,
355
- endedAt,
356
- label,
357
- );
358
- }
359
- return null;
360
- }
361
-
362
- private _parseGlobalSession(rawId: string): SessionChunk | null {
363
- for (const gs of parseGlobalSessions(globalDbPath(this.userDir))) {
364
- if (gs.id !== rawId) continue;
365
- const turns = extractAgentTurns(gs.meta.conversation ?? []);
366
- if (turns.length === 0) return null;
367
-
368
- const startedAt = normalizeTimestamp(gs.meta.createdAt ?? gs.meta.lastUpdatedAt ?? "");
369
- const endedAt = normalizeTimestamp(gs.meta.lastUpdatedAt ?? gs.meta.createdAt ?? "");
370
- const label = gs.meta.name?.trim()
371
- ? gs.meta.name.trim().slice(0, 80)
372
- : provisionalLabel(turns);
373
-
374
- return buildChunk(
375
- safeSessionId("wsg", rawId),
376
- rawId,
377
- `${gs.dbPath}::${rawId}`,
378
- turns,
379
- startedAt,
380
- endedAt,
381
- label,
382
- );
383
- }
384
- return null;
385
- }
386
- }