pi-tuck 1.1.2 → 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 (77) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +7 -3
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +2 -103
  8. package/dist/src/compaction.js +29 -146
  9. package/dist/src/diagnostic-replay.js +2 -2
  10. package/dist/src/diagnostics.d.ts +3 -2
  11. package/dist/src/diagnostics.js +30 -9
  12. package/dist/src/history-tools.js +3 -3
  13. package/dist/src/kept-reads.d.ts +2 -2
  14. package/dist/src/kept-reads.js +144 -8
  15. package/dist/src/ledger.d.ts +1 -1
  16. package/dist/src/ledger.js +5 -3
  17. package/dist/src/legacy-cleanup.d.ts +3 -0
  18. package/dist/src/legacy-cleanup.js +190 -0
  19. package/dist/src/notify.d.ts +3 -0
  20. package/dist/src/notify.js +13 -0
  21. package/dist/src/omissions.d.ts +1 -1
  22. package/dist/src/omissions.js +3 -3
  23. package/dist/src/path-key.d.ts +3 -0
  24. package/dist/src/path-key.js +8 -0
  25. package/dist/src/request-capacity.js +1 -1
  26. package/dist/src/run.d.ts +1 -3
  27. package/dist/src/run.js +3 -5
  28. package/dist/src/source-export.d.ts +1 -1
  29. package/dist/src/source-export.js +1 -1
  30. package/dist/src/status.d.ts +0 -6
  31. package/dist/src/status.js +1 -6
  32. package/dist/src/tuck/core/content.js +6 -9
  33. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  34. package/dist/src/tuck/core/keyword-query.js +1 -1
  35. package/dist/src/tuck/core/search-entries.js +5 -5
  36. package/dist/src/tuck/core/transcript.js +2 -1
  37. package/dist/src/tuck.js +390 -394
  38. package/dist/src/windows-private-storage.d.ts +9 -0
  39. package/dist/src/windows-private-storage.js +90 -0
  40. package/index.ts +18 -82
  41. package/package.json +5 -8
  42. package/src/build-id.ts +1 -1
  43. package/src/compaction.ts +28 -113
  44. package/src/diagnostic-replay.ts +2 -2
  45. package/src/diagnostics.ts +24 -9
  46. package/src/history-tools.ts +3 -3
  47. package/src/kept-reads.ts +78 -10
  48. package/src/ledger.ts +5 -3
  49. package/src/legacy-cleanup.ts +134 -0
  50. package/src/notify.ts +10 -0
  51. package/src/omissions.ts +3 -3
  52. package/src/path-key.ts +9 -0
  53. package/src/request-capacity.ts +1 -1
  54. package/src/run.ts +4 -6
  55. package/src/source-export.ts +1 -1
  56. package/src/status.ts +1 -10
  57. package/src/tuck/core/content.ts +5 -10
  58. package/src/tuck/core/keyword-query.ts +2 -2
  59. package/src/tuck/core/search-entries.ts +5 -5
  60. package/src/tuck/core/transcript.ts +2 -1
  61. package/src/tuck.ts +329 -335
  62. package/src/windows-private-storage.ts +94 -0
  63. package/dist/src/assets.d.ts +0 -58
  64. package/dist/src/assets.js +0 -80
  65. package/dist/src/eligibility-cache.d.ts +0 -19
  66. package/dist/src/eligibility-cache.js +0 -33
  67. package/dist/src/semantic-recall.d.ts +0 -422
  68. package/dist/src/semantic-recall.js +0 -1386
  69. package/dist/src/setup.d.ts +0 -3
  70. package/dist/src/setup.js +0 -191
  71. package/scripts/eg2-runtime.py +0 -307
  72. package/scripts/provision-eg2.py +0 -139
  73. package/scripts/semantic-worker.py +0 -234
  74. package/src/assets.ts +0 -92
  75. package/src/eligibility-cache.ts +0 -43
  76. package/src/semantic-recall.ts +0 -592
  77. package/src/setup.ts +0 -163
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);
@@ -53,7 +53,7 @@ const countMatches = (hay: string, terms: readonly KeywordMatcher[]): number =>
53
53
  const BM25_K = 1.2;
54
54
  const BM25_B = 0.75;
55
55
 
56
- /** Count non-overlapping literal occurrences with the prepared matcher's semantics. */
56
+ /** Count non-overlapping literal occurrences with the prepared matcher's rules. */
57
57
  const termFreq = (text: string, matcher: KeywordMatcher): number => {
58
58
  let count = 0, offset = 0;
59
59
  for (;;) {
@@ -126,12 +126,12 @@ const TOOL_ARGS_BUDGET = 2000;
126
126
  /**
127
127
  * Tool name of the recall tool itself (src/tools/recall.ts). A search
128
128
  * operation must not match its own query or its own prior output: the
129
- * tuck_recall or tuck_search invocation is persisted as an ordinary assistant toolCall (its
129
+ * lookup invocation is persisted as an ordinary assistant toolCall (its
130
130
  * `{ query }` argument, excluded below in `toolCallArgsText`) followed by an
131
131
  * ordinary toolResult message (its `N matches for "<query>"` text, excluded
132
132
  * in `fullText`) — without both exclusions a repeated query keeps matching
133
133
  * its own prior invocation/output and the hit count grows on every search.
134
- * This is a targeted introspection invariant for the two named history lookup tools, not a
134
+ * This is a targeted introspection invariant for recognized history lookup tools, not a
135
135
  * general allowlist/blocklist over tool names or tool results.
136
136
  */
137
137
 
@@ -186,7 +186,7 @@ const fullText = (msg: Message): string => {
186
186
  * stopword filtering and case/duplicate normalization (see the
187
187
  * `effectiveTermCount >= 2` gate below `searchEntriesDetailed` uses before
188
188
  * calling `applyRelativeFloor`). Distinct, not raw count: "auth auth" or
189
- * "Auth AUTH" is semantically a single-term query and must bypass the floor
189
+ * "Auth AUTH" is a single-term query after normalization and must bypass the floor
190
190
  * like any other single term — repeating or casing a word doesn't turn it
191
191
  * into the multi-term OR-tail noise this floor targets. The normalization is
192
192
  * gate-only; it doesn't change `terms` or the BM25 scoring itself, which
@@ -292,7 +292,7 @@ export const searchEntriesDetailed = (
292
292
  // apply the hard cap.
293
293
  scored.sort((a, b) => b.score - a.score);
294
294
  // Gate on DISTINCT normalized terms, not raw term count: "auth auth" or
295
- // "Auth AUTH" is semantically a single-term query and must bypass the
295
+ // "Auth AUTH" is a single-term query after normalization and must bypass the
296
296
  // floor like any other single term — repeating/casing a word doesn't turn
297
297
  // it into the multi-term OR-tail noise this floor targets. This is a
298
298
  // gate-only normalization; it does not change `terms` itself or the BM25
@@ -69,7 +69,8 @@ export const splitSummary = (summary: string): { body: string; closing: string;
69
69
  if (at < 0) return undefined;
70
70
  // A summary saved before the rename keeps its records byte for byte (their lengths are checked); only its closing is pointed at the
71
71
  // tools the model has now.
72
- const closing = header === LEGACY_TRANSCRIPT_HEADER ? summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_search") : summary.slice(at);
72
+ const closing = summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_recall")
73
+ .replaceAll("tuck_search", "tuck_recall").replaceAll("tuck_recall or tuck_recall", "tuck_recall");
73
74
  return { body: summary.slice(header.length + 1, at), closing, version: header === TRANSCRIPT_HEADER ? 2 : 1 };
74
75
  };
75
76
  const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall", "vcc_recall");