/** * Memory search matching — the line-level "find a memory I know exists" * matcher shared by the CLI memdir search (src/memdir/service.ts) and the * SQLite-store web search (services/memory/sqliteBackend.ts). * * Semantics (kept byte-identical with the original CLI implementation): * - pattern is a case-insensitive regex; an invalid regex degrades to a * literal substring match instead of erroring * - line 0 = the filename itself is a matchable surface * - at most 5 matched lines per file, each trimmed and capped at 200 chars */ import type { MemoryMatchLine } from '../memoryBackend' export const SEARCH_MAX_LINES_PER_FILE = 5 const MATCH_LINE_MAX_CHARS = 200 /** Compile the pattern once — regex when valid, substring fallback otherwise. */ function compileMatcher(pattern: string): { test: (s: string) => boolean needle: string } { try { const regex = new RegExp(pattern, 'i') return { test: (s: string) => regex.test(s), needle: pattern.toLowerCase() } } catch { const needle = pattern.toLowerCase() return { test: (s: string) => s.toLowerCase().includes(needle), needle } } } /** * Match a pattern against one memory file's name and content lines. * Returns the matched lines (possibly empty). */ export function matchMemoryLines( pattern: string, filename: string, content: string, ): MemoryMatchLine[] { if (!pattern.trim()) return [] const { test } = compileMatcher(pattern) const lines = content.split('\n') const matches: MemoryMatchLine[] = [] const hit = (line: number, text: string): void => { if (matches.length >= SEARCH_MAX_LINES_PER_FILE) return matches.push({ line, text: text.trim().slice(0, MATCH_LINE_MAX_CHARS) }) } // Line 0 = the filename itself is a matchable surface. if (test(filename)) hit(0, filename) for ( let i = 0; i < lines.length && matches.length < SEARCH_MAX_LINES_PER_FILE; i++ ) { if (test(lines[i]!)) hit(i + 1, lines[i]!) } return matches }