@floydous/pi-agent-kernel 0.3.31 → 0.4.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 (40) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +6 -4
  2. package/CHANGELOG.md +35 -4
  3. package/README.md +39 -74
  4. package/config.example.toml +36 -0
  5. package/docs/configuration.md +11 -3
  6. package/docs/retrieval.md +17 -1
  7. package/docs/testing.md +5 -3
  8. package/package.json +9 -7
  9. package/src/config/agent_kernel_command.ts +91 -91
  10. package/src/config/kernel_config.ts +179 -43
  11. package/src/config/toml.ts +15 -4
  12. package/src/context/session_repair.ts +179 -80
  13. package/src/editing/patch.ts +28 -16
  14. package/src/editing/smart_anchor.ts +29 -36
  15. package/src/editing/syntax-verify.ts +52 -18
  16. package/src/index.ts +257 -219
  17. package/src/lsp/lsp_client.ts +138 -23
  18. package/src/lsp/lsp_formatter.ts +61 -24
  19. package/src/lsp/lsp_installer.ts +277 -561
  20. package/src/lsp/lsp_manager.ts +1 -1
  21. package/src/lsp/lsp_registry.ts +110 -73
  22. package/src/retrieval/ast_search.ts +136 -172
  23. package/src/retrieval/repomap.ts +8 -47
  24. package/src/retrieval/search_bm25.ts +5 -2
  25. package/src/retrieval/search_cache.ts +69 -0
  26. package/src/retrieval/search_chunker.ts +21 -43
  27. package/src/retrieval/search_config.ts +75 -18
  28. package/src/retrieval/search_embedder.ts +8 -16
  29. package/src/retrieval/search_index.ts +923 -123
  30. package/src/retrieval/workspace_walker.ts +262 -0
  31. package/src/safety/atomic_write.ts +59 -20
  32. package/src/safety/epistemic_guard.ts +163 -43
  33. package/src/safety/output_clamper.ts +316 -74
  34. package/src/tools/code_search_output.ts +59 -23
  35. package/src/tools/code_search_tool.ts +42 -46
  36. package/src/tools/context.ts +15 -1
  37. package/src/tools/edit_tool.ts +124 -43
  38. package/src/tools/lsp_tool.ts +17 -4
  39. package/src/tools/read_tool.ts +48 -7
  40. package/config.toml +0 -31
@@ -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: 40)
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 ?? 40;
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
- const originalBytes = Buffer.byteLength(rawText, "utf8");
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 and within bounds, return as-is
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
- !rawText.includes("\n") &&
81
- rawText.length <= maxLineLength
265
+ !textToProcess.includes("\n") &&
266
+ textToProcess.length <= maxLineLength
82
267
  ) {
83
268
  return {
84
- text: rawText,
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 = rawText.split(/\r?\n/);
278
+ const rawLines = textToProcess.split(/\r?\n/);
94
279
  const totalLines = rawLines.length;
95
- let needsTruncation = false;
280
+ let needsTruncation = hostTruncated || priorKernelTruncated;
96
281
 
97
- // Check if any line violates maxLineLength or total lines violate maxLines
98
- if (totalLines > maxLines || originalBytes > maxTotalBytes) {
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: rawText,
297
+ text: textToProcess,
113
298
  truncated: false,
114
299
  originalBytes,
115
300
  returnedBytes: originalBytes,
@@ -118,41 +303,16 @@ export function clampCommandOutput(
118
303
  };
119
304
  }
120
305
 
121
- // Save complete raw output to temporary spillover file (with bounded rotation by mtime to prevent unbounded tmp growth)
122
- let spilloverPath: string | undefined;
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 files = fs
128
- .readdirSync(tempDir)
129
- .filter((f) => f.startsWith("pi_bash_spillover_"))
130
- .map((name) => {
131
- const full = path.join(tempDir, name);
132
- try {
133
- return { name, full, mtime: fs.statSync(full).mtimeMs };
134
- } catch {
135
- return { name, full, mtime: 0 };
136
- }
137
- })
138
- .sort((a, b) => a.mtime - b.mtime);
139
-
140
- if (files.length > 20) {
141
- const toDelete = files.slice(0, files.length - 20);
142
- for (const item of toDelete) {
143
- try {
144
- fs.unlinkSync(item.full);
145
- } catch {}
146
- }
147
- }
148
- } catch {}
149
-
150
- const hash = crypto.randomBytes(4).toString("hex");
151
- const candidatePath = path.join(tempDir, `pi_bash_spillover_${hash}.log`);
152
- fs.writeFileSync(candidatePath, rawText, { encoding: "utf8", mode: 0o600 });
153
- spilloverPath = candidatePath;
154
- } catch (e) {
155
- 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
+ }
156
316
  }
157
317
 
158
318
  // Horizontal Line-Width Clamping & Vertical Head+Tail Capping
@@ -176,27 +336,98 @@ export function clampCommandOutput(
176
336
 
177
337
  let shownLines = totalLines;
178
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
+
179
347
  if (totalLines > maxLines) {
180
348
  const effectiveMaxLines = Math.max(2, maxLines);
181
- const headCount = Math.floor(effectiveMaxLines / 2);
182
- const tailCount = effectiveMaxLines - headCount;
183
- const omittedLines = totalLines - (headCount + tailCount);
184
- shownLines = headCount + tailCount;
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);
185
354
 
186
- // Head lines
187
- for (let i = 0; i < headCount; i++) {
188
- clampedLines.push(formatLine(rawLines[i], i));
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
+ }
189
364
  }
190
365
 
191
- // Middle omission marker
192
- clampedLines.push(
193
- `\n[... ${omittedLines.toLocaleString()} lines omitted ...]\n`,
194
- );
366
+ const hasDiagnosticFailure = !isDiscovery && !isExplicitSuccess && (isExplicitError || diagIndices.length > 0);
195
367
 
196
- // Tail lines
197
- const tailStart = totalLines - tailCount;
198
- for (let i = tailStart; i < totalLines; i++) {
199
- clampedLines.push(formatLine(rawLines[i], i));
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
+ }
200
431
  }
201
432
  } else {
202
433
  for (let i = 0; i < totalLines; i++) {
@@ -206,13 +437,30 @@ export function clampCommandOutput(
206
437
 
207
438
  let resultText = clampedLines.join("\n");
208
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
+
209
462
  // Append concise footer with spillover pointer
210
- let footer = `\n\n[Truncated: ${shownLines}/${totalLines} lines.`;
211
- if (spilloverPath) {
212
- footer += ` Full: ${spilloverPath}]`;
213
- } else {
214
- footer += `]`;
215
- }
463
+ let footer = makeFooter(shownLines);
216
464
 
217
465
  if (Buffer.byteLength(resultText + footer, "utf8") > maxTotalBytes) {
218
466
  const marker = clampedLines.findIndex((line) => /^\n\[\.\.\. /.test(line));
@@ -229,13 +477,7 @@ export function clampCommandOutput(
229
477
  1,
230
478
  );
231
479
  if (!removed.startsWith("\n[... ")) shownLines--;
232
- footer =
233
- "\n\n[Truncated: " +
234
- shownLines +
235
- "/" +
236
- totalLines +
237
- " lines." +
238
- (spilloverPath ? " Full: " + spilloverPath + "]" : "]");
480
+ footer = makeFooter(shownLines);
239
481
  }
240
482
  resultText = clampedLines.join("\n") + footer;
241
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(hit: SearchHit, query: string): string {
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 `${hitHeader(hit)}\n\`\`\`${languageFor(hit.chunk.filePath)}\n${clipped}\n\`\`\``;
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
- function applyBudget(entries: string[], budget: number): { text: string; truncated: boolean } {
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 + entries[index].length;
144
+ const candidateLength = separator.length + entry.text.length;
117
145
  if (used + candidateLength <= budget) {
118
- selected.push(entries[index]);
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(entries[index], budget);
153
+ const clipped = clipToBudget(entry.text, budget);
125
154
  selected.push(clipped);
126
155
  used = clipped.length;
127
- truncated = clipped.length < entries[index].length;
128
- // The first entry is present (possibly clipped), so only entries after
129
- // it are "additional" matches omitted from the response.
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 available = Math.max(0, AUTO_OUTPUT_BUDGET - header.length - 2);
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: `${header}\n\n${boundedText}`,
186
- truncated: result.truncated || boundedText.length < result.text.length,
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(hits.map(summaryHit), AUTO_OUTPUT_BUDGET);
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
  }