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,26 +1,5 @@
1
- import { isLookupTool } from "./recall-operation";
2
- import type { Message } from "@earendil-works/pi-ai";
3
- import type { RenderedEntry } from "./render-entries";
4
- import { textOf, extractToolCallArgsText, clip } from "./content";
5
1
  import { prepareKeywordQuery, type KeywordMatcher } from "./keyword-query";
6
2
 
7
- export interface SearchHit extends RenderedEntry {
8
- /** Number of query terms matched (for ranking) */
9
- matchCount?: number;
10
- }
11
-
12
- /**
13
- * Result of a search, with enough metadata for a caller to report truncation
14
- * honestly (see `searchEntriesDetailed`).
15
- */
16
- export interface SearchResult {
17
- hits: SearchHit[];
18
- /** Genuine matches found before the hard cap was applied (after any
19
- * relative-floor noise filtering). May exceed `hits.length`. */
20
- totalBeforeCap: number;
21
- /** True when the hard cap discarded matches (`totalBeforeCap > hits.length`). */
22
- truncated: boolean;
23
- }
24
3
  /**
25
4
  * Wall-clock budget for one search. A normal query over 400 entries takes ~10ms.
26
5
  * Aborting loudly beats returning a silently truncated match count.
@@ -53,7 +32,7 @@ const countMatches = (hay: string, terms: readonly KeywordMatcher[]): number =>
53
32
  const BM25_K = 1.2;
54
33
  const BM25_B = 0.75;
55
34
 
56
- /** Count non-overlapping literal occurrences with the prepared matcher's semantics. */
35
+ /** Count non-overlapping literal occurrences with the prepared matcher's rules. */
57
36
  const termFreq = (text: string, matcher: KeywordMatcher): number => {
58
37
  let count = 0, offset = 0;
59
38
  for (;;) {
@@ -109,195 +88,29 @@ const bm25Score = (doc: string, terms: readonly KeywordMatcher[], ctx: BM25Conte
109
88
  return score;
110
89
  };
111
90
 
112
- /**
113
- * Aggregate character budget for ALL toolCall arguments appended to one
114
- * message's searchable text — a single shared budget across every toolCall
115
- * in the message, not per call, so N toolCalls can't multiply the bound and
116
- * make one message's contribution to the BM25 doc corpus unbounded.
117
- *
118
- * Head-only cap: content past this budget is not indexed via toolCall
119
- * arguments at all. This is an honest tradeoff, not a proxy for full
120
- * coverage — a Write/Edit tool result commonly only acknowledges success
121
- * (e.g. "wrote 400 lines"), so a fact buried past the cap in a giant
122
- * argument is not guaranteed to be searchable elsewhere either.
123
- */
124
- const TOOL_ARGS_BUDGET = 2000;
125
-
126
- /**
127
- * Tool name of the recall tool itself (src/tools/recall.ts). A search
128
- * operation must not match its own query or its own prior output: the
129
- * tuck_recall or tuck_search invocation is persisted as an ordinary assistant toolCall (its
130
- * `{ query }` argument, excluded below in `toolCallArgsText`) followed by an
131
- * ordinary toolResult message (its `N matches for "<query>"` text, excluded
132
- * in `fullText`) — without both exclusions a repeated query keeps matching
133
- * its own prior invocation/output and the hit count grows on every search.
134
- * This is a targeted introspection invariant for the two named history lookup tools, not a
135
- * general allowlist/blocklist over tool names or tool results.
136
- */
137
-
138
-
139
- /** Text of every toolCall's arguments in a message's content, for search —
140
- * bounded once, in aggregate, by TOOL_ARGS_BUDGET. Excludes the recall
141
- * tool's own arguments (see isLookupTool). */
142
- const toolCallArgsText = (content: Message["content"]): string => {
143
- if (!content || typeof content === "string") return "";
144
- const raw = content
145
- .filter((part) => part.type === "toolCall")
146
- .filter((part) => !isLookupTool(part.name ?? ""))
147
- .map((part) => extractToolCallArgsText(part.arguments))
148
- .filter(Boolean)
149
- .join("\n");
150
- return clip(raw, TOOL_ARGS_BUDGET);
151
- };
152
-
153
- /**
154
- * Build full searchable text for a message: text parts plus toolCall
155
- * arguments (bash command, Write/Edit content, etc.) so a match that only
156
- * exists in a tool call's arguments is still findable.
157
- *
158
- * The recall tool's own toolResult is excluded (searchable text ""): it
159
- * echoes back `N matches for "<query>"` from the *previous* recall call, so
160
- * indexing it would make a repeated query self-match and grow with every
161
- * search. This only affects search indexing — browse/no-query returns
162
- * entries before fullText runs (see `searchEntriesDetailed`), and #N expand reads
163
- * the message/entry directly, not through this function, so the toolResult
164
- * is still fully visible there.
165
- */
166
- const fullText = (msg: Message): string => {
167
- if ((msg as any).role === "bashExecution") {
168
- return `${(msg as any).command ?? ""} ${(msg as any).output ?? ""}`;
169
- }
170
- if (msg.role === "toolResult" && isLookupTool(msg.toolName ?? "")) {
171
- return "";
172
- }
173
- const text = textOf(msg.content);
174
- const argsText = toolCallArgsText(msg.content);
175
- return argsText ? `${text}\n${argsText}` : text;
176
- };
177
-
178
- /**
179
- * Relative BM25 noise floor for MULTI-TERM natural-language queries only:
180
- * after sorting by score, drop hits scoring below this fraction of the top
181
- * score. Relative (not absolute) because BM25 magnitudes vary with corpus
182
- * size and document length, so a fixed score threshold would behave
183
- * inconsistently across short vs. long sessions.
184
- *
185
- * Applied only when the query has >=2 DISTINCT effective terms after
186
- * stopword filtering and case/duplicate normalization (see the
187
- * `effectiveTermCount >= 2` gate below `searchEntriesDetailed` uses before
188
- * calling `applyRelativeFloor`). Distinct, not raw count: "auth auth" or
189
- * "Auth AUTH" is semantically a single-term query and must bypass the floor
190
- * like any other single term — repeating or casing a word doesn't turn it
191
- * into the multi-term OR-tail noise this floor targets. The normalization is
192
- * gate-only; it doesn't change `terms` or the BM25 scoring itself, which
193
- * already matches case-insensitively. For a genuine single term, every hit's
194
- * occurrence already satisfies the whole query — its BM25 score differences
195
- * reflect term frequency and document length, not multi-term OR-tail noise,
196
- * so filtering by it there risks real matches for no corresponding noise
197
- * reduction. The inherited floor is retained unchanged; private-corpus
198
- * observations and their unavailable harness are not public quality evidence.
199
- *
200
- * The top-scoring hit always survives by construction: its own score
201
- * always satisfies `score >= topScore * floor`
202
- * for any floor <= 1, so a non-empty scored[] can never be filtered to zero.
203
- */
204
- const BM25_RELATIVE_FLOOR = 0.2;
205
-
206
- /**
207
- * Hard cap on total SEARCH results, applied after the relative floor so pagination stays bounded regardless
208
- * of how noisy or broad a query is.
209
- *
210
- * The inherited cap is retained unchanged. This is a resource bound, not
211
- * a claim about retrieval quality on an undistributed corpus.
212
- */
213
- const SEARCH_RESULT_CAP = 50;
214
-
215
- /**
216
- * Tuning overrides for `searchEntriesDetailed`; without them a search uses `BM25_RELATIVE_FLOOR` and
217
- * `SEARCH_RESULT_CAP`. `tuckRecall` passes a floor of 0 and a cap of every row, because it pages its own responses.
218
- */
219
- export interface SearchTuning {
220
- relativeFloor?: number;
221
- cap?: number;
222
- }
223
-
224
- /** Drop scored hits below `floor` of the top score. The top hit's own score
225
- * always passes (score >= score * floor for floor <= 1), so this can never
226
- * turn a non-empty `scored` into an empty result. */
227
- const applyRelativeFloor = (
228
- scored: Array<{ hit: SearchHit; score: number }>,
229
- floor: number,
230
- ): Array<{ hit: SearchHit; score: number }> => {
231
- if (scored.length === 0) return scored;
232
- const topScore = scored[0].score;
233
- if (topScore <= 0) return scored;
234
- return scored.filter((s) => s.score >= topScore * floor);
235
- };
236
-
237
- /**
238
- * Bound `hits` to `cap` entries, reporting the pre-cap count so callers can
239
- * signal truncation honestly instead of understating "total matches".
240
- *
241
- * Order preserved, never re-sorted: hits are already highest-score-first, so
242
- * `slice(0, cap)` keeps the top `cap` hits.
243
- */
244
- const capHits = (hits: SearchHit[], cap: number): SearchResult => {
245
- const totalBeforeCap = hits.length;
246
- const capped = totalBeforeCap > cap ? hits.slice(0, cap) : hits;
247
- return { hits: capped, totalBeforeCap, truncated: capped.length < totalBeforeCap };
248
- };
249
-
250
- /** BM25 keyword search with truncation metadata. */
251
- export const searchEntriesDetailed = (
252
- entries: RenderedEntry[],
253
- messages: Message[],
254
- query?: string,
255
- tuning?: SearchTuning,
256
- ): SearchResult => {
257
- if (!query?.trim()) return { hits: entries, totalBeforeCap: entries.length, truncated: false };
258
-
259
- const relativeFloor = tuning?.relativeFloor ?? BM25_RELATIVE_FLOOR;
260
- const cap = tuning?.cap ?? SEARCH_RESULT_CAP;
91
+ /** Rank already-eligible recall rows; filtering and paging belong to the caller. */
92
+ export const rankRecallRows = (rows: readonly { role: string; text: string }[], query: string): number[] => {
261
93
  const rawQuery = query.trim();
262
94
  const checkBudget = startBudget();
263
-
264
- // Natural language / multi-word query: BM25 scoring
265
95
  const prepared = prepareKeywordQuery(rawQuery);
266
96
  const terms = prepared.terms;
267
-
268
- // Build all docs for BM25 context
269
- const docs: string[] = [];
270
- for (let i = 0; i < entries.length; i++) {
271
- const e = entries[i];
272
- const msg = messages[i];
273
- const text = msg ? fullText(msg) : e.summary;
274
- const filePart = e.files?.join(" ") ?? "";
275
- docs.push(`${e.role} ${text} ${filePart}`);
276
- }
277
-
97
+ // Preserve the role prefix and trailing space of the original BM25 documents.
98
+ const docs = rows.map((row) => `${row.role} ${row.text} `);
278
99
  const ctx = buildBM25Context(docs, terms, checkBudget);
279
100
 
280
- const scored: Array<{ hit: SearchHit; score: number }> = [];
281
- for (let i = 0; i < entries.length; i++) {
101
+ const scored: Array<{ index: number; score: number }> = [];
102
+ for (let i = 0; i < rows.length; i++) {
282
103
  checkBudget();
283
- const e = entries[i];
284
104
  const hay = docs[i];
285
- const mc = countMatches(hay, terms);
286
- if (mc === 0) continue;
287
- scored.push({ hit: { ...e, matchCount: mc }, score: bm25Score(hay, terms, ctx) });
105
+ if (countMatches(hay, terms) === 0) continue;
106
+ scored.push({ index: i, score: bm25Score(hay, terms, ctx) });
288
107
  }
289
108
 
290
- // Sort by BM25 score desc, then drop the noisy long tail relative to the
291
- // top score (multi-term queries only — see BM25_RELATIVE_FLOOR), then
292
- // apply the hard cap.
109
+ // Stable sort keeps source order for tied scores, including duplicate terms.
293
110
  scored.sort((a, b) => b.score - a.score);
294
- // Gate on DISTINCT normalized terms, not raw term count: "auth auth" or
295
- // "Auth AUTH" is semantically a single-term query and must bypass the
296
- // floor like any other single term — repeating/casing a word doesn't turn
297
- // it into the multi-term OR-tail noise this floor targets. This is a
298
- // gate-only normalization; it does not change `terms` itself or the BM25
299
- // scoring above, which already matches case-insensitively.
300
- const effectiveTermCount = prepared.coverageTerms.length;
301
- const floored = effectiveTermCount >= 2 ? applyRelativeFloor(scored, relativeFloor) : scored;
302
- return capHits(floored.map((s) => s.hit), cap);
111
+ // Duplicate terms can make IDF negative. Preserve the original zero-floor
112
+ // selection when a multi-term query also has a positive top score.
113
+ const ranked = prepared.coverageTerms.length >= 2 && (scored[0]?.score ?? 0) > 0
114
+ ? scored.filter((s) => s.score >= 0) : scored;
115
+ return ranked.map((s) => s.index);
303
116
  };
@@ -69,7 +69,8 @@ export const splitSummary = (summary: string): { body: string; closing: string;
69
69
  if (at < 0) return undefined;
70
70
  // A summary saved before the rename keeps its records byte for byte (their lengths are checked); only its closing is pointed at the
71
71
  // tools the model has now.
72
- const closing = header === LEGACY_TRANSCRIPT_HEADER ? summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_search") : summary.slice(at);
72
+ const closing = summary.slice(at).replaceAll("vcc_recall", "tuck_recall").replaceAll("vcc_search", "tuck_recall")
73
+ .replaceAll("tuck_search", "tuck_recall").replaceAll("tuck_recall or tuck_recall", "tuck_recall");
73
74
  return { body: summary.slice(header.length + 1, at), closing, version: header === TRANSCRIPT_HEADER ? 2 : 1 };
74
75
  };
75
76
  const LEGACY_RECEIPT_RANGE_NOTICE = RECEIPT_RANGE_NOTICE.replace("tuck_recall", "vcc_recall");