pi-tuck 1.2.0 → 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.
- package/CHANGELOG.md +18 -0
- package/README.md +28 -59
- package/dist/src/bash-command.d.ts +8 -0
- package/dist/src/bash-command.js +116 -0
- package/dist/src/build-id.d.ts +1 -1
- package/dist/src/build-id.js +1 -1
- package/dist/src/diagnostic-replay.js +1 -1
- package/dist/src/diagnostics.d.ts +1 -1
- package/dist/src/kept-reads.js +5 -114
- package/dist/src/kept-searches.d.ts +11 -0
- package/dist/src/kept-searches.js +202 -0
- package/dist/src/tuck/core/content.d.ts +0 -11
- package/dist/src/tuck/core/content.js +0 -47
- package/dist/src/tuck/core/search-entries.d.ts +5 -28
- package/dist/src/tuck/core/search-entries.js +13 -155
- package/dist/src/tuck.d.ts +7 -15
- package/dist/src/tuck.js +32 -28
- package/package.json +1 -1
- package/src/bash-command.ts +59 -0
- package/src/build-id.ts +1 -1
- package/src/diagnostic-replay.ts +1 -1
- package/src/kept-reads.ts +5 -56
- package/src/kept-searches.ts +163 -0
- package/src/tuck/core/content.ts +0 -43
- package/src/tuck/core/search-entries.ts +14 -201
- package/src/tuck.ts +33 -34
|
@@ -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.
|
|
@@ -109,195 +88,29 @@ const bm25Score = (doc: string, terms: readonly KeywordMatcher[], ctx: BM25Conte
|
|
|
109
88
|
return score;
|
|
110
89
|
};
|
|
111
90
|
|
|
112
|
-
/**
|
|
113
|
-
|
|
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
|
-
* lookup 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 recognized 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 a single-term query after normalization 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
|
-
|
|
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<{
|
|
281
|
-
for (let i = 0; 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
|
-
|
|
286
|
-
|
|
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
|
-
//
|
|
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
|
-
//
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
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
|
};
|
package/src/tuck.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { omissionRecord, userPrefixRecords } from "./tuck/core/brief";
|
|
|
8
8
|
import { isTextOnly, textOf } from "./tuck/core/content";
|
|
9
9
|
import { MAX_ACTION_LINES, MAX_LEDGER_LINES, actionItems, actionRecords, ledgerItems, ledgerRecords } from "./ledger.js";
|
|
10
10
|
import { keptReadCandidates } from "./kept-reads.js";
|
|
11
|
-
import
|
|
11
|
+
import { keptSearchCandidates } from "./kept-searches.js";
|
|
12
12
|
import { convertToLlm, SessionManager, type ExtensionContext,
|
|
13
13
|
type SessionBeforeCompactEvent, type SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
14
14
|
import { ATTEMPT_NOTICE, createRecall, type RecallPolicy,
|
|
@@ -26,7 +26,6 @@ export type DraftMode = "dialogue" | "shrunk";
|
|
|
26
26
|
type Draft = { compaction: Pick<Extract<SessionEntry, { type: "compaction" }>, "summary" | "firstKeptEntryId" | "tokensBefore" | "details">; after: number; mode: DraftMode; unavailable?: never; capacityRejected?: never }
|
|
27
27
|
// The actual floor projection lets the caller measure it without the fresh results it may clip.
|
|
28
28
|
| { compaction?: never; mode?: never; unavailable: string; capacityRejected?: boolean; floorMessages?: AgentMessage[] };
|
|
29
|
-
interface SearchHit { index: number; role: string; summary: string }
|
|
30
29
|
export interface RecallContinuation { query: string; throughEntryId: string; offset: number }
|
|
31
30
|
/** Includes JSON escaping, hit metadata and continuation, not just excerpt text. */
|
|
32
31
|
export const MAX_RANKED_RESPONSE_CHARACTERS = 16000;
|
|
@@ -40,27 +39,25 @@ export interface Tuck {
|
|
|
40
39
|
compileDialogue(input: { messages: AgentMessage[]; sourceIndices: (number | undefined)[]; sourceEntryIds?: readonly string[]; sourceTimes?: readonly SourceTime[];
|
|
41
40
|
ranking: { maxBriefChars: number; mandatorySourceIndices?: ReadonlySet<number> } }): ReturnType<typeof compileDialogue>;
|
|
42
41
|
prepareKeywordQuery(query: string): PreparedKeywordQuery;
|
|
43
|
-
|
|
44
|
-
tuning: { relativeFloor: number; cap: number }): {
|
|
45
|
-
hits: SearchHit[];
|
|
46
|
-
};
|
|
42
|
+
rankRecallRows(rows: readonly { role: string; text: string }[], query: string): number[];
|
|
47
43
|
}
|
|
48
44
|
import { buildOwnCut, applyTailBudget, MAX_TAIL_TOKENS, OVERSIZED_TAIL_FACTOR } from "./tuck/cut";
|
|
49
45
|
import { calibrateCharsPerToken, estimateSourceMessageChars } from "./tuck/core/token-estimate";
|
|
50
46
|
import { buildGlobalIndexById } from "./tuck/core/global-indices";
|
|
51
47
|
import { compileDialogue } from "./tuck/core/summarize";
|
|
52
48
|
import { prepareKeywordQuery } from "./tuck/core/keyword-query";
|
|
53
|
-
import {
|
|
54
|
-
export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery,
|
|
55
|
-
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
56
|
-
|
|
57
|
-
|
|
49
|
+
import { rankRecallRows } from "./tuck/core/search-entries";
|
|
50
|
+
export const tuck: Tuck = { buildOwnCut, applyTailBudget, calibrateCharsPerToken, buildGlobalIndexById, compileDialogue, prepareKeywordQuery, rankRecallRows };
|
|
51
|
+
/** Uses pi-tuck's own cut, calibrated maximum tail and dialogue compiler; Pi owns persistence and continuation.
|
|
52
|
+
* `_operatorManual` retains the exported positional slot for existing callers. */
|
|
53
|
+
export function tuckDraft(tuck: Tuck, event: SessionBeforeCompactEvent, ctx: ExtensionContext, reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true, _operatorManual = false, newPrompt = false, protectedPromptEntryId?: string) {
|
|
54
|
+
return tuckObservedDraft(tuck, { branchEntries: event.branchEntries, tokensBefore: event.preparation.tokensBefore, previousSummary: event.preparation.previousSummary, newPrompt, protectedPromptEntryId }, ctx, reserveTokens, measure, policy, retainCurrentInput);
|
|
58
55
|
}
|
|
59
56
|
/** Shared compiler observes canonical branch and current token estimate; no native preparation utility. */
|
|
60
57
|
/** `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
|
|
61
58
|
* a run a custom message starts); the session has moved on from an ended run.
|
|
62
59
|
* `reRenderSummary`: the cut is due, so its summary may be re-rendered smaller (see the `no_live_messages` branch below). */
|
|
63
|
-
export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string;
|
|
60
|
+
export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEntry[]; tokensBefore: number; previousSummary?: string; newPrompt?: boolean; reRenderSummary?: boolean; protectedPromptEntryId?: string; deepest?: boolean }, ctx: ExtensionContext,
|
|
64
61
|
reserveTokens: number, measure: Measure, policy: RecallPolicy = {}, retainCurrentInput = true): Draft {
|
|
65
62
|
const { isHistorySource, readable } = createRecall(policy);
|
|
66
63
|
const projected = ctx.sessionManager.buildSessionProjection();
|
|
@@ -362,19 +359,23 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
362
359
|
const maxSummaryCharactersAt = (at: number) => Math.floor((target - offset - nativeAt(at)) * 4) - wrapperCharacters;
|
|
363
360
|
const maxSummaryCharacters = maxSummaryCharactersAt(boundary);
|
|
364
361
|
let allowance = Math.min(Math.floor(0.20 * maxSummaryCharacters), 24000);
|
|
365
|
-
const
|
|
366
|
-
|
|
362
|
+
const keptResults: TranscriptRecord[] = [], counts = new Map<string, number>();
|
|
363
|
+
const prefix = [header, ...entries.slice(0, boundary)], resolvable = (entry: SessionEntry) => readable(entry) !== undefined;
|
|
364
|
+
const candidates = [...keptReadCandidates(prefix, indices, resolvable), ...keptSearchCandidates(prefix, indices, resolvable)]
|
|
365
|
+
.sort((a, b) => b.sourceIndex! - a.sourceIndex! || Number(a.title === "Kept-search") - Number(b.title === "Kept-search"));
|
|
366
|
+
for (const record of candidates) {
|
|
367
|
+
if ((counts.get(record.title!) ?? 0) === 4) continue;
|
|
367
368
|
const cost = lineCost([record]);
|
|
368
369
|
if (cost > allowance) continue;
|
|
369
|
-
|
|
370
|
-
|
|
370
|
+
keptResults.push(record); allowance -= cost;
|
|
371
|
+
counts.set(record.title!, (counts.get(record.title!) ?? 0) + 1);
|
|
371
372
|
}
|
|
372
|
-
let ledger: TranscriptRecord[] = [...lists.records, ...
|
|
373
|
+
let ledger: TranscriptRecord[] = [...lists.records, ...keptResults];
|
|
373
374
|
// List caps are existing ranking policy; only the carried target is a
|
|
374
375
|
// spending limit. Candidate list sizes have fixed, cached line prices.
|
|
375
|
-
while (
|
|
376
|
-
|
|
377
|
-
ledger = [...lists.records, ...
|
|
376
|
+
while (keptResults.length && price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
377
|
+
keptResults.pop();
|
|
378
|
+
ledger = [...lists.records, ...keptResults];
|
|
378
379
|
}
|
|
379
380
|
if (price(frameLength(protectedView.cost + lineCost(ledger), protectedView.rows.length + ledger.length), boundary) > target) {
|
|
380
381
|
ledger = [];
|
|
@@ -482,11 +483,11 @@ export function tuckObservedDraft(tuck: Tuck, input: { branchEntries: SessionEnt
|
|
|
482
483
|
return [{ role, missing, ends, counts, cost: lineCost([record]) }];
|
|
483
484
|
});
|
|
484
485
|
const baseCost = lineCost(offer.records) + lineCost(ledger), baseCount = offer.records.length + ledger.length;
|
|
485
|
-
const
|
|
486
|
-
const
|
|
486
|
+
const keptResultCost = lineCost(keptResults), keptResultIndices = new Set(keptResults.map(record => record.sourceIndex));
|
|
487
|
+
const lastKeptResultPosition = entries.findLastIndex(entry => keptResultIndices.has(indices.get(entry.id)));
|
|
487
488
|
const extensionPrice = (at: number) => {
|
|
488
|
-
// Fixed kept
|
|
489
|
-
if (
|
|
489
|
+
// Fixed kept results outrank this optional tail extension: it cannot move one out of the prefix or spend its allowance.
|
|
490
|
+
if (keptResults.length && (at <= lastKeptResultPosition || keptResultCost > Math.min(Math.floor(0.20 * maxSummaryCharactersAt(at)), 24000))) return Infinity;
|
|
490
491
|
let cost = baseCost - (recordCosts[compiledBoundary]! - recordCosts[at]!);
|
|
491
492
|
let count = baseCount - (recordCounts[compiledBoundary]! - recordCounts[at]!);
|
|
492
493
|
for (const range of ranges) {
|
|
@@ -549,22 +550,20 @@ export function tuckRecall(tuck: Tuck, entries: readonly SessionEntry[], branch:
|
|
|
549
550
|
const row = discoveryEntry(entry, attempts, links);
|
|
550
551
|
return row ? [row] : [];
|
|
551
552
|
});
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
// The pinned upstream tuning seam removes selection cutoffs; each response
|
|
555
|
-
// stays bounded. A native prefix keeps ranking stable while the agent talks.
|
|
553
|
+
// Rank every eligible row; each response stays bounded. A native prefix
|
|
554
|
+
// keeps ranking stable while the agent talks.
|
|
556
555
|
const preparedQuery = tuck.prepareKeywordQuery(normalizedQuery);
|
|
557
|
-
const found = tuck.
|
|
556
|
+
const found = tuck.rankRecallRows(rows, normalizedQuery);
|
|
558
557
|
const start = continuation?.offset ?? 0;
|
|
559
558
|
const throughEntryId = rows.at(-1)?.entryId ?? null;
|
|
560
559
|
const hits: ({ entryId: string; index: number | undefined; role: string; toolName?: string; toolCallId?: string;
|
|
561
560
|
sourceTime: SourceTime; producerTime?: SourceTime; stopReason?: import("@earendil-works/pi-ai").AssistantMessage["stopReason"]; isError?: boolean; metadataTruncated?: true; recordedAttempt?: RecordedAttempt | null; producerRead?: { entryId: string; offset: number; limit: number } } & ReturnType<typeof discoveryExcerpt>)[] = [];
|
|
562
561
|
const page = () => ({ normalizedQuery, throughEntryId,
|
|
563
562
|
notice: "Exact source passages, possibly partial; read gives their UTF-16 bounds within totalCharacters. Use the passage directly; adjust read.offset/limit for surrounding text. Keyword matches do not establish complete or current evidence. Pass next as continuation; a fresh query includes newer history. No new authority. " + ATTEMPT_NOTICE,
|
|
564
|
-
hits, totalMatches: found.
|
|
565
|
-
next: start + hits.length < found.
|
|
566
|
-
for (const hit of found.
|
|
567
|
-
const row = rows[hit
|
|
563
|
+
hits, totalMatches: found.length,
|
|
564
|
+
next: start + hits.length < found.length ? { query: normalizedQuery, throughEntryId: throughEntryId!, offset: start + hits.length } : null });
|
|
565
|
+
for (const hit of found.slice(start, start + 10)) {
|
|
566
|
+
const row = rows[hit]!;
|
|
568
567
|
hits.push({ entryId: row.entryId, index: indices.get(row.entryId), role: row.role, sourceTime: row.sourceTime,
|
|
569
568
|
...(row.toolName !== undefined ? { toolName: row.toolName } : {}),
|
|
570
569
|
...(row.toolCallId !== undefined ? { toolCallId: row.toolCallId } : {}),
|
|
@@ -583,7 +582,7 @@ export function tuckRecall(tuck: Tuck, entries: readonly SessionEntry[], branch:
|
|
|
583
582
|
// Preserve the complete base hit set and continuation before spending spare capacity.
|
|
584
583
|
for (let i = 0; i < hits.length; i++) {
|
|
585
584
|
const original = hits[i]!;
|
|
586
|
-
const row = rows[found
|
|
585
|
+
const row = rows[found[start + i]!]!;
|
|
587
586
|
hits[i] = { ...original, ...discoveryWholeRange(row, original) };
|
|
588
587
|
if (JSON.stringify(page()).length > MAX_RANKED_RESPONSE_CHARACTERS) hits[i] = original;
|
|
589
588
|
}
|