pi-tuck 1.1.3 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/index.d.ts +2 -6
  3. package/dist/index.js +16 -111
  4. package/dist/src/build-id.d.ts +1 -1
  5. package/dist/src/build-id.js +1 -1
  6. package/dist/src/compaction.d.ts +2 -103
  7. package/dist/src/compaction.js +20 -140
  8. package/dist/src/diagnostic-replay.js +2 -2
  9. package/dist/src/diagnostics.d.ts +3 -2
  10. package/dist/src/diagnostics.js +30 -9
  11. package/dist/src/history-tools.js +3 -3
  12. package/dist/src/kept-reads.d.ts +2 -2
  13. package/dist/src/kept-reads.js +144 -8
  14. package/dist/src/ledger.d.ts +1 -1
  15. package/dist/src/ledger.js +5 -3
  16. package/dist/src/legacy-cleanup.d.ts +3 -0
  17. package/dist/src/legacy-cleanup.js +190 -0
  18. package/dist/src/notify.d.ts +3 -0
  19. package/dist/src/notify.js +13 -0
  20. package/dist/src/omissions.d.ts +1 -1
  21. package/dist/src/omissions.js +3 -3
  22. package/dist/src/path-key.d.ts +3 -0
  23. package/dist/src/path-key.js +8 -0
  24. package/dist/src/request-capacity.js +1 -1
  25. package/dist/src/run.d.ts +1 -3
  26. package/dist/src/run.js +3 -5
  27. package/dist/src/source-export.d.ts +1 -1
  28. package/dist/src/source-export.js +1 -1
  29. package/dist/src/status.d.ts +0 -6
  30. package/dist/src/status.js +1 -6
  31. package/dist/src/tuck/core/content.js +6 -9
  32. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  33. package/dist/src/tuck/core/keyword-query.js +1 -1
  34. package/dist/src/tuck/core/search-entries.js +5 -5
  35. package/dist/src/tuck/core/transcript.js +2 -1
  36. package/dist/src/tuck.js +390 -394
  37. package/dist/src/windows-private-storage.d.ts +9 -0
  38. package/dist/src/windows-private-storage.js +90 -0
  39. package/index.ts +18 -82
  40. package/package.json +5 -8
  41. package/src/build-id.ts +1 -1
  42. package/src/compaction.ts +19 -107
  43. package/src/diagnostic-replay.ts +2 -2
  44. package/src/diagnostics.ts +24 -9
  45. package/src/history-tools.ts +3 -3
  46. package/src/kept-reads.ts +78 -10
  47. package/src/ledger.ts +5 -3
  48. package/src/legacy-cleanup.ts +134 -0
  49. package/src/notify.ts +10 -0
  50. package/src/omissions.ts +3 -3
  51. package/src/path-key.ts +9 -0
  52. package/src/request-capacity.ts +1 -1
  53. package/src/run.ts +4 -6
  54. package/src/source-export.ts +1 -1
  55. package/src/status.ts +1 -10
  56. package/src/tuck/core/content.ts +5 -10
  57. package/src/tuck/core/keyword-query.ts +2 -2
  58. package/src/tuck/core/search-entries.ts +5 -5
  59. package/src/tuck/core/transcript.ts +2 -1
  60. package/src/tuck.ts +329 -335
  61. package/src/windows-private-storage.ts +94 -0
  62. package/dist/src/assets.d.ts +0 -58
  63. package/dist/src/assets.js +0 -80
  64. package/dist/src/eligibility-cache.d.ts +0 -19
  65. package/dist/src/eligibility-cache.js +0 -33
  66. package/dist/src/semantic-recall.d.ts +0 -422
  67. package/dist/src/semantic-recall.js +0 -1386
  68. package/dist/src/setup.d.ts +0 -3
  69. package/dist/src/setup.js +0 -191
  70. package/scripts/eg2-runtime.py +0 -307
  71. package/scripts/provision-eg2.py +0 -139
  72. package/scripts/semantic-worker.py +0 -234
  73. package/src/assets.ts +0 -92
  74. package/src/eligibility-cache.ts +0 -43
  75. package/src/semantic-recall.ts +0 -592
  76. package/src/setup.ts +0 -163
@@ -1,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); }
@@ -15,9 +15,9 @@ export function inspectIncident(records) {
15
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);
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 = "f653b17921c5383797b70c8962152e6b4537a7769e05118290fc34d492a06ec1";
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;
@@ -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[];