opencode-session-searcher 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-session-searcher",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "opencode plugin: search past opencode sessions (search_sessions)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -35,8 +35,8 @@
35
35
  "typecheck": "tsc --noEmit"
36
36
  },
37
37
  "dependencies": {
38
- "@opencode-ai/plugin": "latest",
39
- "@opencode-ai/sdk": "latest"
38
+ "@opencode-ai/plugin": "1.19.0",
39
+ "@opencode-ai/sdk": "1.19.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/bun": "^1.4.3",
package/src/db.test.ts CHANGED
@@ -3,7 +3,16 @@ import { existsSync } from "node:fs"
3
3
  import { Database } from "bun:sqlite"
4
4
  import { homedir } from "node:os"
5
5
  import { join } from "node:path"
6
- import { dbPath, openDB, query, readSession, resolveDbPath, searchSessions, validateSql } from "./db"
6
+ import {
7
+ dbPath,
8
+ openDB,
9
+ query,
10
+ readSession,
11
+ resolveDbPath,
12
+ searchSessions,
13
+ splitSearchTerms,
14
+ validateSql,
15
+ } from "./db"
7
16
 
8
17
  const dbExists = existsSync(dbPath())
9
18
 
@@ -170,3 +179,54 @@ describe("resolveDbPath", () => {
170
179
  )
171
180
  })
172
181
  })
182
+
183
+ describe("splitSearchTerms", () => {
184
+ test("splits on whitespace and lowercases", () => {
185
+ expect(splitSearchTerms(" Auth LOGIN\tflow ")).toEqual(["auth", "login", "flow"])
186
+ })
187
+
188
+ test("keeps a double-quoted phrase as one word", () => {
189
+ expect(splitSearchTerms('"Connection refused" retry')).toEqual(["connection refused", "retry"])
190
+ })
191
+
192
+ test("drops duplicates and empty quotes", () => {
193
+ expect(splitSearchTerms('auth AUTH "" auth')).toEqual(["auth"])
194
+ })
195
+
196
+ test("returns nothing for blank input", () => {
197
+ expect(splitSearchTerms(' "" ')).toEqual([])
198
+ })
199
+ })
200
+
201
+ describe("searchSessions all-words matching", () => {
202
+ test.skipIf(!dbExists)("every title match contains every word, in any order", () => {
203
+ const found = query(
204
+ "SELECT title FROM session WHERE title LIKE '% %' AND length(title) > 10 ORDER BY time_updated DESC LIMIT 1",
205
+ )
206
+ if (found.rows.length === 0) return
207
+ const titleWords = String(found.rows[0].title).toLowerCase().split(/\s+/).filter(Boolean)
208
+ const reversed = [titleWords[titleWords.length - 1], titleWords[0]].join(" ")
209
+ const result = searchSessions(reversed, { scope: "titles", limit: 50 })
210
+ expect(result.words).toEqual(splitSearchTerms(reversed))
211
+ expect(result.matches.length).toBeGreaterThan(0)
212
+ for (const m of result.matches) {
213
+ const title = String(m.title).toLowerCase()
214
+ for (const w of result.words) expect(title).toContain(w)
215
+ }
216
+ })
217
+
218
+ test.skipIf(!dbExists)("session scope requires every word in the same part", () => {
219
+ const found = query(
220
+ "SELECT p.session_id AS id FROM part p WHERE json_extract(p.data, '$.type') = 'text' LIMIT 1",
221
+ )
222
+ const sessionId = found.rows[0].id as string
223
+ const result = searchSessions("e a", { scope: "session", sessionId, limit: 20 })
224
+ expect(result.words).toEqual(["e", "a"])
225
+ const impossible = searchSessions("e zzqqxx-no-such-word-9f3", { scope: "session", sessionId, limit: 20 })
226
+ expect(impossible.matches).toEqual([])
227
+ })
228
+
229
+ test("rejects a query of only empty quotes", () => {
230
+ expect(() => searchSessions('""')).toThrow(/non-empty/)
231
+ })
232
+ })
package/src/db.ts CHANGED
@@ -71,6 +71,8 @@ export type SearchMatch = {
71
71
  export type SearchResult = {
72
72
  scope: SearchScope
73
73
  term: string
74
+ /** The words that all had to match (a quoted phrase is one word). */
75
+ words: string[]
74
76
  matches: SearchMatch[]
75
77
  truncated: boolean
76
78
  elapsedMs: number
@@ -325,27 +327,47 @@ export function readSession(
325
327
  }
326
328
  }
327
329
 
330
+ /**
331
+ * Split a search query into the words that must all match.
332
+ * Whitespace separates words; a double-quoted phrase stays one word.
333
+ * Lowercased and de-duplicated.
334
+ */
335
+ export function splitSearchTerms(query: string): string[] {
336
+ const words: string[] = []
337
+ for (const m of query.matchAll(/"([^"]*)"|(\S+)/g)) {
338
+ const word = (m[1] ?? m[2] ?? "").trim().toLowerCase()
339
+ if (word && !words.includes(word)) words.push(word)
340
+ }
341
+ return words
342
+ }
343
+
344
+ function likePattern(word: string): string {
345
+ return `%${word.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
346
+ }
347
+
328
348
  export function searchSessions(
329
349
  term: string,
330
350
  opts: { sessionId?: string; scope?: SearchScope; limit?: number } = {},
331
351
  ): SearchResult {
332
352
  const needle = term.trim()
333
- if (!needle) throw new Error("query must be a non-empty search term")
353
+ const words = splitSearchTerms(needle)
354
+ if (words.length === 0) throw new Error("query must be a non-empty search term")
334
355
  const scope: SearchScope = opts.scope ?? (opts.sessionId ? "session" : "global")
335
356
  if (scope === "session" && !opts.sessionId) {
336
357
  throw new Error('scope "session" requires a session_id')
337
358
  }
338
359
  const limit = clamp(opts.limit, 1, 200, 25)
339
- const pattern = `%${needle.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
360
+ const patterns = words.map(likePattern)
361
+ const allLike = (column: string) => words.map(() => `${column} LIKE ? ESCAPE '\\'`).join(" AND ")
340
362
  const db = openDB()
341
363
  const started = performance.now()
342
364
  try {
343
365
  if (scope === "titles") {
344
366
  const rows = db
345
367
  .prepare(
346
- "SELECT id, title, directory, agent, time_created FROM session WHERE title LIKE ? ESCAPE '\\' ORDER BY time_updated DESC LIMIT ?",
368
+ `SELECT id, title, directory, agent, time_created FROM session WHERE ${allLike("title")} ORDER BY time_updated DESC LIMIT ?`,
347
369
  )
348
- .all(pattern, limit + 1) as any[]
370
+ .all(...patterns, limit + 1) as any[]
349
371
  const truncated = rows.length > limit
350
372
  if (truncated) rows.pop()
351
373
  const matches: SearchMatch[] = rows.map((r) => ({
@@ -359,7 +381,7 @@ export function searchSessions(
359
381
  type: null,
360
382
  snippet: null,
361
383
  }))
362
- return { scope, term: needle, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
384
+ return { scope, term: needle, words, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
363
385
  }
364
386
  const order = scope === "session" ? "ASC" : "DESC"
365
387
  const sessionFilter = scope === "session" ? "AND p.session_id = ? " : ""
@@ -372,10 +394,13 @@ export function searchSessions(
372
394
  `FROM part p ` +
373
395
  `JOIN message m ON m.id = p.message_id ` +
374
396
  `JOIN session s ON s.id = p.session_id ` +
375
- `WHERE p.data LIKE ? ESCAPE '\\' ${sessionFilter}` +
397
+ `WHERE ${allLike("p.data")} ${sessionFilter}` +
376
398
  `ORDER BY p.time_created ${order} LIMIT ?`
399
+ // The snippet is centred on the first word.
377
400
  const params: unknown[] =
378
- scope === "session" ? [needle, pattern, opts.sessionId, limit + 1] : [needle, pattern, limit + 1]
401
+ scope === "session"
402
+ ? [words[0], ...patterns, opts.sessionId, limit + 1]
403
+ : [words[0], ...patterns, limit + 1]
379
404
  const rows = db.prepare(sql).all(...(params as any[])) as any[]
380
405
  const truncated = rows.length > limit
381
406
  if (truncated) rows.pop()
@@ -390,7 +415,7 @@ export function searchSessions(
390
415
  type: r.type ?? null,
391
416
  snippet: r.snippet ?? null,
392
417
  }))
393
- return { scope, term: needle, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
418
+ return { scope, term: needle, words, matches, truncated, elapsedMs: Math.round(performance.now() - started) }
394
419
  } finally {
395
420
  db.close()
396
421
  }
package/src/index.ts CHANGED
@@ -60,13 +60,14 @@ function extractPartTexts(part: any, depth: Depth): string[] {
60
60
  return texts
61
61
  }
62
62
 
63
- function buildSnippet(text: string, query: string): string | null {
63
+ /** Every word must appear in the text; the snippet is centred on the first one. */
64
+ function buildSnippet(text: string, words: string[]): string | null {
64
65
  const lower = text.toLowerCase()
65
- const idx = lower.indexOf(query)
66
- if (idx === -1) return null
66
+ if (!words.every((w) => lower.includes(w))) return null
67
+ const idx = lower.indexOf(words[0])
67
68
 
68
69
  const start = Math.max(0, idx - SNIPPET_RADIUS)
69
- const end = Math.min(text.length, idx + query.length + SNIPPET_RADIUS)
70
+ const end = Math.min(text.length, idx + words[0].length + SNIPPET_RADIUS)
70
71
  let snippet = text.slice(start, end).replace(/\n/g, " ")
71
72
  if (start > 0) snippet = "..." + snippet
72
73
  if (end < text.length) snippet = snippet + "..."
@@ -76,7 +77,7 @@ function buildSnippet(text: string, query: string): string | null {
76
77
  async function scanSession(
77
78
  client: any,
78
79
  sessionID: string,
79
- query: string,
80
+ words: string[],
80
81
  depth: Depth,
81
82
  ): Promise<Match[]> {
82
83
  const matches: Match[] = []
@@ -92,7 +93,7 @@ async function scanSession(
92
93
  for (const part of entry.parts ?? []) {
93
94
  const texts = extractPartTexts(part, depth)
94
95
  for (const text of texts) {
95
- const snippet = buildSnippet(text, query)
96
+ const snippet = buildSnippet(text, words)
96
97
  if (snippet) {
97
98
  matches.push({ role, snippet, timestamp })
98
99
  }
@@ -251,7 +252,7 @@ function formatDbSessionRead(result: db.ReadSessionResult): string {
251
252
 
252
253
  function formatDbSearch(result: db.SearchResult): string {
253
254
  const header =
254
- `Scope: ${result.scope} | Term: "${result.term}" | ` +
255
+ `Scope: ${result.scope} | Words (all must match): ${result.words.map((w) => JSON.stringify(w)).join(" ")} | ` +
255
256
  `${result.matches.length} match${result.matches.length === 1 ? "" : "es"} in ${result.elapsedMs} ms` +
256
257
  (result.truncated ? " (capped at limit)" : "")
257
258
  if (result.matches.length === 0) return `${header}\n\nNo matches found.`
@@ -302,7 +303,12 @@ const plugin: Plugin = async (ctx) => ({
302
303
  "Pass session_id or session_ids to target specific sessions. " +
303
304
  "Pass parent_session_id to search only child sessions of a parent.",
304
305
  args: {
305
- query: tool.schema.string().describe("Search term (case-insensitive substring match)"),
306
+ query: tool.schema
307
+ .string()
308
+ .describe(
309
+ "Words to search for (case-insensitive). Every word must appear in the same part; " +
310
+ 'wrap a phrase in double quotes to match it exactly, e.g. "connection refused" retry',
311
+ ),
306
312
  session_id: tool.schema
307
313
  .string()
308
314
  .optional()
@@ -346,7 +352,8 @@ const plugin: Plugin = async (ctx) => ({
346
352
  .describe("Max sessions to scan (default: 20)"),
347
353
  },
348
354
  async execute(args) {
349
- const query = args.query.toLowerCase()
355
+ const words = db.splitSearchTerms(args.query)
356
+ if (words.length === 0) throw new Error("query must be a non-empty search term")
350
357
  const depth: Depth = args.depth ?? "conversation"
351
358
  const limit = args.limit ?? 5
352
359
  const maxSessions = args.max_sessions ?? 20
@@ -377,7 +384,7 @@ const plugin: Plugin = async (ctx) => ({
377
384
  const results: SessionResult[] = []
378
385
 
379
386
  for (const session of sessions) {
380
- const matches = await scanSession(ctx.client, session.id, query, depth)
387
+ const matches = await scanSession(ctx.client, session.id, words, depth)
381
388
  if (matches.length > 0) {
382
389
  results.push({
383
390
  sessionID: session.id,
@@ -535,14 +542,19 @@ const plugin: Plugin = async (ctx) => ({
535
542
 
536
543
  db_search: tool({
537
544
  description:
538
- "Substring search over session content, tiered by scope. " +
545
+ "Search session content, tiered by scope; every word in the query must appear in the same part (or title). " +
539
546
  '"titles": session titles only — instant. ' +
540
547
  '"session": every part of one session — milliseconds (requires session_id). ' +
541
548
  '"global": every part of every session — full table scan, typically 10–30 seconds; narrow first (titles, project, session) when possible. ' +
542
549
  'Default scope: "session" when session_id is given, otherwise "global". ' +
543
550
  "Matches conversation text, reasoning, and tool inputs/outputs. Returns snippets with session titles and roles.",
544
551
  args: {
545
- query: tool.schema.string().describe("Search term (case-insensitive substring; % and _ match literally)"),
552
+ query: tool.schema
553
+ .string()
554
+ .describe(
555
+ "Words to search for (case-insensitive; % and _ match literally). Every word must appear in the same part " +
556
+ '(or title); wrap a phrase in double quotes to match it exactly, e.g. "connection refused" retry',
557
+ ),
546
558
  session_id: tool.schema
547
559
  .string()
548
560
  .optional()