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,116 @@
1
+ import { posix } from "node:path";
2
+ // A deliberately bounded shell recognizer: substitutions, redirections and
3
+ // unrecognized composition never certify a command as read-only.
4
+ function shellWords(command, windows) {
5
+ const words = [];
6
+ let word = "", quote = "", started = false, simple = true;
7
+ const flush = () => { if (started)
8
+ words.push(word); word = ""; started = false; };
9
+ for (let i = 0; i < command.length; i++) {
10
+ const c = command[i];
11
+ if (quote === "'") {
12
+ if (c === quote)
13
+ quote = "";
14
+ else
15
+ word += c;
16
+ continue;
17
+ }
18
+ if (c === "\\" && !windows) {
19
+ if (command[i + 1] === "\n") {
20
+ i++;
21
+ continue;
22
+ }
23
+ started = true;
24
+ if (i + 1 < command.length)
25
+ word += command[++i];
26
+ else
27
+ simple = false;
28
+ continue;
29
+ }
30
+ if (c === "$" || c === "`")
31
+ simple = false;
32
+ if (windows && (c === "%" || c === "^"))
33
+ simple = false;
34
+ if (quote) {
35
+ if (c === quote)
36
+ quote = "";
37
+ else
38
+ word += c;
39
+ continue;
40
+ }
41
+ if (c === "'" || c === '"') {
42
+ quote = c;
43
+ started = true;
44
+ }
45
+ else if (/\s/u.test(c)) {
46
+ flush();
47
+ if (c === "\n") {
48
+ words.push(";");
49
+ simple = false;
50
+ }
51
+ }
52
+ else if (/[|&;<>]/u.test(c)) {
53
+ flush();
54
+ const op = command[i + 1] === c ? c + command[++i] : c;
55
+ words.push(op);
56
+ }
57
+ else {
58
+ word += c;
59
+ started = true;
60
+ if (/[(){}]/u.test(c))
61
+ simple = false;
62
+ }
63
+ }
64
+ flush();
65
+ return { words, simple: simple && !quote };
66
+ }
67
+ const readers = new Set(["ls", "cat", "head", "tail", "wc", "pwd", "echo", "tree", "file", "stat", "grep", "rg"]);
68
+ const windowsReaders = new Set(["type", "dir", "get-content", "get-childitem", "select-string", "findstr"]);
69
+ const windowsMutators = new Set(["set-content", "add-content", "out-file", "remove-item", "move-item", "copy-item", "new-item", "del", "move", "copy", "ren"]);
70
+ const gitMutations = new Set(["checkout", "restore", "stash", "apply", "reset", "pull", "merge", "rebase", "am"]);
71
+ function mutatingGit(words) {
72
+ return words.some((word, at) => {
73
+ if (posix.basename(word.replace(/\\/gu, "/")).replace(/\.exe$/iu, "").toLowerCase() !== "git")
74
+ return false;
75
+ for (let i = at + 1; i < words.length; i++) {
76
+ const arg = words[i];
77
+ if (["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"].includes(arg)) {
78
+ i++;
79
+ continue;
80
+ }
81
+ if (arg.startsWith("-"))
82
+ continue;
83
+ return gitMutations.has(arg);
84
+ }
85
+ return false;
86
+ });
87
+ }
88
+ function readOnly(words, simple) {
89
+ if (!simple)
90
+ return false;
91
+ if (words[0] === "cd" && words[2] === "&&")
92
+ words = words.slice(3);
93
+ if (!words.length || words.some(word => ["&&", "||", "&", ";", ">", ">>", "<", "<<"].includes(word)))
94
+ return false;
95
+ const commands = [[]];
96
+ for (const word of words) {
97
+ if (word === "|")
98
+ commands.push([]);
99
+ else
100
+ commands.at(-1).push(word);
101
+ }
102
+ return commands.every(([name, ...args]) => readers.has(name) || windowsReaders.has(name?.toLowerCase() ?? "") ||
103
+ name === "find" && !args.some(arg => /^-(exec|ok|delete|fprint)/u.test(arg)) ||
104
+ name === "sed" && args.includes("-n") && !args.some(arg => /^-[^-]*i|^--in-place/u.test(arg)) ||
105
+ name === "git" && ["status", "log", "diff", "show"].includes(args[0]));
106
+ }
107
+ /** Classify the recorded shell independently of the host OS. Both kept-result lanes use this decision. */
108
+ export function classifyBash(command, cwd) {
109
+ const commandName = command.trim().split(/\s/u)[0].toLowerCase();
110
+ const windows = /^[a-z]:[\\/]|\\/iu.test(cwd ?? "") || /[a-z]:\\/iu.test(command) ||
111
+ windowsReaders.has(commandName) || windowsMutators.has(commandName);
112
+ const { words, simple } = shellWords(command, windows);
113
+ return { words, windows, readOnly: readOnly(words, simple),
114
+ mutatesAll: mutatingGit(words) || !simple && mutatingGit(command.split(/[\s'"`();|&]+/u)),
115
+ directory: words[0] === "cd" && words[2] === "&&" ? words[1] : undefined };
116
+ }
@@ -1 +1 @@
1
- export declare const BUILD_ID = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
1
+ export declare const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
@@ -1 +1 @@
1
- export const BUILD_ID = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
1
+ export const BUILD_ID = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
@@ -1,5 +1,4 @@
1
- import { type Run } from "./run.js";
2
- import { type SemanticRecallController } from "./semantic-recall.js";
1
+ import { Run } from "./run.js";
3
2
  import { type RecorderOptions } from "./diagnostics.js";
4
3
  import { type AgentMessage } from "./budget.js";
5
4
  import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry } from "@earendil-works/pi-coding-agent";
@@ -38,12 +37,6 @@ export declare function compactionState(model: {
38
37
  contextWindow?: number;
39
38
  } | undefined, enabled: boolean): CompactionState;
40
39
  export interface CompactionOptions {
41
- semanticRecall?: SemanticRecallController;
42
- /** Whether `tuck_search` exists: false where semantic recall cannot run (off Apple silicon), so the model is offered word recall only. */
43
- search?: boolean;
44
- /** Optional host-owned transient operator preference; handle operations never call back. */
45
- onSemanticSetting?: (enabled: boolean) => Promise<unknown>;
46
- semanticStatus?: () => unknown;
47
40
  diagnostics?: RecorderOptions;
48
41
  /** Optional read-only observation of actual corrected budget checks; no request content. */
49
42
  observeBudget?: (measurement: {
@@ -86,104 +79,10 @@ export interface CompactionOptions {
86
79
  }
87
80
  export declare function installCompaction(pi: ExtensionAPI, options?: CompactionOptions): Promise<{
88
81
  close: () => Promise<void>;
89
- semanticRecall: SemanticRecallController;
90
- setSemanticEnabled: (enabled: boolean, ctx: ExtensionContext) => Promise<{
91
- setup: import("./semantic-recall.js").SemanticSetup;
92
- setupMessage: string | null;
93
- enabled: boolean;
94
- configured: boolean;
95
- cleanupError: string | null;
96
- state: import("./semantic-recall.js").SemanticState;
97
- snapshotId: string | null;
98
- throughEntryId: string | null;
99
- eligibleSources: number;
100
- totalUnits: number;
101
- coveredUnits: number;
102
- indexingComplete: boolean;
103
- lastError: string | null;
104
- window: {
105
- indexedCharacters: number;
106
- windowCharacters: number;
107
- outOfViewCharacters: number;
108
- eligibleCharacters: number;
109
- oldestCoveredEntryId: string | null;
110
- oldestCoveredTime: string | null;
111
- conversation: {
112
- indexedCharacters: number;
113
- outOfViewCharacters: number;
114
- };
115
- toolResults: {
116
- indexedCharacters: number;
117
- outOfViewCharacters: number;
118
- oldestCoveredTime: string | null;
119
- };
120
- } | null;
121
- recovery: {
122
- attempts: number;
123
- integrity: boolean;
124
- retryAt: string | null;
125
- } | null;
126
- operations: {
127
- preparationEmbeddings: number;
128
- queryEmbeddings: number;
129
- };
130
- limits: {
131
- keyword: number;
132
- broad: number;
133
- };
134
- }>;
135
- semanticStatus: () => {
136
- host?: unknown;
137
- local: {
138
- setup: import("./semantic-recall.js").SemanticSetup;
139
- setupMessage: string | null;
140
- enabled: boolean;
141
- configured: boolean;
142
- cleanupError: string | null;
143
- state: import("./semantic-recall.js").SemanticState;
144
- snapshotId: string | null;
145
- throughEntryId: string | null;
146
- eligibleSources: number;
147
- totalUnits: number;
148
- coveredUnits: number;
149
- indexingComplete: boolean;
150
- lastError: string | null;
151
- window: {
152
- indexedCharacters: number;
153
- windowCharacters: number;
154
- outOfViewCharacters: number;
155
- eligibleCharacters: number;
156
- oldestCoveredEntryId: string | null;
157
- oldestCoveredTime: string | null;
158
- conversation: {
159
- indexedCharacters: number;
160
- outOfViewCharacters: number;
161
- };
162
- toolResults: {
163
- indexedCharacters: number;
164
- outOfViewCharacters: number;
165
- oldestCoveredTime: string | null;
166
- };
167
- } | null;
168
- recovery: {
169
- attempts: number;
170
- integrity: boolean;
171
- retryAt: string | null;
172
- } | null;
173
- operations: {
174
- preparationEmbeddings: number;
175
- queryEmbeddings: number;
176
- };
177
- limits: {
178
- keyword: number;
179
- broad: number;
180
- };
181
- };
182
- };
183
82
  state: (ctx: ExtensionContext) => CompactionState;
184
83
  inspectState: (ctx: ExtensionContext) => {
185
84
  run: Readonly<Run> | undefined;
186
- phase: "starting" | "failed" | "decided" | "claimed" | "expired" | "admitted" | "commit-failed" | undefined;
85
+ phase: "decided" | "claimed" | "expired" | "starting" | "admitted" | "failed" | "commit-failed" | undefined;
187
86
  calibrationIdentity: string;
188
87
  pendingCut: boolean;
189
88
  };
@@ -1,8 +1,7 @@
1
1
  import { textOf } from "./tuck/core/content.js";
2
- import { PendingCut, StartingPrompt, createRun } from "./run.js";
2
+ import { PendingCut, StartingPrompt, Run } from "./run.js";
3
3
  import { requestReplyFloor, replyFit, carriesPrompt, thinkingOnlyLength, piContextSafetyMargin, loadPiRequestMath, seedContextWindow, WINDOW_RECEIPT } from "./request-capacity.js";
4
4
  import { BUILD_ID } from "./build-id.js";
5
- import { createSemanticRecall, budgetSemantic } from "./semantic-recall.js";
6
5
  import { DIAGNOSTIC_BUILD, IncidentRecorder, attachReceipt, permittedEntries, receiptId, findReceiptEntry } from "./diagnostics.js";
7
6
  import { createHash } from "node:crypto";
8
7
  import { readFileSync } from "node:fs";
@@ -20,7 +19,7 @@ import { MAX_RECALL_CHARACTERS, MAX_RECALL_ENTRY_ID_CHARACTERS, MAX_RECALL_QUERY
20
19
  import { tuck, tuckDraft, tuckObservedDraft, tuckRecall } from "./tuck.js";
21
20
  import { LOADED_VERSION, statusText } from "./status.js";
22
21
  import { ImageRecallInput, historyImage, historyAround } from "./history-image.js";
23
- import { eligibilityKey, eligibilityKeyMoved, memoizedEligibleSources } from "./eligibility-cache.js";
22
+ import { notify } from "./notify.js";
24
23
  import { applyHistoryTools, historyToolDeclarations, historyToolNames, stageHistoryTools } from "./history-tools.js";
25
24
  const query = Type.String({ minLength: 1, maxLength: MAX_RECALL_QUERY_CHARACTERS });
26
25
  const entryId = Type.String({ minLength: 1, maxLength: MAX_RECALL_ENTRY_ID_CHARACTERS });
@@ -42,7 +41,6 @@ const RecallInput = Type.Union([
42
41
  Type.Object({ index: Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }), query: Type.Optional(query), ...paging }, { additionalProperties: false }),
43
42
  Type.Object(paging, { additionalProperties: false }),
44
43
  ]);
45
- const SearchInput = Type.Object({ query, priorResults: Type.Optional(Type.Array(Type.Object({ sourceSha: Type.String({ minLength: 64, maxLength: 64 }), read: Type.Object({ entryId, offset: Type.Integer({ minimum: 0 }), limit: Type.Integer({ minimum: 0 }) }, { additionalProperties: false }) }, { additionalProperties: false }), { maxItems: 20 })) }, { additionalProperties: false });
46
44
  const reply = (value) => ({ content: [{ type: "text", text: JSON.stringify(value) }], details: {} });
47
45
  /** The compactor's verdict that this attempt cannot be made: the cut it needs cannot be made, or the request cannot fit. Like every failure but
48
46
  * a `CommitFault`, it ends with its attempt (`resetRun`), and the next attempt plans afresh from the session as it is. */
@@ -55,15 +53,6 @@ class CommitFault extends Error {
55
53
  /** A refusal for want of room, which the user can remedy: it carries advice. */
56
54
  class CapacityError extends Refusal {
57
55
  }
58
- function notify(ctx, message, level) {
59
- try {
60
- if (ctx.hasUI === false)
61
- process.stderr.write(message + "\n");
62
- else
63
- ctx.ui.notify(message, level);
64
- }
65
- catch { /* ended */ }
66
- }
67
56
  /** What a capacity refusal tells the operator. When the provider has counted far more input than pi-tuck's estimate, the refusal most
68
57
  * likely comes from that counting (an upstream behind a router can spend much more context on tool schemas), so the notice says so. */
69
58
  export const refusalNotice = (message, factor) => message + "; shorten the input, use a model with a larger window, or lower Pi's compaction.reserveTokens, then retry." +
@@ -181,24 +170,13 @@ export async function installCompaction(pi, options = {}) {
181
170
  const cutAt = options.cutAt ?? DEFAULT_CUT_AT;
182
171
  if (!validCutAt(cutAt))
183
172
  throw new Error("Invalid cut point: cutAt must be a number above 0 and at most 1");
184
- const semantic = options.semanticRecall ?? createSemanticRecall(), search = options.search ?? true;
185
173
  const hostAccess = () => {
186
174
  if (!active())
187
175
  throw new Error("Compaction host is inactive");
188
176
  options.assertAccess?.();
189
177
  };
190
- let semanticTransition = Promise.resolve();
191
- let semanticRequest = 0;
192
- const semanticPending = new Set();
193
- // Semantic indexing outlives any one attempt, so it checks only that the host still grants access: a compactor failure, which ends with its
194
- // attempt, must not read as a revocation (that disables semantic recall and deletes its index for the rest of the session).
195
- // A prompt's cut reaches the requests at once but the session only at the end of the first turn: until then search sees the history as the model does.
196
178
  const view = (ctx, threshold = false) => (threshold && run?.expired ? liveCut : run?.cut ?? liveCut).view(ctx);
197
179
  const liveCut = new PendingCut();
198
- const semanticProvider = (ctx) => () => {
199
- const current = view(ctx);
200
- return memoizedEligibleSources(ctx, options.recallPolicy, hostAccess, current.pending ? current.keptFromId : undefined);
201
- };
202
180
  const recorder = new IncidentRecorder(options.diagnostics);
203
181
  let proposalId;
204
182
  const observe = (ctx) => recorder.measureInline(() => {
@@ -242,66 +220,14 @@ export async function installCompaction(pi, options = {}) {
242
220
  ctx.ui.notify(JSON.stringify(recorder.status()), "info");
243
221
  } });
244
222
  pi.on("session_compact", (_event, ctx) => observe(ctx));
245
- // A saved cut moves entries out of view: index them now, in the background, even for a session that has not searched or whose worker the idle limit stopped.
246
- pi.on("session_compact", (_event, ctx) => { if (!standDown(ctx))
247
- semantic.indexAtCut(semanticProvider(ctx)); });
248
- pi.on("session_shutdown", async () => { semanticRequest++; recorder.stop("session-shutdown"); await semantic.close(); await Promise.allSettled([...semanticPending]); });
249
- pi.on("session_start", () => { semanticRequest++; semanticTransition = semantic.close(); void semanticTransition.catch(error => { options.fail?.(error); }); });
250
- pi.on("turn_end", (_event, ctx) => { semantic.schedule(semanticProvider(ctx)); });
251
- const applySemanticEnabled = async (enabled, ctx) => {
252
- const request = ++semanticRequest;
253
- if (!enabled) {
254
- semanticTransition = semantic.disable();
255
- await semanticTransition;
256
- return semantic.status();
257
- }
258
- await semanticTransition;
259
- if (request !== semanticRequest)
260
- return semantic.status();
261
- access();
262
- if (!semantic.status().configured)
263
- await semantic.configureExternal(ctx.cwd);
264
- if (request !== semanticRequest)
265
- return semantic.status();
266
- access();
267
- semantic.enable();
268
- semantic.schedule(semanticProvider(ctx));
269
- return semantic.status();
270
- };
271
- const setSemanticEnabled = (enabled, ctx) => {
272
- const operation = applySemanticEnabled(enabled, ctx);
273
- semanticPending.add(operation);
274
- void operation.then(() => semanticPending.delete(operation), () => semanticPending.delete(operation));
275
- return operation;
276
- };
277
- const semanticStatus = () => ({ local: semantic.status(), ...(options.semanticStatus ? { host: options.semanticStatus() } : {}) });
278
- pi.registerCommand("tuck-semantic", { description: "Semantic recall for this session: on, off or status. To turn it off everywhere, set \"semanticRecall\": false in pi-tuck.json in Pi's agent folder.", handler: async (args, ctx) => {
279
- const command = args.trim();
280
- if (!["on", "off", "status"].includes(command)) {
281
- ctx.ui.notify("Use on, off or status", "warning");
282
- return;
283
- }
284
- const errors = [];
285
- if (command !== "status") {
286
- const enabled = command === "on";
287
- // Both owners start directly. Off must attempt every host handle even if this one fails.
288
- const operations = [setSemanticEnabled(enabled, ctx)];
289
- if (options.onSemanticSetting)
290
- operations.push(Promise.resolve().then(() => options.onSemanticSetting(enabled)).then(() => semantic.status()));
291
- for (const result of await Promise.allSettled(operations))
292
- if (result.status === "rejected")
293
- errors.push(String(result.reason));
294
- }
295
- ctx.ui.notify(JSON.stringify({ ...semanticStatus(), ...(errors.length ? { errors } : {}) }), errors.length ? "warning" : "info");
296
- } });
223
+ pi.on("session_shutdown", () => { recorder.stop("session-shutdown"); });
297
224
  pi.registerCommand("tuck", { description: "pi-tuck's state in this session: version, cuts, cut point, search", handler: async (_args, ctx) => {
298
- const state = semantic.status();
299
- ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, search, semantic: state, pending: view(ctx).pending }), "info");
225
+ ctx.ui.notify(statusText({ version: LOADED_VERSION, active: active(), compaction: stateFor(ctx), branch: ctx.sessionManager.getBranch(), cutAt: options.cutAt, pending: view(ctx).pending }), "info");
300
226
  } });
301
227
  // Pi's native start/settled events bracket the run and its post-turn cuts.
302
228
  let run;
303
229
  // A commit-failed phase survives attempts/tree moves until session_start: native memory may be ahead of disk.
304
- const failure = () => run?.phase === "failed" || run?.phase === "commit-failed" ? run.error : undefined;
230
+ const failure = () => run?.error;
305
231
  const protectedPrompt = (ctx) => run?.prompt?.id(ctx.sessionManager.getBranch());
306
232
  const clips = () => run?.clips ?? emptyClips;
307
233
  const emptyClips = new Map();
@@ -316,7 +242,7 @@ export async function installCompaction(pi, options = {}) {
316
242
  if (run?.phase === "commit-failed")
317
243
  run.clear();
318
244
  else
319
- run = createRun(phase);
245
+ run = new Run(phase);
320
246
  };
321
247
  const stateFor = (ctx) => compactionState(ctx.model, settingsFor().getCompactionSettings(ctx.model).enabled);
322
248
  // A prerequisite can change with the model/settings; discard the old plan before returning control to native.
@@ -437,7 +363,7 @@ export async function installCompaction(pi, options = {}) {
437
363
  // extension's agent_settled, a failure) must not erase it. Only the final assistant reply decides it; a successful retry clears it.
438
364
  let lengthStop = false;
439
365
  pi.on("agent_start", (_event, ctx) => { if (standDown(ctx))
440
- return; run ??= createRun("starting"); if (!failure())
366
+ return; run ??= new Run("starting"); if (!failure())
441
367
  run.transition("admitted", ctx); run.thinkingRetryPending = false; lengthStop = false; calibration.pending = undefined; });
442
368
  pi.on("message_end", event => { if (event.message.role === "assistant")
443
369
  lengthStop = event.message.stopReason === "length"; });
@@ -576,7 +502,7 @@ export async function installCompaction(pi, options = {}) {
576
502
  const receipted = run?.refusalReceipted;
577
503
  calibration.pending = undefined;
578
504
  // Keep the same terminal run until Pi settles; later start hooks cannot admit it.
579
- run ??= createRun("starting");
505
+ run ??= new Run("starting");
580
506
  run.clear();
581
507
  run.transition(fault instanceof CommitFault ? "commit-failed" : "failed", ctx, fault);
582
508
  run.refusalReceipted = true;
@@ -622,7 +548,7 @@ export async function installCompaction(pi, options = {}) {
622
548
  });
623
549
  pi.registerTool({
624
550
  name: "tuck_recall", label: "pi-tuck history", parameters: RecallInput,
625
- description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. " + (search ? "Use tuck_search for historical information relevant to a question, including different wording and qualifications. " : "") + "Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Hidden reasoning and system records are excluded.",
551
+ description: "Keyword lookup locates particular text in your current branch. {query} returns ranked passages with read coordinates; punctuation separates words. Pass the returned next as {continuation} unchanged. Knowing an identifier does not itself justify narrowing discovery. {entryId} or {index} (a summary sourceIndex or #N) reads one source, optionally with query, offset and limit in UTF-16 characters (limit defaults to 8000). {} browses history; {around} expands neighbors; {entryId,image} reads an image; outputPath writes an original to a file with the native write tool. Hidden reasoning and system records are excluded.",
626
552
  async execute(_id, raw, signal, _update, ctx) {
627
553
  access();
628
554
  const input = checkedInput(raw);
@@ -649,43 +575,6 @@ export async function installCompaction(pi, options = {}) {
649
575
  return reply(tuckRecall(tuck, ctx.sessionManager.getEntries(), branch, input, options.recallPolicy));
650
576
  },
651
577
  });
652
- if (search)
653
- pi.registerTool({ name: "tuck_search", label: "History search", parameters: SearchInput,
654
- description: "Find historical information relevant to a question, including different wording and related qualifications. Combines keyword and local embedding search. Knowing a name or identifier does not imply keyword-only lookup is sufficient. Returns original evidence up to 20000 characters; not exhaustive. Semantic search may be off or incomplete, which is not the same as no matches. Read exact originals and their context with tuck_recall at the returned locators. priorResults lists sources already read: pass each returned source's sourceSha and read unchanged.",
655
- async execute(_id, raw, signal, _update, ctx) {
656
- access();
657
- if (!Check(SearchInput, raw))
658
- throw new Error("Invalid broad search input");
659
- const input = structuredClone(raw);
660
- recorder.capture("recall-action", "authorized-native-tool-invocation-no-result-copy", input);
661
- // Bind the actual independent lexical offer, including attribution derived
662
- // from custom markers and receipts excluded from semantic indexing. Rebuild
663
- // under current caller policy after await, when the session moved; never send this block to the encoder.
664
- // Keyword search over a very long history can hit its time limit. That limit guards one call, not the semantic half: the agent still gets the
665
- // semantic results, and is told the keyword half stopped (seen in the field on an 84.7 MB session, where the whole search failed instead).
666
- const wordOffer = () => {
667
- try {
668
- return tuckRecall(tuck, ctx.sessionManager.getEntries(), ctx.sessionManager.getBranch(), { query: input.query }, options.recallPolicy);
669
- }
670
- catch (error) {
671
- if (error instanceof Error && error.message.startsWith("Search aborted:"))
672
- return { status: "keyword_timeout", notice: "Keyword search stopped at its time limit on this long history; the semantic results follow. For a keyword match, use more specific words or read an entry by index.", hits: [] };
673
- throw error;
674
- }
675
- };
676
- // The key is taken in the same synchronous step as the first lexical pass. After the await the second pass runs only if it moved (see eligibilityKey); a moved key alone invalidates nothing.
677
- // The snapshot id check covers every in-contract change (any branch change moves the id); the key-gated second pass is defence in depth for out-of-contract callers.
678
- const provider = semanticProvider(ctx), initialSnapshot = provider(), initialKey = eligibilityKey(ctx), words = wordOffer(), wordText = JSON.stringify(words);
679
- const related = await semantic.search(input.query, provider, signal, (input.priorResults ?? []).map(({ sourceSha, read }) => ({ entryId: read.entryId, sourceSha, start: read.offset, end: read.offset + read.limit })), words);
680
- access();
681
- if (signal?.aborted)
682
- throw Object.assign(new Error('Semantic recall cancelled'), { name: 'AbortError' });
683
- const now = provider();
684
- if (initialSnapshot.id !== now.id || (eligibilityKeyMoved(ctx, initialKey) && wordText !== JSON.stringify(wordOffer())))
685
- return { ...reply({ status: "snapshot_invalidated", notice: "Search source eligibility or version changed; no earlier evidence delivered. Request a fresh query." }), isError: true };
686
- const page = budgetSemantic(related, 20000 - wordText.length - 1);
687
- return { content: [{ type: "text", text: wordText }, { type: "text", text: JSON.stringify(page) }], details: { semantic: { status: page.status, snapshotId: page.coverage.snapshotId } } };
688
- } });
689
578
  pi.on("session_before_compact", (event, ctx) => {
690
579
  try {
691
580
  if (standDown(ctx))
@@ -745,7 +634,7 @@ export async function installCompaction(pi, options = {}) {
745
634
  // Every cut asked while no run is admitted (an operator's cut) is planned for a run that has not begun: the session has moved on
746
635
  // from any run that ended. A retry is inside its run.
747
636
  const draft = tuckDraft(tuck, event, ctx, reserve, plannerMeasureFor(ctx), options.recallPolicy, retain, operatorManual, operatorManual || run?.phase !== "admitted", run?.phase === "admitted" ? protectedPrompt(ctx) : undefined);
748
- return draft.compaction ? { draft: true, after: draft.after, mode: draft.mode, compaction: draft.compaction, reserve,
637
+ return draft.compaction ? { draft: true, after: draft.after, compaction: draft.compaction, reserve,
749
638
  messages: plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages }
750
639
  : { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
751
640
  },
@@ -831,7 +720,7 @@ export async function installCompaction(pi, options = {}) {
831
720
  return { kind: "fault", capacity: Boolean(draft.capacityRejected), message: draft.unavailable };
832
721
  const messages = plannedView(ctx, { type: "compaction", ...draft.compaction }).session.buildSessionProjection().messages;
833
722
  assertNativeToolRounds(messages);
834
- return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages), mode: draft.mode,
723
+ return { kind: "cut", target: "room", plan: { draft: true, after: measureFor(ctx)(messages),
835
724
  compaction: draft.compaction, reserve: 0, messages } };
836
725
  };
837
726
  // The cut before a run, decided on `input` while the session is idle; before_agent_start decides only for a run no input started (one a
@@ -884,7 +773,7 @@ export async function installCompaction(pi, options = {}) {
884
773
  candidate.plan({ type: "compaction", ...draft.compaction, tokensBefore: before }, branchLength);
885
774
  const messages = candidate.view(ctx).session.buildSessionProjection().messages;
886
775
  assertNativeToolRounds(messages);
887
- return { draft: true, after: measure(messages), mode: draft.mode, compaction: draft.compaction, reserve, messages };
776
+ return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
888
777
  },
889
778
  });
890
779
  let decision = gate.kind === "plan" ? decide(room, band, gate.opportunistic) : { kind: "defer" };
@@ -912,7 +801,7 @@ export async function installCompaction(pi, options = {}) {
912
801
  const prompted = run && ["decided", "claimed", "expired"].includes(run.phase) && event.messageType !== "custom";
913
802
  if (!prompted && !failure())
914
803
  beginRun("starting");
915
- run ??= createRun("starting");
804
+ run ??= new Run("starting");
916
805
  if (!failure() && run.phase !== "starting")
917
806
  run.transition("starting", ctx);
918
807
  const prompt = event.messageType === "custom" ? textOf(event.message.content) : event.prompt;
@@ -931,7 +820,7 @@ export async function installCompaction(pi, options = {}) {
931
820
  else
932
821
  applyHistoryTools(pi, false);
933
822
  const staged = pi.getActiveTools();
934
- event.systemPromptOptions.selectedTools = historyToolNames(pi, event.systemPromptOptions.selectedTools, true).filter(name => name !== "tuck_recall" && name !== "tuck_search" || staged.includes(name));
823
+ event.systemPromptOptions.selectedTools = historyToolNames(pi, event.systemPromptOptions.selectedTools, true).filter(name => name !== "tuck_recall" || staged.includes(name));
935
824
  }
936
825
  catch (error) {
937
826
  fail(error, ctx);
@@ -993,7 +882,7 @@ export async function installCompaction(pi, options = {}) {
993
882
  const lastCut = ctx.sessionManager.getBranch().findLast(entry => entry.type === "compaction");
994
883
  if (reason === "run-end" && lastAssistant && (!lastCut || lastAssistant.timestamp > Date.parse(lastCut.timestamp)) &&
995
884
  !saved.some(message => message.role === "assistant" &&
996
- !["error", "aborted"].includes(message.stopReason) && message.usage && calculateContextTokens(message.usage) > 0)) {
885
+ !isDiscardedResponse(message) && message.usage && calculateContextTokens(message.usage) > 0)) {
997
886
  const forecast = historyToolDeclarations(saved, toolShapes(historyToolNames(pi, pi.getActiveTools(), true)), true);
998
887
  if (forecast !== saved) {
999
888
  const head = getCurrentSystemMessage(convertToLlm(forecast));
@@ -1039,7 +928,7 @@ export async function installCompaction(pi, options = {}) {
1039
928
  const messages = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
1040
929
  assertNativeToolRounds(messages);
1041
930
  previews.push(messages);
1042
- return { draft: true, after: measure(messages), mode: draft.mode, compaction: draft.compaction, reserve, messages };
931
+ return { draft: true, after: measure(messages), compaction: draft.compaction, reserve, messages };
1043
932
  },
1044
933
  });
1045
934
  };
@@ -1117,21 +1006,14 @@ export async function installCompaction(pi, options = {}) {
1117
1006
  };
1118
1007
  const atBoundary = (event, ctx, reason, decide) => {
1119
1008
  const current = view(ctx);
1120
- if (!current.pending) {
1121
- const result = decide ? boundaryCut(event, ctx, reason) : undefined;
1122
- // Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
1123
- if (result?.entries.some(entry => entry.type === "compaction"))
1124
- setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
1125
- return result;
1126
- }
1009
+ if (!current.pending)
1010
+ return decide ? boundaryCut(event, ctx, reason) : undefined;
1127
1011
  const entry = run.cut.take();
1128
1012
  const preview = current.session, context = Object.create(ctx, { sessionManager: { value: preview } });
1129
1013
  const more = decide && !event.entries.length
1130
1014
  ? boundaryCut({ ...event, context: { ...event.context, contextMessages: preview.buildSessionProjection().messages } }, context, reason) : undefined;
1131
1015
  const { tokensBefore: _, ...cut } = entry;
1132
1016
  const saved = { ...cut, firstKeptEntryId: current.keptFromId };
1133
- // As for a cut Pi makes (session_compact): the history the cut leaves behind is indexed, once Pi has committed the entries.
1134
- setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
1135
1017
  return { entries: [...event.entries, saved, ...(more?.entries ?? [])] };
1136
1018
  };
1137
1019
  const retryLength = (event, ctx) => {
@@ -1185,8 +1067,6 @@ export async function installCompaction(pi, options = {}) {
1185
1067
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
1186
1068
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
1187
1069
  markBoundary(drafts);
1188
- // As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
1189
- setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
1190
1070
  return { entries: drafts, continue: true };
1191
1071
  };
1192
1072
  pi.on("turn_end", (event, ctx) => {
@@ -1256,7 +1136,7 @@ export async function installCompaction(pi, options = {}) {
1256
1136
  return { draft: false, capacityRejected: Boolean(draft.capacityRejected), reason: draft.unavailable };
1257
1137
  const kept = plannedView(ctx, { type: "compaction", ...draft.compaction, tokensBefore: before }).session.buildSessionProjection().messages;
1258
1138
  assertNativeToolRounds(kept);
1259
- return { draft: true, after: measure(kept), mode: draft.mode, compaction: draft.compaction, reserve, messages: kept };
1139
+ return { draft: true, after: measure(kept), compaction: draft.compaction, reserve, messages: kept };
1260
1140
  },
1261
1141
  });
1262
1142
  const project = (candidate) => candidate.kind === "cut"
@@ -1421,7 +1301,7 @@ export async function installCompaction(pi, options = {}) {
1421
1301
  fail(error, ctx);
1422
1302
  }
1423
1303
  });
1424
- return { close: async () => { semanticRequest++; recorder.stop("caller-close"); await semantic.close(); await Promise.allSettled([...semanticPending]); }, semanticRecall: semantic, setSemanticEnabled, semanticStatus, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1304
+ return { close: async () => { recorder.stop("caller-close"); }, state: stateFor, inspectState: (ctx) => ({ run: run, phase: run?.phase, calibrationIdentity: calibration.identity, pendingCut: view(ctx).pending }) };
1425
1305
  }
1426
1306
  function checkedInput(raw) { if (!Check(RecallInput, raw))
1427
1307
  throw new Error("Invalid recall input"); return structuredClone(raw); }
@@ -12,12 +12,12 @@ export function inspectIncident(records) {
12
12
  if (i.branchEntryIds?.length)
13
13
  manager.branch(i.branchEntryIds.at(-1));
14
14
  const ctx = { sessionManager: manager, cwd: '/offline-compaction-replay', model: { contextWindow: i.contextWindow } };
15
- const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary, operatorManual: i.operatorManual }, ctx, i.reserve, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
15
+ const draft = tuckObservedDraft(tuck, { branchEntries: manager.getBranch(), tokensBefore: i.tokensBefore, previousSummary: i.previousSummary }, ctx, i.reserve, messages => measurableConversationTokens(messages, ctx), {}, i.retainCurrentInput);
16
16
  const proposal = records.find(r => r.kind === 'proposal' && r.data?.details?.diagnosticReceipt?.id === i.receiptId)?.data;
17
17
  const matchesRecordedProposal = proposal && draft.compaction ? proposal.summary === draft.compaction.summary && proposal.firstKeptEntryId === draft.compaction.firstKeptEntryId : null;
18
- return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, semantic fidelity, persistence or transmission claim.' };
18
+ return { mode: 'deterministic-selection-replay', draft, receiptId: i.receiptId ?? null, matchesRecordedProposal, notice: 'Supplied permitted originals and resolved state only; no tools, inference, meaning preservation, persistence or transmission claim.' };
19
19
  });
20
- return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all semantic secrets.' };
20
+ return { build: DIAGNOSTIC_BUILD, records: records.length, results, notice: 'Prepared context is a public hook observation, not wire or provider history. Structural redaction does not detect all secrets conveyed by meaning.' };
21
21
  }
22
22
  export function readableIncident(records) {
23
23
  return '# Compaction incident\n\n' + JSON.stringify(inspectIncident(records), null, 2) + '\n\n' + records.map(r => `## ${r.kind} (${r.scope})${r.partial ? ' — PARTIAL' : ''}\n\n${JSON.stringify(r.data, null, 2)}`).join('\n\n');
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "d3c9d03a4fd2a19793701c4c043b680a24b0a5f219c4c3ab6f7c3a232feb333e";
3
+ export declare const DIAGNOSTIC_BUILD = "cf1509ac0cd19e83fc1fa7ab43c0639d57a02dac127a7e7639e79b9b00b58092";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -62,7 +62,7 @@ export interface IncidentRecord {
62
62
  partial: boolean;
63
63
  }
64
64
  /** A bounded clone. Budget is charged before every copy; forbidden fields are never traversed.
65
- * This is conservative structural/pattern redaction, not semantic secret detection. */
65
+ * This is conservative structural/pattern redaction, not detection of secrets conveyed by meaning. */
66
66
  export declare function boundedCopy(value: unknown, limit: number): {
67
67
  data: unknown;
68
68
  characters: number;
@@ -73,6 +73,7 @@ export declare function permittedEntries(entries: SessionEntry[], policy?: Recal
73
73
  partial: boolean;
74
74
  };
75
75
  export declare class IncidentRecorder {
76
+ private windowsFile?;
76
77
  private queue;
77
78
  private queued;
78
79
  private total;