nlm-memory 0.4.2 → 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 (285) hide show
  1. package/README.md +72 -34
  2. package/dist/cli/nlm.js +223 -33
  3. package/dist/cli/nlm.js.map +1 -1
  4. package/dist/core/adapters/cursor.d.ts +45 -0
  5. package/dist/core/adapters/cursor.js +397 -0
  6. package/dist/core/adapters/cursor.js.map +1 -0
  7. package/dist/core/adapters/from-source.js +10 -0
  8. package/dist/core/adapters/from-source.js.map +1 -1
  9. package/dist/core/adapters/windsurf.d.ts +44 -0
  10. package/dist/core/adapters/windsurf.js +299 -0
  11. package/dist/core/adapters/windsurf.js.map +1 -0
  12. package/dist/core/hook/claude-settings.d.ts +12 -5
  13. package/dist/core/hook/claude-settings.js +21 -6
  14. package/dist/core/hook/claude-settings.js.map +1 -1
  15. package/dist/core/sources/source-registry.d.ts +1 -1
  16. package/dist/core/sources/source-registry.js +18 -0
  17. package/dist/core/sources/source-registry.js.map +1 -1
  18. package/dist/core/storage/sqlite-session-store.d.ts +2 -0
  19. package/dist/core/storage/sqlite-session-store.js +38 -2
  20. package/dist/core/storage/sqlite-session-store.js.map +1 -1
  21. package/dist/hook/hook-auth.d.ts +13 -0
  22. package/dist/hook/hook-auth.js +19 -0
  23. package/dist/hook/hook-auth.js.map +1 -0
  24. package/dist/hook/prompt-recall-hook.js +7 -1
  25. package/dist/hook/prompt-recall-hook.js.map +1 -1
  26. package/dist/hook/session-start-hook.js +4 -1
  27. package/dist/hook/session-start-hook.js.map +1 -1
  28. package/dist/hook/stop-hook.js +4 -1
  29. package/dist/hook/stop-hook.js.map +1 -1
  30. package/dist/http/app.d.ts +2 -0
  31. package/dist/http/app.js +76 -1
  32. package/dist/http/app.js.map +1 -1
  33. package/dist/install/claude-code.js +1 -1
  34. package/dist/install/claude-code.js.map +1 -1
  35. package/dist/install/cursor.d.ts +25 -0
  36. package/dist/install/cursor.js +43 -0
  37. package/dist/install/cursor.js.map +1 -0
  38. package/dist/install/nlm-dir-perms.d.ts +19 -0
  39. package/dist/install/nlm-dir-perms.js +43 -0
  40. package/dist/install/nlm-dir-perms.js.map +1 -0
  41. package/dist/install/ollama.d.ts +18 -1
  42. package/dist/install/ollama.js +62 -7
  43. package/dist/install/ollama.js.map +1 -1
  44. package/dist/install/setup.d.ts +4 -0
  45. package/dist/install/setup.js +141 -18
  46. package/dist/install/setup.js.map +1 -1
  47. package/dist/install/windsurf.d.ts +25 -0
  48. package/dist/install/windsurf.js +43 -0
  49. package/dist/install/windsurf.js.map +1 -0
  50. package/dist/mcp/server.js +20 -1
  51. package/dist/mcp/server.js.map +1 -1
  52. package/dist/shared/types.d.ts +4 -0
  53. package/dist/ui/assets/{index-BA6IpU8g.css → index-Beo8psd-.css} +1 -1
  54. package/dist/ui/assets/index-CSPTTeeM.js +69 -0
  55. package/dist/ui/index.html +2 -2
  56. package/package.json +26 -1
  57. package/plugin/scripts/prompt-recall-hook.mjs +55 -4
  58. package/plugin/scripts/stop-hook.mjs +57 -6
  59. package/.agents/plugins/marketplace.json +0 -20
  60. package/.github/workflows/ci.yml +0 -30
  61. package/dist/ui/assets/index-B_qIVV0k.js +0 -69
  62. package/docs/methodology/re-derivation-rate.md +0 -112
  63. package/docs/methodology/useful-hit-rate.md +0 -79
  64. package/docs/plans/2026-05-20-fts5-lexical-recall.md +0 -1088
  65. package/docs/plans/2026-05-20-recall-daemon-wedge-fix.md +0 -662
  66. package/docs/plans/2026-05-20-recall-hook-design.md +0 -131
  67. package/docs/plans/2026-05-20-recall-hook-implementation.md +0 -1222
  68. package/docs/plans/desktop-product.md +0 -69
  69. package/docs/plans/factstore-design.md +0 -236
  70. package/logs/CHANGELOG/CHANGELOG-2026.md +0 -1389
  71. package/logs/CHANGELOG/CHANGELOG.md +0 -337
  72. package/migrations/000_initial_schema.sql +0 -174
  73. package/migrations/001_entity_type_rename.sql +0 -17
  74. package/migrations/002_adapter_state_extend.sql +0 -12
  75. package/migrations/003_session_embeddings.sql +0 -11
  76. package/migrations/004_facts.sql +0 -46
  77. package/migrations/005_sources.sql +0 -31
  78. package/migrations/006_providers.sql +0 -33
  79. package/migrations/007_source_tokens.sql +0 -17
  80. package/migrations/008_fts_rebuild.sql +0 -9
  81. package/migrations/009_session_embedding_chunks.sql +0 -46
  82. package/migrations/010_sources_opencode.sql +0 -30
  83. package/migrations/011_sources_hermes_agent.sql +0 -30
  84. package/migrations/012_sources_aider.sql +0 -30
  85. package/migrations/013_adapter_state_failure_count.sql +0 -12
  86. package/plugin-hermes-agent/README.md +0 -49
  87. package/plugin-hermes-agent/__init__.py +0 -75
  88. package/plugin-hermes-agent/plugin.yaml +0 -15
  89. package/scripts/backfill-citations.mjs +0 -0
  90. package/scripts/build-codex-plugin.mjs +0 -61
  91. package/scripts/deepseek-probe.mjs +0 -67
  92. package/scripts/extract-triples.mjs +0 -207
  93. package/scripts/longmemeval/embedding-cache.ts +0 -77
  94. package/scripts/longmemeval/fetch-dataset.sh +0 -25
  95. package/scripts/longmemeval/run-harness.ts +0 -315
  96. package/scripts/longmemeval/scorer.ts +0 -99
  97. package/scripts/longmemeval/tsconfig.json +0 -9
  98. package/scripts/longmemeval/types.ts +0 -35
  99. package/scripts/nlm-daily-digest.py +0 -239
  100. package/scripts/nlm-daily-digest.sh +0 -28
  101. package/src/cli/classify-parity.ts +0 -257
  102. package/src/cli/launchctl-helpers.ts +0 -49
  103. package/src/cli/nlm.ts +0 -885
  104. package/src/core/actions/actions-log.ts +0 -118
  105. package/src/core/actions/overlay.ts +0 -117
  106. package/src/core/adapters/aider.ts +0 -205
  107. package/src/core/adapters/claude-code.ts +0 -293
  108. package/src/core/adapters/common.ts +0 -54
  109. package/src/core/adapters/from-source.ts +0 -57
  110. package/src/core/adapters/hermes-agent.ts +0 -240
  111. package/src/core/adapters/hermes.ts +0 -277
  112. package/src/core/adapters/jsonl-generic.ts +0 -208
  113. package/src/core/adapters/opencode.ts +0 -281
  114. package/src/core/adapters/pi.ts +0 -264
  115. package/src/core/classifier/prompt.ts +0 -200
  116. package/src/core/dataset/build-dataset.ts +0 -463
  117. package/src/core/embedding/chunk-body.ts +0 -76
  118. package/src/core/embedding/embed-backfill.ts +0 -210
  119. package/src/core/embedding/embed-normalize.ts +0 -135
  120. package/src/core/facts/backfill-facts.ts +0 -254
  121. package/src/core/facts/extract-facts.ts +0 -50
  122. package/src/core/hook/citation-detect.ts +0 -124
  123. package/src/core/hook/cite-memo.ts +0 -68
  124. package/src/core/hook/claude-settings.ts +0 -166
  125. package/src/core/hook/gate.ts +0 -25
  126. package/src/core/hook/hook-log.ts +0 -41
  127. package/src/core/hook/memo-sweep.ts +0 -164
  128. package/src/core/hook/memo.ts +0 -67
  129. package/src/core/hook/pointer-block.ts +0 -26
  130. package/src/core/hook/select.ts +0 -32
  131. package/src/core/hook/transcript.ts +0 -121
  132. package/src/core/ingest/ingest-session.ts +0 -111
  133. package/src/core/providers/provider-models.ts +0 -100
  134. package/src/core/providers/provider-registry.ts +0 -196
  135. package/src/core/recall/citation-log.ts +0 -108
  136. package/src/core/recall/filter.ts +0 -27
  137. package/src/core/recall/index.ts +0 -6
  138. package/src/core/recall/match-fields.ts +0 -40
  139. package/src/core/recall/query-log.ts +0 -149
  140. package/src/core/recall/query-shape.ts +0 -66
  141. package/src/core/recall/recall-service.ts +0 -320
  142. package/src/core/recall/recent-log.ts +0 -59
  143. package/src/core/recall/tokenize.ts +0 -18
  144. package/src/core/recall/useful-scan.ts +0 -336
  145. package/src/core/recall-facts/fact-query-log.ts +0 -150
  146. package/src/core/recall-facts/fact-recall-service.ts +0 -327
  147. package/src/core/scheduler/scan-once.ts +0 -142
  148. package/src/core/scheduler/scheduler.ts +0 -225
  149. package/src/core/sources/source-registry.ts +0 -260
  150. package/src/core/storage/db-restore.ts +0 -133
  151. package/src/core/storage/live-status.ts +0 -45
  152. package/src/core/storage/migrate.ts +0 -72
  153. package/src/core/storage/sqlite-fact-store.ts +0 -304
  154. package/src/core/storage/sqlite-session-store.ts +0 -765
  155. package/src/hook/prompt-recall-hook.ts +0 -174
  156. package/src/hook/session-end-hook.ts +0 -81
  157. package/src/hook/session-start-hook.ts +0 -165
  158. package/src/hook/stop-hook.ts +0 -236
  159. package/src/http/app.ts +0 -1137
  160. package/src/install/claude-code.ts +0 -128
  161. package/src/install/codex.ts +0 -367
  162. package/src/install/hermes-agent.ts +0 -76
  163. package/src/install/hermes.ts +0 -78
  164. package/src/install/ollama.ts +0 -211
  165. package/src/install/setup.ts +0 -368
  166. package/src/llm/classifier-box.ts +0 -64
  167. package/src/llm/deepseek-client.ts +0 -150
  168. package/src/llm/env-autoload.ts +0 -55
  169. package/src/llm/ollama-client.ts +0 -189
  170. package/src/mcp/server.ts +0 -534
  171. package/src/ports/fact-store.ts +0 -102
  172. package/src/ports/llm-client.ts +0 -52
  173. package/src/ports/logger.ts +0 -16
  174. package/src/ports/session-store.ts +0 -45
  175. package/src/ports/transcript-adapter.ts +0 -55
  176. package/src/shared/types.ts +0 -145
  177. package/src/ui/App.tsx +0 -58
  178. package/src/ui/components/PromoteOpenButton.tsx +0 -65
  179. package/src/ui/components/SessionDrawer.tsx +0 -136
  180. package/src/ui/components/SideNav.tsx +0 -162
  181. package/src/ui/components/Skeleton.tsx +0 -107
  182. package/src/ui/index.html +0 -13
  183. package/src/ui/lib/actions.ts +0 -30
  184. package/src/ui/lib/api.ts +0 -92
  185. package/src/ui/lib/dataset.ts +0 -141
  186. package/src/ui/lib/registries.ts +0 -155
  187. package/src/ui/lib/view-settings.ts +0 -41
  188. package/src/ui/main.tsx +0 -15
  189. package/src/ui/pages/Live.tsx +0 -229
  190. package/src/ui/pages/Pulse.tsx +0 -415
  191. package/src/ui/pages/Recall.tsx +0 -190
  192. package/src/ui/pages/River.tsx +0 -308
  193. package/src/ui/pages/Search.tsx +0 -93
  194. package/src/ui/pages/Stub.tsx +0 -9
  195. package/src/ui/pages/Thread.tsx +0 -262
  196. package/src/ui/pages/settings/Classifier.tsx +0 -227
  197. package/src/ui/pages/settings/Data.tsx +0 -190
  198. package/src/ui/pages/settings/Index.tsx +0 -65
  199. package/src/ui/pages/settings/Labels.tsx +0 -224
  200. package/src/ui/pages/settings/Providers.tsx +0 -305
  201. package/src/ui/pages/settings/SettingsSubnav.tsx +0 -28
  202. package/src/ui/pages/settings/Sources.tsx +0 -326
  203. package/src/ui/pages/settings/Views.tsx +0 -96
  204. package/src/ui/styles.css +0 -1766
  205. package/src/ui/tsconfig.json +0 -21
  206. package/src/ui/vite.config.ts +0 -19
  207. package/tests/fixtures/claude_code/short_session.jsonl +0 -2
  208. package/tests/fixtures/claude_code/standard_iso.jsonl +0 -4
  209. package/tests/fixtures/claude_code/tool_heavy.jsonl +0 -8
  210. package/tests/fixtures/claude_code/with_subagent.jsonl +0 -7
  211. package/tests/fixtures/facts.ts +0 -17
  212. package/tests/fixtures/golden-corpus.ts +0 -85
  213. package/tests/fixtures/hermes/paired_request_dump.json +0 -24
  214. package/tests/fixtures/hermes/paired_session.json +0 -23
  215. package/tests/fixtures/hermes/request_dump.json +0 -28
  216. package/tests/fixtures/hermes/session_iso.json +0 -38
  217. package/tests/fixtures/hermes/session_unix.json +0 -38
  218. package/tests/fixtures/hermes/system_only.json +0 -18
  219. package/tests/fixtures/pi/error-connection-abort.jsonl +0 -8
  220. package/tests/fixtures/pi/short-successful.jsonl +0 -5
  221. package/tests/fixtures/pi/with-custom-message.jsonl +0 -6
  222. package/tests/fixtures/sessions.ts +0 -22
  223. package/tests/integration/backfill-facts.test.ts +0 -362
  224. package/tests/integration/citation-explicit.test.ts +0 -111
  225. package/tests/integration/cite-event.test.ts +0 -169
  226. package/tests/integration/cite-memo.test.ts +0 -87
  227. package/tests/integration/db-restore.test.ts +0 -153
  228. package/tests/integration/embed-backfill.test.ts +0 -176
  229. package/tests/integration/fact-supersedence.test.ts +0 -313
  230. package/tests/integration/fts-index.test.ts +0 -60
  231. package/tests/integration/getbyids-sqlite.test.ts +0 -60
  232. package/tests/integration/hermes-agent-hooks.test.ts +0 -248
  233. package/tests/integration/hook-claude-settings.test.ts +0 -205
  234. package/tests/integration/hook-log.test.ts +0 -54
  235. package/tests/integration/hook-memo.test.ts +0 -68
  236. package/tests/integration/hook-pre-compact.test.ts +0 -105
  237. package/tests/integration/hook-subagent-start.test.ts +0 -102
  238. package/tests/integration/http.test.ts +0 -401
  239. package/tests/integration/keyword-search-fts.test.ts +0 -66
  240. package/tests/integration/mcp-recall-logging.test.ts +0 -88
  241. package/tests/integration/mcp.test.ts +0 -248
  242. package/tests/integration/memo-sweep.test.ts +0 -91
  243. package/tests/integration/prompt-recall-hook.test.ts +0 -88
  244. package/tests/integration/provider-registry.test.ts +0 -107
  245. package/tests/integration/recall-golden.test.ts +0 -59
  246. package/tests/integration/recall-sqlite.test.ts +0 -169
  247. package/tests/integration/scheduler.test.ts +0 -391
  248. package/tests/integration/session-end-hook.test.ts +0 -48
  249. package/tests/integration/session-start-hook.test.ts +0 -126
  250. package/tests/integration/source-registry.test.ts +0 -120
  251. package/tests/integration/sqlite-fact-store.test.ts +0 -346
  252. package/tests/integration/stop-hook.test.ts +0 -560
  253. package/tests/integration/wal-checkpoint.test.ts +0 -49
  254. package/tests/unit/cli/launchctl-helpers.test.ts +0 -60
  255. package/tests/unit/core/adapters/aider.test.ts +0 -230
  256. package/tests/unit/core/adapters/claude-code.test.ts +0 -118
  257. package/tests/unit/core/adapters/hermes-agent.test.ts +0 -329
  258. package/tests/unit/core/adapters/hermes.test.ts +0 -81
  259. package/tests/unit/core/adapters/jsonl-generic.test.ts +0 -142
  260. package/tests/unit/core/adapters/opencode.test.ts +0 -354
  261. package/tests/unit/core/adapters/pi.test.ts +0 -110
  262. package/tests/unit/core/classifier/prompt.test.ts +0 -126
  263. package/tests/unit/core/embedding/chunk-body.test.ts +0 -100
  264. package/tests/unit/core/facts/extract-facts.test.ts +0 -117
  265. package/tests/unit/core/filter.test.ts +0 -40
  266. package/tests/unit/core/hook/citation-detect-cite-session.test.ts +0 -96
  267. package/tests/unit/core/hook/citation-detect.test.ts +0 -124
  268. package/tests/unit/core/hook/gate.test.ts +0 -29
  269. package/tests/unit/core/hook/pointer-block.test.ts +0 -22
  270. package/tests/unit/core/hook/select.test.ts +0 -66
  271. package/tests/unit/core/match-fields.test.ts +0 -39
  272. package/tests/unit/core/mcp-cite-session.test.ts +0 -51
  273. package/tests/unit/core/providers/provider-models.test.ts +0 -101
  274. package/tests/unit/core/query-shape.test.ts +0 -92
  275. package/tests/unit/core/recall-facts/fact-recall-service.test.ts +0 -258
  276. package/tests/unit/core/recall-service.test.ts +0 -200
  277. package/tests/unit/core/storage/live-status.test.ts +0 -54
  278. package/tests/unit/core/tokenize.test.ts +0 -32
  279. package/tests/unit/core/useful-scan.test.ts +0 -537
  280. package/tests/unit/llm/embed.test.ts +0 -93
  281. package/tests/unit/llm/ollama-client.test.ts +0 -124
  282. package/tests/unit/scripts/longmemeval-scorer.test.ts +0 -114
  283. package/tsconfig.json +0 -31
  284. package/tsconfig.test.json +0 -11
  285. package/vitest.config.ts +0 -22
@@ -1,281 +0,0 @@
1
- /**
2
- * OpenCode adapter.
3
- *
4
- * Reads the OpenCode SQLite database at:
5
- * macOS: ~/Library/Application Support/opencode/opencode.db
6
- * Linux: $XDG_DATA_HOME/opencode/opencode.db (default ~/.local/share/opencode/opencode.db)
7
- *
8
- * Unlike the JSONL-based adapters, OpenCode stores all sessions and messages
9
- * in a single SQLite file. `discover()` queries the sessions table and returns
10
- * session IDs (not file paths). `parseSession()` treats its string argument as
11
- * a session ID and reconstructs a SessionChunk from the messages and parts tables.
12
- *
13
- * Part types extracted:
14
- * - text (non-ignored): the conversational prose
15
- * - tool : summarized as [tool: <name>]
16
- * All other part types (reasoning, step-start/finish, snapshot, patch,
17
- * compaction, agent, retry, subtask) are structural and skipped.
18
- *
19
- * Format reference: verified against sst/opencode migration
20
- * 20260127222353_familiar_lady_ursula and session.sql.ts, 2026-05-28.
21
- */
22
-
23
- import { existsSync, readFileSync } from "node:fs";
24
- import { homedir } from "node:os";
25
- import { join } from "node:path";
26
- import Database from "better-sqlite3";
27
- import type {
28
- DetectionResult,
29
- DiscoverOptions,
30
- SessionChunk,
31
- TranscriptAdapter,
32
- } from "@ports/transcript-adapter.js";
33
- import { durationMinutes, normalizeTimestamp } from "./common.js";
34
-
35
- const TOOL_OUTPUT_PREVIEW_CHARS = 240;
36
-
37
- export interface OpenCodeAdapterOptions {
38
- readonly dbPath?: string;
39
- }
40
-
41
- interface Turn {
42
- readonly role: "user" | "assistant";
43
- readonly text: string;
44
- readonly timestamp: string;
45
- }
46
-
47
- interface SessionRow {
48
- readonly id: string;
49
- readonly directory: string;
50
- readonly title: string;
51
- readonly time_created: number;
52
- readonly time_updated: number;
53
- }
54
-
55
- interface MessageRow {
56
- readonly id: string;
57
- readonly time_created: number;
58
- readonly data: string;
59
- }
60
-
61
- interface PartRow {
62
- readonly message_id: string;
63
- readonly time_created: number;
64
- readonly data: string;
65
- }
66
-
67
- interface MessageInfo {
68
- readonly role: "user" | "assistant";
69
- }
70
-
71
- interface TextPartData {
72
- readonly type: "text";
73
- readonly text: string;
74
- readonly ignored?: boolean;
75
- }
76
-
77
- interface ToolPartData {
78
- readonly type: "tool";
79
- readonly tool: string;
80
- readonly state?: Record<string, unknown>;
81
- }
82
-
83
- type PartData = TextPartData | ToolPartData | { readonly type: string };
84
-
85
- export function defaultDbPath(): string {
86
- if (process.env["OPENCODE_DB_PATH"]) return process.env["OPENCODE_DB_PATH"];
87
- if (process.platform === "darwin") {
88
- return join(homedir(), "Library", "Application Support", "opencode", "opencode.db");
89
- }
90
- const xdg = process.env["XDG_DATA_HOME"] ?? join(homedir(), ".local", "share");
91
- return join(xdg, "opencode", "opencode.db");
92
- }
93
-
94
- function readGitBranch(directory: string): string {
95
- try {
96
- const head = readFileSync(join(directory, ".git", "HEAD"), "utf8").trim();
97
- const match = /^ref: refs\/heads\/(.+)$/.exec(head);
98
- return match ? (match[1] ?? "") : "";
99
- } catch {
100
- return "";
101
- }
102
- }
103
-
104
- function extractTurns(messages: MessageRow[], partsByMessage: Map<string, PartData[]>): Turn[] {
105
- const turns: Turn[] = [];
106
- for (const msg of messages) {
107
- let info: MessageInfo;
108
- try {
109
- info = JSON.parse(msg.data) as MessageInfo;
110
- } catch {
111
- continue;
112
- }
113
- if (info.role !== "user" && info.role !== "assistant") continue;
114
-
115
- const parts = partsByMessage.get(msg.id) ?? [];
116
- const segments: string[] = [];
117
-
118
- for (const p of parts) {
119
- if (p.type === "text") {
120
- const tp = p as TextPartData;
121
- if (!tp.ignored && tp.text) segments.push(tp.text);
122
- } else if (p.type === "tool") {
123
- const tp = p as ToolPartData;
124
- const output = extractToolOutput(tp);
125
- segments.push(output ? `[tool: ${tp.tool}] ${output}` : `[tool: ${tp.tool}]`);
126
- }
127
- }
128
-
129
- const text = segments.join("\n").trim();
130
- if (!text) continue;
131
-
132
- turns.push({ role: info.role, text, timestamp: normalizeTimestamp(msg.time_created) });
133
- }
134
- return turns;
135
- }
136
-
137
- function extractToolOutput(part: ToolPartData): string {
138
- const state = part.state;
139
- if (!state) return "";
140
- const output =
141
- (state["output"] as string | undefined) ??
142
- (state["result"] as string | undefined) ??
143
- "";
144
- if (typeof output !== "string" || !output) return "";
145
- const preview = output.slice(0, TOOL_OUTPUT_PREVIEW_CHARS);
146
- return output.length > TOOL_OUTPUT_PREVIEW_CHARS ? `${preview}…` : preview;
147
- }
148
-
149
- function provisionalLabel(turns: ReadonlyArray<Turn>): string {
150
- for (const t of turns) {
151
- if (t.role !== "user") continue;
152
- const first = t.text.split("\n", 1)[0]?.trim();
153
- if (first) return first.slice(0, 80);
154
- }
155
- return "Untitled session";
156
- }
157
-
158
- export class OpenCodeAdapter implements TranscriptAdapter {
159
- readonly name = "opencode";
160
- readonly runtimeVersion = "opencode/1.0";
161
- readonly transcriptKind = "opencode-sqlite";
162
-
163
- private readonly dbPath: string;
164
-
165
- constructor(opts: OpenCodeAdapterOptions = {}) {
166
- this.dbPath = opts.dbPath ?? defaultDbPath();
167
- }
168
-
169
- detect(): DetectionResult {
170
- if (existsSync(this.dbPath)) {
171
- return { adapterName: this.name, enabled: true, path: this.dbPath, hint: null };
172
- }
173
- return { adapterName: this.name, enabled: false, path: null, hint: "opencode.db not found" };
174
- }
175
-
176
- async discover(options?: DiscoverOptions): Promise<ReadonlyArray<string>> {
177
- if (!existsSync(this.dbPath)) return [];
178
- let db: Database.Database | undefined;
179
- try {
180
- db = new Database(this.dbPath, { readonly: true });
181
- let rows: { id: string }[];
182
- if (options?.since) {
183
- const sinceMs = options.since.getTime();
184
- rows = db
185
- .prepare<[number], { id: string }>(
186
- `SELECT id FROM session WHERE time_archived IS NULL AND time_updated >= ?`,
187
- )
188
- .all(sinceMs);
189
- } else {
190
- rows = db
191
- .prepare<[], { id: string }>(
192
- `SELECT id FROM session WHERE time_archived IS NULL`,
193
- )
194
- .all();
195
- }
196
- return rows.map((r) => r.id);
197
- } catch {
198
- return [];
199
- } finally {
200
- db?.close();
201
- }
202
- }
203
-
204
- async parseSession(sessionId: string): Promise<SessionChunk | null> {
205
- if (!existsSync(this.dbPath)) return null;
206
- let db: Database.Database | undefined;
207
- try {
208
- db = new Database(this.dbPath, { readonly: true });
209
-
210
- const session = db
211
- .prepare<[string], SessionRow>(
212
- `SELECT id, directory, title, time_created, time_updated
213
- FROM session WHERE id = ?`,
214
- )
215
- .get(sessionId);
216
- if (!session) return null;
217
-
218
- const messages = db
219
- .prepare<[string], MessageRow>(
220
- `SELECT id, time_created, data FROM message
221
- WHERE session_id = ? ORDER BY time_created ASC`,
222
- )
223
- .all(sessionId);
224
-
225
- const partRows = db
226
- .prepare<[string], PartRow>(
227
- `SELECT message_id, time_created, data FROM part
228
- WHERE session_id = ? ORDER BY time_created ASC`,
229
- )
230
- .all(sessionId);
231
-
232
- const partsByMessage = new Map<string, PartData[]>();
233
- for (const row of partRows) {
234
- let data: PartData;
235
- try {
236
- data = JSON.parse(row.data) as PartData;
237
- } catch {
238
- continue;
239
- }
240
- const bucket = partsByMessage.get(row.message_id);
241
- if (bucket) {
242
- bucket.push(data);
243
- } else {
244
- partsByMessage.set(row.message_id, [data]);
245
- }
246
- }
247
-
248
- const turns = extractTurns(messages, partsByMessage);
249
- if (turns.length === 0) return null;
250
-
251
- const startedAt = normalizeTimestamp(session.time_created);
252
- const endedAt = normalizeTimestamp(session.time_updated);
253
- const transcript = turns.map((t) => `${t.role}: ${t.text}`).join("\n\n");
254
-
255
- const label =
256
- session.title && session.title !== "New session"
257
- ? session.title.slice(0, 80)
258
- : provisionalLabel(turns);
259
-
260
- return {
261
- id: `oc_${sessionId}`,
262
- runtime: this.runtimeVersion,
263
- runtimeSessionId: sessionId,
264
- sourcePath: `${this.dbPath}::${sessionId}`,
265
- startedAt,
266
- endedAt,
267
- durationMin: durationMinutes(startedAt, endedAt),
268
- turnCount: turns.length,
269
- byteRange: [0, Buffer.byteLength(transcript, "utf8")],
270
- projectDir: session.directory,
271
- gitBranch: readGitBranch(session.directory),
272
- text: transcript,
273
- label,
274
- };
275
- } catch {
276
- return null;
277
- } finally {
278
- db?.close();
279
- }
280
- }
281
- }
@@ -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
- }