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
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SessionEntry, SessionHeader } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { TranscriptRecord } from "./tuck/core/transcript.js";
|
|
3
|
+
interface Pipeline {
|
|
4
|
+
directory?: string;
|
|
5
|
+
stages: string[][];
|
|
6
|
+
}
|
|
7
|
+
export declare const parseSearchCommand: (command: string, windows?: boolean) => Pipeline | undefined;
|
|
8
|
+
export declare function searchPathsMatch(a: string, b: string): boolean;
|
|
9
|
+
/** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
|
|
10
|
+
export declare function keptSearchCandidates(entries: readonly (SessionEntry | SessionHeader)[], indices: ReadonlyMap<string, number>, resolvable: (entry: SessionEntry) => boolean): TranscriptRecord[];
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { classifyBash } from "./bash-command.js";
|
|
2
|
+
import { pathKey } from "./path-key.js";
|
|
3
|
+
import { isTextOnly, textOf } from "./tuck/core/content.js";
|
|
4
|
+
import { extractPath } from "./tuck/core/tool-args.js";
|
|
5
|
+
const searchTail = new Set(["head", "tail", "sort", "uniq", "wc", "cut", "grep"]);
|
|
6
|
+
/** A small shell lexer, not a shell interpreter. Unclassified shell syntax fails closed. */
|
|
7
|
+
function pipeline(command, windows) {
|
|
8
|
+
if (/[;<>`\r\n]/u.test(command) || command.includes("$("))
|
|
9
|
+
return;
|
|
10
|
+
const expands = (at) => command[at] === "$" && /[\w{@*#!?$-]/u.test(command[at + 1] ?? "");
|
|
11
|
+
const tokens = [];
|
|
12
|
+
let word = "", started = false, quote = "";
|
|
13
|
+
const flush = () => { if (started)
|
|
14
|
+
tokens.push({ word }); word = ""; started = false; };
|
|
15
|
+
for (let at = 0; at < command.length; at++) {
|
|
16
|
+
const ch = command[at];
|
|
17
|
+
if (quote) {
|
|
18
|
+
if (ch === quote)
|
|
19
|
+
quote = "";
|
|
20
|
+
else if (!windows && ch === "\\" && quote === '"' && /[\\"$]/u.test(command[at + 1] ?? ""))
|
|
21
|
+
word += command[++at];
|
|
22
|
+
else if (quote === '"' && expands(at))
|
|
23
|
+
return;
|
|
24
|
+
else
|
|
25
|
+
word += ch;
|
|
26
|
+
}
|
|
27
|
+
else if (ch === "'" || ch === '"') {
|
|
28
|
+
quote = ch;
|
|
29
|
+
started = true;
|
|
30
|
+
}
|
|
31
|
+
else if (!windows && ch === "\\") {
|
|
32
|
+
if (++at === command.length)
|
|
33
|
+
return;
|
|
34
|
+
word += command[at];
|
|
35
|
+
started = true;
|
|
36
|
+
}
|
|
37
|
+
else if (/\s/u.test(ch))
|
|
38
|
+
flush();
|
|
39
|
+
else if (ch === "|" || ch === "&") {
|
|
40
|
+
flush();
|
|
41
|
+
const op = command[at + 1] === ch ? ch + command[++at] : ch;
|
|
42
|
+
if (op !== "|" && op !== "&&")
|
|
43
|
+
return;
|
|
44
|
+
tokens.push({ word: op, operator: true });
|
|
45
|
+
}
|
|
46
|
+
else if (/[()]/u.test(ch) || ch === "#" && !started || expands(at))
|
|
47
|
+
return;
|
|
48
|
+
else {
|
|
49
|
+
word += ch;
|
|
50
|
+
started = true;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (quote)
|
|
54
|
+
return;
|
|
55
|
+
flush();
|
|
56
|
+
let directory;
|
|
57
|
+
if (tokens[0]?.word === "cd" && tokens[1] && !tokens[1].operator && tokens[1].word &&
|
|
58
|
+
!tokens[1].word.startsWith("-") && tokens[2]?.operator && tokens[2].word === "&&") {
|
|
59
|
+
directory = tokens[1].word;
|
|
60
|
+
tokens.splice(0, 3);
|
|
61
|
+
}
|
|
62
|
+
const stages = [[]];
|
|
63
|
+
for (const token of tokens) {
|
|
64
|
+
if (token.operator) {
|
|
65
|
+
if (token.word !== "|" || !stages.at(-1).length)
|
|
66
|
+
return;
|
|
67
|
+
stages.push([]);
|
|
68
|
+
}
|
|
69
|
+
else
|
|
70
|
+
stages.at(-1).push(token.word);
|
|
71
|
+
}
|
|
72
|
+
if (!stages.at(-1).length)
|
|
73
|
+
return;
|
|
74
|
+
return { directory, stages };
|
|
75
|
+
}
|
|
76
|
+
const isSearch = ({ stages }) => ["grep", "rg"].includes(stages[0][0]) &&
|
|
77
|
+
stages.slice(1).every(stage => searchTail.has(stage[0]));
|
|
78
|
+
export const parseSearchCommand = (command, windows = false) => {
|
|
79
|
+
const parsed = pipeline(command, windows);
|
|
80
|
+
return parsed && isSearch(parsed) ? parsed : undefined;
|
|
81
|
+
};
|
|
82
|
+
// Options whose next word is a value, rather than a path operand. Pattern-file options name files too.
|
|
83
|
+
const searchValues = new Set(["regexp", "file", "after-context", "before-context", "context", "max-count", "color", "colour",
|
|
84
|
+
"binary-files", "devices", "directories", "exclude", "exclude-dir", "include", "label", "glob", "iglob", "type", "type-not",
|
|
85
|
+
"type-add", "type-clear", "encoding", "engine", "max-columns", "max-depth", "max-filesize", "path-separator",
|
|
86
|
+
"pre", "pre-glob", "replace", "sort", "sortr", "threads", "ignore-file", "hostname-bin", "hyperlink-format", "field-match-separator", "field-context-separator"]);
|
|
87
|
+
const shortValues = { grep: "efABCmDd", rg: "efgtrjABCmME",
|
|
88
|
+
head: "nc", tail: "ncs", sort: "ktoST", uniq: "fsw", cut: "bcfd" };
|
|
89
|
+
const otherValues = new Set(["lines", "bytes", "sleep-interval", "key", "field-separator", "output", "buffer-size", "temporary-directory",
|
|
90
|
+
"skip-fields", "skip-chars", "check-chars", "characters", "fields", "delimiter"]);
|
|
91
|
+
function pathOperands(stage) {
|
|
92
|
+
const [name, ...args] = stage, search = name === "grep" || name === "rg";
|
|
93
|
+
const paths = [], positional = [];
|
|
94
|
+
let literal = false, explicitPattern = false, filesOnly = false;
|
|
95
|
+
for (let at = 0; at < args.length; at++) {
|
|
96
|
+
const arg = args[at];
|
|
97
|
+
if (!literal && arg === "--") {
|
|
98
|
+
literal = true;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (!literal && arg.startsWith("--")) {
|
|
102
|
+
const [option, ...value] = arg.slice(2).split("=");
|
|
103
|
+
if (search && (option === "regexp" || option === "file"))
|
|
104
|
+
explicitPattern = true;
|
|
105
|
+
if (name === "rg" && option === "files")
|
|
106
|
+
filesOnly = true;
|
|
107
|
+
if ((search ? searchValues : otherValues).has(option)) {
|
|
108
|
+
const optional = name === "grep" && (option === "color" || option === "colour");
|
|
109
|
+
const operand = value.length ? value.join("=") : optional ? undefined : args[++at];
|
|
110
|
+
if (option === "file" && operand)
|
|
111
|
+
paths.push(operand);
|
|
112
|
+
}
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (!literal && arg.startsWith("-") && arg !== "-") {
|
|
116
|
+
for (let i = 1; i < arg.length; i++)
|
|
117
|
+
if (shortValues[name]?.includes(arg[i])) {
|
|
118
|
+
const option = arg[i], value = arg.slice(i + 1) || args[++at];
|
|
119
|
+
if (search && (option === "e" || option === "f"))
|
|
120
|
+
explicitPattern = true;
|
|
121
|
+
if (search && option === "f" && value)
|
|
122
|
+
paths.push(value);
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
positional.push(arg);
|
|
128
|
+
}
|
|
129
|
+
if (search && !explicitPattern && !filesOnly)
|
|
130
|
+
positional.shift();
|
|
131
|
+
return [...paths, ...positional].filter(path => path && path !== "-");
|
|
132
|
+
}
|
|
133
|
+
export function searchPathsMatch(a, b) {
|
|
134
|
+
const left = pathKey(a).replace(/^\/+|\/+$/gu, ""), right = pathKey(b).replace(/^\/+|\/+$/gu, "");
|
|
135
|
+
return !!left && !!right && (left === right || left.endsWith("/" + right) || right.endsWith("/" + left));
|
|
136
|
+
}
|
|
137
|
+
/** Whole search results from this prefix only. Calls, rather than result arrival, order invalidations. */
|
|
138
|
+
export function keptSearchCandidates(entries, indices, resolvable) {
|
|
139
|
+
const cwd = entries.find((entry) => entry.type === "session")?.cwd;
|
|
140
|
+
const results = new Map(entries.flatMap(entry => entry.type === "message" && entry.message.role === "toolResult" ? [[entry.message.toolCallId, entry.message]] : []));
|
|
141
|
+
const searches = new Map();
|
|
142
|
+
const mutations = [];
|
|
143
|
+
let order = 0, lastUnsafeBash = -1;
|
|
144
|
+
for (const entry of entries) {
|
|
145
|
+
if (entry.type === "message" && entry.message.role === "bashExecution") {
|
|
146
|
+
order++;
|
|
147
|
+
if (!classifyBash(entry.message.command, cwd).readOnly)
|
|
148
|
+
lastUnsafeBash = order;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (entry.type !== "message" || entry.message.role !== "assistant")
|
|
152
|
+
continue;
|
|
153
|
+
for (const block of entry.message.content) {
|
|
154
|
+
if (block.type !== "toolCall")
|
|
155
|
+
continue;
|
|
156
|
+
order++;
|
|
157
|
+
const args = block.arguments && typeof block.arguments === "object" ? block.arguments : {};
|
|
158
|
+
if (block.name === "bash") {
|
|
159
|
+
const command = args.command;
|
|
160
|
+
const classified = typeof command === "string" ? classifyBash(command, cwd) : undefined;
|
|
161
|
+
if (!classified?.readOnly)
|
|
162
|
+
lastUnsafeBash = order;
|
|
163
|
+
const parsed = typeof command === "string" ? parseSearchCommand(command, classified.windows) : undefined;
|
|
164
|
+
if (parsed)
|
|
165
|
+
searches.set(block.id, { command: command, parsed, order });
|
|
166
|
+
}
|
|
167
|
+
else if (["write", "edit"].includes(block.name) && !results.get(block.id)?.isError) {
|
|
168
|
+
const path = extractPath(args);
|
|
169
|
+
if (path)
|
|
170
|
+
mutations.push({ path: pathKey(path), order });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const seen = new Set(), records = [];
|
|
175
|
+
for (let at = entries.length - 1; at >= 0; at--) {
|
|
176
|
+
const entry = entries[at];
|
|
177
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult")
|
|
178
|
+
continue;
|
|
179
|
+
const search = searches.get(entry.message.toolCallId);
|
|
180
|
+
if (!search)
|
|
181
|
+
continue;
|
|
182
|
+
const key = search.command.replace(/\s+/gu, " ").trim();
|
|
183
|
+
if (seen.has(key))
|
|
184
|
+
continue;
|
|
185
|
+
seen.add(key);
|
|
186
|
+
const sourceIndex = indices.get(entry.id);
|
|
187
|
+
if (search.order < lastUnsafeBash || entry.message.isError || !isTextOnly(entry.message.content) || sourceIndex === undefined || !resolvable(entry))
|
|
188
|
+
continue;
|
|
189
|
+
const text = textOf(entry.message.content);
|
|
190
|
+
if (!text.length || text.length > 2000)
|
|
191
|
+
continue;
|
|
192
|
+
const paths = [...search.parsed.stages.flatMap(pathOperands), ...text.split("\n").flatMap(line => {
|
|
193
|
+
const prefix = /^((?:[a-z]:[\\/])?[^:\r\n]+):/iu.exec(line)?.[1];
|
|
194
|
+
return prefix ? [prefix] : [];
|
|
195
|
+
})].map(path => pathKey(path, search.parsed.directory ? pathKey(search.parsed.directory, cwd) : undefined));
|
|
196
|
+
if (mutations.some(mutation => mutation.order > search.order && paths.some(path => searchPathsMatch(path, mutation.path))))
|
|
197
|
+
continue;
|
|
198
|
+
records.push({ kind: "section", title: "Kept-search", sourceIndex,
|
|
199
|
+
text: `bash ${search.command} (as recorded at #${sourceIndex}; no file it lists was written or edited since):\n${text}` });
|
|
200
|
+
}
|
|
201
|
+
return records;
|
|
202
|
+
}
|
|
@@ -1,17 +1,6 @@
|
|
|
1
1
|
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
-
export declare const clip: (text: string, max?: number) => string;
|
|
3
2
|
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
4
3
|
export declare const isTextOnly: (content: string | readonly {
|
|
5
4
|
type: string;
|
|
6
5
|
}[] | undefined) => boolean;
|
|
7
6
|
export declare const textOf: (content: Message["content"]) => string;
|
|
8
|
-
/**
|
|
9
|
-
* Extract every scalar string argument from a tool call for search indexing
|
|
10
|
-
* — command, query, content, oldText/newText, etc. Generic value walk (no
|
|
11
|
-
* tool-name allowlist): top-level strings plus strings one level into
|
|
12
|
-
* array-of-object fields (e.g. `edits`). Unbounded by design — a single
|
|
13
|
-
* toolCall's raw argument text — so a message with several toolCalls doesn't
|
|
14
|
-
* silently multiply an internal cap. The caller (search-entries.ts) applies
|
|
15
|
-
* one shared budget across all toolCalls in a message.
|
|
16
|
-
*/
|
|
17
|
-
export declare const extractToolCallArgsText: (args: Record<string, unknown>) => string;
|
|
@@ -1,17 +1,3 @@
|
|
|
1
|
-
export const clip = (text, max = 200) => {
|
|
2
|
-
if (text.length <= max)
|
|
3
|
-
return text;
|
|
4
|
-
// Try to cut at a word boundary
|
|
5
|
-
const cut = text.lastIndexOf(" ", max);
|
|
6
|
-
let end = cut > max * 0.6 ? cut : max;
|
|
7
|
-
// Avoid splitting a surrogate pair
|
|
8
|
-
if (end > 0 && end < text.length) {
|
|
9
|
-
const code = text.charCodeAt(end - 1);
|
|
10
|
-
if (code >= 0xd800 && code <= 0xdbff)
|
|
11
|
-
end--;
|
|
12
|
-
}
|
|
13
|
-
return text.slice(0, end);
|
|
14
|
-
};
|
|
15
1
|
/** Content that is a string or only text blocks: what quoting can deliver whole. */
|
|
16
2
|
export const isTextOnly = (content) => typeof content === "string" || (Array.isArray(content) && content.every((part) => part.type === "text"));
|
|
17
3
|
export const textOf = (content) => {
|
|
@@ -21,36 +7,3 @@ export const textOf = (content) => {
|
|
|
21
7
|
return content;
|
|
22
8
|
return content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
23
9
|
};
|
|
24
|
-
/**
|
|
25
|
-
* Extract every scalar string argument from a tool call for search indexing
|
|
26
|
-
* — command, query, content, oldText/newText, etc. Generic value walk (no
|
|
27
|
-
* tool-name allowlist): top-level strings plus strings one level into
|
|
28
|
-
* array-of-object fields (e.g. `edits`). Unbounded by design — a single
|
|
29
|
-
* toolCall's raw argument text — so a message with several toolCalls doesn't
|
|
30
|
-
* silently multiply an internal cap. The caller (search-entries.ts) applies
|
|
31
|
-
* one shared budget across all toolCalls in a message.
|
|
32
|
-
*/
|
|
33
|
-
export const extractToolCallArgsText = (args) => {
|
|
34
|
-
if (!args || typeof args !== "object")
|
|
35
|
-
return "";
|
|
36
|
-
const parts = [];
|
|
37
|
-
for (const value of Object.values(args)) {
|
|
38
|
-
if (typeof value === "string") {
|
|
39
|
-
parts.push(value);
|
|
40
|
-
}
|
|
41
|
-
else if (Array.isArray(value)) {
|
|
42
|
-
for (const item of value) {
|
|
43
|
-
if (typeof item === "string") {
|
|
44
|
-
parts.push(item);
|
|
45
|
-
}
|
|
46
|
-
else if (item && typeof item === "object") {
|
|
47
|
-
for (const v of Object.values(item)) {
|
|
48
|
-
if (typeof v === "string")
|
|
49
|
-
parts.push(v);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
return parts.join("\n");
|
|
56
|
-
};
|
|
@@ -1,28 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
7
|
-
/**
|
|
8
|
-
* Result of a search, with enough metadata for a caller to report truncation
|
|
9
|
-
* honestly (see `searchEntriesDetailed`).
|
|
10
|
-
*/
|
|
11
|
-
export interface SearchResult {
|
|
12
|
-
hits: SearchHit[];
|
|
13
|
-
/** Genuine matches found before the hard cap was applied (after any
|
|
14
|
-
* relative-floor noise filtering). May exceed `hits.length`. */
|
|
15
|
-
totalBeforeCap: number;
|
|
16
|
-
/** True when the hard cap discarded matches (`totalBeforeCap > hits.length`). */
|
|
17
|
-
truncated: boolean;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Tuning overrides for `searchEntriesDetailed`; without them a search uses `BM25_RELATIVE_FLOOR` and
|
|
21
|
-
* `SEARCH_RESULT_CAP`. `tuckRecall` passes a floor of 0 and a cap of every row, because it pages its own responses.
|
|
22
|
-
*/
|
|
23
|
-
export interface SearchTuning {
|
|
24
|
-
relativeFloor?: number;
|
|
25
|
-
cap?: number;
|
|
26
|
-
}
|
|
27
|
-
/** BM25 keyword search with truncation metadata. */
|
|
28
|
-
export declare const searchEntriesDetailed: (entries: RenderedEntry[], messages: Message[], query?: string, tuning?: SearchTuning) => SearchResult;
|
|
1
|
+
/** Rank already-eligible recall rows; filtering and paging belong to the caller. */
|
|
2
|
+
export declare const rankRecallRows: (rows: readonly {
|
|
3
|
+
role: string;
|
|
4
|
+
text: string;
|
|
5
|
+
}[], query: string) => number[];
|
|
@@ -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.
|
|
@@ -70,168 +68,28 @@ const bm25Score = (doc, terms, ctx) => {
|
|
|
70
68
|
}
|
|
71
69
|
return score;
|
|
72
70
|
};
|
|
73
|
-
/**
|
|
74
|
-
|
|
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
|
-
* lookup 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 recognized 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 a single-term query after normalization 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
|
-
//
|
|
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 <
|
|
81
|
+
for (let i = 0; i < rows.length; i++) {
|
|
216
82
|
checkBudget();
|
|
217
|
-
const e = entries[i];
|
|
218
83
|
const hay = docs[i];
|
|
219
|
-
|
|
220
|
-
if (mc === 0)
|
|
84
|
+
if (countMatches(hay, terms) === 0)
|
|
221
85
|
continue;
|
|
222
|
-
scored.push({
|
|
86
|
+
scored.push({ index: i, score: bm25Score(hay, terms, ctx) });
|
|
223
87
|
}
|
|
224
|
-
//
|
|
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
|
-
//
|
|
229
|
-
//
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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
|
};
|
package/dist/src/tuck.d.ts
CHANGED
|
@@ -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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
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;
|