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
@@ -1,5 +1,3 @@
1
- import { isLookupTool } from "./recall-operation.js";
2
- import { textOf, extractToolCallArgsText, clip } from "./content.js";
3
1
  import { prepareKeywordQuery } from "./keyword-query.js";
4
2
  /**
5
3
  * Wall-clock budget for one search. A normal query over 400 entries takes ~10ms.
@@ -26,7 +24,7 @@ const countMatches = (hay, terms) => terms.reduce((count, term) => count + Numbe
26
24
  // ── BM25-lite scoring ──
27
25
  const BM25_K = 1.2;
28
26
  const BM25_B = 0.75;
29
- /** Count non-overlapping literal occurrences with the prepared matcher's semantics. */
27
+ /** Count non-overlapping literal occurrences with the prepared matcher's rules. */
30
28
  const termFreq = (text, matcher) => {
31
29
  let count = 0, offset = 0;
32
30
  for (;;) {
@@ -70,168 +68,28 @@ const bm25Score = (doc, terms, ctx) => {
70
68
  }
71
69
  return score;
72
70
  };
73
- /**
74
- * Aggregate character budget for ALL toolCall arguments appended to one
75
- * message's searchable text — a single shared budget across every toolCall
76
- * in the message, not per call, so N toolCalls can't multiply the bound and
77
- * make one message's contribution to the BM25 doc corpus unbounded.
78
- *
79
- * Head-only cap: content past this budget is not indexed via toolCall
80
- * arguments at all. This is an honest tradeoff, not a proxy for full
81
- * coverage — a Write/Edit tool result commonly only acknowledges success
82
- * (e.g. "wrote 400 lines"), so a fact buried past the cap in a giant
83
- * argument is not guaranteed to be searchable elsewhere either.
84
- */
85
- const TOOL_ARGS_BUDGET = 2000;
86
- /**
87
- * Tool name of the recall tool itself (src/tools/recall.ts). A search
88
- * operation must not match its own query or its own prior output: the
89
- * tuck_recall or tuck_search invocation is persisted as an ordinary assistant toolCall (its
90
- * `{ query }` argument, excluded below in `toolCallArgsText`) followed by an
91
- * ordinary toolResult message (its `N matches for "<query>"` text, excluded
92
- * in `fullText`) — without both exclusions a repeated query keeps matching
93
- * its own prior invocation/output and the hit count grows on every search.
94
- * This is a targeted introspection invariant for the two named history lookup tools, not a
95
- * general allowlist/blocklist over tool names or tool results.
96
- */
97
- /** Text of every toolCall's arguments in a message's content, for search —
98
- * bounded once, in aggregate, by TOOL_ARGS_BUDGET. Excludes the recall
99
- * tool's own arguments (see isLookupTool). */
100
- const toolCallArgsText = (content) => {
101
- if (!content || typeof content === "string")
102
- return "";
103
- const raw = content
104
- .filter((part) => part.type === "toolCall")
105
- .filter((part) => !isLookupTool(part.name ?? ""))
106
- .map((part) => extractToolCallArgsText(part.arguments))
107
- .filter(Boolean)
108
- .join("\n");
109
- return clip(raw, TOOL_ARGS_BUDGET);
110
- };
111
- /**
112
- * Build full searchable text for a message: text parts plus toolCall
113
- * arguments (bash command, Write/Edit content, etc.) so a match that only
114
- * exists in a tool call's arguments is still findable.
115
- *
116
- * The recall tool's own toolResult is excluded (searchable text ""): it
117
- * echoes back `N matches for "<query>"` from the *previous* recall call, so
118
- * indexing it would make a repeated query self-match and grow with every
119
- * search. This only affects search indexing — browse/no-query returns
120
- * entries before fullText runs (see `searchEntriesDetailed`), and #N expand reads
121
- * the message/entry directly, not through this function, so the toolResult
122
- * is still fully visible there.
123
- */
124
- const fullText = (msg) => {
125
- if (msg.role === "bashExecution") {
126
- return `${msg.command ?? ""} ${msg.output ?? ""}`;
127
- }
128
- if (msg.role === "toolResult" && isLookupTool(msg.toolName ?? "")) {
129
- return "";
130
- }
131
- const text = textOf(msg.content);
132
- const argsText = toolCallArgsText(msg.content);
133
- return argsText ? `${text}\n${argsText}` : text;
134
- };
135
- /**
136
- * Relative BM25 noise floor for MULTI-TERM natural-language queries only:
137
- * after sorting by score, drop hits scoring below this fraction of the top
138
- * score. Relative (not absolute) because BM25 magnitudes vary with corpus
139
- * size and document length, so a fixed score threshold would behave
140
- * inconsistently across short vs. long sessions.
141
- *
142
- * Applied only when the query has >=2 DISTINCT effective terms after
143
- * stopword filtering and case/duplicate normalization (see the
144
- * `effectiveTermCount >= 2` gate below `searchEntriesDetailed` uses before
145
- * calling `applyRelativeFloor`). Distinct, not raw count: "auth auth" or
146
- * "Auth AUTH" is semantically a single-term query and must bypass the floor
147
- * like any other single term — repeating or casing a word doesn't turn it
148
- * into the multi-term OR-tail noise this floor targets. The normalization is
149
- * gate-only; it doesn't change `terms` or the BM25 scoring itself, which
150
- * already matches case-insensitively. For a genuine single term, every hit's
151
- * occurrence already satisfies the whole query — its BM25 score differences
152
- * reflect term frequency and document length, not multi-term OR-tail noise,
153
- * so filtering by it there risks real matches for no corresponding noise
154
- * reduction. The inherited floor is retained unchanged; private-corpus
155
- * observations and their unavailable harness are not public quality evidence.
156
- *
157
- * The top-scoring hit always survives by construction: its own score
158
- * always satisfies `score >= topScore * floor`
159
- * for any floor <= 1, so a non-empty scored[] can never be filtered to zero.
160
- */
161
- const BM25_RELATIVE_FLOOR = 0.2;
162
- /**
163
- * Hard cap on total SEARCH results, applied after the relative floor so pagination stays bounded regardless
164
- * of how noisy or broad a query is.
165
- *
166
- * The inherited cap is retained unchanged. This is a resource bound, not
167
- * a claim about retrieval quality on an undistributed corpus.
168
- */
169
- const SEARCH_RESULT_CAP = 50;
170
- /** Drop scored hits below `floor` of the top score. The top hit's own score
171
- * always passes (score >= score * floor for floor <= 1), so this can never
172
- * turn a non-empty `scored` into an empty result. */
173
- const applyRelativeFloor = (scored, floor) => {
174
- if (scored.length === 0)
175
- return scored;
176
- const topScore = scored[0].score;
177
- if (topScore <= 0)
178
- return scored;
179
- return scored.filter((s) => s.score >= topScore * floor);
180
- };
181
- /**
182
- * Bound `hits` to `cap` entries, reporting the pre-cap count so callers can
183
- * signal truncation honestly instead of understating "total matches".
184
- *
185
- * Order preserved, never re-sorted: hits are already highest-score-first, so
186
- * `slice(0, cap)` keeps the top `cap` hits.
187
- */
188
- const capHits = (hits, cap) => {
189
- const totalBeforeCap = hits.length;
190
- const capped = totalBeforeCap > cap ? hits.slice(0, cap) : hits;
191
- return { hits: capped, totalBeforeCap, truncated: capped.length < totalBeforeCap };
192
- };
193
- /** BM25 keyword search with truncation metadata. */
194
- export const searchEntriesDetailed = (entries, messages, query, tuning) => {
195
- if (!query?.trim())
196
- return { hits: entries, totalBeforeCap: entries.length, truncated: false };
197
- const relativeFloor = tuning?.relativeFloor ?? BM25_RELATIVE_FLOOR;
198
- const cap = tuning?.cap ?? SEARCH_RESULT_CAP;
71
+ /** Rank already-eligible recall rows; filtering and paging belong to the caller. */
72
+ export const rankRecallRows = (rows, query) => {
199
73
  const rawQuery = query.trim();
200
74
  const checkBudget = startBudget();
201
- // Natural language / multi-word query: BM25 scoring
202
75
  const prepared = prepareKeywordQuery(rawQuery);
203
76
  const terms = prepared.terms;
204
- // Build all docs for BM25 context
205
- const docs = [];
206
- for (let i = 0; i < entries.length; i++) {
207
- const e = entries[i];
208
- const msg = messages[i];
209
- const text = msg ? fullText(msg) : e.summary;
210
- const filePart = e.files?.join(" ") ?? "";
211
- docs.push(`${e.role} ${text} ${filePart}`);
212
- }
77
+ // Preserve the role prefix and trailing space of the original BM25 documents.
78
+ const docs = rows.map((row) => `${row.role} ${row.text} `);
213
79
  const ctx = buildBM25Context(docs, terms, checkBudget);
214
80
  const scored = [];
215
- for (let i = 0; i < entries.length; i++) {
81
+ for (let i = 0; i < rows.length; i++) {
216
82
  checkBudget();
217
- const e = entries[i];
218
83
  const hay = docs[i];
219
- const mc = countMatches(hay, terms);
220
- if (mc === 0)
84
+ if (countMatches(hay, terms) === 0)
221
85
  continue;
222
- scored.push({ hit: { ...e, matchCount: mc }, score: bm25Score(hay, terms, ctx) });
86
+ scored.push({ index: i, score: bm25Score(hay, terms, ctx) });
223
87
  }
224
- // Sort by BM25 score desc, then drop the noisy long tail relative to the
225
- // top score (multi-term queries only — see BM25_RELATIVE_FLOOR), then
226
- // apply the hard cap.
88
+ // Stable sort keeps source order for tied scores, including duplicate terms.
227
89
  scored.sort((a, b) => b.score - a.score);
228
- // Gate on DISTINCT normalized terms, not raw term count: "auth auth" or
229
- // "Auth AUTH" is semantically a single-term query and must bypass the
230
- // floor like any other single term — repeating/casing a word doesn't turn
231
- // it into the multi-term OR-tail noise this floor targets. This is a
232
- // gate-only normalization; it does not change `terms` itself or the BM25
233
- // scoring above, which already matches case-insensitively.
234
- const effectiveTermCount = prepared.coverageTerms.length;
235
- const floored = effectiveTermCount >= 2 ? applyRelativeFloor(scored, relativeFloor) : scored;
236
- return capHits(floored.map((s) => s.hit), cap);
90
+ // Duplicate terms can make IDF negative. Preserve the original zero-floor
91
+ // selection when a multi-term query also has a positive top score.
92
+ const ranked = prepared.coverageTerms.length >= 2 && (scored[0]?.score ?? 0) > 0
93
+ ? scored.filter((s) => s.score >= 0) : scored;
94
+ return ranked.map((s) => s.index);
237
95
  };
@@ -44,7 +44,8 @@ export const splitSummary = (summary) => {
44
44
  return undefined;
45
45
  // A summary saved before the rename keeps its records byte for byte (their lengths are checked); only its closing is pointed at the
46
46
  // tools the model has now.
47
- const closing = header === LEGACY_TRANSCRIPT_HEADER ? summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_search") : summary.slice(at);
47
+ const closing = summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_recall")
48
+ .replaceAll("tuck_search", "tuck_recall").replaceAll("tuck_recall or tuck_recall", "tuck_recall");
48
49
  return { body: summary.slice(header.length + 1, at), closing, version: header === TRANSCRIPT_HEADER ? 2 : 1 };
49
50
  };
50
51
  const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall", "vcc_recall");
@@ -1,5 +1,4 @@
1
1
  import { type SourceTime } from "./tuck/core/source-time.js";
2
- import type { Message } from "@earendil-works/pi-ai";
3
2
  import { convertToLlm, type ExtensionContext, type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
4
3
  import { type RecallPolicy, type PreparedKeywordQuery, type RecordedAttempt, type RecallOptions } from "./recall.js";
5
4
  type AgentMessage = Parameters<typeof convertToLlm>[0][number];
@@ -26,11 +25,6 @@ type Draft = {
26
25
  capacityRejected?: boolean;
27
26
  floorMessages?: AgentMessage[];
28
27
  };
29
- interface SearchHit {
30
- index: number;
31
- role: string;
32
- summary: string;
33
- }
34
28
  export interface RecallContinuation {
35
29
  query: string;
36
30
  throughEntryId: string;
@@ -64,17 +58,16 @@ export interface Tuck {
64
58
  };
65
59
  }): ReturnType<typeof compileDialogue>;
66
60
  prepareKeywordQuery(query: string): PreparedKeywordQuery;
67
- searchEntriesDetailed(entries: SearchHit[], messages: Message[], query: string, tuning: {
68
- relativeFloor: number;
69
- cap: number;
70
- }): {
71
- hits: SearchHit[];
72
- };
61
+ rankRecallRows(rows: readonly {
62
+ role: string;
63
+ text: string;
64
+ }[], query: string): number[];
73
65
  }
74
66
  import { compileDialogue } from "./tuck/core/summarize.js";
75
67
  export declare const tuck: Tuck;
76
- /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation. */
77
- export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string): Draft;
68
+ /** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
69
+ * `_operatorManual` retains the exported positional slot for existing callers. */
70
+ export declare function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy?: RecallPolicy, retainCurrentInput?: boolean, _operatorManual?: boolean, newPrompt?: boolean, protectedPromptEntryId?: string): Draft;
78
71
  /** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
79
72
  /** `newPrompt`: the cut is planned for a run that has not begun (a prompt Pi has not appended yet, an operator's manual cut, Pi's own cut before
80
73
  * a run a custom message starts); the session has moved on from an ended run.
@@ -83,7 +76,6 @@ export declare function tuckObservedDraft(tuck: Tuck, input: {
83
76
  branchEntries: SessionEntry[];
84
77
  tokensBefore: number;
85
78
  previousSummary?: string;
86
- operatorManual?: boolean;
87
79
  newPrompt?: boolean;
88
80
  reRenderSummary?: boolean;
89
81
  protectedPromptEntryId?: string;