@floydous/pi-agent-kernel 0.4.0 → 0.4.2
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/AGENT_KERNEL_SYS_PROMPT.md +8 -4
- package/CHANGELOG.md +40 -87
- package/README.md +39 -74
- package/config.example.toml +1 -1
- package/docs/retrieval.md +2 -0
- package/package.json +7 -6
- package/src/config/agent_kernel_command.ts +29 -14
- package/src/config/kernel_config.ts +175 -30
- package/src/context/session_repair.ts +166 -85
- package/src/editing/patch.ts +28 -16
- package/src/editing/smart_anchor.ts +13 -29
- package/src/editing/syntax-verify.ts +35 -11
- package/src/index.ts +161 -141
- package/src/lsp/lsp_client.ts +101 -20
- package/src/lsp/lsp_formatter.ts +57 -22
- package/src/lsp/lsp_installer.ts +272 -487
- package/src/lsp/lsp_manager.ts +1 -1
- package/src/lsp/lsp_registry.ts +75 -46
- package/src/retrieval/search_bm25.ts +5 -2
- package/src/retrieval/search_cache.ts +69 -0
- package/src/retrieval/search_chunker.ts +12 -9
- package/src/retrieval/search_config.ts +20 -8
- package/src/retrieval/search_embedder.ts +8 -16
- package/src/retrieval/search_index.ts +552 -121
- package/src/safety/atomic_write.ts +59 -20
- package/src/safety/epistemic_guard.ts +440 -67
- package/src/safety/output_clamper.ts +316 -76
- package/src/tools/code_search_output.ts +59 -23
- package/src/tools/code_search_tool.ts +42 -46
- package/src/tools/context.ts +15 -1
- package/src/tools/edit_tool.ts +114 -36
- package/src/tools/lsp_tool.ts +5 -2
- package/src/tools/read_tool.ts +44 -3
|
@@ -2,12 +2,17 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as crypto from "node:crypto";
|
|
5
|
+
import { getPiHomeDir } from "../config/kernel_config";
|
|
5
6
|
import { kernelDebug } from "./kernel_debug";
|
|
6
7
|
|
|
7
8
|
export interface ClampingOptions {
|
|
8
9
|
maxLineLength?: number; // Maximum width per line (default: 300)
|
|
9
|
-
maxLines?: number; // Maximum lines shown to model (default:
|
|
10
|
+
maxLines?: number; // Maximum lines shown to model (default: 100)
|
|
10
11
|
maxTotalBytes?: number; // Maximum total bytes before spilling (default: 20 * 1024 = 20 KB)
|
|
12
|
+
spilloverDir?: string;
|
|
13
|
+
maxSpilloverFiles?: number;
|
|
14
|
+
maxSpilloverBytes?: number;
|
|
15
|
+
isError?: boolean;
|
|
11
16
|
}
|
|
12
17
|
|
|
13
18
|
export interface ClampingResult {
|
|
@@ -20,6 +25,89 @@ export interface ClampingResult {
|
|
|
20
25
|
shownLines: number;
|
|
21
26
|
}
|
|
22
27
|
|
|
28
|
+
const SPILL_PREFIX = "pi_bash_spillover_";
|
|
29
|
+
const DEFAULT_SPILL_FILES = 20;
|
|
30
|
+
const DEFAULT_SPILL_BYTES = 50 * 1024 * 1024;
|
|
31
|
+
|
|
32
|
+
export function getSpilloverRoot(cwd = process.cwd()): string {
|
|
33
|
+
const base = getPiHomeDir();
|
|
34
|
+
const workspaceId = crypto
|
|
35
|
+
.createHash("sha256")
|
|
36
|
+
.update(process.platform === "win32" ? path.resolve(cwd).toLowerCase() : path.resolve(cwd))
|
|
37
|
+
.digest("hex")
|
|
38
|
+
.slice(0, 24);
|
|
39
|
+
return path.join(base, "cache", "pi-agent-kernel", "spillover", workspaceId);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function ensureSpilloverDirectory(directory: string): string {
|
|
43
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
44
|
+
const stat = fs.lstatSync(directory);
|
|
45
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
|
46
|
+
throw new Error("Spillover directory must be a real directory");
|
|
47
|
+
}
|
|
48
|
+
return fs.realpathSync(directory);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isOwnedRegularFile(filePath: string): boolean {
|
|
52
|
+
try {
|
|
53
|
+
const stat = fs.lstatSync(filePath);
|
|
54
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return false;
|
|
55
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
|
|
56
|
+
return uid === undefined || stat.uid === uid;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function pruneSpillovers(directory: string, maxFiles: number, maxBytes: number): void {
|
|
63
|
+
const files = fs
|
|
64
|
+
.readdirSync(directory)
|
|
65
|
+
.filter((name) => name.startsWith(SPILL_PREFIX))
|
|
66
|
+
.map((name) => {
|
|
67
|
+
const full = path.join(directory, name);
|
|
68
|
+
try {
|
|
69
|
+
const stat = fs.lstatSync(full);
|
|
70
|
+
return { full, size: stat.size, mtime: stat.mtimeMs, owned: isOwnedRegularFile(full) };
|
|
71
|
+
} catch {
|
|
72
|
+
return { full, size: 0, mtime: 0, owned: false };
|
|
73
|
+
}
|
|
74
|
+
})
|
|
75
|
+
.filter((item) => item.owned)
|
|
76
|
+
.sort((a, b) => a.mtime - b.mtime);
|
|
77
|
+
let totalBytes = files.reduce((sum, file) => sum + file.size, 0);
|
|
78
|
+
let remainingFiles = files.length;
|
|
79
|
+
for (const file of files) {
|
|
80
|
+
if (remainingFiles <= maxFiles && totalBytes <= maxBytes) break;
|
|
81
|
+
try {
|
|
82
|
+
fs.unlinkSync(file.full);
|
|
83
|
+
totalBytes -= file.size;
|
|
84
|
+
remainingFiles--;
|
|
85
|
+
} catch {}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function writeSpillover(rawText: string, directory: string, maxFiles: number, maxBytes: number): string {
|
|
90
|
+
const realDirectory = ensureSpilloverDirectory(directory);
|
|
91
|
+
let candidate = "";
|
|
92
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
93
|
+
candidate = path.join(realDirectory, `${SPILL_PREFIX}${crypto.randomBytes(16).toString("hex")}.log`);
|
|
94
|
+
try {
|
|
95
|
+
const fd = fs.openSync(candidate, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
96
|
+
try {
|
|
97
|
+
fs.writeFileSync(fd, rawText, "utf8");
|
|
98
|
+
fs.fsyncSync(fd);
|
|
99
|
+
} finally {
|
|
100
|
+
fs.closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
pruneSpillovers(realDirectory, maxFiles, maxBytes);
|
|
103
|
+
return candidate;
|
|
104
|
+
} catch (error: any) {
|
|
105
|
+
if (error?.code !== "EEXIST") throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
throw new Error("Unable to create an exclusive spillover file");
|
|
109
|
+
}
|
|
110
|
+
|
|
23
111
|
/**
|
|
24
112
|
* Identify if a command is primarily a discovery/search/listing command
|
|
25
113
|
* where aggressive line-width clamping and match capping should be enforced.
|
|
@@ -51,6 +139,57 @@ export function isDiscoveryCommand(command: string): boolean {
|
|
|
51
139
|
return false;
|
|
52
140
|
}
|
|
53
141
|
|
|
142
|
+
export function isExecutionOrTestCommand(command: string): boolean {
|
|
143
|
+
if (!command) return false;
|
|
144
|
+
const trimmed = command.trim().toLowerCase();
|
|
145
|
+
return /\b(test|vitest|jest|pytest|ava|mocha|cargo|tsc|build|check)\b/.test(trimmed);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const HOST_TRUNCATION_REGEX =
|
|
149
|
+
/(?:\r?\n){2}\[Showing (?:lines \d+-\d+ of \d+(?: \([^)]+\))?|last [^)]+\))\.\s*Full output:\s*([^\]]+)\]\s*$/;
|
|
150
|
+
|
|
151
|
+
const KERNEL_TRUNCATION_REGEX =
|
|
152
|
+
/(?:\r?\n){2}\[Truncated[^\r\n\]]*?(?:\.\s*(?:Full|Spillover):\s*([^\]\r\n]+?)(?:\s*\(use offset\/limit[^)]*\)|\s*\(received fragment only\))?)?\]\s*$/;
|
|
153
|
+
|
|
154
|
+
function validateHostSpilloverPath(candidatePath: string): string | undefined {
|
|
155
|
+
try {
|
|
156
|
+
const trimmed = candidatePath.trim().replace(/^["']|["']$/g, "");
|
|
157
|
+
// Reject UNC paths and protocol paths
|
|
158
|
+
if (trimmed.startsWith("\\\\") || trimmed.startsWith("//")) return undefined;
|
|
159
|
+
|
|
160
|
+
const resolved = path.resolve(trimmed);
|
|
161
|
+
if (!fs.existsSync(resolved)) return undefined;
|
|
162
|
+
|
|
163
|
+
// Must not be a symbolic link and must be a regular file
|
|
164
|
+
const lstat = fs.lstatSync(resolved);
|
|
165
|
+
if (lstat.isSymbolicLink() || !lstat.isFile()) return undefined;
|
|
166
|
+
|
|
167
|
+
// Filename must strictly match Pi core's accumulator naming convention: pi-(bash|powershell|output)-<hex>.log
|
|
168
|
+
const base = path.basename(resolved);
|
|
169
|
+
if (!/^pi-(?:bash|powershell|output)-[a-f0-9]+\.log$/i.test(base)) {
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Must be directly contained in the OS temp directory (canonicalized real path)
|
|
174
|
+
const realResolved = fs.realpathSync(resolved);
|
|
175
|
+
const realTempDir = fs.realpathSync(os.tmpdir());
|
|
176
|
+
const parentDir = path.dirname(realResolved);
|
|
177
|
+
|
|
178
|
+
const isSameDir = process.platform === "win32"
|
|
179
|
+
? parentDir.toLowerCase() === realTempDir.toLowerCase()
|
|
180
|
+
: parentDir === realTempDir;
|
|
181
|
+
|
|
182
|
+
if (!isSameDir) {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return resolved;
|
|
187
|
+
} catch (e: any) {
|
|
188
|
+
kernelDebug(e);
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
54
193
|
/**
|
|
55
194
|
* Clamps output lines horizontally and vertically to prevent context bloat
|
|
56
195
|
* from single-line minified files, lockfiles, or massive multi-file matches.
|
|
@@ -66,22 +205,68 @@ export function clampCommandOutput(
|
|
|
66
205
|
options?: ClampingOptions,
|
|
67
206
|
): ClampingResult {
|
|
68
207
|
const maxLineLength = options?.maxLineLength ?? 300;
|
|
69
|
-
const maxLines = options?.maxLines ??
|
|
208
|
+
const maxLines = options?.maxLines ?? 100;
|
|
70
209
|
const maxTotalBytes = options?.maxTotalBytes ?? 20 * 1024;
|
|
71
210
|
if (!Number.isSafeInteger(maxTotalBytes) || maxTotalBytes < 0) {
|
|
72
211
|
throw new RangeError("maxTotalBytes must be a nonnegative safe integer");
|
|
73
212
|
}
|
|
74
213
|
|
|
75
|
-
|
|
214
|
+
// Detect prior truncation footer at the end of rawText:
|
|
215
|
+
// either from host harness (Pi core) or an earlier Agent Kernel pass
|
|
216
|
+
let textToProcess = rawText;
|
|
217
|
+
let hostTruncated = false;
|
|
218
|
+
let priorKernelTruncated = false;
|
|
219
|
+
let hostSpilloverPath: string | undefined;
|
|
220
|
+
let priorSpilloverPath: string | undefined;
|
|
221
|
+
|
|
222
|
+
const kernelMatch = rawText.match(KERNEL_TRUNCATION_REGEX);
|
|
223
|
+
if (kernelMatch && kernelMatch.index !== undefined) {
|
|
224
|
+
priorKernelTruncated = true;
|
|
225
|
+
textToProcess = rawText.slice(0, kernelMatch.index);
|
|
226
|
+
const candidate = kernelMatch[1]?.trim();
|
|
227
|
+
if (candidate) {
|
|
228
|
+
const cleanCandidate = candidate.replace(/\s*\(use offset\/limit.*\)$/i, "").trim();
|
|
229
|
+
hostSpilloverPath = validateHostSpilloverPath(cleanCandidate);
|
|
230
|
+
if (!hostSpilloverPath && fs.existsSync(cleanCandidate)) {
|
|
231
|
+
try {
|
|
232
|
+
const lstat = fs.lstatSync(cleanCandidate);
|
|
233
|
+
if (!lstat.isSymbolicLink() && lstat.isFile()) {
|
|
234
|
+
priorSpilloverPath = path.resolve(cleanCandidate);
|
|
235
|
+
}
|
|
236
|
+
} catch {}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
} else {
|
|
240
|
+
const hostMatch = rawText.match(HOST_TRUNCATION_REGEX);
|
|
241
|
+
if (hostMatch && hostMatch.index !== undefined) {
|
|
242
|
+
hostTruncated = true;
|
|
243
|
+
textToProcess = rawText.slice(0, hostMatch.index);
|
|
244
|
+
const candidate = hostMatch[1].trim();
|
|
245
|
+
hostSpilloverPath = validateHostSpilloverPath(candidate);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
let originalBytes = Buffer.byteLength(rawText, "utf8");
|
|
250
|
+
if (hostSpilloverPath) {
|
|
251
|
+
try {
|
|
252
|
+
originalBytes = fs.statSync(hostSpilloverPath).size;
|
|
253
|
+
} catch {}
|
|
254
|
+
} else if (priorSpilloverPath) {
|
|
255
|
+
try {
|
|
256
|
+
originalBytes = fs.statSync(priorSpilloverPath).size;
|
|
257
|
+
} catch {}
|
|
258
|
+
}
|
|
76
259
|
|
|
77
|
-
// If the entire output is small
|
|
260
|
+
// If the entire output is small, within bounds, and host did not truncate, return as-is
|
|
78
261
|
if (
|
|
262
|
+
!hostTruncated &&
|
|
263
|
+
!priorKernelTruncated &&
|
|
79
264
|
originalBytes <= maxTotalBytes &&
|
|
80
|
-
!
|
|
81
|
-
|
|
265
|
+
!textToProcess.includes("\n") &&
|
|
266
|
+
textToProcess.length <= maxLineLength
|
|
82
267
|
) {
|
|
83
268
|
return {
|
|
84
|
-
text:
|
|
269
|
+
text: textToProcess,
|
|
85
270
|
truncated: false,
|
|
86
271
|
originalBytes,
|
|
87
272
|
returnedBytes: originalBytes,
|
|
@@ -90,12 +275,12 @@ export function clampCommandOutput(
|
|
|
90
275
|
};
|
|
91
276
|
}
|
|
92
277
|
|
|
93
|
-
const rawLines =
|
|
278
|
+
const rawLines = textToProcess.split(/\r?\n/);
|
|
94
279
|
const totalLines = rawLines.length;
|
|
95
|
-
let needsTruncation =
|
|
280
|
+
let needsTruncation = hostTruncated || priorKernelTruncated;
|
|
96
281
|
|
|
97
|
-
// Check if any line violates maxLineLength or total lines violate maxLines
|
|
98
|
-
if (totalLines > maxLines ||
|
|
282
|
+
// Check if any line violates maxLineLength or total lines violate maxLines or bytes violate maxTotalBytes
|
|
283
|
+
if (totalLines > maxLines || Buffer.byteLength(textToProcess, "utf8") > maxTotalBytes) {
|
|
99
284
|
needsTruncation = true;
|
|
100
285
|
}
|
|
101
286
|
|
|
@@ -109,7 +294,7 @@ export function clampCommandOutput(
|
|
|
109
294
|
// If no truncation is necessary, return clean output
|
|
110
295
|
if (!needsTruncation) {
|
|
111
296
|
return {
|
|
112
|
-
text:
|
|
297
|
+
text: textToProcess,
|
|
113
298
|
truncated: false,
|
|
114
299
|
originalBytes,
|
|
115
300
|
returnedBytes: originalBytes,
|
|
@@ -118,43 +303,16 @@ export function clampCommandOutput(
|
|
|
118
303
|
};
|
|
119
304
|
}
|
|
120
305
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
try {
|
|
124
|
-
const tempDir = os.tmpdir();
|
|
125
|
-
// Prune older spillover logs (> 20 files, oldest first by mtime)
|
|
306
|
+
let spilloverPath = hostSpilloverPath || priorSpilloverPath;
|
|
307
|
+
if (!spilloverPath) {
|
|
126
308
|
try {
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
return { name, full, isFile: stat.isFile() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
|
|
135
|
-
} catch {
|
|
136
|
-
return { name, full, isFile: false, mtime: 0 };
|
|
137
|
-
}
|
|
138
|
-
})
|
|
139
|
-
.filter((item) => item.isFile)
|
|
140
|
-
.sort((a, b) => a.mtime - b.mtime);
|
|
141
|
-
|
|
142
|
-
if (files.length > 20) {
|
|
143
|
-
const toDelete = files.slice(0, files.length - 20);
|
|
144
|
-
for (const item of toDelete) {
|
|
145
|
-
try {
|
|
146
|
-
fs.unlinkSync(item.full);
|
|
147
|
-
} catch {}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
} catch {}
|
|
151
|
-
|
|
152
|
-
const hash = crypto.randomBytes(4).toString("hex");
|
|
153
|
-
const candidatePath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
|
|
154
|
-
fs.writeFileSync(candidatePath, rawText, { encoding: "utf8", mode: 0o600 });
|
|
155
|
-
spilloverPath = candidatePath;
|
|
156
|
-
} catch (e) {
|
|
157
|
-
kernelDebug(e);
|
|
309
|
+
const directory = options?.spilloverDir || getSpilloverRoot();
|
|
310
|
+
const maxFiles = options?.maxSpilloverFiles ?? DEFAULT_SPILL_FILES;
|
|
311
|
+
const maxBytes = options?.maxSpilloverBytes ?? DEFAULT_SPILL_BYTES;
|
|
312
|
+
spilloverPath = writeSpillover(textToProcess, directory, maxFiles, maxBytes);
|
|
313
|
+
} catch (e) {
|
|
314
|
+
kernelDebug(e);
|
|
315
|
+
}
|
|
158
316
|
}
|
|
159
317
|
|
|
160
318
|
// Horizontal Line-Width Clamping & Vertical Head+Tail Capping
|
|
@@ -178,27 +336,98 @@ export function clampCommandOutput(
|
|
|
178
336
|
|
|
179
337
|
let shownLines = totalLines;
|
|
180
338
|
|
|
339
|
+
const DIAGNOSTIC_PATTERNS = [
|
|
340
|
+
/^\s*(?:FAIL|✕|×)\s+\S+/,
|
|
341
|
+
/\bAssertionError:\s/,
|
|
342
|
+
/\berror\[E\d+\]:\s/,
|
|
343
|
+
/\b(?:TypeError|SyntaxError|ReferenceError|Error):\s/,
|
|
344
|
+
/-->\s+\S+:\d+:\d+/,
|
|
345
|
+
];
|
|
346
|
+
|
|
181
347
|
if (totalLines > maxLines) {
|
|
182
348
|
const effectiveMaxLines = Math.max(2, maxLines);
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
const
|
|
186
|
-
|
|
349
|
+
const isDiscovery = isDiscoveryCommand(command);
|
|
350
|
+
const diagIndices: number[] = [];
|
|
351
|
+
const isExplicitError = options?.isError === true;
|
|
352
|
+
const isExplicitSuccess = options?.isError === false;
|
|
353
|
+
const isUnflaggedTestOrBuild = options?.isError === undefined && !isDiscovery && isExecutionOrTestCommand(command);
|
|
187
354
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
355
|
+
if (!isDiscovery && !isExplicitSuccess && (isExplicitError || isUnflaggedTestOrBuild)) {
|
|
356
|
+
const patternsToScan = isExplicitError
|
|
357
|
+
? DIAGNOSTIC_PATTERNS
|
|
358
|
+
: [/^\s*(?:FAIL|✕|×)\s+\S+/, /-->\s+\S+:\d+:\d+/, /^\s*error\[E\d+\]:\s/];
|
|
359
|
+
for (let i = 0; i < totalLines; i++) {
|
|
360
|
+
if (patternsToScan.some((pat) => pat.test(rawLines[i]))) {
|
|
361
|
+
diagIndices.push(i);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
191
364
|
}
|
|
192
365
|
|
|
193
|
-
|
|
194
|
-
clampedLines.push(
|
|
195
|
-
`\n[... ${omittedLines.toLocaleString()} lines omitted ...]\n`,
|
|
196
|
-
);
|
|
366
|
+
const hasDiagnosticFailure = !isDiscovery && !isExplicitSuccess && (isExplicitError || diagIndices.length > 0);
|
|
197
367
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
368
|
+
if (hasDiagnosticFailure && effectiveMaxLines >= 8) {
|
|
369
|
+
const headCount = Math.min(4, Math.max(2, Math.floor(effectiveMaxLines * 0.12)));
|
|
370
|
+
const tailCount = Math.min(5, Math.max(2, Math.floor(effectiveMaxLines * 0.15)));
|
|
371
|
+
const windowBudget = effectiveMaxLines - headCount - tailCount;
|
|
372
|
+
|
|
373
|
+
let windowStart: number;
|
|
374
|
+
let windowEnd: number;
|
|
375
|
+
|
|
376
|
+
if (diagIndices.length > 0) {
|
|
377
|
+
const primaryDiag = diagIndices[0];
|
|
378
|
+
const half = Math.floor(windowBudget / 2);
|
|
379
|
+
windowStart = Math.max(headCount, primaryDiag - half);
|
|
380
|
+
windowEnd = Math.min(totalLines - tailCount, windowStart + windowBudget);
|
|
381
|
+
if (windowEnd === totalLines - tailCount) {
|
|
382
|
+
windowStart = Math.max(headCount, windowEnd - windowBudget);
|
|
383
|
+
}
|
|
384
|
+
} else {
|
|
385
|
+
// No explicit pattern matched but isError is set: bias toward tail
|
|
386
|
+
windowEnd = totalLines - tailCount;
|
|
387
|
+
windowStart = Math.max(headCount, windowEnd - windowBudget);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Head lines
|
|
391
|
+
for (let i = 0; i < headCount; i++) {
|
|
392
|
+
clampedLines.push(formatLine(rawLines[i], i));
|
|
393
|
+
}
|
|
394
|
+
if (windowStart > headCount) {
|
|
395
|
+
clampedLines.push(`\n[... ${(windowStart - headCount).toLocaleString()} lines omitted ...]\n`);
|
|
396
|
+
}
|
|
397
|
+
// Diagnostic window
|
|
398
|
+
for (let i = windowStart; i < windowEnd; i++) {
|
|
399
|
+
clampedLines.push(formatLine(rawLines[i], i));
|
|
400
|
+
}
|
|
401
|
+
if (totalLines - tailCount > windowEnd) {
|
|
402
|
+
clampedLines.push(`\n[... ${(totalLines - tailCount - windowEnd).toLocaleString()} lines omitted ...]\n`);
|
|
403
|
+
}
|
|
404
|
+
// Tail lines
|
|
405
|
+
for (let i = totalLines - tailCount; i < totalLines; i++) {
|
|
406
|
+
clampedLines.push(formatLine(rawLines[i], i));
|
|
407
|
+
}
|
|
408
|
+
shownLines = headCount + (windowEnd - windowStart) + tailCount;
|
|
409
|
+
} else {
|
|
410
|
+
// Standard symmetric head/tail split
|
|
411
|
+
const headCount = Math.floor(effectiveMaxLines / 2);
|
|
412
|
+
const tailCount = effectiveMaxLines - headCount;
|
|
413
|
+
const omittedLines = totalLines - (headCount + tailCount);
|
|
414
|
+
shownLines = headCount + tailCount;
|
|
415
|
+
|
|
416
|
+
// Head lines
|
|
417
|
+
for (let i = 0; i < headCount; i++) {
|
|
418
|
+
clampedLines.push(formatLine(rawLines[i], i));
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Middle omission marker
|
|
422
|
+
clampedLines.push(
|
|
423
|
+
`\n[... ${omittedLines.toLocaleString()} lines omitted ...]\n`,
|
|
424
|
+
);
|
|
425
|
+
|
|
426
|
+
// Tail lines
|
|
427
|
+
const tailStart = totalLines - tailCount;
|
|
428
|
+
for (let i = tailStart; i < totalLines; i++) {
|
|
429
|
+
clampedLines.push(formatLine(rawLines[i], i));
|
|
430
|
+
}
|
|
202
431
|
}
|
|
203
432
|
} else {
|
|
204
433
|
for (let i = 0; i < totalLines; i++) {
|
|
@@ -208,13 +437,30 @@ export function clampCommandOutput(
|
|
|
208
437
|
|
|
209
438
|
let resultText = clampedLines.join("\n");
|
|
210
439
|
|
|
440
|
+
const makeFooter = (linesShown: number): string => {
|
|
441
|
+
if (hostTruncated || (priorKernelTruncated && hostSpilloverPath)) {
|
|
442
|
+
if (hostSpilloverPath) {
|
|
443
|
+
if (linesShown < totalLines) {
|
|
444
|
+
return `\n\n[Truncated: ${linesShown} lines shown (host truncated). Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
|
|
445
|
+
}
|
|
446
|
+
return `\n\n[Truncated by host harness. Full: ${hostSpilloverPath} (use offset/limit with read if needed)]`;
|
|
447
|
+
}
|
|
448
|
+
if (spilloverPath) {
|
|
449
|
+
return `\n\n[Truncated by host harness. Spillover: ${spilloverPath} (received fragment only)]`;
|
|
450
|
+
}
|
|
451
|
+
return `\n\n[Truncated by host harness]`;
|
|
452
|
+
}
|
|
453
|
+
let f = `\n\n[Truncated: ${linesShown}/${totalLines} lines.`;
|
|
454
|
+
if (spilloverPath) {
|
|
455
|
+
f += ` Full: ${spilloverPath} (use offset/limit with read if needed)]`;
|
|
456
|
+
} else {
|
|
457
|
+
f += `]`;
|
|
458
|
+
}
|
|
459
|
+
return f;
|
|
460
|
+
};
|
|
461
|
+
|
|
211
462
|
// Append concise footer with spillover pointer
|
|
212
|
-
let footer =
|
|
213
|
-
if (spilloverPath) {
|
|
214
|
-
footer += ` Full: ${spilloverPath}]`;
|
|
215
|
-
} else {
|
|
216
|
-
footer += `]`;
|
|
217
|
-
}
|
|
463
|
+
let footer = makeFooter(shownLines);
|
|
218
464
|
|
|
219
465
|
if (Buffer.byteLength(resultText + footer, "utf8") > maxTotalBytes) {
|
|
220
466
|
const marker = clampedLines.findIndex((line) => /^\n\[\.\.\. /.test(line));
|
|
@@ -231,13 +477,7 @@ export function clampCommandOutput(
|
|
|
231
477
|
1,
|
|
232
478
|
);
|
|
233
479
|
if (!removed.startsWith("\n[... ")) shownLines--;
|
|
234
|
-
footer =
|
|
235
|
-
"\n\n[Truncated: " +
|
|
236
|
-
shownLines +
|
|
237
|
-
"/" +
|
|
238
|
-
totalLines +
|
|
239
|
-
" lines." +
|
|
240
|
-
(spilloverPath ? " Full: " + spilloverPath + "]" : "]");
|
|
480
|
+
footer = makeFooter(shownLines);
|
|
241
481
|
}
|
|
242
482
|
resultText = clampedLines.join("\n") + footer;
|
|
243
483
|
if (Buffer.byteLength(resultText, "utf8") > maxTotalBytes) {
|
|
@@ -13,10 +13,17 @@ const PREVIEW_CHAR_LIMIT = 1_400;
|
|
|
13
13
|
const AUTO_FULL_CHAR_LIMIT = 6_000;
|
|
14
14
|
const AUTO_PREVIEW_HIT_LIMIT = 3;
|
|
15
15
|
|
|
16
|
+
export interface VisibleCodeRange {
|
|
17
|
+
chunkId: string;
|
|
18
|
+
startLine: number;
|
|
19
|
+
endLine: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
16
22
|
export interface FormattedCodeSearchResults {
|
|
17
23
|
text: string;
|
|
18
24
|
mode: Exclude<CodeSearchMode, "auto"> | "mixed";
|
|
19
25
|
truncated: boolean;
|
|
26
|
+
visibleRanges: VisibleCodeRange[];
|
|
20
27
|
}
|
|
21
28
|
|
|
22
29
|
function normalizePath(filePath: string): string {
|
|
@@ -77,7 +84,10 @@ function bestMatchingLine(lines: string[], queryTerms: string[]): number {
|
|
|
77
84
|
* the search decision while avoiding a forced full-file read in the common
|
|
78
85
|
* multi-result case.
|
|
79
86
|
*/
|
|
80
|
-
function queryPreview(
|
|
87
|
+
function queryPreview(
|
|
88
|
+
hit: SearchHit,
|
|
89
|
+
query: string,
|
|
90
|
+
): { text: string; visibleRange?: VisibleCodeRange } {
|
|
81
91
|
const lines = hit.chunk.content.split("\n");
|
|
82
92
|
const terms = Array.from(new Set(tokenizeCode(query)));
|
|
83
93
|
const bestLine = bestMatchingLine(lines, terms);
|
|
@@ -93,10 +103,18 @@ function queryPreview(hit: SearchHit, query: string): string {
|
|
|
93
103
|
const before = start > 0 ? `... lines ${hit.chunk.startLine}-${lineStart - 1} omitted ...\n` : "";
|
|
94
104
|
const after = end < lines.length ? `\n... lines ${lineEnd + 1}-${hit.chunk.endLine} omitted ...` : "";
|
|
95
105
|
const boundedExcerpt = `${before}${excerpt}${after}`;
|
|
96
|
-
const clipped = boundedExcerpt.length > PREVIEW_CHAR_LIMIT
|
|
106
|
+
const clipped = boundedExcerpt.length > PREVIEW_CHAR_LIMIT;
|
|
107
|
+
const previewBody = clipped
|
|
97
108
|
? `${boundedExcerpt.slice(0, PREVIEW_CHAR_LIMIT)}\n... preview clipped ...`
|
|
98
109
|
: boundedExcerpt;
|
|
99
|
-
return
|
|
110
|
+
return {
|
|
111
|
+
text: `${hitHeader(hit)}\n\`\`\`${languageFor(hit.chunk.filePath)}\n${previewBody}\n\`\`\``,
|
|
112
|
+
// A char-clipped body may omit most of its final line, so it cannot
|
|
113
|
+
// authorize a complete source line. Omit the range instead of guessing.
|
|
114
|
+
visibleRange: clipped
|
|
115
|
+
? undefined
|
|
116
|
+
: { chunkId: hit.chunk.id, startLine: lineStart, endLine: lineEnd },
|
|
117
|
+
};
|
|
100
118
|
}
|
|
101
119
|
|
|
102
120
|
function clipToBudget(text: string, budget: number): string {
|
|
@@ -105,28 +123,39 @@ function clipToBudget(text: string, budget: number): string {
|
|
|
105
123
|
return `${text.slice(0, budget - 27)}\n... output clipped ...`;
|
|
106
124
|
}
|
|
107
125
|
|
|
108
|
-
|
|
126
|
+
interface BudgetEntry {
|
|
127
|
+
text: string;
|
|
128
|
+
visibleRange?: VisibleCodeRange;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function applyBudget(
|
|
132
|
+
entries: BudgetEntry[],
|
|
133
|
+
budget: number,
|
|
134
|
+
): { text: string; truncated: boolean; visibleRanges: VisibleCodeRange[] } {
|
|
109
135
|
const selected: string[] = [];
|
|
136
|
+
const visibleRanges: VisibleCodeRange[] = [];
|
|
110
137
|
let used = 0;
|
|
111
138
|
let omitted = 0;
|
|
112
139
|
let truncated = false;
|
|
113
140
|
|
|
114
141
|
for (let index = 0; index < entries.length; index++) {
|
|
142
|
+
const entry = entries[index]!;
|
|
115
143
|
const separator = selected.length > 0 ? "\n\n" : "";
|
|
116
|
-
const candidateLength = separator.length +
|
|
144
|
+
const candidateLength = separator.length + entry.text.length;
|
|
117
145
|
if (used + candidateLength <= budget) {
|
|
118
|
-
selected.push(
|
|
146
|
+
selected.push(entry.text);
|
|
119
147
|
used += candidateLength;
|
|
148
|
+
if (entry.visibleRange) visibleRanges.push(entry.visibleRange);
|
|
120
149
|
continue;
|
|
121
150
|
}
|
|
122
151
|
|
|
123
152
|
if (selected.length === 0) {
|
|
124
|
-
const clipped = clipToBudget(
|
|
153
|
+
const clipped = clipToBudget(entry.text, budget);
|
|
125
154
|
selected.push(clipped);
|
|
126
155
|
used = clipped.length;
|
|
127
|
-
truncated = clipped.length <
|
|
128
|
-
//
|
|
129
|
-
//
|
|
156
|
+
truncated = clipped.length < entry.text.length;
|
|
157
|
+
// A clipped entry cannot prove that its full declared source range
|
|
158
|
+
// was returned, so its evidence range is intentionally omitted.
|
|
130
159
|
omitted = entries.length - index - 1;
|
|
131
160
|
} else {
|
|
132
161
|
omitted = entries.length - index;
|
|
@@ -146,7 +175,7 @@ function applyBudget(entries: string[], budget: number): { text: string; truncat
|
|
|
146
175
|
}
|
|
147
176
|
}
|
|
148
177
|
|
|
149
|
-
return { text: selected.join("\n\n"), truncated };
|
|
178
|
+
return { text: selected.join("\n\n"), truncated, visibleRanges };
|
|
150
179
|
}
|
|
151
180
|
|
|
152
181
|
function resolveAutoMode(hits: SearchHit[]): Exclude<CodeSearchMode, "auto"> | "mixed" {
|
|
@@ -167,23 +196,22 @@ function decorateResult(
|
|
|
167
196
|
requestedMode: CodeSearchMode,
|
|
168
197
|
hitCount: number,
|
|
169
198
|
): FormattedCodeSearchResults {
|
|
170
|
-
const header = `[code_search mode=${requestedMode}->${result.mode}; matches=${hitCount}]`;
|
|
171
|
-
// Explicit full mode is the compatibility escape hatch: preserve the
|
|
172
|
-
// pre-change body exactly so callers that parse the legacy output do not
|
|
173
|
-
// need to change. Auto-full still gets the diagnostic header below.
|
|
174
199
|
if (result.mode === "full" && requestedMode === "full") {
|
|
175
200
|
return result;
|
|
176
201
|
}
|
|
177
|
-
if (result.mode === "full") {
|
|
178
|
-
return { ...result, text: `${header}\n\n${result.text}` };
|
|
179
|
-
}
|
|
180
202
|
|
|
181
|
-
const
|
|
203
|
+
const notice = result.mode === "mixed"
|
|
204
|
+
? `${hitCount} matches returned; first ${Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} shown as previews, remaining ${hitCount - Math.min(AUTO_PREVIEW_HIT_LIMIT, hitCount)} summarized.`
|
|
205
|
+
: "";
|
|
206
|
+
const prefix = notice ? `${notice}\n\n` : "";
|
|
207
|
+
const available = Math.max(0, AUTO_OUTPUT_BUDGET - prefix.length);
|
|
182
208
|
const boundedText = clipToBudget(result.text, available);
|
|
209
|
+
const finalClipped = boundedText.length < result.text.length;
|
|
183
210
|
return {
|
|
184
211
|
...result,
|
|
185
|
-
text: `${
|
|
186
|
-
truncated: result.truncated ||
|
|
212
|
+
text: `${prefix}${boundedText}`,
|
|
213
|
+
truncated: result.truncated || finalClipped,
|
|
214
|
+
visibleRanges: finalClipped ? [] : result.visibleRanges,
|
|
187
215
|
};
|
|
188
216
|
}
|
|
189
217
|
|
|
@@ -205,6 +233,11 @@ export function formatCodeSearchResults(
|
|
|
205
233
|
text: hits.map(fullHit).join("\n\n"),
|
|
206
234
|
mode: "full",
|
|
207
235
|
truncated: false,
|
|
236
|
+
visibleRanges: hits.map((hit) => ({
|
|
237
|
+
chunkId: hit.chunk.id,
|
|
238
|
+
startLine: hit.chunk.startLine,
|
|
239
|
+
endLine: hit.chunk.endLine,
|
|
240
|
+
})),
|
|
208
241
|
},
|
|
209
242
|
requestedMode,
|
|
210
243
|
hits.length,
|
|
@@ -212,7 +245,10 @@ export function formatCodeSearchResults(
|
|
|
212
245
|
}
|
|
213
246
|
|
|
214
247
|
if (autoMode === "summary") {
|
|
215
|
-
const bounded = applyBudget(
|
|
248
|
+
const bounded = applyBudget(
|
|
249
|
+
hits.map((hit) => ({ text: summaryHit(hit) })),
|
|
250
|
+
AUTO_OUTPUT_BUDGET,
|
|
251
|
+
);
|
|
216
252
|
return decorateResult({ ...bounded, mode: "summary" }, requestedMode, hits.length);
|
|
217
253
|
}
|
|
218
254
|
|
|
@@ -231,7 +267,7 @@ export function formatCodeSearchResults(
|
|
|
231
267
|
.map((hit) => queryPreview(hit, query));
|
|
232
268
|
const remainingSummary = hits
|
|
233
269
|
.slice(AUTO_PREVIEW_HIT_LIMIT)
|
|
234
|
-
.map(summaryHit);
|
|
270
|
+
.map((hit) => ({ text: summaryHit(hit) }));
|
|
235
271
|
const bounded = applyBudget([...topPreview, ...remainingSummary], AUTO_OUTPUT_BUDGET);
|
|
236
272
|
return decorateResult({ ...bounded, mode: "mixed" }, requestedMode, hits.length);
|
|
237
273
|
}
|