pi-tuck 1.1.3 → 1.3.1

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 (86) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +28 -59
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/bash-command.d.ts +8 -0
  6. package/dist/src/bash-command.js +116 -0
  7. package/dist/src/build-id.d.ts +1 -1
  8. package/dist/src/build-id.js +1 -1
  9. package/dist/src/compaction.d.ts +2 -103
  10. package/dist/src/compaction.js +20 -140
  11. package/dist/src/diagnostic-replay.js +3 -3
  12. package/dist/src/diagnostics.d.ts +3 -2
  13. package/dist/src/diagnostics.js +30 -9
  14. package/dist/src/history-tools.js +3 -3
  15. package/dist/src/kept-reads.d.ts +2 -2
  16. package/dist/src/kept-reads.js +35 -8
  17. package/dist/src/kept-searches.d.ts +11 -0
  18. package/dist/src/kept-searches.js +202 -0
  19. package/dist/src/ledger.d.ts +1 -1
  20. package/dist/src/ledger.js +5 -3
  21. package/dist/src/legacy-cleanup.d.ts +3 -0
  22. package/dist/src/legacy-cleanup.js +190 -0
  23. package/dist/src/notify.d.ts +3 -0
  24. package/dist/src/notify.js +13 -0
  25. package/dist/src/omissions.d.ts +1 -1
  26. package/dist/src/omissions.js +3 -3
  27. package/dist/src/path-key.d.ts +3 -0
  28. package/dist/src/path-key.js +8 -0
  29. package/dist/src/request-capacity.js +1 -1
  30. package/dist/src/run.d.ts +1 -3
  31. package/dist/src/run.js +3 -5
  32. package/dist/src/source-export.d.ts +1 -1
  33. package/dist/src/source-export.js +1 -1
  34. package/dist/src/status.d.ts +0 -6
  35. package/dist/src/status.js +1 -6
  36. package/dist/src/tuck/core/content.d.ts +0 -11
  37. package/dist/src/tuck/core/content.js +5 -55
  38. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  39. package/dist/src/tuck/core/keyword-query.js +1 -1
  40. package/dist/src/tuck/core/search-entries.d.ts +5 -28
  41. package/dist/src/tuck/core/search-entries.js +14 -156
  42. package/dist/src/tuck/core/transcript.js +2 -1
  43. package/dist/src/tuck.d.ts +7 -15
  44. package/dist/src/tuck.js +409 -409
  45. package/dist/src/windows-private-storage.d.ts +9 -0
  46. package/dist/src/windows-private-storage.js +90 -0
  47. package/index.ts +18 -82
  48. package/package.json +5 -8
  49. package/src/bash-command.ts +59 -0
  50. package/src/build-id.ts +1 -1
  51. package/src/compaction.ts +19 -107
  52. package/src/diagnostic-replay.ts +3 -3
  53. package/src/diagnostics.ts +24 -9
  54. package/src/history-tools.ts +3 -3
  55. package/src/kept-reads.ts +27 -10
  56. package/src/kept-searches.ts +163 -0
  57. package/src/ledger.ts +5 -3
  58. package/src/legacy-cleanup.ts +134 -0
  59. package/src/notify.ts +10 -0
  60. package/src/omissions.ts +3 -3
  61. package/src/path-key.ts +9 -0
  62. package/src/request-capacity.ts +1 -1
  63. package/src/run.ts +4 -6
  64. package/src/source-export.ts +1 -1
  65. package/src/status.ts +1 -10
  66. package/src/tuck/core/content.ts +4 -52
  67. package/src/tuck/core/keyword-query.ts +2 -2
  68. package/src/tuck/core/search-entries.ts +15 -202
  69. package/src/tuck/core/transcript.ts +2 -1
  70. package/src/tuck.ts +350 -357
  71. package/src/windows-private-storage.ts +94 -0
  72. package/dist/src/assets.d.ts +0 -58
  73. package/dist/src/assets.js +0 -80
  74. package/dist/src/eligibility-cache.d.ts +0 -19
  75. package/dist/src/eligibility-cache.js +0 -33
  76. package/dist/src/semantic-recall.d.ts +0 -422
  77. package/dist/src/semantic-recall.js +0 -1386
  78. package/dist/src/setup.d.ts +0 -3
  79. package/dist/src/setup.js +0 -191
  80. package/scripts/eg2-runtime.py +0 -307
  81. package/scripts/provision-eg2.py +0 -139
  82. package/scripts/semantic-worker.py +0 -234
  83. package/src/assets.ts +0 -92
  84. package/src/eligibility-cache.ts +0 -43
  85. package/src/semantic-recall.ts +0 -592
  86. package/src/setup.ts +0 -163
@@ -0,0 +1,163 @@
1
+ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
+ import { classifyBash } from "./bash-command";
3
+ import { pathKey } from "./path-key";
4
+ import { isTextOnly, textOf } from "./tuck/core/content";
5
+ import { extractPath } from "./tuck/core/tool-args";
6
+ import type { TranscriptRecord } from "./tuck/core/transcript";
7
+
8
+ interface Pipeline { directory?: string; stages: string[][] }
9
+ const searchTail = new Set(["head", "tail", "sort", "uniq", "wc", "cut", "grep"]);
10
+
11
+ /** A small shell lexer, not a shell interpreter. Unclassified shell syntax fails closed. */
12
+ function pipeline(command: string, windows: boolean): Pipeline | undefined {
13
+ if (/[;<>`\r\n]/u.test(command) || command.includes("$(")) return;
14
+ const expands = (at: number) => command[at] === "$" && /[\w{@*#!?$-]/u.test(command[at + 1] ?? "");
15
+ const tokens: { word: string; operator?: boolean }[] = [];
16
+ let word = "", started = false, quote = "";
17
+ const flush = () => { if (started) tokens.push({ word }); word = ""; started = false; };
18
+ for (let at = 0; at < command.length; at++) {
19
+ const ch = command[at]!;
20
+ if (quote) {
21
+ if (ch === quote) quote = "";
22
+ else if (!windows && ch === "\\" && quote === '"' && /[\\"$]/u.test(command[at + 1] ?? "")) word += command[++at];
23
+ else if (quote === '"' && expands(at)) return;
24
+ else word += ch;
25
+ } else if (ch === "'" || ch === '"') { quote = ch; started = true; }
26
+ else if (!windows && ch === "\\") { if (++at === command.length) return; word += command[at]; started = true; }
27
+ else if (/\s/u.test(ch)) flush();
28
+ else if (ch === "|" || ch === "&") {
29
+ flush();
30
+ const op = command[at + 1] === ch ? ch + command[++at] : ch;
31
+ if (op !== "|" && op !== "&&") return;
32
+ tokens.push({ word: op, operator: true });
33
+ } else if (/[()]/u.test(ch) || ch === "#" && !started || expands(at)) return;
34
+ else { word += ch; started = true; }
35
+ }
36
+ if (quote) return;
37
+ flush();
38
+ let directory: string | undefined;
39
+ if (tokens[0]?.word === "cd" && tokens[1] && !tokens[1].operator && tokens[1].word &&
40
+ !tokens[1].word.startsWith("-") && tokens[2]?.operator && tokens[2].word === "&&") {
41
+ directory = tokens[1].word; tokens.splice(0, 3);
42
+ }
43
+ const stages: string[][] = [[]];
44
+ for (const token of tokens) {
45
+ if (token.operator) {
46
+ if (token.word !== "|" || !stages.at(-1)!.length) return;
47
+ stages.push([]);
48
+ } else stages.at(-1)!.push(token.word);
49
+ }
50
+ if (!stages.at(-1)!.length) return;
51
+ return { directory, stages };
52
+ }
53
+
54
+ const isSearch = ({ stages }: Pipeline) => ["grep", "rg"].includes(stages[0]![0]!) &&
55
+ stages.slice(1).every(stage => searchTail.has(stage[0]!));
56
+
57
+ export const parseSearchCommand = (command: string, windows = false): Pipeline | undefined => {
58
+ const parsed = pipeline(command, windows);
59
+ return parsed && isSearch(parsed) ? parsed : undefined;
60
+ };
61
+
62
+ // Options whose next word is a value, rather than a path operand. Pattern-file options name files too.
63
+ const searchValues = new Set(["regexp", "file", "after-context", "before-context", "context", "max-count", "color", "colour",
64
+ "binary-files", "devices", "directories", "exclude", "exclude-dir", "include", "label", "glob", "iglob", "type", "type-not",
65
+ "type-add", "type-clear", "encoding", "engine", "max-columns", "max-depth", "max-filesize", "path-separator",
66
+ "pre", "pre-glob", "replace", "sort", "sortr", "threads", "ignore-file", "hostname-bin", "hyperlink-format", "field-match-separator", "field-context-separator"]);
67
+ const shortValues: Record<string, string> = { grep: "efABCmDd", rg: "efgtrjABCmME",
68
+ head: "nc", tail: "ncs", sort: "ktoST", uniq: "fsw", cut: "bcfd" };
69
+ const otherValues = new Set(["lines", "bytes", "sleep-interval", "key", "field-separator", "output", "buffer-size", "temporary-directory",
70
+ "skip-fields", "skip-chars", "check-chars", "characters", "fields", "delimiter"]);
71
+
72
+ function pathOperands(stage: string[]): string[] {
73
+ const [name, ...args] = stage, search = name === "grep" || name === "rg";
74
+ const paths: string[] = [], positional: string[] = [];
75
+ let literal = false, explicitPattern = false, filesOnly = false;
76
+ for (let at = 0; at < args.length; at++) {
77
+ const arg = args[at]!;
78
+ if (!literal && arg === "--") { literal = true; continue; }
79
+ if (!literal && arg.startsWith("--")) {
80
+ const [option, ...value] = arg.slice(2).split("=");
81
+ if (search && (option === "regexp" || option === "file")) explicitPattern = true;
82
+ if (name === "rg" && option === "files") filesOnly = true;
83
+ if ((search ? searchValues : otherValues).has(option!)) {
84
+ const optional = name === "grep" && (option === "color" || option === "colour");
85
+ const operand = value.length ? value.join("=") : optional ? undefined : args[++at];
86
+ if (option === "file" && operand) paths.push(operand);
87
+ }
88
+ continue;
89
+ }
90
+ if (!literal && arg.startsWith("-") && arg !== "-") {
91
+ for (let i = 1; i < arg.length; i++) if (shortValues[name!]?.includes(arg[i]!)) {
92
+ const option = arg[i]!, value = arg.slice(i + 1) || args[++at];
93
+ if (search && (option === "e" || option === "f")) explicitPattern = true;
94
+ if (search && option === "f" && value) paths.push(value);
95
+ break;
96
+ }
97
+ continue;
98
+ }
99
+ positional.push(arg);
100
+ }
101
+ if (search && !explicitPattern && !filesOnly) positional.shift();
102
+ return [...paths, ...positional].filter(path => path && path !== "-");
103
+ }
104
+
105
+ export function searchPathsMatch(a: string, b: string): boolean {
106
+ const left = pathKey(a).replace(/^\/+|\/+$/gu, ""), right = pathKey(b).replace(/^\/+|\/+$/gu, "");
107
+ return !!left && !!right && (left === right || left.endsWith("/" + right) || right.endsWith("/" + left));
108
+ }
109
+
110
+ /** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
111
+ export function keptSearchCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>,
112
+ resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[] {
113
+ const cwd = entries.find((entry): entry is SessionHeader => entry.type === "session")?.cwd;
114
+ const results = new Map(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [[entry.message.toolCallId, entry.message] as const] : []));
115
+ const searches = new Map<string, { command: string; parsed: Pipeline; order: number }>();
116
+ const mutations: { path: string; order: number }[] = [];
117
+ let order = 0, lastUnsafeBash = -1;
118
+ for (const entry of entries) {
119
+ if (entry.type === "message" && entry.message.role === "bashExecution") {
120
+ order++;
121
+ if (!classifyBash(entry.message.command, cwd).readOnly) lastUnsafeBash = order;
122
+ continue;
123
+ }
124
+ if (entry.type !== "message" || entry.message.role !== "assistant") continue;
125
+ for (const block of entry.message.content) {
126
+ if (block.type !== "toolCall") continue;
127
+ order++;
128
+ const args = block.arguments && typeof block.arguments === "object" ? block.arguments as Record<string, unknown> : {};
129
+ if (block.name === "bash") {
130
+ const command = args.command;
131
+ const classified = typeof command === "string" ? classifyBash(command, cwd) : undefined;
132
+ if (!classified?.readOnly) lastUnsafeBash = order;
133
+ const parsed = typeof command === "string" ? parseSearchCommand(command, classified!.windows) : undefined;
134
+ if (parsed) searches.set(block.id, { command: command as string, parsed, order });
135
+ } else if (["write", "edit"].includes(block.name) && !results.get(block.id)?.isError) {
136
+ const path = extractPath(args);
137
+ if (path) mutations.push({ path: pathKey(path), order });
138
+ }
139
+ }
140
+ }
141
+ const seen = new Set<string>(), records: TranscriptRecord[] = [];
142
+ for (let at = entries.length - 1; at >= 0; at--) {
143
+ const entry = entries[at]!;
144
+ if (entry.type !== "message" || entry.message.role !== "toolResult") continue;
145
+ const search = searches.get(entry.message.toolCallId);
146
+ if (!search) continue;
147
+ const key = search.command.replace(/\s+/gu, " ").trim();
148
+ if (seen.has(key)) continue;
149
+ seen.add(key);
150
+ const sourceIndex = indices.get(entry.id);
151
+ if (search.order < lastUnsafeBash || entry.message.isError || !isTextOnly(entry.message.content) || sourceIndex === undefined || !resolvable(entry)) continue;
152
+ const text = textOf(entry.message.content);
153
+ if (!text.length || text.length > 2000) continue;
154
+ const paths = [...search.parsed.stages.flatMap(pathOperands), ...text.split("\n").flatMap(line => {
155
+ const prefix = /^((?:[a-z]:[\\/])?[^:\r\n]+):/iu.exec(line)?.[1];
156
+ return prefix ? [prefix] : [];
157
+ })].map(path => pathKey(path, search.parsed.directory ? pathKey(search.parsed.directory, cwd) : undefined));
158
+ if (mutations.some(mutation => mutation.order > search.order && paths.some(path => searchPathsMatch(path, mutation.path)))) continue;
159
+ records.push({ kind: "section", title: "Kept-search", sourceIndex,
160
+ text: `bash ${search.command} (as recorded at #${sourceIndex}; no file it lists was written or edited since):\n${text}` });
161
+ }
162
+ return records;
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);
@@ -1,59 +1,11 @@
1
1
  import type { Message } from "@earendil-works/pi-ai";
2
2
 
3
- export const clip = (text: string, max = 200): string => {
4
- if (text.length <= max) return text;
5
- // Try to cut at a word boundary
6
- const cut = text.lastIndexOf(" ", max);
7
- let end = cut > max * 0.6 ? cut : max;
8
- // Avoid splitting a surrogate pair
9
- if (end > 0 && end < text.length) {
10
- const code = text.charCodeAt(end - 1);
11
- if (code >= 0xd800 && code <= 0xdbff) end--;
12
- }
13
- return text.slice(0, end);
14
- };
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
3
  /** Content that is a string or only text blocks: what quoting can deliver whole. */
25
4
  export const isTextOnly = (content: string | readonly { type: string }[] | undefined): boolean =>
26
5
  typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
27
6
 
28
- export const textOf = (content: Message["content"]): string =>
29
- textParts(content).join("\n");
30
-
31
- /**
32
- * Extract every scalar string argument from a tool call for search indexing
33
- * — command, query, content, oldText/newText, etc. Generic value walk (no
34
- * tool-name allowlist): top-level strings plus strings one level into
35
- * array-of-object fields (e.g. `edits`). Unbounded by design — a single
36
- * toolCall's raw argument text — so a message with several toolCalls doesn't
37
- * silently multiply an internal cap. The caller (search-entries.ts) applies
38
- * one shared budget across all toolCalls in a message.
39
- */
40
- export const extractToolCallArgsText = (args: Record<string, unknown>): string => {
41
- if (!args || typeof args !== "object") return "";
42
- const parts: string[] = [];
43
- for (const value of Object.values(args)) {
44
- if (typeof value === "string") {
45
- parts.push(value);
46
- } else if (Array.isArray(value)) {
47
- for (const item of value) {
48
- if (typeof item === "string") {
49
- parts.push(item);
50
- } else if (item && typeof item === "object") {
51
- for (const v of Object.values(item)) {
52
- if (typeof v === "string") parts.push(v);
53
- }
54
- }
55
- }
56
- }
57
- }
58
- return parts.join("\n");
7
+ export const textOf = (content: Message["content"]): string => {
8
+ if (!content) return "";
9
+ if (typeof content === "string") return content;
10
+ return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
59
11
  };
@@ -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);