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
@@ -5,6 +5,7 @@ import { mkdir, open, readdir, lstat, unlink, realpath } 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 } from './recall.js';
8
+ import { assertWindowsPrivateStorage, createPrivateDirectory, protectWindowsIncidentFile } from './windows-private-storage.js';
8
9
  export const DIAGNOSTIC_BUILD = BUILD_ID;
9
10
  export function attachReceipt(draft, reason, reserveTokens, contextWindow, resolved = {}) {
10
11
  const details = draft.details && typeof draft.details === 'object' ? draft.details : {};
@@ -17,7 +18,7 @@ export function receiptId(entry) {
17
18
  }
18
19
  export function findReceiptEntry(entries, id) { const matches = entries.filter(entry => entry.type === "compaction" && receiptId(entry) === id); return matches.length === 1 ? matches[0] : undefined; }
19
20
  /** A bounded clone. Budget is charged before every copy; forbidden fields are never traversed.
20
- * This is conservative structural/pattern redaction, not semantic secret detection. */
21
+ * This is conservative structural/pattern redaction, not detection of secrets conveyed by meaning. */
21
22
  export function boundedCopy(value, limit) {
22
23
  let remaining = limit, partial = false;
23
24
  const spend = (n) => { if (n > remaining) {
@@ -96,6 +97,7 @@ export function permittedEntries(entries, policy = {}) {
96
97
  return { entries: allowed, partial };
97
98
  }
98
99
  export class IncidentRecorder {
100
+ windowsFile;
99
101
  queue = [];
100
102
  queued = 0;
101
103
  total = 0;
@@ -122,7 +124,7 @@ export class IncidentRecorder {
122
124
  constructor(options = {}) {
123
125
  const bound = (value, fallback, max) => Number.isSafeInteger(value) && value > 0 ? Math.min(value, max) : fallback;
124
126
  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) };
125
- this.directory = resolve(options.directory ?? join(homedir(), '.local/state/pi-tuck-incidents'));
127
+ this.directory = resolve(options.directory ?? join(homedir(), '.local', 'state', 'pi-tuck-incidents'));
126
128
  }
127
129
  get waitingForCut() { return this.enabled && this.nextCut && !this.sawCut; }
128
130
  get enabled() { return this.state === 'recording'; }
@@ -152,7 +154,7 @@ export class IncidentRecorder {
152
154
  this.path = join(this.directory, 'tuck-incident-' + this.id + '.jsonl');
153
155
  this.timer = setTimeout(() => this.stop(this.sawCut ? 'duration-exhausted' : 'no-cut-expired'), this.options.durationMs);
154
156
  this.timer.unref();
155
- this.capture('start', 'operator-session-control', { id: this.id, build: DIAGNOSTIC_BUILD, nextCut, notice: 'Structural/pattern exclusions; partial replay possible. No semantic secret guarantee.' });
157
+ 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.' });
156
158
  }
157
159
  measureInline(operation) { if (!this.enabled)
158
160
  return operation(); const started = performance.now(); try {
@@ -225,6 +227,7 @@ export class IncidentRecorder {
225
227
  this.pumping = Promise.resolve().then(() => this.pump()); }
226
228
  async pump() {
227
229
  try {
230
+ const windows = process.platform === 'win32';
228
231
  // Resolve existing ancestors before creating anything; an outside path may
229
232
  // traverse a parent symlink into the active project.
230
233
  let ancestor = this.directory;
@@ -246,24 +249,36 @@ export class IncidentRecorder {
246
249
  const rel = relative(physicalProject, physicalDirectory);
247
250
  if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)))
248
251
  throw new Error('Recorder directory resolves inside project');
249
- await mkdir(this.directory, { recursive: true, mode: 0o700 });
252
+ if (!windows)
253
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
254
+ else if (missing.length)
255
+ await createPrivateDirectory(this.directory);
250
256
  const directoryStat = await lstat(this.directory);
251
- if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || (directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.())
257
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || !windows && ((directoryStat.mode & 0o077) !== 0 || directoryStat.uid !== process.getuid?.()))
252
258
  throw new Error('Recorder directory ownership/permissions');
253
259
  const names = [];
254
260
  for (const name of await readdir(this.directory))
255
261
  if (/^tuck-incident-[0-9a-f-]{36}\.jsonl$/.test(name)) {
256
262
  const stat = await lstat(join(this.directory, name));
257
- if (!stat.isFile() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
263
+ if (!stat.isFile() || stat.isSymbolicLink() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077)))
258
264
  throw new Error('Retention ownership gap');
259
265
  names.push({ name, time: stat.mtimeMs });
260
266
  }
267
+ if (windows)
268
+ await assertWindowsPrivateStorage([this.directory, ...names.map(({ name }) => join(this.directory, name))]);
261
269
  names.sort((a, b) => a.time - b.time);
262
270
  while (names.length >= this.options.maxFiles) {
263
271
  const { name } = names.shift();
264
272
  if (join(this.directory, name) !== this.path)
265
273
  await unlink(join(this.directory, name));
266
274
  }
275
+ if (windows && !this.options.write && !this.windowsFile) {
276
+ // O_NOFOLLOW is unavailable on Windows. Exclusive creation rejects an existing link/file,
277
+ // and the same handle is retained until recording stops; subsequent pumps never reopen the path.
278
+ this.windowsFile = await open(this.path, 'wx', 0o600);
279
+ await protectWindowsIncidentFile(this.path);
280
+ await assertWindowsPrivateStorage([this.path]);
281
+ }
267
282
  while (this.queue.length) {
268
283
  const line = this.queue.shift();
269
284
  this.queued -= line.length;
@@ -272,17 +287,18 @@ export class IncidentRecorder {
272
287
  if (this.options.write)
273
288
  await this.options.write(this.path, line);
274
289
  else {
275
- const file = await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
290
+ const file = this.windowsFile ?? await open(this.path, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
276
291
  try {
277
292
  const stat = await file.stat();
278
293
  if (stat.size + Buffer.byteLength(line) > this.options.maxFileBytes)
279
294
  throw new Error('File bound');
280
- if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
295
+ if (!stat.isFile() || !windows && (stat.uid !== process.getuid?.() || (stat.mode & 0o077)))
281
296
  throw new Error('Recorder file ownership/permissions');
282
297
  await file.write(line);
283
298
  }
284
299
  finally {
285
- await file.close();
300
+ if (!windows)
301
+ await file.close();
286
302
  }
287
303
  }
288
304
  }
@@ -297,6 +313,11 @@ export class IncidentRecorder {
297
313
  this.safeNotify('Compaction recorder storage failed; incident has a gap');
298
314
  }
299
315
  finally {
316
+ if (!this.enabled && this.windowsFile) {
317
+ const file = this.windowsFile;
318
+ this.windowsFile = undefined;
319
+ await file.close().catch(() => { });
320
+ }
300
321
  this.pumping = undefined;
301
322
  if (this.queue.length)
302
323
  this.schedule();
@@ -1,6 +1,6 @@
1
1
  import { getCurrentTools } from "@earendil-works/pi-ai";
2
2
  import { convertToLlm } from "@earendil-works/pi-coding-agent";
3
- const own = (name) => name === "tuck_recall" || name === "tuck_search";
3
+ const own = (name) => name === "tuck_recall";
4
4
  /** Native Pi compactions do not make pi-tuck history available. No session-wide activation state. */
5
5
  export const hasTuckCut = (branch) => branch.some(entry => entry.type === "compaction" && entry.details?.compactor === "pi-tuck");
6
6
  /** Preserve the host's loadout and its order; only our registered tools may change. */
@@ -8,7 +8,7 @@ export function historyToolNames(pi, names, enabled) {
8
8
  if (!enabled)
9
9
  return names.filter(name => !own(name));
10
10
  const registered = new Set(pi.getAllTools().map(tool => tool.name));
11
- return [...names, ...["tuck_recall", "tuck_search"].filter(name => registered.has(name) && !names.includes(name))];
11
+ return [...names, ...["tuck_recall"].filter(name => registered.has(name) && !names.includes(name))];
12
12
  }
13
13
  export function applyHistoryTools(pi, enabled) {
14
14
  const current = pi.getActiveTools(), next = historyToolNames(pi, current, enabled);
@@ -43,7 +43,7 @@ export function historyToolDeclarations(messages, tools, enabled) {
43
43
  // Leave an already-correct transcript byte-identical, including the original placement of our declarations.
44
44
  const declared = getCurrentTools(convertToLlm(messages));
45
45
  const wanted = enabled ? tools.filter(tool => own(tool.name)) : [];
46
- if (enabled && wanted.every(tool => declared.some(current => own(current.name) && current.name === tool.name)) &&
46
+ if (enabled && wanted.every(tool => declared.some(current => current.name === tool.name)) &&
47
47
  declared.filter(tool => own(tool.name)).length === wanted.length)
48
48
  return messages;
49
49
  if (!enabled || !wanted.length)
@@ -1,4 +1,4 @@
1
- import type { SessionEntry } from "@earendil-works/pi-coding-agent";
1
+ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
2
  import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
3
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
- export declare function keptReadCandidates(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
4
+ export declare function keptReadCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
@@ -1,24 +1,51 @@
1
+ import { classifyBash } from "./bash-command.js";
2
+ import { pathKey } from "./path-key.js";
1
3
  import { isTextOnly, textOf } from "./tuck/core/content.js";
2
4
  import { extractPath } from "./tuck/core/tool-args.js";
3
5
  /** Whole successful text reads, newest result first. Mutations invalidate earlier calls even when they fail or have no result. */
4
6
  export function keptReadCandidates(entries, indices, resolvable) {
7
+ const cwd = entries.find((entry) => entry.type === "session")?.cwd;
5
8
  const reads = new Map(), mutations = new Map();
9
+ let allMutated = -1;
6
10
  let order = 0;
7
11
  for (const entry of entries) {
8
12
  if (entry.type !== "message" || entry.message.role !== "assistant")
9
13
  continue;
10
14
  for (const block of entry.message.content) {
11
- if (block.type !== "toolCall" || !["read", "write", "edit"].includes(block.name) ||
15
+ if (block.type !== "toolCall" || !["read", "write", "edit", "bash"].includes(block.name) ||
12
16
  !block.arguments || typeof block.arguments !== "object")
13
17
  continue;
14
- const path = extractPath(block.arguments);
18
+ const args = block.arguments;
19
+ order++;
20
+ if (block.name === "bash") {
21
+ if (!reads.size || typeof args.command !== "string")
22
+ continue;
23
+ const command = classifyBash(args.command, cwd), { words } = command;
24
+ if (command.readOnly)
25
+ continue;
26
+ if (command.mutatesAll) {
27
+ allMutated = order;
28
+ continue;
29
+ }
30
+ const base = command.directory === undefined ? cwd : pathKey(command.directory, cwd);
31
+ const names = [...words, ...args.command.split(/[\s'"`=;|&()<>{},]+/u)];
32
+ for (const name of names)
33
+ if (name) {
34
+ mutations.set(pathKey(name), order);
35
+ mutations.set(pathKey(name, base), order);
36
+ }
37
+ continue;
38
+ }
39
+ const path = extractPath(args);
15
40
  if (!path || /[\r\n]/u.test(path))
16
41
  continue;
17
- order++;
18
- if (block.name === "read")
19
- reads.set(block.id, { path, order });
42
+ const key = pathKey(path, cwd);
43
+ if (block.name === "read") {
44
+ if (!("offset" in args) && !("limit" in args))
45
+ reads.set(block.id, { path, key, order });
46
+ }
20
47
  else
21
- mutations.set(path, order);
48
+ mutations.set(key, order);
22
49
  }
23
50
  }
24
51
  const seen = new Set(), records = [];
@@ -27,12 +54,12 @@ export function keptReadCandidates(entries, indices, resolvable) {
27
54
  if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.isError || !isTextOnly(entry.message.content))
28
55
  continue;
29
56
  const read = reads.get(entry.message.toolCallId), sourceIndex = indices.get(entry.id);
30
- if (!read || seen.has(read.path) || (mutations.get(read.path) ?? -1) > read.order)
57
+ if (!read || seen.has(read.key) || Math.max(allMutated, mutations.get(read.key) ?? -1, mutations.get(pathKey(read.path)) ?? -1) > read.order)
31
58
  continue;
32
59
  const text = textOf(entry.message.content);
33
60
  if (!text.length || sourceIndex === undefined || !resolvable(entry))
34
61
  continue;
35
- seen.add(read.path);
62
+ seen.add(read.key);
36
63
  records.push({ kind: "section", title: "Kept-read", sourceIndex,
37
64
  text: `read ${read.path} (as recorded at #${sourceIndex}; no write or edit recorded since):\n${text}` });
38
65
  }
@@ -0,0 +1,11 @@
1
+ import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
2
+ import type { TranscriptRecord } from "./tuck/core/transcript.js";
3
+ interface Pipeline {
4
+ directory?: string;
5
+ stages: string[][];
6
+ }
7
+ export declare const parseSearchCommand: (command: string, windows?: boolean) => Pipeline | undefined;
8
+ export declare function searchPathsMatch(a: string, b: string): boolean;
9
+ /** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
10
+ export declare function keptSearchCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
11
+ export {};
@@ -0,0 +1,202 @@
1
+ import { classifyBash } from "./bash-command.js";
2
+ import { pathKey } from "./path-key.js";
3
+ import { isTextOnly, textOf } from "./tuck/core/content.js";
4
+ import { extractPath } from "./tuck/core/tool-args.js";
5
+ const searchTail = new Set(["head", "tail", "sort", "uniq", "wc", "cut", "grep"]);
6
+ /** A small shell lexer, not a shell interpreter. Unclassified shell syntax fails closed. */
7
+ function pipeline(command, windows) {
8
+ if (/[;<>`\r\n]/u.test(command) || command.includes("$("))
9
+ return;
10
+ const expands = (at) => command[at] === "$" && /[\w{@*#!?$-]/u.test(command[at + 1] ?? "");
11
+ const tokens = [];
12
+ let word = "", started = false, quote = "";
13
+ const flush = () => { if (started)
14
+ tokens.push({ word }); word = ""; started = false; };
15
+ for (let at = 0; at < command.length; at++) {
16
+ const ch = command[at];
17
+ if (quote) {
18
+ if (ch === quote)
19
+ quote = "";
20
+ else if (!windows && ch === "\\" && quote === '"' && /[\\"$]/u.test(command[at + 1] ?? ""))
21
+ word += command[++at];
22
+ else if (quote === '"' && expands(at))
23
+ return;
24
+ else
25
+ word += ch;
26
+ }
27
+ else if (ch === "'" || ch === '"') {
28
+ quote = ch;
29
+ started = true;
30
+ }
31
+ else if (!windows && ch === "\\") {
32
+ if (++at === command.length)
33
+ return;
34
+ word += command[at];
35
+ started = true;
36
+ }
37
+ else if (/\s/u.test(ch))
38
+ flush();
39
+ else if (ch === "|" || ch === "&") {
40
+ flush();
41
+ const op = command[at + 1] === ch ? ch + command[++at] : ch;
42
+ if (op !== "|" && op !== "&&")
43
+ return;
44
+ tokens.push({ word: op, operator: true });
45
+ }
46
+ else if (/[()]/u.test(ch) || ch === "#" && !started || expands(at))
47
+ return;
48
+ else {
49
+ word += ch;
50
+ started = true;
51
+ }
52
+ }
53
+ if (quote)
54
+ return;
55
+ flush();
56
+ let directory;
57
+ if (tokens[0]?.word === "cd" && tokens[1] && !tokens[1].operator && tokens[1].word &&
58
+ !tokens[1].word.startsWith("-") && tokens[2]?.operator && tokens[2].word === "&&") {
59
+ directory = tokens[1].word;
60
+ tokens.splice(0, 3);
61
+ }
62
+ const stages = [[]];
63
+ for (const token of tokens) {
64
+ if (token.operator) {
65
+ if (token.word !== "|" || !stages.at(-1).length)
66
+ return;
67
+ stages.push([]);
68
+ }
69
+ else
70
+ stages.at(-1).push(token.word);
71
+ }
72
+ if (!stages.at(-1).length)
73
+ return;
74
+ return { directory, stages };
75
+ }
76
+ const isSearch = ({ stages }) => ["grep", "rg"].includes(stages[0][0]) &&
77
+ stages.slice(1).every(stage => searchTail.has(stage[0]));
78
+ export const parseSearchCommand = (command, windows = false) => {
79
+ const parsed = pipeline(command, windows);
80
+ return parsed && isSearch(parsed) ? parsed : undefined;
81
+ };
82
+ // Options whose next word is a value, rather than a path operand. Pattern-file options name files too.
83
+ const searchValues = new Set(["regexp", "file", "after-context", "before-context", "context", "max-count", "color", "colour",
84
+ "binary-files", "devices", "directories", "exclude", "exclude-dir", "include", "label", "glob", "iglob", "type", "type-not",
85
+ "type-add", "type-clear", "encoding", "engine", "max-columns", "max-depth", "max-filesize", "path-separator",
86
+ "pre", "pre-glob", "replace", "sort", "sortr", "threads", "ignore-file", "hostname-bin", "hyperlink-format", "field-match-separator", "field-context-separator"]);
87
+ const shortValues = { grep: "efABCmDd", rg: "efgtrjABCmME",
88
+ head: "nc", tail: "ncs", sort: "ktoST", uniq: "fsw", cut: "bcfd" };
89
+ const otherValues = new Set(["lines", "bytes", "sleep-interval", "key", "field-separator", "output", "buffer-size", "temporary-directory",
90
+ "skip-fields", "skip-chars", "check-chars", "characters", "fields", "delimiter"]);
91
+ function pathOperands(stage) {
92
+ const [name, ...args] = stage, search = name === "grep" || name === "rg";
93
+ const paths = [], positional = [];
94
+ let literal = false, explicitPattern = false, filesOnly = false;
95
+ for (let at = 0; at < args.length; at++) {
96
+ const arg = args[at];
97
+ if (!literal && arg === "--") {
98
+ literal = true;
99
+ continue;
100
+ }
101
+ if (!literal && arg.startsWith("--")) {
102
+ const [option, ...value] = arg.slice(2).split("=");
103
+ if (search && (option === "regexp" || option === "file"))
104
+ explicitPattern = true;
105
+ if (name === "rg" && option === "files")
106
+ filesOnly = true;
107
+ if ((search ? searchValues : otherValues).has(option)) {
108
+ const optional = name === "grep" && (option === "color" || option === "colour");
109
+ const operand = value.length ? value.join("=") : optional ? undefined : args[++at];
110
+ if (option === "file" && operand)
111
+ paths.push(operand);
112
+ }
113
+ continue;
114
+ }
115
+ if (!literal && arg.startsWith("-") && arg !== "-") {
116
+ for (let i = 1; i < arg.length; i++)
117
+ if (shortValues[name]?.includes(arg[i])) {
118
+ const option = arg[i], value = arg.slice(i + 1) || args[++at];
119
+ if (search && (option === "e" || option === "f"))
120
+ explicitPattern = true;
121
+ if (search && option === "f" && value)
122
+ paths.push(value);
123
+ break;
124
+ }
125
+ continue;
126
+ }
127
+ positional.push(arg);
128
+ }
129
+ if (search && !explicitPattern && !filesOnly)
130
+ positional.shift();
131
+ return [...paths, ...positional].filter(path => path && path !== "-");
132
+ }
133
+ export function searchPathsMatch(a, b) {
134
+ const left = pathKey(a).replace(/^\/+|\/+$/gu, ""), right = pathKey(b).replace(/^\/+|\/+$/gu, "");
135
+ return !!left && !!right && (left === right || left.endsWith("/" + right) || right.endsWith("/" + left));
136
+ }
137
+ /** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
138
+ export function keptSearchCandidates(entries, indices, resolvable) {
139
+ const cwd = entries.find((entry) => entry.type === "session")?.cwd;
140
+ const results = new Map(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [[entry.message.toolCallId, entry.message]] : []));
141
+ const searches = new Map();
142
+ const mutations = [];
143
+ let order = 0, lastUnsafeBash = -1;
144
+ for (const entry of entries) {
145
+ if (entry.type === "message" && entry.message.role === "bashExecution") {
146
+ order++;
147
+ if (!classifyBash(entry.message.command, cwd).readOnly)
148
+ lastUnsafeBash = order;
149
+ continue;
150
+ }
151
+ if (entry.type !== "message" || entry.message.role !== "assistant")
152
+ continue;
153
+ for (const block of entry.message.content) {
154
+ if (block.type !== "toolCall")
155
+ continue;
156
+ order++;
157
+ const args = block.arguments && typeof block.arguments === "object" ? block.arguments : {};
158
+ if (block.name === "bash") {
159
+ const command = args.command;
160
+ const classified = typeof command === "string" ? classifyBash(command, cwd) : undefined;
161
+ if (!classified?.readOnly)
162
+ lastUnsafeBash = order;
163
+ const parsed = typeof command === "string" ? parseSearchCommand(command, classified.windows) : undefined;
164
+ if (parsed)
165
+ searches.set(block.id, { command: command, parsed, order });
166
+ }
167
+ else if (["write", "edit"].includes(block.name) && !results.get(block.id)?.isError) {
168
+ const path = extractPath(args);
169
+ if (path)
170
+ mutations.push({ path: pathKey(path), order });
171
+ }
172
+ }
173
+ }
174
+ const seen = new Set(), records = [];
175
+ for (let at = entries.length - 1; at >= 0; at--) {
176
+ const entry = entries[at];
177
+ if (entry.type !== "message" || entry.message.role !== "toolResult")
178
+ continue;
179
+ const search = searches.get(entry.message.toolCallId);
180
+ if (!search)
181
+ continue;
182
+ const key = search.command.replace(/\s+/gu, " ").trim();
183
+ if (seen.has(key))
184
+ continue;
185
+ seen.add(key);
186
+ const sourceIndex = indices.get(entry.id);
187
+ if (search.order < lastUnsafeBash || entry.message.isError || !isTextOnly(entry.message.content) || sourceIndex === undefined || !resolvable(entry))
188
+ continue;
189
+ const text = textOf(entry.message.content);
190
+ if (!text.length || text.length > 2000)
191
+ continue;
192
+ const paths = [...search.parsed.stages.flatMap(pathOperands), ...text.split("\n").flatMap(line => {
193
+ const prefix = /^((?:[a-z]:[\\/])?[^:\r\n]+):/iu.exec(line)?.[1];
194
+ return prefix ? [prefix] : [];
195
+ })].map(path => pathKey(path, search.parsed.directory ? pathKey(search.parsed.directory, cwd) : undefined));
196
+ if (mutations.some(mutation => mutation.order > search.order && paths.some(path => searchPathsMatch(path, mutation.path))))
197
+ continue;
198
+ records.push({ kind: "section", title: "Kept-search", sourceIndex,
199
+ text: `bash ${search.command} (as recorded at #${sourceIndex}; no file it lists was written or edited since):\n${text}` });
200
+ }
201
+ return records;
202
+ }
@@ -18,7 +18,7 @@ export interface LedgerItem {
18
18
  }
19
19
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
20
20
  * 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. */
21
- export declare function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string>): LedgerItem[];
21
+ export declare function ledgerItems(entries: readonly SessionEntry[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean, failedCalls: ReadonlySet<string>, cwd?: string): LedgerItem[];
22
22
  /** The ledger: a heading, one record per listed path (at most `keep` and the line cap, newest first), then a count of the older ones.
23
23
  * Each line carries its own source index, so a later native omission of that entry removes that line only. */
24
24
  export declare function ledgerRecords(items: readonly LedgerItem[], keep?: number): TranscriptRecord[];
@@ -1,6 +1,7 @@
1
1
  import { isLookupTool } from "./tuck/core/recall-operation.js";
2
2
  import { isDiscardedResponse } from "./protocol.js";
3
3
  import { extractPath } from "./tuck/core/tool-args.js";
4
+ import { pathKey } from "./path-key.js";
4
5
  /** Owner default; older distinct paths are counted, not listed. */
5
6
  export const MAX_LEDGER_LINES = 60;
6
7
  const LEDGER_TITLE = "Files";
@@ -14,7 +15,7 @@ export const head = (text, max) => {
14
15
  };
15
16
  /** Paths exactly as recorded in read/write/edit tool-call arguments before the cut, newest last operation first. Nothing is inferred.
16
17
  * 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. */
17
- export function ledgerItems(entries, indices, resolvable, failedCalls) {
18
+ export function ledgerItems(entries, indices, resolvable, failedCalls, cwd) {
18
19
  const results = new Map();
19
20
  for (const entry of entries)
20
21
  if (entry.type === "message" && entry.message.role === "toolResult")
@@ -32,8 +33,9 @@ export function ledgerItems(entries, indices, resolvable, failedCalls) {
32
33
  const path = operation && extractPath(block.arguments);
33
34
  if (!operation || !path || /[\r\n]/u.test(path) || operation === "wrote/edited" && failedCalls.has(block.id))
34
35
  continue;
35
- last.delete(path);
36
- last.set(path, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
36
+ const key = pathKey(path, cwd);
37
+ last.delete(key);
38
+ last.set(key, { path, operation, entry, target: operation === "read" ? results.get(block.id) ?? entry : entry });
37
39
  }
38
40
  }
39
41
  // Only listed lines show a locator, so resolvability (which renders the entry) is checked for those alone.
@@ -0,0 +1,3 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ /** Once per home, including partial attempts. A later recreation belongs to whoever created it. */
3
+ export declare function cleanupLegacyFiles(ctx: ExtensionContext): Promise<void>;