pi-tuck 1.1.3 → 1.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/index.d.ts +2 -6
  3. package/dist/index.js +16 -111
  4. package/dist/src/build-id.d.ts +1 -1
  5. package/dist/src/build-id.js +1 -1
  6. package/dist/src/compaction.d.ts +2 -103
  7. package/dist/src/compaction.js +20 -140
  8. package/dist/src/diagnostic-replay.js +2 -2
  9. package/dist/src/diagnostics.d.ts +3 -2
  10. package/dist/src/diagnostics.js +30 -9
  11. package/dist/src/history-tools.js +3 -3
  12. package/dist/src/kept-reads.d.ts +2 -2
  13. package/dist/src/kept-reads.js +144 -8
  14. package/dist/src/ledger.d.ts +1 -1
  15. package/dist/src/ledger.js +5 -3
  16. package/dist/src/legacy-cleanup.d.ts +3 -0
  17. package/dist/src/legacy-cleanup.js +190 -0
  18. package/dist/src/notify.d.ts +3 -0
  19. package/dist/src/notify.js +13 -0
  20. package/dist/src/omissions.d.ts +1 -1
  21. package/dist/src/omissions.js +3 -3
  22. package/dist/src/path-key.d.ts +3 -0
  23. package/dist/src/path-key.js +8 -0
  24. package/dist/src/request-capacity.js +1 -1
  25. package/dist/src/run.d.ts +1 -3
  26. package/dist/src/run.js +3 -5
  27. package/dist/src/source-export.d.ts +1 -1
  28. package/dist/src/source-export.js +1 -1
  29. package/dist/src/status.d.ts +0 -6
  30. package/dist/src/status.js +1 -6
  31. package/dist/src/tuck/core/content.js +6 -9
  32. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  33. package/dist/src/tuck/core/keyword-query.js +1 -1
  34. package/dist/src/tuck/core/search-entries.js +5 -5
  35. package/dist/src/tuck/core/transcript.js +2 -1
  36. package/dist/src/tuck.js +390 -394
  37. package/dist/src/windows-private-storage.d.ts +9 -0
  38. package/dist/src/windows-private-storage.js +90 -0
  39. package/index.ts +18 -82
  40. package/package.json +5 -8
  41. package/src/build-id.ts +1 -1
  42. package/src/compaction.ts +19 -107
  43. package/src/diagnostic-replay.ts +2 -2
  44. package/src/diagnostics.ts +24 -9
  45. package/src/history-tools.ts +3 -3
  46. package/src/kept-reads.ts +78 -10
  47. package/src/ledger.ts +5 -3
  48. package/src/legacy-cleanup.ts +134 -0
  49. package/src/notify.ts +10 -0
  50. package/src/omissions.ts +3 -3
  51. package/src/path-key.ts +9 -0
  52. package/src/request-capacity.ts +1 -1
  53. package/src/run.ts +4 -6
  54. package/src/source-export.ts +1 -1
  55. package/src/status.ts +1 -10
  56. package/src/tuck/core/content.ts +5 -10
  57. package/src/tuck/core/keyword-query.ts +2 -2
  58. package/src/tuck/core/search-entries.ts +5 -5
  59. package/src/tuck/core/transcript.ts +2 -1
  60. package/src/tuck.ts +329 -335
  61. package/src/windows-private-storage.ts +94 -0
  62. package/dist/src/assets.d.ts +0 -58
  63. package/dist/src/assets.js +0 -80
  64. package/dist/src/eligibility-cache.d.ts +0 -19
  65. package/dist/src/eligibility-cache.js +0 -33
  66. package/dist/src/semantic-recall.d.ts +0 -422
  67. package/dist/src/semantic-recall.js +0 -1386
  68. package/dist/src/setup.d.ts +0 -3
  69. package/dist/src/setup.js +0 -191
  70. package/scripts/eg2-runtime.py +0 -307
  71. package/scripts/provision-eg2.py +0 -139
  72. package/scripts/semantic-worker.py +0 -234
  73. package/src/assets.ts +0 -92
  74. package/src/eligibility-cache.ts +0 -43
  75. package/src/semantic-recall.ts +0 -592
  76. package/src/setup.ts +0 -163
@@ -1,11 +1,12 @@
1
1
  import { BUILD_ID } from './build-id.js';
2
2
  import { constants } from 'node:fs';
3
3
  import { randomUUID } from 'node:crypto';
4
- import { mkdir, open, readdir, lstat, unlink, realpath } from 'node:fs/promises';
4
+ import { mkdir, open, readdir, lstat, unlink, realpath, type FileHandle } from 'node:fs/promises';
5
5
  import { join, resolve, relative, isAbsolute, dirname, basename } from 'node:path';
6
6
  import { homedir } from 'node:os';
7
7
  import { createRecall, type RecallPolicy } from './recall.js';
8
8
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
9
+ import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
9
10
  export const DIAGNOSTIC_BUILD = BUILD_ID;
10
11
  export interface Receipt { id: string; build: string; reason: string; selectedView: string; boundary: string; settings: { draftReservedTokens: number; contextWindow: number; responseReserveTokens?: number; hostInputTokens?: number; mandatoryInputTokens?: number; target?: 'band' | 'room'; triggerMarginTokens?: number; cutAt?: number; calibrationFactor?: number; calibrationWindow?: number[]; calibrationIdentity?: string; learnedContextWindow?: number; activeInputCeilingTokens?: number | null }; before: { value: number; unit: 'estimated-input-tokens'; scope: 'native-preparation' | 'public-conversation' }; after: { value: number | null; unit: 'estimated-input-tokens'; scope: 'draft-preview' }; }
11
12
  export function attachReceipt<T extends { details?: unknown; firstKeptEntryId: string; tokensBefore: number }>(draft: T, reason: string, reserveTokens: number, contextWindow: number, resolved: Partial<Receipt['settings']> = {}): T & { details: Record<string, unknown> & { diagnosticReceipt: Receipt } } {
@@ -21,7 +22,7 @@ export function findReceiptEntry(entries: SessionEntry[], id: string) { const ma
21
22
  export interface RecorderOptions { directory?: string; maxContentCharacters?: number; maxQueueCharacters?: number; maxFileBytes?: number; maxFiles?: number; durationMs?: number; write?: (path: string, content: string) => Promise<void>; }
22
23
  export interface IncidentRecord { kind: string; scope: string; data: unknown; partial: boolean; }
23
24
  /** A bounded clone. Budget is charged before every copy; forbidden fields are never traversed.
24
- * This is conservative structural/pattern redaction, not semantic secret detection. */
25
+ * This is conservative structural/pattern redaction, not detection of secrets conveyed by meaning. */
25
26
  export function boundedCopy(value: unknown, limit: number): { data: unknown; characters: number; partial: boolean } {
26
27
  let remaining = limit, partial = false;
27
28
  const spend = (n: number) => { if (n > remaining) { partial = true; return false; } remaining -= n; return true; };
@@ -60,6 +61,7 @@ export function permittedEntries(entries: SessionEntry[], policy: RecallPolicy =
60
61
  return { entries: allowed, partial };
61
62
  }
62
63
  export class IncidentRecorder {
64
+ private windowsFile?: FileHandle;
63
65
  private queue: string[] = []; private queued = 0; private total = 0; private pumping?: Promise<void>; private timer?: ReturnType<typeof setTimeout>;
64
66
  private captureCalls = 0; private inlineMs = 0; private hookMs = 0;
65
67
  private projectDirectory = ''; private id = ''; private path = ''; private state = 'off'; private nextCut = false; private sawCut = false; private requests = 0; private response = false;
@@ -70,7 +72,7 @@ export class IncidentRecorder {
70
72
  constructor(options: RecorderOptions = {}) {
71
73
  const bound = (value: number | undefined, fallback: number, max: number) => Number.isSafeInteger(value) && value! > 0 ? Math.min(value!,max) : fallback;
72
74
  this.options = { ...options, maxContentCharacters: bound(options.maxContentCharacters,200000,1500000), maxQueueCharacters: bound(options.maxQueueCharacters,500000,3000000), maxFileBytes: bound(options.maxFileBytes,2000000,10000000), maxFiles: bound(options.maxFiles,4,8), durationMs: bound(options.durationMs,120000,600000) };
73
- this.directory = resolve(options.directory ?? join(homedir(), '.local/state/pi-tuck-incidents')); }
75
+ this.directory = resolve(options.directory ?? join(homedir(), '.local', 'state', 'pi-tuck-incidents')); }
74
76
  get waitingForCut() { return this.enabled && this.nextCut && !this.sawCut; }
75
77
  get enabled() { return this.state === 'recording'; }
76
78
  status() { return { state: this.state, incidentId: this.id || null, queuedCharacters: this.queued, recordedCharacters: this.total, path: this.path || null, captureCalls: this.captureCalls, inlineMilliseconds: this.inlineMs, inlineHookMilliseconds: this.hookMs }; }
@@ -80,7 +82,7 @@ export class IncidentRecorder {
80
82
  if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) { notify('Recorder directory must be outside project'); return; }
81
83
  this.projectDirectory = resolve(project); this.notify = notify; this.state = 'recording'; this.nextCut = nextCut; this.sawCut = false; this.requests = 0; this.response = false; this.total = 0; this.captureCalls = 0; this.inlineMs = 0; this.hookMs = 0; this.id = randomUUID(); this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
82
84
  this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs); this.timer.unref();
83
- this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. No semantic secret guarantee.' });
85
+ this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. Secrets without recognizable patterns may remain.' });
84
86
  }
85
87
  measureInline<T>(operation: () => T): T { if (!this.enabled) return operation(); const started = performance.now(); try { return operation(); } finally { this.hookMs += performance.now() - started; } }
86
88
  capture(kind: string, scope: string, value: unknown, inheritedPartial = false) {
@@ -113,6 +115,7 @@ export class IncidentRecorder {
113
115
  private schedule() { if (!this.pumping) this.pumping = Promise.resolve().then(() => this.pump()); }
114
116
  private async pump() {
115
117
  try {
118
+ const windows = process.platform === 'win32';
116
119
  // Resolve existing ancestors before creating anything; an outside path may
117
120
  // traverse a parent symlink into the active project.
118
121
  let ancestor = this.directory; const missing: string[] = [];
@@ -124,21 +127,33 @@ export class IncidentRecorder {
124
127
  const physicalProject = await realpath(this.projectDirectory).catch(() => this.projectDirectory);
125
128
  const rel = relative(physicalProject, physicalDirectory);
126
129
  if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) throw new Error('Recorder directory resolves inside project');
127
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
130
+ if (!windows) await mkdir(this.directory, { recursive: true, mode: 0o700 });
131
+ else if (missing.length) await createPrivateDirectory(this.directory);
128
132
  const directoryStat = await lstat(this.directory);
129
- if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || (directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.()) throw new Error('Recorder directory ownership/permissions');
133
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || !windows && ((directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.())) throw new Error('Recorder directory ownership/permissions');
130
134
  const names: { name: string; time: number }[] = [];
131
- for (const name of await readdir(this.directory)) if (/^tuck-incident-[0-9a-f-]{36}\.jsonl$/.test(name)) { const stat = await lstat(join(this.directory,name)); if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error('Retention ownership gap'); names.push({name,time:stat.mtimeMs}); }
135
+ for (const name of await readdir(this.directory)) if (/^tuck-incident-[0-9a-f-]{36}\.jsonl$/.test(name)) { const stat = await lstat(join(this.directory,name)); if (!stat.isFile() || stat.isSymbolicLink() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077))) throw new Error('Retention ownership gap'); names.push({name,time:stat.mtimeMs}); }
136
+ if (windows) await assertWindowsPrivateStorage([this.directory, ...names.map(({ name }) => join(this.directory, name))]);
132
137
  names.sort((a,b)=>a.time-b.time);
133
138
  while (names.length >= this.options.maxFiles) { const { name } = names.shift()!; if (join(this.directory, name) !== this.path) await unlink(join(this.directory, name)); }
139
+ if (windows && !this.options.write && !this.windowsFile) {
140
+ // O_NOFOLLOW is unavailable on Windows. Exclusive creation rejects an existing link/file,
141
+ // and the same handle is retained until recording stops; subsequent pumps never reopen the path.
142
+ this.windowsFile = await open(this.path, 'wx', 0o600);
143
+ await protectWindowsIncidentFile(this.path);
144
+ await assertWindowsPrivateStorage([this.path]);
145
+ }
134
146
  while (this.queue.length) {
135
147
  const line = this.queue.shift()!; this.queued -= line.length;
136
148
  if (Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound');
137
149
  if (this.options.write) await this.options.write(this.path, line);
138
- else { const file = await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try { const stat = await file.stat(); if (stat.size + Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound'); if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077)) throw new Error('Recorder file ownership/permissions'); await file.write(line); } finally { await file.close(); } }
150
+ else { const file = this.windowsFile ?? await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try { const stat = await file.stat(); if (stat.size + Buffer.byteLength(line) > this.options.maxFileBytes) throw new Error('File bound'); if (!stat.isFile() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077))) throw new Error('Recorder file ownership/permissions'); await file.write(line); } finally { if (!windows) await file.close(); } }
139
151
  }
140
152
  } catch { this.queue = []; this.queued = 0; if (this.timer) clearTimeout(this.timer); this.timer = undefined; this.state = 'storage-failed-gap'; this.safeNotify('Compaction recorder storage failed; incident has a gap'); }
141
- finally { this.pumping = undefined; if (this.queue.length) this.schedule(); }
153
+ finally {
154
+ if (!this.enabled && this.windowsFile) { const file = this.windowsFile; this.windowsFile = undefined; await file.close().catch(() => {}); }
155
+ this.pumping = undefined; if (this.queue.length) this.schedule();
156
+ }
142
157
  }
143
158
  async flush() { while (this.pumping) await this.pumping; }
144
159
  }
@@ -2,7 +2,7 @@ import { getCurrentTools } from "@earendil-works/pi-ai";
2
2
  import { convertToLlm, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import type { Messages, ToolShape } from "./budget.js";
4
4
 
5
- const own = (name: string) => name === "tuck_recall" || name === "tuck_search";
5
+ const own = (name: string) => name === "tuck_recall";
6
6
  /** Native Pi compactions do not make pi-tuck history available. No session-wide activation state. */
7
7
  export const hasTuckCut = (branch: readonly { type: string; details?: unknown }[]): boolean => branch.some(entry =>
8
8
  entry.type === "compaction" && (entry.details as { compactor?: unknown } | null)?.compactor === "pi-tuck");
@@ -11,7 +11,7 @@ export const hasTuckCut = (branch: readonly { type: string; details?: unknown }[
11
11
  export function historyToolNames(pi: ExtensionAPI, names: readonly string[], enabled: boolean): string[] {
12
12
  if (!enabled) return names.filter(name => !own(name));
13
13
  const registered = new Set(pi.getAllTools().map(tool => tool.name));
14
- return [...names, ...["tuck_recall", "tuck_search"].filter(name => registered.has(name) && !names.includes(name))];
14
+ return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
15
15
  }
16
16
 
17
17
  export function applyHistoryTools(pi: ExtensionAPI, enabled: boolean): void {
@@ -45,7 +45,7 @@ export function historyToolDeclarations(messages: Messages, tools: readonly Tool
45
45
  // Leave an already-correct transcript byte-identical, including the original placement of our declarations.
46
46
  const declared = getCurrentTools(convertToLlm(messages));
47
47
  const wanted = enabled ? tools.filter(tool => own(tool.name)) : [];
48
- if (enabled && wanted.every(tool => declared.some(current => own(current.name) && current.name === tool.name)) &&
48
+ if (enabled && wanted.every(tool => declared.some(current => current.name === tool.name)) &&
49
49
  declared.filter(tool => own(tool.name)).length === wanted.length) return messages;
50
50
  if (!enabled || !wanted.length) return changed ? filtered : messages;
51
51
  const at = filtered.findLastIndex(message => message.role === "system");
package/src/kept-reads.ts CHANGED
@@ -1,23 +1,91 @@
1
- import type { SessionEntry } from "@earendil-works/pi-coding-agent";
1
+ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
+ import { posix } from "node:path";
3
+ import { pathKey } from "./path-key";
2
4
  import { isTextOnly, textOf } from "./tuck/core/content";
3
5
  import { extractPath } from "./tuck/core/tool-args";
4
6
  import type { TranscriptRecord } from "./tuck/core/transcript";
5
7
 
8
+ // A deliberately bounded shell recognizer: substitutions, redirections and
9
+ // unrecognized composition never certify a command as read-only.
10
+ function shellWords(command: string, windows: boolean): { words: string[]; simple: boolean } {
11
+ const words: string[] = []; let word = "", quote = "", started = false, simple = true;
12
+ const flush = () => { if (started) words.push(word); word = ""; started = false; };
13
+ for (let i = 0; i < command.length; i++) {
14
+ const c = command[i]!;
15
+ if (quote === "'") { if (c === quote) quote = ""; else word += c; continue; }
16
+ if (c === "\\" && !windows) { if (command[i + 1] === "\n") { i++; continue; } started = true; if (i + 1 < command.length) word += command[++i]; else simple = false; continue; }
17
+ if (c === "$" || c === "`") simple = false;
18
+ if (windows && (c === "%" || c === "^")) simple = false;
19
+ if (quote) { if (c === quote) quote = ""; else word += c; continue; }
20
+ if (c === "'" || c === '"') { quote = c; started = true; }
21
+ else if (/\s/u.test(c)) { flush(); if (c === "\n") { words.push(";"); simple = false; } }
22
+ else if (/[|&;<>]/u.test(c)) { flush(); const op = command[i + 1] === c ? c + command[++i] : c; words.push(op); }
23
+ else { word += c; started = true; if (/[(){}]/u.test(c)) simple = false; }
24
+ }
25
+ flush(); return { words, simple: simple && !quote };
26
+ }
27
+ const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
28
+ const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
29
+ const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
30
+ const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
31
+ function mutatingGit(words: string[]): boolean {
32
+ return words.some((word, at) => {
33
+ if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git") return false;
34
+ for (let i = at + 1; i < words.length; i++) {
35
+ const arg = words[i]!;
36
+ if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) { i++; continue; }
37
+ if (arg.startsWith("-")) continue;
38
+ return gitMutations.has(arg);
39
+ }
40
+ return false;
41
+ });
42
+ }
43
+ function readOnly(words: string[], simple: boolean): boolean {
44
+ if (!simple) return false;
45
+ if (words[0] === "cd" && words[2] === "&&") words = words.slice(3);
46
+ if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word))) return false;
47
+ const commands: string[][] = [[]];
48
+ for (const word of words) { if (word === "|") commands.push([]); else commands.at(-1)!.push(word); }
49
+ return commands.every(([name, ...args]) => readers.has(name!) || windowsReaders.has(name?.toLowerCase() ?? "") ||
50
+ name === "find" && !args.some(arg => /^-(exec|delete|fprint)/u.test(arg)) ||
51
+ name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
52
+ name === "git" && ["status", "log", "diff", "show"].includes(args[0]!));
53
+ }
54
+
6
55
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
7
- export function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>,
56
+ export function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
8
57
  resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
9
- const reads = new Map<string, { path: string; order: number }>(), mutations = new Map<string, number>();
58
+ const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
59
+ const reads = new Map<string, { path: string; key: string; order: number }>(), mutations = new Map<string, number>();
60
+ let allMutated = -1;
10
61
  let order = 0;
11
62
  for (const entry of entries) {
12
63
  if (entry.type !== "message" || entry.message.role !== "assistant") continue;
13
64
  for (const block of entry.message.content) {
14
- if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
65
+ if (block.type !== "toolCall" || !["read", "write", "edit", "bash"].includes(block.name) ||
15
66
  !block.arguments || typeof block.arguments !== "object") continue;
16
- const path = extractPath(block.arguments as Record<string, unknown>);
17
- if (!path || /[\r\n]/u.test(path)) continue;
67
+ const args = block.arguments as Record<string, unknown>;
18
68
  order++;
19
- if (block.name === "read") reads.set(block.id, { path, order });
20
- else mutations.set(path, order);
69
+ if (block.name === "bash") {
70
+ if (!reads.size || typeof args.command !== "string") continue;
71
+ // Interpret the recorded shell, even when this session is read on another OS.
72
+ const commandName = args.command.trim().split(/\s/u)[0]!.toLowerCase();
73
+ const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(args.command) ||
74
+ windowsReaders.has(commandName) || windowsMutators.has(commandName);
75
+ const { words, simple } = shellWords(args.command, windows);
76
+ if (readOnly(words, simple)) continue;
77
+ if (mutatingGit(words) || !simple && mutatingGit(args.command.split(/[\s'"`();|&]+/u))) { allMutated = order; continue; }
78
+ const base = words[0] === "cd" && words[2] === "&&" ? pathKey(words[1]!, cwd) : cwd;
79
+ const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
80
+ for (const name of names) if (name) { mutations.set(pathKey(name), order); mutations.set(pathKey(name, base), order); }
81
+ continue;
82
+ }
83
+ const path = extractPath(args);
84
+ if (!path || /[\r\n]/u.test(path)) continue;
85
+ const key = pathKey(path, cwd);
86
+ if (block.name === "read") {
87
+ if (!("offset" in args) && !("limit" in args)) reads.set(block.id, { path, key, order });
88
+ } else mutations.set(key, order);
21
89
  }
22
90
  }
23
91
  const seen = new Set<string>(), records: TranscriptRecord[] = [];
@@ -25,10 +93,10 @@ export function keptReadCandidates(entries: readonly SessionEntry[], indices: Re
25
93
  const entry = entries[at]!;
26
94
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content)) continue;
27
95
  const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
28
- if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order) continue;
96
+ if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order) continue;
29
97
  const text = textOf(entry.message.content);
30
98
  if (!text.length || sourceIndex === undefined || !resolvable(entry)) continue;
31
- seen.add(read.path);
99
+ seen.add(read.key);
32
100
  records.push({ kind: "section", title: "Kept-read", sourceIndex,
33
101
  text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
34
102
  }
package/src/ledger.ts CHANGED
@@ -3,6 +3,7 @@ import { isLookupTool } from "./tuck/core/recall-operation";
3
3
  import { isDiscardedResponse } from "./protocol";
4
4
  import { extractPath } from "./tuck/core/tool-args";
5
5
  import type { TranscriptRecord } from "./tuck/core/transcript";
6
+ import { pathKey } from "./path-key";
6
7
 
7
8
  /** Owner default; older distinct paths are counted, not listed. */
8
9
  export const MAX_LEDGER_LINES = 60;
@@ -25,7 +26,7 @@ export interface LedgerItem { path: string; operation: "wrote/edited" | "read";
25
26
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
26
27
  * A call from a failed or aborted response, a write/edit whose result is an error, and a path with a line break are not listed. */
27
28
  export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean,
28
- failedCalls: ReadonlySet<string>): LedgerItem[] {
29
+ failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[] {
29
30
  const results = new Map<string, SessionEntry>();
30
31
  for (const entry of entries) if (entry.type === "message" && entry.message.role === "toolResult") results.set(entry.message.toolCallId, entry);
31
32
  const last = new Map<string, { path: string; operation: LedgerItem["operation"]; entry: SessionEntry; target: SessionEntry }>();
@@ -37,8 +38,9 @@ export function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyM
37
38
  const operation = OPERATIONS.get(block.name);
38
39
  const path = operation && extractPath(block.arguments as Record<string, unknown>);
39
40
  if (!operation || !path || /[\r\n]/u.test(path) || operation === "wrote/edited" && failedCalls.has(block.id)) continue;
40
- last.delete(path);
41
- last.set(path, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
41
+ const key = pathKey(path, cwd);
42
+ last.delete(key);
43
+ last.set(key, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
42
44
  }
43
45
  }
44
46
  // Only listed lines show a locator, so resolvability (which renders the entry) is checked for those alone.
@@ -0,0 +1,134 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { execFile } from "node:child_process";
3
+ import { lstat, mkdir, readdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, join } from "node:path";
6
+ import { notify } from "./notify.js";
7
+
8
+ const pending = new Map<string, Promise<void>>();
9
+ const directories = ["runtime", "python", "index", "downloads"] as const;
10
+ const temporaryDirectory = /^(?:staging-\d+|\.pi-semantic-[A-Za-z0-9]{6})$/;
11
+ const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === "ENOENT";
12
+
13
+ async function realDirectory(path: string): Promise<boolean> {
14
+ try { return (await lstat(path)).isDirectory(); } // lstat never admits a symlink.
15
+ catch (error) { if (missing(error)) return false; throw error; }
16
+ }
17
+
18
+ /** Recognize the EG-2 pin fields written by the old setup/provisioner, without pinning a particular release's hashes. */
19
+ function ownPins(value: unknown): boolean {
20
+ const record = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === "object" && !Array.isArray(v);
21
+ const strings = (v: Record<string, unknown>, keys: string[]) => keys.every(key => typeof v[key] === "string");
22
+ if (!record(value)) return false;
23
+ const { embedding, backend, runtime } = value;
24
+ return record(embedding) && record(backend) && record(runtime)
25
+ && embedding.model === "google/embeddinggemma-2" && backend.name === "llama.cpp"
26
+ && strings(embedding, ["revision", "queryInstruction", "documentInstruction", "pooling", "dtype"])
27
+ && embedding.dimensions === 768 && embedding.maxTokens === 8192 && embedding.textOnly === true
28
+ && strings(backend, ["commit", "artifact", "computePrecision", "compute", "modelRepository", "modelRevision", "modelSHA256"])
29
+ && typeof backend.gpuLayers === "number" && strings(runtime, ["tokenizers", "python"]);
30
+ }
31
+
32
+ async function ownRuntime(path: string): Promise<boolean> {
33
+ for (const child of await readdir(path)) {
34
+ // These names come only from this directory's inventory; never follow links to claim ownership.
35
+ const directory = join(path, child), pins = join(directory, "pins.json");
36
+ try {
37
+ if (await realDirectory(directory) && (await lstat(pins)).isFile() && ownPins(JSON.parse(await readFile(pins, "utf8")))) return true;
38
+ } catch (error) { if (!missing(error) && !(error instanceof SyntaxError)) throw error; }
39
+ }
40
+ return false;
41
+ }
42
+
43
+ /** lsof uses exit 1 with no output for no matching open files; every other failure is unsafe to delete. */
44
+ async function idle(path: string): Promise<boolean> {
45
+ return new Promise((done, reject) => {
46
+ execFile("lsof", ["-t", "+D", path], { timeout: 3000, killSignal: "SIGKILL", maxBuffer: 16 * 1024 }, (error, stdout, stderr) => {
47
+ if (stdout.trim()) { done(false); return; }
48
+ if (error && !(error.code === 1 && !error.killed && !error.signal && !stderr.trim())) reject(error);
49
+ else if (stderr.trim()) reject(new Error(stderr.trim()));
50
+ else done(true);
51
+ });
52
+ });
53
+ }
54
+
55
+ /** One bounded, best-effort measurement of only the candidates, so retained files are not counted as freed. */
56
+ async function sizes(paths: string[]): Promise<Map<string, number>> {
57
+ if (process.platform === "win32" || !paths.length) return new Map();
58
+ const started = performance.now();
59
+ return new Promise(done => {
60
+ try {
61
+ execFile("du", ["-sk", ...paths], { timeout: 1000, killSignal: "SIGKILL", maxBuffer: 16 * 1024 }, (error, stdout) => {
62
+ const measured = new Map<string, number>();
63
+ if (!error && performance.now() - started <= 1000) for (const line of stdout.trimEnd().split("\n")) {
64
+ const match = /^\s*(\d+)\s+(.+)$/.exec(line);
65
+ if (match && paths.includes(match[2]!)) measured.set(match[2]!, Number(match[1]));
66
+ }
67
+ done(measured);
68
+ });
69
+ } catch { done(new Map()); }
70
+ });
71
+ }
72
+
73
+ function reportFailure(failure: unknown): void {
74
+ try {
75
+ const reason = String((failure as NodeJS.ErrnoException).code ?? failure).replace(/[\r\n]+/g, " ");
76
+ process.stderr.write(`pi-tuck could not finish removing its old search files: ${reason}\n`);
77
+ } catch { /* A closed stderr must not break a session either. */ }
78
+ }
79
+
80
+ /** Once per home, including partial attempts. A later recreation belongs to whoever created it. */
81
+ export function cleanupLegacyFiles(ctx: ExtensionContext): Promise<void> {
82
+ let home: string;
83
+ try { home = homedir(); }
84
+ catch (error) { reportFailure(error); return Promise.resolve(); }
85
+ // Deliberately independent of Pi's per-arm agent folder.
86
+ const agent = join(home, ".pi", "agent"), root = join(agent, "pi-tuck"), marker = join(agent, "pi-tuck-semantic-removed");
87
+ const held = pending.get(root);
88
+ if (held) return held;
89
+ const cleanup = (async () => {
90
+ let failure: unknown, started = false, removedRoot = false, freed = 0, sized = process.platform !== "win32";
91
+ const removed: string[] = [];
92
+ try {
93
+ // Check this before inspecting or sizing the old root, even if Pi's agent folder points elsewhere.
94
+ try { await lstat(marker); return; }
95
+ catch (error) { if (!missing(error)) throw error; }
96
+ await readdir(home); // An unreadable/missing home means no attempt could start; retry on the next load.
97
+ if (process.platform === "win32" || !await realDirectory(root)) { started = true; return; }
98
+ const children = await readdir(root);
99
+ started = true;
100
+ const names = [...directories, ...children.filter(name => temporaryDirectory.exec(name)?.[0] === name)];
101
+ const candidates: string[] = [];
102
+ for (const name of names) {
103
+ const path = join(root, name);
104
+ try {
105
+ if (await realDirectory(path) && (name !== "runtime" || await ownRuntime(path)) && await idle(path)) candidates.push(path);
106
+ } catch (error) { failure ??= error; }
107
+ }
108
+ const measured = await sizes(candidates);
109
+ for (const path of candidates) {
110
+ try {
111
+ if (!await realDirectory(root) || !await realDirectory(path)) continue;
112
+ await rm(path, { recursive: true, force: false });
113
+ removed.push(basename(path));
114
+ sized &&= measured.has(path);
115
+ freed += measured.get(path) ?? 0;
116
+ } catch (error) { if (!missing(error)) failure ??= error; }
117
+ }
118
+ // rmdir, rather than recursive removal, preserves every foreign file or skipped directory/link.
119
+ try { await rmdir(root); removedRoot = true; }
120
+ catch (error) { if (!missing(error) && !["ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) failure ??= error; }
121
+ } catch (error) { failure ??= error; }
122
+ finally {
123
+ if (started) try {
124
+ await mkdir(agent, { recursive: true });
125
+ await writeFile(marker, "", { flag: "wx" });
126
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") failure ??= error; }
127
+ if (removed.length || removedRoot) notify(ctx, `pi-tuck removed its old semantic search files from ${root}${sized ? ` (about ${Math.round(freed / 1024)} MB freed)` : ""}.${removed.length ? ` Removed: ${removed.join(", ")}.` : ""}`, "info");
128
+ if (failure) reportFailure(failure);
129
+ }
130
+ })();
131
+ pending.set(root, cleanup);
132
+ void cleanup.finally(() => { pending.delete(root); });
133
+ return cleanup;
134
+ }
package/src/notify.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Operator notices stay outside model context; an ended UI or closed stderr cannot break the session. */
4
+ export function notify(ctx: ExtensionContext, message: string, level: "info" | "warning" | "error"): boolean {
5
+ try {
6
+ if (ctx.hasUI === false) process.stderr.write(message + "\n");
7
+ else ctx.ui.notify(message, level);
8
+ return true;
9
+ } catch { return false; }
10
+ }
package/src/omissions.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionContext, SessionEntry } from '@earendil-works/pi-coding-agent';
2
2
  import { buildGlobalIndexById } from './tuck/core/global-indices';
3
- import { parseRecords, serializeRecord, splitSummary, transcriptHeader } from './tuck/core/transcript';
3
+ import { CLOSING_SEPARATOR, parseRecords, serializeRecord, splitSummary, transcriptHeader } from './tuck/core/transcript';
4
4
  import { textOf } from "./tuck/core/content";
5
5
  import { isDiscardedResponse } from "./protocol";
6
6
  import { createRecall, type RecallPolicy } from './recall';
@@ -15,7 +15,7 @@ export function omittedSourceIndices(entries: readonly SessionEntry[], branch: r
15
15
  const indices = buildGlobalIndexById(entries);
16
16
  return new Set([...edits].flatMap(id => indices.has(id) ? [indices.get(id)!] : []));
17
17
  }
18
- /** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or semantic inference. */
18
+ /** Preserve surviving record bytes/order, and the summary's format (a v1 summary stays v1). No text matching or inference about meaning. */
19
19
  export function filterOmittedSummary(summary: string, omitted: ReadonlySet<number>, sources?: readonly SessionEntry[], rangeOmitted = omitted): string {
20
20
  if (!omitted.size) return summary;
21
21
  const split = splitSummary(summary);
@@ -76,7 +76,7 @@ export function filterCustomQuotes(summary: string, entries: readonly SessionEnt
76
76
  if (!split) throw new Error('Cannot resolve custom sources in an unsupported compaction summary');
77
77
  const { body, closing, version } = split;
78
78
  const records = parseRecords(body, version);
79
- if (!records.some(record => record.role === "custom")) return summary;
79
+ if (!records.some(record => record.role === "custom")) return summary.slice(0, summary.indexOf(CLOSING_SEPARATOR)) + closing;
80
80
  const omitted = new Set(branch.flatMap(entry => entry.type === 'context_edit' && entry.replacement === null ? [entry.targetId] : []));
81
81
  const eligible = createRecall(policy).isHistorySource, indices = buildGlobalIndexById(entries);
82
82
  const globalCounts = new Map<string, number>(), branchSources = new Map<string, SessionEntry[]>();
@@ -0,0 +1,9 @@
1
+ import { posix } from "node:path";
2
+
3
+ /** Lexical identity for recorded paths, independent of the machine reading the session.
4
+ * Only drive letters fold case; callers retain the original spelling for display. */
5
+ export function pathKey(path: string, cwd?: string): string {
6
+ const slashes = (value: string) => value.replace(/\\/gu, "/").replace(/^[A-Z]:/u, drive => drive.toLowerCase());
7
+ const name = slashes(path);
8
+ return posix.normalize(cwd && !posix.isAbsolute(name) && !/^[a-z]:\//u.test(name) ? posix.join(slashes(cwd), name) : name);
9
+ }
@@ -123,7 +123,7 @@ export function carriesPrompt(messages: Messages, prompt: string, role: 'user' |
123
123
  }
124
124
  if (message.role !== 'compactionSummary') return false;
125
125
  const split = splitSummary(message.summary);
126
- return split !== null && split !== undefined && parseRecords(split.body, split.version).some(record =>
126
+ return split !== undefined && parseRecords(split.body, split.version).some(record =>
127
127
  record.kind === 'excerpt' && record.role === role && record.text.includes(prompt));
128
128
  });
129
129
  }
package/src/run.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import { SessionManager, type ExtensionContext, type SessionEntry, type SessionBoundaryDraft } from '@earendil-works/pi-coding-agent';
2
2
  import { hasTuckCut } from './history-tools.js';
3
- import { viewStart } from './semantic-recall.js';
4
3
  import { textOf } from './tuck/core/content.js';
5
4
  import type { Clip } from './clip.js';
6
5
 
7
6
  export type CutEntry = { type: 'compaction'; summary: string; firstKeptEntryId: string; tokensBefore: number; details?: unknown };
8
7
  type Context = Pick<ExtensionContext, 'cwd' | 'sessionManager'>;
9
- export interface CutView { session: ExtensionContext['sessionManager']; keptFromId: string | undefined; viewStart: number; hasTuckCut: boolean; pending: boolean }
8
+ export interface CutView { session: ExtensionContext['sessionManager']; keptFromId: string | undefined; hasTuckCut: boolean; pending: boolean }
10
9
 
11
10
  /** The only owner of a cut that requests carry before Pi saves it. */
12
11
  export class PendingCut {
@@ -18,7 +17,7 @@ export class PendingCut {
18
17
  take() { const cut = this.cut; this.clear(); return cut; }
19
18
  view(ctx: Context, entries: readonly SessionBoundaryDraft[] = []): CutView {
20
19
  const live = ctx.sessionManager, leaf = live.getLeafId?.(), held = this.preview;
21
- // Native entries are append-only; a leaf move invalidates both the saved and pending views, as in the eligibility cache.
20
+ // Native entries are append-only; a leaf move invalidates both the saved and pending views.
22
21
  if (!entries.length && leaf !== undefined && held && held.manager === live && held.cwd === ctx.cwd && held.leaf === leaf) return held.view;
23
22
  const branch = live.getBranch(), cut = this.cut;
24
23
  const remember = (view: CutView) => {
@@ -28,7 +27,7 @@ export class PendingCut {
28
27
  if (!cut && !entries.length) {
29
28
  const last = branch.findLast(entry => entry.type === 'compaction');
30
29
  return remember({ session: live, keptFromId: last?.type === 'compaction' ? last.firstKeptEntryId : undefined,
31
- viewStart: viewStart(branch), hasTuckCut: hasTuckCut(branch), pending: false });
30
+ hasTuckCut: hasTuckCut(branch), pending: false });
32
31
  }
33
32
  // A compact-all plan predates the prompt. Keep from the first appended entry, skipping our capacity receipts.
34
33
  const keptFromId = cut && (cut.firstKeptEntryId || branch.slice(this.branchLength)
@@ -46,7 +45,7 @@ export class PendingCut {
46
45
  }
47
46
  const previewBranch = session.getBranch(), last = previewBranch.findLast(entry => entry.type === 'compaction');
48
47
  return remember({ session, keptFromId: last?.type === 'compaction' ? last.firstKeptEntryId : undefined,
49
- viewStart: viewStart(previewBranch), hasTuckCut: hasTuckCut(previewBranch), pending: Boolean(cut) });
48
+ hasTuckCut: hasTuckCut(previewBranch), pending: Boolean(cut) });
50
49
  }
51
50
  }
52
51
 
@@ -124,4 +123,3 @@ export class Run {
124
123
  this.thinkingRetryPending = false; this.refusalReceipted = false; this.expiredPlan = false;
125
124
  }
126
125
  }
127
- export const createRun = (phase: ConstructorParameters<typeof Run>[0]): Run => new Run(phase);
@@ -2,7 +2,7 @@ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { buildGlobalIndexById } from "./tuck/core/global-indices";
3
3
  import { createRecall, type RecallPolicy, type ReadableEntry } from "./recall";
4
4
 
5
- /** Select one original readable source. No filesystem, state, paging or semantic inference. */
5
+ /** Select one original readable source. No filesystem, state, paging or inference about meaning. */
6
6
  export function exportSource(entries: readonly SessionEntry[], branch: readonly SessionEntry[],
7
7
  input: { entryId: string } | { index: number }, policy: RecallPolicy = {}): (ReadableEntry & { index: number | undefined }) | undefined {
8
8
  if (branch.some(e => e.type === "context_edit" && e.replacement !== null))
package/src/status.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
- import type { SemanticState } from "./semantic-recall";
4
3
 
5
4
  /** The version of the package this code was loaded from: the open session keeps it until Pi restarts, whatever is installed since. */
6
5
  export const LOADED_VERSION: string = (() => {
@@ -19,8 +18,6 @@ export function statusText(input: {
19
18
  branch: readonly { type: string; tokensBefore?: unknown; details?: unknown; customType?: unknown; data?: unknown }[];
20
19
  pending?: boolean;
21
20
  cutAt: number | undefined;
22
- search: boolean;
23
- semantic: { state: SemanticState; lastError: string | null };
24
21
  }): string {
25
22
  if (!input.active) return `pi-tuck ${input.version} is loaded but inactive in this host; Pi's own compaction runs.`;
26
23
  if (input.compaction?.kind === 'standingDown') return `pi-tuck ${input.version}: standing down: ${input.compaction.reason}; Pi's own compaction runs.`;
@@ -32,10 +29,6 @@ export function statusText(input: {
32
29
  const native = cuts.length - ours.length;
33
30
  const retries = input.branch.filter(entry => entry.type === "custom" && entry.customType === "pi-tuck-capacity" &&
34
31
  (entry.data as { kind?: unknown } | null | undefined)?.kind === "retry").length;
35
- const searchLine = !input.search ? "Search: by keyword (search by meaning needs macOS on Apple silicon)."
36
- : input.semantic.state === "ready" || input.semantic.state === "waiting" ? "Search: by meaning and keyword."
37
- : input.semantic.state === "preparing" ? "Search: by meaning and keyword; indexing history in the background."
38
- : `Search: by keyword; ${lower(input.semantic.lastError ?? "semantic recall is off in this session (/tuck-semantic on)")}.`.replace(/\.\.$/, ".");
39
32
  return [
40
33
  `pi-tuck ${input.version} (the version this session loaded; restart Pi after an update).`,
41
34
  cutLine,
@@ -43,8 +36,6 @@ export function statusText(input: {
43
36
  ...(input.pending ? ["A cut is pending: requests already carry it; the first boundary saves it."] : []),
44
37
  ...(native > 0 ? [`Pi's own compaction cut ${native} time${native === 1 ? "" : "s"} in this session.`] : []),
45
38
  input.cutAt === undefined ? "Cut point: adapts by itself." : `Cut point: fixed at cutAt ${input.cutAt} of the input room. Remove cutAt from pi-tuck.json to let it adapt.`,
46
- searchLine,
39
+ "Search: by keyword.",
47
40
  ].join("\n");
48
41
  }
49
-
50
- const lower = (text: string) => text.charAt(0).toLowerCase() + text.slice(1);
@@ -13,20 +13,15 @@ export const clip = (text: string, max = 200): string => {
13
13
  return text.slice(0, end);
14
14
  };
15
15
 
16
- const textParts = (content: Message["content"]): string[] => {
17
- if (!content) return [];
18
- if (typeof content === "string") return [content];
19
- return content
20
- .filter((part) => part.type === "text")
21
- .map((part) => part.text);
22
- };
23
-
24
16
  /** Content that is a string or only text blocks: what quoting can deliver whole. */
25
17
  export const isTextOnly = (content: string | readonly { type: string }[] | undefined): boolean =>
26
18
  typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
27
19
 
28
- export const textOf = (content: Message["content"]): string =>
29
- textParts(content).join("\n");
20
+ export const textOf = (content: Message["content"]): string => {
21
+ if (!content) return "";
22
+ if (typeof content === "string") return content;
23
+ return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
24
+ };
30
25
 
31
26
  /**
32
27
  * Extract every scalar string argument from a tool call for search indexing
@@ -5,7 +5,7 @@ export interface KeywordMatcher {
5
5
  test(text: string): boolean;
6
6
  /** Stateless first match at or after fromIndex, in UTF-16 source coordinates. */
7
7
  find(text: string, fromIndex?: number): { index: number; text: string } | undefined;
8
- /** Equality under the exact matcher semantics, rather than case folding. */
8
+ /** Equality under the exact matcher rules, rather than case folding. */
9
9
  equivalent(other: KeywordMatcher): boolean;
10
10
  }
11
11
 
@@ -51,7 +51,7 @@ const matcher = (term: string): KeywordMatcher => {
51
51
  };
52
52
  };
53
53
 
54
- /** Prepare the natural-keyword semantics shared by ranking and localization. */
54
+ /** Prepare the natural-keyword rules shared by ranking and localization. */
55
55
  export const prepareKeywordQuery = (query: string): PreparedKeywordQuery => {
56
56
  const raw = query.trim().split(/\s+/).filter(Boolean);
57
57
  const meaningful = raw.filter((term) => !STOPWORDS.has(term.toLowerCase()) && term.length > 1);