@sion10032/pi-sessions 0.0.0-stage → 0.1.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/src/search.ts ADDED
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Query parsing and relevance ranking for the session picker.
3
+ *
4
+ * A query is either a list of tokens (plain words and quoted phrases) or a
5
+ * single `re:<pattern>` regular expression. Matching is case-insensitive
6
+ * throughout.
7
+ *
8
+ * Ranking is layered so what the user typed in the name always beats a hit
9
+ * buried in message text, which in turn beats a scattered fuzzy match:
10
+ *
11
+ * score = tier * 1_000_000 + fuzzy score (lower is better)
12
+ *
13
+ * With several tokens the worst (highest) token score wins, so a token that
14
+ * only fuzzy-matches drags the whole session down.
15
+ */
16
+ import type { SessionInfo } from "@earendil-works/pi-coding-agent";
17
+ import { fuzzyMatch } from "@earendil-works/pi-tui";
18
+
19
+ import { cleanName } from "./paths.ts";
20
+ import type { SessionRecord, SortMode } from "./types.ts";
21
+
22
+ /** A plain whitespace-delimited word, or a quoted phrase taken literally. */
23
+ export interface QueryToken {
24
+ kind: "word" | "phrase";
25
+ value: string;
26
+ }
27
+
28
+ export interface ParsedQuery {
29
+ mode: "tokens" | "regex";
30
+ tokens: QueryToken[];
31
+ regex?: RegExp;
32
+ /** Set when `re:` carried an empty or invalid pattern; such a query matches nothing. */
33
+ error?: string;
34
+ /** True when the raw input was blank, so nothing should be filtered. */
35
+ empty: boolean;
36
+ }
37
+
38
+ const TIER_NAME = 0;
39
+ const TIER_TEXT = 1;
40
+ const TIER_FUZZY = 2;
41
+
42
+ /** A better tier always wins over any fuzzy tie-break score. */
43
+ const TIER_STRIDE = 1_000_000;
44
+
45
+ /** The sentinel `cleanName` returns for a missing or empty name. */
46
+ const UNNAMED = "(unnamed)";
47
+
48
+ interface ScoredTier {
49
+ tier: number;
50
+ /** Fuzzy quality inside the tier; lower is better. */
51
+ score: number;
52
+ }
53
+
54
+ const NAME: ScoredTier = { tier: TIER_NAME, score: 0 };
55
+ const TEXT: ScoredTier = { tier: TIER_TEXT, score: 0 };
56
+
57
+ function tierScore(match: ScoredTier): number {
58
+ return match.tier * TIER_STRIDE + match.score;
59
+ }
60
+
61
+ function combine(match: ScoredTier | undefined): number | undefined {
62
+ return match === undefined ? undefined : tierScore(match);
63
+ }
64
+
65
+ /** Lowercase and collapse whitespace, so phrases survive line breaks. */
66
+ function normalizeText(text: string): string {
67
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
68
+ }
69
+
70
+ interface CachedText {
71
+ /** The `allMessagesText` the derived views below were built from. */
72
+ source: string;
73
+ /** The source, lowercased, for substring matching. */
74
+ lower: string;
75
+ /** The source, lowercased with whitespace collapsed, for phrases. */
76
+ normalized: string;
77
+ }
78
+
79
+ /**
80
+ * `allMessagesText` can reach megabytes, while the picker re-filters and
81
+ * re-sorts on every keystroke. Derive the searchable views once per
82
+ * `SessionInfo` and reuse them; comparing `source` as well keeps an in-place
83
+ * text update from matching stale text. Entries die with their session.
84
+ */
85
+ const textCache = new WeakMap<SessionInfo, CachedText>();
86
+
87
+ function messageText(info: SessionInfo): CachedText {
88
+ const source = info.allMessagesText ?? "";
89
+ const cached = textCache.get(info);
90
+ if (cached && cached.source === source) return cached;
91
+ const fresh: CachedText = {
92
+ source,
93
+ lower: source.toLowerCase(),
94
+ normalized: normalizeText(source),
95
+ };
96
+ textCache.set(info, fresh);
97
+ return fresh;
98
+ }
99
+
100
+ /** Split on whitespace, keeping `"quoted phrases"` together. */
101
+ function tokenize(trimmed: string): QueryToken[] {
102
+ const tokens: QueryToken[] = [];
103
+ let buffer = "";
104
+ let inQuote = false;
105
+ const flush = (kind: QueryToken["kind"]): void => {
106
+ const value = buffer.trim();
107
+ buffer = "";
108
+ if (value) tokens.push({ kind, value });
109
+ };
110
+ for (const ch of trimmed) {
111
+ if (ch === '"') {
112
+ flush(inQuote ? "phrase" : "word");
113
+ inQuote = !inQuote;
114
+ continue;
115
+ }
116
+ if (!inQuote && /\s/.test(ch)) {
117
+ flush("word");
118
+ continue;
119
+ }
120
+ buffer += ch;
121
+ }
122
+ if (inQuote) {
123
+ // Unbalanced quotes are more likely a typo than an unfinished phrase:
124
+ // fall back to plain whitespace tokenization.
125
+ return trimmed.split(/\s+/).map((value) => ({ kind: "word" as const, value }));
126
+ }
127
+ flush("word");
128
+ return tokens;
129
+ }
130
+
131
+ /**
132
+ * Parse user input into tokens or a regular expression. A `re:` prefix wins
133
+ * over quoting. `empty` marks blank input; an unusable `re:` pattern instead
134
+ * sets `error`, and `matchScore` then matches nothing.
135
+ */
136
+ export function parseQuery(raw: string): ParsedQuery {
137
+ const trimmed = raw.trim();
138
+ if (!trimmed) return { mode: "tokens", tokens: [], empty: true };
139
+ if (trimmed.startsWith("re:")) {
140
+ const pattern = trimmed.slice(3).trim();
141
+ if (!pattern) return { mode: "regex", tokens: [], error: "Empty regex", empty: false };
142
+ try {
143
+ return { mode: "regex", tokens: [], regex: new RegExp(pattern, "i"), empty: false };
144
+ } catch (error) {
145
+ return {
146
+ mode: "regex",
147
+ tokens: [],
148
+ error: error instanceof Error ? error.message : String(error),
149
+ empty: false,
150
+ };
151
+ }
152
+ }
153
+ return { mode: "tokens", tokens: tokenize(trimmed), empty: false };
154
+ }
155
+
156
+ /** True when the session carries a real name, not a blank or bare legacy tag. */
157
+ export function hasName(info: SessionInfo): boolean {
158
+ return cleanName(info.name) !== UNNAMED;
159
+ }
160
+
161
+ /** The searchable name: the cleaned name, or empty when there is none. */
162
+ function searchableName(info: SessionInfo): string {
163
+ return hasName(info) ? cleanName(info.name) : "";
164
+ }
165
+
166
+ /**
167
+ * Match one plain word against a session: the name first, then the id, all
168
+ * message text and the cwd, and finally a fuzzy match over the name and cwd.
169
+ */
170
+ function wordTier(info: SessionInfo, word: string): ScoredTier | undefined {
171
+ const needle = word.toLowerCase();
172
+ const name = searchableName(info);
173
+ if (name && name.toLowerCase().includes(needle)) return NAME;
174
+ if (
175
+ info.id.toLowerCase().includes(needle) ||
176
+ messageText(info).lower.includes(needle) ||
177
+ info.cwd.toLowerCase().includes(needle)
178
+ ) {
179
+ return TEXT;
180
+ }
181
+ let best: number | undefined;
182
+ for (const candidate of [name, info.cwd]) {
183
+ const match = fuzzyMatch(word, candidate);
184
+ if (match.matches && (best === undefined || match.score < best)) best = match.score;
185
+ }
186
+ return best === undefined ? undefined : { tier: TIER_FUZZY, score: best };
187
+ }
188
+
189
+ /**
190
+ * Match a quoted phrase after collapsing whitespace: in the name it is a
191
+ * name hit, anywhere in the id, message text or cwd a text hit. Anything
192
+ * looser would not be a phrase.
193
+ */
194
+ function phraseTier(info: SessionInfo, phrase: string): ScoredTier | undefined {
195
+ const needle = normalizeText(phrase);
196
+ if (!needle) return undefined;
197
+ if (normalizeText(searchableName(info)).includes(needle)) return NAME;
198
+ // Normalizing field by field and joining the non-empty parts gives the same
199
+ // collapsed string as normalizing the raw join, without re-processing the
200
+ // cached message text on every keystroke.
201
+ const text = [normalizeText(info.id), messageText(info).normalized, normalizeText(info.cwd)]
202
+ .filter(Boolean)
203
+ .join(" ");
204
+ return text.includes(needle) ? TEXT : undefined;
205
+ }
206
+
207
+ /** A regex is tested against the name first, then the id, message text and cwd. */
208
+ function regexTier(info: SessionInfo, regex: RegExp): ScoredTier | undefined {
209
+ const name = searchableName(info);
210
+ if (name && regex.test(name)) return NAME;
211
+ const text = [info.id, messageText(info).source, info.cwd];
212
+ return text.some((field) => regex.test(field)) ? TEXT : undefined;
213
+ }
214
+
215
+ /**
216
+ * Relevance of one session for a parsed query; undefined means it does not
217
+ * match and must be filtered out. A blank query scores everything 0.
218
+ */
219
+ export function matchScore(info: SessionInfo, query: ParsedQuery): number | undefined {
220
+ if (query.error) return undefined;
221
+ if (query.mode === "regex") return query.regex ? combine(regexTier(info, query.regex)) : undefined;
222
+ if (query.tokens.length === 0) return 0;
223
+ let worst = 0;
224
+ for (const token of query.tokens) {
225
+ const match = token.kind === "phrase" ? phraseTier(info, token.value) : wordTier(info, token.value);
226
+ if (match === undefined) return undefined;
227
+ worst = Math.max(worst, tierScore(match));
228
+ }
229
+ return worst;
230
+ }
231
+
232
+ /** True when the query selects every record instead of filtering and ranking. */
233
+ function matchesEverything(query: ParsedQuery): boolean {
234
+ return query.empty || (query.mode === "tokens" && query.tokens.length === 0);
235
+ }
236
+
237
+ function byModifiedDesc(a: SessionRecord, b: SessionRecord): number {
238
+ return b.info.modified.getTime() - a.info.modified.getTime();
239
+ }
240
+
241
+ /**
242
+ * Order records for display. Without an effective query every record is kept
243
+ * and only `modified` matters. Otherwise non-matches are dropped and `recent`
244
+ * orders by `modified`, while `threaded` and `relevance` rank by score and
245
+ * break ties by `modified`.
246
+ */
247
+ export function sortRecords(records: SessionRecord[], query: ParsedQuery, sort: SortMode): SessionRecord[] {
248
+ if (matchesEverything(query)) return [...records].sort(byModifiedDesc);
249
+ const scored: { record: SessionRecord; score: number }[] = [];
250
+ for (const record of records) {
251
+ const score = matchScore(record.info, query);
252
+ if (score !== undefined) scored.push({ record, score });
253
+ }
254
+ if (sort === "recent") return scored.map((row) => row.record).sort(byModifiedDesc);
255
+ return scored
256
+ .sort((a, b) => a.score - b.score || byModifiedDesc(a.record, b.record))
257
+ .map((row) => row.record);
258
+ }