@hcflabs/pi-session-recall 0.0.0-stage → 5.2.8

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.
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Hydration: direct JSONL parsing of Pi session files (never SessionManager.open —
3
+ * it rewrites legacy files), branch-aware windows, READ head/tail.
4
+ * Pure functions over file paths; no SQLite access.
5
+ */
6
+ /// <reference types="node" />
7
+ import { readTranscriptEntries, type TranscriptEntry } from "./transcript.ts";
8
+ import type { WindowMessage } from "./types.ts";
9
+
10
+ export interface WindowResult {
11
+ messages: WindowMessage[];
12
+ messagesBefore: number;
13
+ messagesAfter: number;
14
+ /** Tip of the branch the window was resolved on — pass back as branchTip to
15
+ * keep scrolling on this branch across forks. May be a non-message entry id. */
16
+ branchTip: string;
17
+ }
18
+
19
+ export interface ReadResult {
20
+ messages: WindowMessage[];
21
+ totalMessages: number;
22
+ truncated: boolean;
23
+ /** Resolved leaf branch, or null when no selected message can be hydrated. */
24
+ branchTip: string | null;
25
+ }
26
+
27
+ export interface ReadOptions {
28
+ /** Preparation view: retain only non-empty user/assistant text. */
29
+ userAssistantTextOnly?: boolean;
30
+ }
31
+
32
+ interface Entry {
33
+ id: string;
34
+ parentId: string | null;
35
+ type: string;
36
+ timestamp?: string;
37
+ message?: {
38
+ role?: string;
39
+ content?: string | Array<{ type?: string; text?: string }>;
40
+ };
41
+ }
42
+
43
+ /** Project a boundary entry onto the shape hydration consumes. Entries without
44
+ * a validated id pair are dropped (they carry no hydratable position). */
45
+ function toEntry(t: TranscriptEntry): Entry | null {
46
+ if (t.id === undefined) return null;
47
+ const rec = t.data as Record<string, unknown>;
48
+ const message = rec.message !== null && typeof rec.message === "object"
49
+ ? (rec.message as Entry["message"])
50
+ : undefined;
51
+ return {
52
+ id: t.id,
53
+ parentId: t.parentId ?? null,
54
+ type: typeof rec.type === "string" ? rec.type : "",
55
+ timestamp: typeof rec.timestamp === "string" ? rec.timestamp : undefined,
56
+ message,
57
+ };
58
+ }
59
+
60
+ /** Parse JSONL lines; malformed lines are skipped and duplicate/invalid ids are
61
+ * handled by the shared transcript boundary. Entries stream out of the
62
+ * boundary's generator and only successfully projected ones are pushed. */
63
+ function parseSessionEntries(sessionPath: string): Entry[] {
64
+ // The bounded snapshot read (O_NONBLOCK + descriptor validation + fixed-size
65
+ // read) is shared with the index engine; the fd pins the inode so a
66
+ // concurrent append after fstat waits until the next hydration call.
67
+ const entries: Entry[] = [];
68
+ for (const t of readTranscriptEntries(sessionPath)) {
69
+ const projected = toEntry(t);
70
+ if (projected !== null) entries.push(projected);
71
+ }
72
+ return entries;
73
+ }
74
+
75
+ /** Leaf = last entry in file order whose ancestry contains a message; detached
76
+ * trailing metadata must not hide the transcript.
77
+ * Linear time: each entry's ancestry verdict is memoized, so every parent
78
+ * chain segment is traversed once regardless of how many trailing candidates
79
+ * share ancestry. Cycle handling matches branch(): truncation at the first
80
+ * revisit means every path node's truncated chain is a suffix of the path,
81
+ * so one walk's verdict covers all its memoized nodes. */
82
+ function leafId(entriesById: Map<string, Entry>, entries: Entry[]): string | null {
83
+ const hasMessageAncestor = new Map<string, boolean>();
84
+ let leaf: string | null = null;
85
+ for (const start of entries) {
86
+ const path: Entry[] = [];
87
+ const onPath = new Set<string>();
88
+ let cur: Entry = start;
89
+ for (;;) {
90
+ const known = hasMessageAncestor.get(cur.id);
91
+ if (known !== undefined) {
92
+ for (const e of path) hasMessageAncestor.set(e.id, known);
93
+ break;
94
+ }
95
+ if (onPath.has(cur.id)) {
96
+ // No message was found before revisiting (we exit on message first).
97
+ for (const e of path) hasMessageAncestor.set(e.id, false);
98
+ break;
99
+ }
100
+ onPath.add(cur.id);
101
+ path.push(cur);
102
+ if (cur.type === "message") {
103
+ // Every node above the first message has one in its ancestry too.
104
+ for (const e of path) hasMessageAncestor.set(e.id, true);
105
+ break;
106
+ }
107
+ const parent = cur.parentId ? entriesById.get(cur.parentId) : undefined;
108
+ if (!parent) {
109
+ for (const e of path) hasMessageAncestor.set(e.id, false);
110
+ break;
111
+ }
112
+ cur = parent;
113
+ }
114
+ if (hasMessageAncestor.get(start.id)) leaf = start.id;
115
+ }
116
+ return leaf;
117
+ }
118
+
119
+ /** Walk parentId chain from entry to root, reversed (root→entry). */
120
+ function branch(entriesById: Map<string, Entry>, entryId: string): Entry[] {
121
+ const chain: Entry[] = [];
122
+ let cur: Entry | undefined = entriesById.get(entryId);
123
+ // ponytail: cycle guard for corrupt files — revisit only if real sessions ever contain cycles
124
+ const seen = new Set<string>();
125
+ while (cur && !seen.has(cur.id)) {
126
+ seen.add(cur.id);
127
+ chain.push(cur);
128
+ cur = cur.parentId ? entriesById.get(cur.parentId) : undefined;
129
+ }
130
+ return chain.reverse();
131
+ }
132
+
133
+ /** Deepest entry in file order whose ancestry contains tipId (tipId itself if none). */
134
+ function deepestDescendant(entries: Entry[], anchorId: string): string {
135
+ const onBranch = new Set([anchorId]);
136
+ let tip = anchorId;
137
+ for (const e of entries) {
138
+ if (e.parentId && onBranch.has(e.parentId)) {
139
+ onBranch.add(e.id);
140
+ tip = e.id;
141
+ }
142
+ }
143
+ return tip;
144
+ }
145
+
146
+ function toWindowMessage(e: Entry): WindowMessage {
147
+ const m = e.message ?? {};
148
+ const content =
149
+ typeof m.content === "string"
150
+ ? m.content
151
+ : Array.isArray(m.content)
152
+ ? m.content
153
+ .filter((p) => p?.type === "text" && typeof p.text === "string")
154
+ .map((p) => p.text)
155
+ .join("\n")
156
+ : "";
157
+ return {
158
+ entryId: e.id,
159
+ role: typeof m.role === "string" ? m.role.slice(0, 32) : "",
160
+ content,
161
+ timestamp: e.timestamp?.slice(0, 128) ?? "",
162
+ };
163
+ }
164
+
165
+ /** Active-branch messages for a given tip, root→tip chronological. */
166
+ function branchMessages(
167
+ entriesById: Map<string, Entry>,
168
+ tipId: string,
169
+ ): WindowMessage[] {
170
+ return branch(entriesById, tipId)
171
+ .filter((e) => e.type === "message")
172
+ .map(toWindowMessage);
173
+ }
174
+
175
+ /** Resolve a scroll cursor to a message: the cursor itself when it is a
176
+ * message, otherwise its nearest message ancestor. Throws when the cursor is
177
+ * unknown or has no message ancestor. */
178
+ function resolveMessageCursor(
179
+ entriesById: Map<string, Entry>,
180
+ anchorEntryId: string,
181
+ ): Entry {
182
+ const anchor = entriesById.get(anchorEntryId);
183
+ if (!anchor) throw new Error(`anchor entry ${anchorEntryId} not found in session`);
184
+ let cur: Entry | undefined = anchor;
185
+ const seen = new Set<string>();
186
+ while (cur && cur.type !== "message" && !seen.has(cur.id)) {
187
+ seen.add(cur.id);
188
+ cur = cur.parentId ? entriesById.get(cur.parentId) : undefined;
189
+ }
190
+ if (!cur || cur.type !== "message") throw new Error(`anchor entry ${anchorEntryId} has no message ancestor`);
191
+ return cur;
192
+ }
193
+
194
+ export function getWindow(
195
+ sessionPath: string,
196
+ anchorEntryId: string,
197
+ windowN: number,
198
+ opts?: { branchTip?: string },
199
+ ): WindowResult {
200
+ const entries = parseSessionEntries(sessionPath);
201
+ const entriesById = new Map(entries.map((e) => [e.id, e]));
202
+ // A non-message branch-tip cursor centers on its nearest message ancestor;
203
+ // the non-message tip itself stays branchTip so scrolling remains on branch.
204
+ const messageAnchor = resolveMessageCursor(entriesById, anchorEntryId);
205
+ const anchorEntryIdMsg = messageAnchor.id;
206
+
207
+ let tip: string;
208
+ if (opts?.branchTip) {
209
+ // Explicit branch selection: resolve the branch from its tip (deepest
210
+ // descendant), independent of where the window centers.
211
+ resolveMessageCursor(entriesById, opts.branchTip); // unknown tip → throw
212
+ tip = deepestDescendant(entries, opts.branchTip);
213
+ if (!branch(entriesById, tip).some((e) => e.id === messageAnchor.id)) {
214
+ throw new Error(`anchor entry ${anchorEntryId} is not on branch ${opts.branchTip}`);
215
+ }
216
+ } else {
217
+ tip = deepestDescendant(entries, anchorEntryId);
218
+ }
219
+ const msgs = branchMessages(entriesById, tip);
220
+ const idx = msgs.findIndex((m) => m.entryId === anchorEntryIdMsg);
221
+ if (idx < 0) throw new Error(`anchor entry ${anchorEntryId} is not a message`);
222
+ const start = Math.max(0, idx - windowN);
223
+ const end = Math.min(msgs.length - 1, idx + windowN);
224
+ return {
225
+ messages: msgs.slice(start, end + 1).map((m) =>
226
+ m.entryId === anchorEntryIdMsg ? { ...m, anchor: true } : m,
227
+ ),
228
+ messagesBefore: idx,
229
+ messagesAfter: msgs.length - 1 - idx,
230
+ branchTip: tip,
231
+ };
232
+ }
233
+
234
+ export function readSession(
235
+ sessionPath: string,
236
+ head = 20,
237
+ tail = 10,
238
+ opts?: ReadOptions,
239
+ ): ReadResult {
240
+ const entries = parseSessionEntries(sessionPath);
241
+ const entriesById = new Map(entries.map((e) => [e.id, e]));
242
+ const leaf = leafId(entriesById, entries);
243
+ if (!leaf) return { messages: [], totalMessages: 0, truncated: false, branchTip: null };
244
+ const rawMessages = branchMessages(entriesById, leaf);
245
+ const msgs = opts?.userAssistantTextOnly
246
+ ? rawMessages.filter((m) => (m.role === "user" || m.role === "assistant") && m.content.trim().length > 0)
247
+ : rawMessages;
248
+ const branchTip = msgs.length > 0 ? leaf : null;
249
+ if (msgs.length > head + tail) {
250
+ return {
251
+ messages: [...msgs.slice(0, head), ...msgs.slice(-tail)],
252
+ totalMessages: msgs.length,
253
+ truncated: true,
254
+ branchTip,
255
+ };
256
+ }
257
+ return { messages: msgs, totalMessages: msgs.length, truncated: false, branchTip };
258
+ }
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Pure query sanitization and SQL planning for session search.
3
+ */
4
+ import type { SQLInputValue, SQLOutputValue } from "node:sqlite";
5
+
6
+ export const MAX_QUERY_CHARS = 512;
7
+
8
+ const OPERATOR_RE = /\b(OR|AND|NOT|NEAR)\b/;
9
+ // FTS5 string syntax: `""` inside a quoted phrase is one literal quote.
10
+ const TOKEN_RE = /"((?:[^"]|"")*)"|(\S+)/g;
11
+ const unescapePhrase = (s: string): string => s.replaceAll('""', '"');
12
+
13
+ interface QueryTerm {
14
+ text: string;
15
+ operator: boolean;
16
+ nearDistance: boolean;
17
+ quoted: boolean;
18
+ }
19
+
20
+ function collectQueryTerms(query: string): QueryTerm[] {
21
+ const terms: QueryTerm[] = [];
22
+ let depth = 0;
23
+ let pendingNear = false;
24
+ let nearDepth = 0;
25
+ let afterNearComma = false;
26
+ for (const match of spaceParensOutsideQuotes(query).matchAll(TOKEN_RE)) {
27
+ const phrase = match[1];
28
+ let raw = phrase === undefined ? match[2] ?? "" : unescapePhrase(phrase);
29
+ if (phrase === undefined && raw === "(") {
30
+ depth++;
31
+ if (pendingNear) {
32
+ nearDepth = depth;
33
+ pendingNear = false;
34
+ }
35
+ continue;
36
+ }
37
+ if (phrase === undefined && raw === ")") {
38
+ if (depth === nearDepth) {
39
+ nearDepth = 0;
40
+ afterNearComma = false;
41
+ }
42
+ depth = Math.max(0, depth - 1);
43
+ continue;
44
+ }
45
+ const hasNearComma = phrase === undefined && nearDepth > 0 && raw.endsWith(",");
46
+ // An attached distance like `NEAR(Go Rust,10)` has no standalone comma
47
+ // token; split it so the numeric tail is recognized as the distance.
48
+ let attachedDistance: string | undefined;
49
+ if (!hasNearComma && phrase === undefined && nearDepth > 0) {
50
+ const attached = /^(.*),(\d+)$/.exec(raw);
51
+ if (attached) {
52
+ raw = attached[1];
53
+ attachedDistance = attached[2];
54
+ }
55
+ }
56
+ // Unmatched quote delimiters are malformed syntax, not searchable text.
57
+ // Phrases arrive already unescaped via raw.
58
+ const text = phrase === undefined ? raw.replace(/^[.,!?;:()]+|[.,!?;:()]+$/g, "").replace(/"/g, "") : raw;
59
+ if (text) {
60
+ const operator = phrase === undefined && /^(?:OR|AND|NOT|NEAR)$/.test(text);
61
+ const nearDistance = nearDepth > 0 && afterNearComma && /^\d+$/.test(text);
62
+ terms.push({ text, operator, nearDistance, quoted: phrase !== undefined });
63
+ if (operator && text === "NEAR") pendingNear = true;
64
+ }
65
+ if (attachedDistance !== undefined) terms.push({ text: attachedDistance, operator: false, nearDistance: true, quoted: false });
66
+ if (hasNearComma) afterNearComma = true;
67
+ }
68
+ return terms;
69
+ }
70
+
71
+ function quoteTerm(term: QueryTerm): string {
72
+ // Prefix expansion belongs only to an unquoted trailing star. An explicitly
73
+ // quoted `"deploy*"` searches for the literal asterisk.
74
+ if (!term.quoted && term.text.endsWith("*")) return `"${term.text.slice(0, -1).replace(/"/g, '""')}"*`;
75
+ return `"${term.text.replace(/"/g, '""')}"`;
76
+ }
77
+
78
+ function quoteTerms(terms: QueryTerm[], sep: string): string {
79
+ return terms.map(quoteTerm).join(sep);
80
+ }
81
+
82
+ interface FtsQueryPlan {
83
+ /** Candidate FTS5 MATCH expressions in try order. */
84
+ ftsCandidates: string[];
85
+ /** When true, fall back to SQL LIKE (also forced when every term < 3 chars). */
86
+ forceLike: boolean;
87
+ }
88
+
89
+ /**
90
+ * Sanitize ladder: trim + 512 cap; implicit-AND quoting when no explicit
91
+ * FTS5 operator; raw pass-through otherwise; recovery candidates are the
92
+ * fully-quoted form, then OR-expansion; LIKE covers everything else.
93
+ */
94
+ export function buildFtsQueryPlan(rawQuery: string): FtsQueryPlan {
95
+ let query = rawQuery.trim();
96
+ if (query.length > MAX_QUERY_CHARS) query = query.slice(0, MAX_QUERY_CHARS);
97
+ if (!query) return { ftsCandidates: [], forceLike: false };
98
+
99
+ const queryTerms = collectQueryTerms(query);
100
+ const hasOperator = OPERATOR_RE.test(query);
101
+ // Short terms vanish under trigram MATCH — for natural-language queries
102
+ // (AND semantics) that silently breaks the query. Explicit-operator queries
103
+ // route there too (`Go OR Rust` silently drops the Go side); the boolean
104
+ // LIKE fallback preserves their AND/OR/NOT semantics.
105
+ if (
106
+ queryTerms.some(
107
+ (term) => !term.operator && !term.nearDistance && [...term.text.replace(/["()*]/g, "")].length < 3,
108
+ )
109
+ ) {
110
+ return { ftsCandidates: [], forceLike: true };
111
+ }
112
+
113
+ const operands = queryTerms.filter((term) => !term.operator && !term.nearDistance);
114
+ // Recovery operands exclude syntax operators so a malformed query can never
115
+ // broaden into matches on AND/OR/NOT/NEAR themselves.
116
+ const natural = quoteTerms(operands, " ");
117
+ const orExpanded = operands.length > 1 ? quoteTerms(operands, " OR ") : null;
118
+
119
+ if (!hasOperator) {
120
+ // Quoted form cannot fail to parse; OR-expand only as breadth fallback.
121
+ return { ftsCandidates: orExpanded ? [natural, orExpanded] : [natural], forceLike: false };
122
+ }
123
+ // Explicit operators: raw first, then recovery paths.
124
+ const candidates = [query, natural];
125
+ if (orExpanded) candidates.push(orExpanded);
126
+ return { ftsCandidates: candidates, forceLike: false };
127
+ }
128
+
129
+ /** Unicode-aware case fold for all LIKE comparisons (column values via ulower,
130
+ * bound operand patterns, snippet matching). toLowerCase alone is not an
131
+ * equivalence for Greek: word-final Σ lowercases to ς while a typed query uses
132
+ * σ. ponytail: normalizes final sigma only, not full Unicode CaseFolding.txt
133
+ * (e.g. ß→ss stays unmatched); add a fold table if that ever matters. */
134
+ export function foldCase(s: string): string {
135
+ return s.toLowerCase().replaceAll("ς", "σ");
136
+ }
137
+
138
+ function normalizeLikeTerm(term: string, quoted = false): string {
139
+ // Only an unquoted trailing star is prefix syntax. Quoted stars stay literal.
140
+ return !quoted && term.endsWith("*") ? term.slice(0, -1) : term;
141
+ }
142
+
143
+ function likePattern(term: string): string {
144
+ // Fold here too: escaping is unaffected because % _ \ have no case variants.
145
+ return `%${foldCase(term).replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
146
+ }
147
+
148
+ // Parameterized translation of simple AND/OR/NOT/NEAR queries to SQL LIKE so
149
+ // short operands (trigram floor) keep boolean semantics. User input only ever
150
+ // reaches SQL as bound data.
151
+ function likeClause(term: string, quoted = false): { clause: string; params: string[] } | null {
152
+ term = normalizeLikeTerm(term, quoted);
153
+ if (!term) return null;
154
+ const pattern = likePattern(term);
155
+ return {
156
+ clause: "(ulower(m.head) LIKE ? ESCAPE '\\' OR ulower(m.tail) LIKE ? ESCAPE '\\')",
157
+ params: [pattern, pattern],
158
+ };
159
+ }
160
+
161
+ interface LikeSql {
162
+ where: string;
163
+ params: SQLInputValue[];
164
+ }
165
+
166
+ /** Character-position analogue of trigram FTS5 NEAR for LIKE-only operands.
167
+ * Trigram positions make N allow at most N-2 characters between phrases. */
168
+ export function nearLike(textValue: SQLOutputValue, termsValue: SQLOutputValue, distanceValue: SQLOutputValue): number {
169
+ if (typeof textValue !== "string" || typeof termsValue !== "string" || typeof distanceValue !== "number") return 0;
170
+ // Duplicate operands cannot affect the all-distinct-terms-present predicate,
171
+ // and the 512-char query cap otherwise admits hundreds of them.
172
+ const needles = [...new Set((JSON.parse(termsValue) as string[]).map(foldCase))];
173
+ const text = foldCase(textValue);
174
+ // Deduplication can leave one needle: presence satisfies any distance,
175
+ // while the multi-needle span math below demands an impossible negative gap.
176
+ if (needles.length === 1) return text.includes(needles[0]) ? 1 : 0;
177
+ const codePointAt = new Uint32Array(text.length + 1);
178
+ let point = 0;
179
+ for (let i = 0; i < text.length; point++) {
180
+ const width = (text.codePointAt(i) ?? 0) > 0xffff ? 2 : 1;
181
+ codePointAt[i] = point;
182
+ if (width === 2) codePointAt[i + 1] = point;
183
+ i += width;
184
+ }
185
+ codePointAt[text.length] = point;
186
+
187
+ const occurrences: { start: number; end: number; term: number }[] = [];
188
+ for (const [term, needle] of needles.entries()) {
189
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) {
190
+ occurrences.push({ start: codePointAt[at], end: codePointAt[at + needle.length], term });
191
+ }
192
+ }
193
+ occurrences.sort((a, b) => a.start - b.start || a.end - b.end);
194
+
195
+ const counts = new Uint16Array(needles.length);
196
+ let present = 0;
197
+ let left = 0;
198
+ for (let right = 0; right < occurrences.length; right++) {
199
+ if (counts[occurrences[right].term]++ === 0) present++;
200
+ while (present === needles.length) {
201
+ if (occurrences[right].start - occurrences[left].end + 2 <= distanceValue) return 1;
202
+ if (--counts[occurrences[left++].term] === 0) present--;
203
+ }
204
+ }
205
+ return 0;
206
+ }
207
+
208
+ interface LikeToken {
209
+ phrase?: string;
210
+ word?: string;
211
+ }
212
+
213
+ function parseNearLikeSql(tokens: LikeToken[], start: number): { sql: LikeSql; end: number } | null {
214
+ if (tokens[start + 1]?.word !== "(") return null;
215
+ const operands: { text: string; quoted: boolean }[] = [];
216
+ let sawComma = false;
217
+ let distanceText: string | undefined;
218
+
219
+ for (let i = start + 2; i < tokens.length; i++) {
220
+ const token = tokens[i];
221
+ if (token.word === ")") {
222
+ if (operands.length < 2 || (sawComma && distanceText === undefined)) return null;
223
+ const distance = distanceText === undefined ? 10 : Number(distanceText);
224
+ if (distanceText !== undefined && (!/^\d+$/.test(distanceText) || !Number.isSafeInteger(distance))) return null;
225
+ const terms = operands.map((term) => normalizeLikeTerm(term.text, term.quoted));
226
+ if (terms.some((term) => !term)) return null;
227
+ const clauses = terms.map((term) => likeClause(term, true)!);
228
+ const encoded = JSON.stringify(terms);
229
+ return {
230
+ sql: {
231
+ where: `(${clauses.map((clause) => clause.clause).join(" AND ")} AND (unear(m.head, ?, ?) OR unear(m.tail, ?, ?)))`,
232
+ params: [...clauses.flatMap((clause) => clause.params), encoded, distance, encoded, distance],
233
+ },
234
+ end: i,
235
+ };
236
+ }
237
+ if (token.phrase !== undefined) {
238
+ if (sawComma) return null;
239
+ operands.push({ text: token.phrase, quoted: true });
240
+ continue;
241
+ }
242
+
243
+ const word = token.word ?? "";
244
+ if (!word || word === "(" || /^(?:AND|OR|NOT|NEAR)$/.test(word) || word.includes('"')) return null;
245
+ const comma = word.indexOf(",");
246
+ if (comma >= 0) {
247
+ if (sawComma || word.indexOf(",", comma + 1) >= 0) return null;
248
+ const before = word.slice(0, comma).replace(/^[.!?;:]+|[.!?;:]+$/g, "");
249
+ if (before) operands.push({ text: before, quoted: false });
250
+ sawComma = true;
251
+ distanceText = word.slice(comma + 1) || undefined;
252
+ } else if (sawComma) {
253
+ if (distanceText !== undefined) return null;
254
+ distanceText = word;
255
+ } else {
256
+ const text = word.replace(/^[.!?;:]+|[.!?;:]+$/g, "");
257
+ if (!text) return null;
258
+ operands.push({ text, quoted: false });
259
+ }
260
+ }
261
+ return null;
262
+ }
263
+
264
+ /** Space out parens that act as grouping syntax while leaving quoted phrases
265
+ * like "C(ABI)" intact. */
266
+ function spaceParensOutsideQuotes(q: string): string {
267
+ let out = "";
268
+ let inQuote = false;
269
+ for (const c of q) {
270
+ if (c === '"') inQuote = !inQuote;
271
+ out += !inQuote && (c === "(" || c === ")") ? ` ${c} ` : c;
272
+ }
273
+ return out;
274
+ }
275
+
276
+ function buildBooleanLikeSql(rawQuery: string): LikeSql | null {
277
+ let query = rawQuery.trim();
278
+ if (!query) return null;
279
+ // Imbalance detection/recovery is quote-aware: parentheses inside quoted
280
+ // operands ("func(") are literals and must survive.
281
+ let depth = 0;
282
+ let inQuote = false;
283
+ for (const c of query) {
284
+ if (c === '"') inQuote = !inQuote;
285
+ else if (!inQuote && c === "(") depth++;
286
+ else if (!inQuote && c === ")" && --depth < 0) break;
287
+ }
288
+ if (depth !== 0) {
289
+ inQuote = false;
290
+ query = [...query].map((c) => {
291
+ if (c === '"') inQuote = !inQuote;
292
+ return !inQuote && (c === "(" || c === ")") ? " " : c;
293
+ }).join("");
294
+ }
295
+
296
+ const tokens: LikeToken[] = [...spaceParensOutsideQuotes(query).matchAll(TOKEN_RE)]
297
+ .map((m) => (m[1] !== undefined ? { phrase: unescapePhrase(m[1]) } : { word: m[2] ?? "" }))
298
+ .filter((t) => (t.phrase !== undefined ? t.phrase !== "" : t.word !== ""));
299
+ const fail = (): LikeSql | null => tokens.some((token) => token.word === "NEAR") ? { where: "0", params: [] } : null;
300
+ const sql: string[] = [];
301
+ const params: SQLInputValue[] = [];
302
+ let expectingOperand = true;
303
+ depth = 0;
304
+
305
+ for (let i = 0; i < tokens.length; i++) {
306
+ const token = tokens[i];
307
+ const word = token.word;
308
+ if (word === "(") {
309
+ if (!expectingOperand) sql.push("AND");
310
+ sql.push("(");
311
+ depth++;
312
+ expectingOperand = true;
313
+ continue;
314
+ }
315
+ if (word === ")") {
316
+ if (expectingOperand || depth-- === 0) return fail();
317
+ sql.push(")");
318
+ expectingOperand = false;
319
+ continue;
320
+ }
321
+ if (word === "AND" || word === "OR") {
322
+ if (expectingOperand) return fail();
323
+ sql.push(word);
324
+ expectingOperand = true;
325
+ continue;
326
+ }
327
+ if (word === "NOT") {
328
+ if (!expectingOperand) sql.push("AND");
329
+ sql.push("NOT");
330
+ expectingOperand = true;
331
+ continue;
332
+ }
333
+ if (word === "NEAR") {
334
+ const near = parseNearLikeSql(tokens, i);
335
+ if (near === null) return fail();
336
+ if (!expectingOperand) sql.push("AND");
337
+ sql.push(near.sql.where);
338
+ params.push(...near.sql.params);
339
+ expectingOperand = false;
340
+ i = near.end;
341
+ continue;
342
+ }
343
+
344
+ const term = token.phrase ?? word?.replace(/^[.,!?;:]+|[.,!?;:]+$/g, "").replace(/"/g, "") ?? "";
345
+ const clause = likeClause(term, token.phrase !== undefined);
346
+ if (clause === null) return fail();
347
+ if (!expectingOperand) sql.push("AND");
348
+ sql.push(clause.clause);
349
+ params.push(...clause.params);
350
+ expectingOperand = false;
351
+ }
352
+
353
+ return expectingOperand || depth !== 0 ? fail() : { where: sql.join(" "), params };
354
+ }
355
+
356
+ interface LikeQueryPlan extends LikeSql {
357
+ terms: string[];
358
+ }
359
+
360
+ export function buildLikeQueryPlan(rawQuery: string): LikeQueryPlan | null {
361
+ const query = rawQuery.trim().slice(0, MAX_QUERY_CHARS);
362
+ // Keep quoted operator words as operands and omit NEAR's optional numeric
363
+ // distance; only unquoted syntax tokens are excluded.
364
+ const terms = collectQueryTerms(query)
365
+ .filter((term) => !term.operator && !term.nearDistance)
366
+ .map((term) => normalizeLikeTerm(term.text, term.quoted))
367
+ .filter(Boolean);
368
+ if (terms.length === 0) return null;
369
+
370
+ // Boolean LIKE preserves simple AND/OR/NOT; unsupported shapes degrade
371
+ // to AND-of-terms. Both forms are fully parameterized.
372
+ const bool = buildBooleanLikeSql(query);
373
+ const clauses = terms.map((term) => likeClause(term, true)!);
374
+ return {
375
+ terms,
376
+ where: bool?.where ?? clauses.map((clause) => clause.clause).join(" AND "),
377
+ params: bool?.params ?? clauses.flatMap((clause) => clause.params),
378
+ };
379
+ }