@criogaid/pi-hashline-edit 0.1.3 → 0.3.0

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 (44) hide show
  1. package/README.md +77 -23
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +87 -10
  4. package/src/core/apply.ts +106 -84
  5. package/src/core/lines.test.ts +12 -1
  6. package/src/core/lines.ts +43 -1
  7. package/src/core/ranges.test.ts +28 -0
  8. package/src/core/ranges.ts +25 -0
  9. package/src/core/text.ts +5 -0
  10. package/src/core/types.ts +37 -20
  11. package/src/integration/grep-rg.test.ts +188 -1
  12. package/src/pi/action-fusion.test.ts +3 -1
  13. package/src/pi/action-fusion.ts +38 -35
  14. package/src/pi/anchor-format.test.ts +30 -0
  15. package/src/pi/anchor-format.ts +28 -0
  16. package/src/pi/config.ts +1 -1
  17. package/src/pi/edit-tool.ts +91 -100
  18. package/src/pi/execute.test.ts +239 -14
  19. package/src/pi/failure-context.test.ts +99 -62
  20. package/src/pi/failure-context.ts +67 -64
  21. package/src/pi/failure-path.test.ts +20 -2
  22. package/src/pi/file-commit.test.ts +21 -0
  23. package/src/pi/file-commit.ts +35 -3
  24. package/src/pi/fusion-card.test.ts +38 -1
  25. package/src/pi/fusion-card.ts +41 -17
  26. package/src/pi/grep-tool.ts +84 -55
  27. package/src/pi/grep.test.ts +77 -6
  28. package/src/pi/mutation-result.ts +48 -9
  29. package/src/pi/path.ts +22 -0
  30. package/src/pi/pi.test.ts +64 -2
  31. package/src/pi/read-tool.ts +9 -30
  32. package/src/pi/registration.test.ts +28 -1
  33. package/src/pi/render.test.ts +111 -0
  34. package/src/pi/render.ts +30 -6
  35. package/src/pi/replace-tool.ts +144 -140
  36. package/src/pi/replace.test.ts +193 -1
  37. package/src/pi/result-safety.test.ts +241 -8
  38. package/src/pi/rg-line-filter.test.ts +7 -1
  39. package/src/pi/rg-line-filter.ts +10 -12
  40. package/src/pi/rg-line-ranges.test.ts +10 -0
  41. package/src/pi/rg-line-ranges.ts +21 -15
  42. package/src/pi/rg-text-view.ts +88 -0
  43. package/src/pi/write-tool.ts +13 -47
  44. package/src/pi/write.test.ts +25 -36
@@ -6,10 +6,16 @@ import type { ActionFusionProgress } from "./action-fusion.ts";
6
6
  const CARD_TYPE = "hashline-then-run";
7
7
  const RESULT_TYPE = "hashline-then-run-result";
8
8
 
9
+ type CommandCardData = Pick<ActionFusionProgress, "toolCallId" | "commandText" | "command" | "output" | "reason"> & { version: 1 };
10
+
11
+ function commandCardData({ toolCallId, commandText, command, output, reason }: ActionFusionProgress): CommandCardData {
12
+ return { version: 1, toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
13
+ }
14
+
9
15
  /** Render one durable transcript card per fused command without adding model context. */
10
16
  export function registerFusionCards(pi: ExtensionAPI) {
11
17
  const bash = createBashToolDefinition(process.cwd());
12
- const states = new Map<string, ActionFusionProgress>();
18
+ const states = new Map<string, CommandCardData>();
13
19
  const active = new Set<string>();
14
20
 
15
21
  const restore = (ctx: ExtensionContext) => {
@@ -17,16 +23,29 @@ export function registerFusionCards(pi: ExtensionAPI) {
17
23
  active.clear();
18
24
  for (const entry of ctx.sessionManager.getBranch()) {
19
25
  if (entry.type !== "custom" || (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)) continue;
20
- const data = entry.data as ActionFusionProgress | undefined;
26
+ const data = entry.data as (ActionFusionProgress & { version?: number }) | undefined;
21
27
  if (data && typeof data.toolCallId === "string" && typeof data.commandText === "string" && typeof data.output === "string") {
22
- states.set(data.toolCallId, data);
28
+ const restored = commandCardData(data);
29
+ // Older snapshots stored the compound error in output. Recover only a known command wrapper.
30
+ if (data.version !== 1 && ["skipped", "cancelled", "failed", "timeout"].includes(data.command)) {
31
+ const marker = data.command === "cancelled" ? "[then_run:skipped]" : "[then_run:failed]";
32
+ const fileState = data.publication === "PUBLISHED" ? "File changes are saved."
33
+ : data.publication === "NOT_PUBLISHED" ? "No file changes were published." : "File state is uncertain.";
34
+ const prefix = `mutation completed; then_run did not complete successfully ${marker}\n${fileState} Command ${data.command}.\n`;
35
+ if (data.command !== "skipped" && data.output.startsWith(prefix)) restored.output = data.output.slice(prefix.length);
36
+ else {
37
+ restored.output = "";
38
+ restored.reason = data.command === "skipped" ? "Command was not run." : "Legacy failure details are available in the original tool result.";
39
+ }
40
+ }
41
+ states.set(data.toolCallId, restored);
23
42
  }
24
43
  }
25
44
  };
26
45
  pi.on("session_start", (_event, ctx) => restore(ctx));
27
46
  pi.on("session_tree", (_event, ctx) => restore(ctx));
28
47
 
29
- pi.registerEntryRenderer<ActionFusionProgress>(CARD_TYPE, (entry, { expanded }, theme) => {
48
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
30
49
  const initial = entry.data;
31
50
  if (!initial) return undefined;
32
51
  const statusText = new Text("", 0, 0);
@@ -40,26 +59,30 @@ export function registerFusionCards(pi: ExtensionAPI) {
40
59
  // Read live state during rendering; native tool updates schedule the repaint.
41
60
  const current = states.get(initial.toolCallId) ?? initial;
42
61
  const pending = current.command === "waiting" || current.command === "running";
43
- const status = pending && !active.has(current.toolCallId) ? "interrupted (final status unknown)" : current.command;
44
- const color = pending ? "warning" : current.command === "succeeded" ? "success" : "error";
45
- const background = pending ? "toolPendingBg" : current.command === "succeeded" ? "toolSuccessBg" : "toolErrorBg";
62
+ const interrupted = pending && !active.has(current.toolCallId);
63
+ const status = interrupted ? "interrupted (final status unknown)" : current.command;
64
+ const failed = current.command === "failed" || current.command === "timeout";
65
+ const color = pending || current.command === "cancelled" ? "warning" : failed ? "error" : current.command === "succeeded" ? "success" : "dim";
66
+ const background = pending && !interrupted ? "toolPendingBg" : failed ? "toolErrorBg" : current.command === "succeeded" ? "toolSuccessBg" : "customMessageBg";
46
67
  box.setBgFn((line) => theme.bg(background, line));
47
- const stale = current.freshness === "changed" || current.freshness === "missing" ? `\nAnchors are stale: target ${current.freshness}.` : "";
48
- statusText.setText(`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}\n${current.path}\npublication=${current.publication} freshness=${current.freshness}${stale}`);
68
+ statusText.setText(`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`);
49
69
  const context = {
50
70
  args: { command: current.commandText }, toolCallId: current.toolCallId, cwd: process.cwd(),
51
71
  state: rendererState, invalidate: () => box.invalidate(),
52
72
  // Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
53
- executionStarted: false, argsComplete: true, isPartial: pending, expanded, showImages: false,
54
- isError: !pending && current.command !== "succeeded",
73
+ executionStarted: false, argsComplete: true, isPartial: pending && !interrupted, expanded, showImages: false,
74
+ isError: failed,
55
75
  };
56
76
  call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
57
- result = bash.renderResult!({ content: [{ type: "text", text: current.output }], details: undefined },
58
- { expanded, isPartial: pending }, theme, { ...context, lastComponent: result });
59
77
  box.clear();
60
78
  box.addChild(statusText);
61
79
  box.addChild(call);
62
- box.addChild(result);
80
+ if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
81
+ if (current.output || current.command === "succeeded" || failed) {
82
+ result = bash.renderResult!({ content: [{ type: "text", text: current.output }], details: undefined },
83
+ { expanded, isPartial: context.isPartial }, theme, { ...context, lastComponent: result });
84
+ box.addChild(result);
85
+ }
63
86
  return box.render(width);
64
87
  },
65
88
  };
@@ -67,12 +90,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
67
90
 
68
91
  return (progress: ActionFusionProgress) => {
69
92
  const first = !states.has(progress.toolCallId);
70
- states.set(progress.toolCallId, progress);
93
+ const data = commandCardData(progress);
94
+ states.set(progress.toolCallId, data);
71
95
  const pending = progress.command === "waiting" || progress.command === "running";
72
96
  if (pending) active.add(progress.toolCallId);
73
97
  else active.delete(progress.toolCallId);
74
98
  // Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
75
- if (first) pi.appendEntry(CARD_TYPE, progress);
76
- if (!pending) pi.appendEntry(RESULT_TYPE, progress);
99
+ if (first) pi.appendEntry(CARD_TYPE, data);
100
+ if (!pending) pi.appendEntry(RESULT_TYPE, data);
77
101
  };
78
102
  }
@@ -26,7 +26,6 @@
26
26
 
27
27
  import {
28
28
  truncateHead,
29
- truncateLine,
30
29
  formatSize,
31
30
  DEFAULT_MAX_BYTES,
32
31
  } from "@earendil-works/pi-coding-agent";
@@ -35,14 +34,14 @@ import { Type } from "typebox";
35
34
  import { Text } from "@earendil-works/pi-tui";
36
35
  import { readFile, realpath, stat } from "node:fs/promises";
37
36
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
38
- import { computeLineHash } from "../core/hash.ts";
39
- import { splitLines } from "../core/lines.ts";
37
+ import { normalizeLineEndings, splitLines } from "../core/lines.ts";
40
38
  import { decodeEditableText } from "../core/text.ts";
41
- import { getState } from "./state.ts";
42
- import { canonicalPath } from "./read-tool.ts";
43
- import { parseHashline } from "./render.ts";
39
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
40
+ import { canonicalPath } from "./path.ts";
41
+ import { parseHashline, renderToolError } from "./render.ts";
44
42
  import {
45
43
  COMMON_RG_ARGS,
44
+ type RgRunResult,
46
45
  createLinePredicate,
47
46
  matcherArgs,
48
47
  resolveIgnoreCase,
@@ -54,10 +53,11 @@ import {
54
53
  type LinePredicate,
55
54
  type SearchModes,
56
55
  } from "./rg-line-filter.ts";
56
+ import { runRgTextView } from "./rg-text-view.ts";
57
57
  import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
58
58
 
59
59
  const DEFAULT_LIMIT = 100;
60
- /** Max chars per result line for display (mirrors pi's truncate.ts; not exported there). */
60
+ /** Maximum UTF-16 units in a line preview, excluding its partial-line label. */
61
61
  const GREP_MAX_LINE_LENGTH = 500;
62
62
  const GREP_CONTEXT_MAX = 20;
63
63
  const MAX_ALL_PATTERNS = 16;
@@ -67,10 +67,35 @@ const FILTER_BATCH_BYTES = 1024 * 1024;
67
67
  const FILE_BATCH_SIZE = 64;
68
68
  const FILE_BATCH_ARG_BYTES = 16 * 1024;
69
69
  const MAX_PENDING_RANGES = 262_144;
70
- const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched all patterns as literal text";
70
+ const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
71
71
  const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
72
72
  const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
73
73
 
74
+ /** Exclusion scans must succeed: incomplete exclusions could admit false matches. */
75
+ function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
76
+ const message = result.stderr.trim() || (!result.stopped && result.code !== 0 && result.code !== 1
77
+ ? `ripgrep exited with code ${result.code}` : "");
78
+ if (!message) return;
79
+ if (!warnings) throw new Error(message);
80
+ warnings.push(message);
81
+ }
82
+
83
+ function formatSearchWarnings(warnings: readonly string[]): string {
84
+ if (!warnings.length) return "";
85
+ const summary = truncateHead([...new Set(warnings)].join("\n"), { maxBytes: 4 * 1024 });
86
+ return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? "\nAdditional search diagnostics omitted (4 KiB limit)." : ""}]`;
87
+ }
88
+
89
+ function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
90
+ if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
91
+ let start = Math.max(0, Math.min(column - 100, text.length - GREP_MAX_LINE_LENGTH));
92
+ // Slice at UTF-16 boundaries without splitting an astral character.
93
+ if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
94
+ let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
95
+ if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
96
+ return { text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`, wasTruncated: true };
97
+ }
98
+
74
99
  async function resolveLiteralMode(
75
100
  patterns: readonly string[],
76
101
  explicit: boolean | undefined,
@@ -78,6 +103,7 @@ async function resolveLiteralMode(
78
103
  backend: GrepBackend,
79
104
  modes: Pick<SearchModes, "engine" | "multiline">,
80
105
  signal: AbortSignal | undefined,
106
+ allowFallback: boolean,
81
107
  ): Promise<boolean> {
82
108
  if (modes.engine === "pcre2") return false;
83
109
  if (explicit === true) return true;
@@ -101,6 +127,7 @@ async function resolveLiteralMode(
101
127
  if (result.code === 0 || result.code === 1) return false;
102
128
  if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
103
129
  if (explicit === false) throw new Error(result.stderr.trim());
130
+ if (!allowFallback) throw new Error(`Invalid regex in compound query; automatic literal fallback is disabled. Fix the regex or set literal:true for all patterns.\n${result.stderr.trim()}`);
104
131
  return true;
105
132
  }
106
133
  throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
@@ -120,7 +147,7 @@ function clampContext(context: number | undefined): number {
120
147
  const grepOverrideSchema = Type.Object({
121
148
  pattern: Type.Union([Type.String(), Type.Array(Type.String())], {
122
149
  description:
123
- "Non-empty pattern(s). Arrays use matchMode.",
150
+ "Non-empty string or array (OR by default). For code snippets with regex punctuation, set literal:true; use an array for alternatives instead of joining literals with |.",
124
151
  }),
125
152
  matchMode: Type.Optional(
126
153
  Type.Union([Type.Literal("any"), Type.Literal("all")], {
@@ -155,7 +182,7 @@ const grepOverrideSchema = Type.Object({
155
182
  ),
156
183
  literal: Type.Optional(
157
184
  Type.Boolean({
158
- description: "true: literal; false: regex, no fallback. Shared by pattern/excludePattern. Default: literal unless any pattern has regex syntax; any rg parse failure makes all literal.",
185
+ description: "Set true for literal code text, especially calls, brackets, pipes, and backslashes. Set false only for intentional valid regex. Applies to pattern and excludePattern. Automatic mode tries regex for metacharacters; only one pattern without exclusions can fall back, searching the entire input literally.",
159
186
  }),
160
187
  ),
161
188
  noIgnore: Type.Optional(Type.Boolean({
@@ -185,6 +212,7 @@ const grepOverrideSchema = Type.Object({
185
212
  interface RgMatch {
186
213
  filePath: string;
187
214
  lineNumber: number;
215
+ column?: number;
188
216
  }
189
217
 
190
218
  /** @internal — injectable process boundary for deterministic tests. */
@@ -235,6 +263,7 @@ async function filterExplicitFilesByGlob(
235
263
  scope: SearchScope,
236
264
  paths: readonly SearchPathInfo[],
237
265
  signal: AbortSignal | undefined,
266
+ warnings: string[],
238
267
  ): Promise<string[]> {
239
268
  const explicitFiles = paths.filter(({ isFile }) => isFile);
240
269
  if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
@@ -255,9 +284,7 @@ async function filterExplicitFilesByGlob(
255
284
  allowed.add(fileKey(path));
256
285
  return true;
257
286
  });
258
- if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
259
- throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
260
- }
287
+ recordSearchDiagnostics(listed, warnings);
261
288
  return paths
262
289
  .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
263
290
  .map(({ path }) => path);
@@ -306,6 +333,8 @@ async function scanPatternRanges(
306
333
  word: boolean,
307
334
  signal: AbortSignal | undefined,
308
335
  lineCounts: Map<string, number>,
336
+ warnings?: string[],
337
+ columns?: Map<string, Map<number, number>>,
309
338
  ): Promise<Map<string, LineRange[]>> {
310
339
  if (files.length === 0) return new Map();
311
340
  const args = [
@@ -339,14 +368,14 @@ async function scanPatternRanges(
339
368
  if (!Array.isArray(data.submatches)) throw new Error("Invalid rg submatch protocol");
340
369
  if (data.submatches.length === 0) submatches = [{ start: bytes.length, end: bytes.length }];
341
370
  else submatches = data.submatches.map((match: any) => ({ start: match.start, end: match.end }));
342
- const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount);
371
+ const fileColumns = columns?.get(filePath) ?? new Map<number, number>();
372
+ const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount, columns ? fileColumns : undefined);
373
+ columns?.set(filePath, fileColumns);
343
374
  result.set(filePath, unionRanges(result.get(filePath) ?? [], ranges));
344
375
  if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
345
376
  return true;
346
377
  });
347
- if (!run.stopped && run.code !== 0 && run.code !== 1) {
348
- throw new Error(run.stderr.trim() || `ripgrep exited with code ${run.code}`);
349
- }
378
+ recordSearchDiagnostics(run, warnings);
350
379
  return result;
351
380
  }
352
381
 
@@ -361,10 +390,11 @@ interface ComplexSearchOptions {
361
390
  word: boolean;
362
391
  limit: number;
363
392
  signal?: AbortSignal;
393
+ warnings: string[];
364
394
  }
365
395
 
366
396
  async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMatch[]; matchLimitReached: boolean; identities: Map<string, FileIdentity> }> {
367
- const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal } = options;
397
+ const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal, warnings } = options;
368
398
  const raw: RgMatch[] = [];
369
399
  const identities = new Map<string, FileIdentity>();
370
400
  const seen = new Set<string>();
@@ -379,11 +409,12 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
379
409
  if (files.length === 0) return true;
380
410
  for (const file of files) identities.set(file, await fileIdentity(file));
381
411
  const lineCounts = new Map<string, number>();
412
+ const columns = new Map<string, Map<number, number>>();
382
413
 
383
414
  let included = new Map<string, LineRange[]>();
384
415
  for (let index = 0; index < patterns.length; index++) {
385
416
  const candidates = matchMode === "all" && index > 0 ? files.filter((file) => included.has(file)) : files;
386
- const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts);
417
+ const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts, warnings, columns);
387
418
  included = index === 0 ? ranges : combineRangeMaps(included, ranges, matchMode === "all" ? "intersect" : "union");
388
419
  if (matchMode === "all" && included.size === 0) break;
389
420
  }
@@ -406,7 +437,7 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
406
437
  }
407
438
  for (const [start, end] of included.get(file) ?? []) {
408
439
  for (let lineNumber = start; lineNumber < end; lineNumber++) {
409
- raw.push({ filePath: file, lineNumber });
440
+ raw.push({ filePath: file, lineNumber, column: columns.get(file)?.get(lineNumber) });
410
441
  if (raw.length >= limit) {
411
442
  matchLimitReached = true;
412
443
  return false;
@@ -434,9 +465,7 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
434
465
  batchBytes += Buffer.byteLength(filePath) + 1;
435
466
  return batch.length >= FILE_BATCH_SIZE || batchBytes >= FILE_BATCH_ARG_BYTES ? processBatch() : true;
436
467
  });
437
- if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
438
- throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
439
- }
468
+ recordSearchDiagnostics(listed, warnings);
440
469
  if (!matchLimitReached && batch.length) await processBatch();
441
470
  return { raw, matchLimitReached, identities };
442
471
  }
@@ -502,7 +531,7 @@ export function makeGrepOverride(cwd: string) {
502
531
  /** @internal — build a grep override with deterministic process backends for tests. */
503
532
  export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<GrepBackend>) {
504
533
  const backend: GrepBackend = {
505
- runRg,
534
+ runRg: runRgTextView,
506
535
  runRgPaths,
507
536
  resolveIgnoreCase,
508
537
  validatePatterns,
@@ -514,10 +543,11 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
514
543
  name: "grep" as const,
515
544
  label: "grep",
516
545
  description:
517
- "Search file contents with ripgrep and return LINE#HASH anchors for physical lines. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
546
+ "Search LF-normalized file contents with ripgrep and return LINE#HASH anchors for logical lines. CRLF queries normalize to LF; standalone CR stays content. Supports standard or PCRE2 regexes, multiline matching, ignore overrides, and linked directories.",
518
547
  promptSnippet: "Search file contents with ripgrep",
519
548
  promptGuidelines: [
520
549
  "Prefer the grep tool for file-content searches.",
550
+ "Set literal:true when searching code text containing regex punctuation (for example pi.on(, compact(, or \\0); use a pattern array for literal alternatives. Use literal:false only for intentional valid regex.",
521
551
  "Use returned grep anchors directly for edits; no re-read needed.",
522
552
  "Use files/count when only paths or counts are needed; use matchMode all and excludePattern instead of shell pipelines.",
523
553
  ],
@@ -557,11 +587,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
557
587
 
558
588
  renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
559
589
  if (isPartial) return new Text(theme.fg("warning", "Searching…"), 0, 0);
560
- if (context?.isError) {
561
- const t =
562
- result.content?.[0]?.type === "text" ? result.content[0].text.split("\n")[0] : "Error";
563
- return new Text(theme.fg("error", t), 0, 0);
564
- }
590
+ if (context?.isError) return renderToolError(result, theme);
565
591
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
566
592
  const styled = toDisplayLines(out, theme);
567
593
  const maxLines = expanded ? styled.length : 15;
@@ -579,17 +605,18 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
579
605
  signal: AbortSignal | undefined,
580
606
  _onUpdate: any,
581
607
  ): Promise<any> {
582
- const state = getState();
583
608
  if (signal?.aborted) throw new Error("Operation aborted");
609
+ const anchors = createAnchorFormatter();
610
+ const warnings: string[] = [];
584
611
 
585
- const patterns = toArray(params.pattern);
612
+ const patterns = toArray(params.pattern).map(normalizeLineEndings);
586
613
  if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
587
614
  if (patterns.some((pattern) => pattern.trim() === "")) {
588
615
  throw new Error("pattern must not be empty");
589
616
  }
590
617
 
591
618
  const rgPath = bundledRgPath;
592
- const excludes = toArray(params.excludePattern);
619
+ const excludes = toArray(params.excludePattern).map(normalizeLineEndings);
593
620
  const matchMode: "any" | "all" = params.matchMode ?? "any";
594
621
  const outputMode: "content" | "files" | "count" = params.outputMode ?? "content";
595
622
  const globs = toArray(params.glob);
@@ -600,7 +627,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
600
627
  }
601
628
  const allPatterns = [...patterns, ...excludes];
602
629
  const literal = await resolveLiteralMode(
603
- allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal,
630
+ allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal, patterns.length === 1 && excludes.length === 0,
604
631
  );
605
632
  const literalFallback = !params.pcre2 && params.literal === undefined && literal &&
606
633
  allPatterns.some((pattern) => REGEX_SYNTAX.test(pattern));
@@ -620,7 +647,6 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
620
647
  follow: params.follow === true,
621
648
  searchPaths,
622
649
  };
623
- const hashLen = state.config.hashLen;
624
650
 
625
651
  const pathInfo: SearchPathInfo[] = [];
626
652
  for (const searchPath of searchPaths) {
@@ -629,7 +655,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
629
655
  }
630
656
  scope = {
631
657
  ...scope,
632
- searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal),
658
+ searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal, warnings),
633
659
  };
634
660
  if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
635
661
  throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
@@ -650,7 +676,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
650
676
  await backend.validatePatterns(rgPath, excludes, modes, false, signal);
651
677
  const result = await complexSearch({
652
678
  backend, rgPath, scope, patterns, excludes, matchMode, modes,
653
- word: !!wordMatch, limit: effectiveLimit, signal,
679
+ word: !!wordMatch, limit: effectiveLimit, signal, warnings,
654
680
  });
655
681
  raw = result.raw;
656
682
  matchLimitReached = result.matchLimitReached;
@@ -675,7 +701,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
675
701
  ? backend.createLinePredicate(rgPath, excludes, modes, false, signal)
676
702
  : undefined;
677
703
  const predicates: LinePredicate[] = [...andPredicates, ...(exclusionPredicate ? [exclusionPredicate] : [])];
678
- const batch: { filePath: string; lineNumber: number; line: Buffer }[] = [];
704
+ const batch: { filePath: string; lineNumber: number; line: Buffer; column: number }[] = [];
679
705
  let batchBytes = 0;
680
706
  const flushBatch = async (): Promise<boolean> => {
681
707
  const candidates = batch.splice(0);
@@ -686,7 +712,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
686
712
  if (!decisions.every((results, predicate) =>
687
713
  predicate < andPredicates.length ? results[index] : !results[index],
688
714
  )) continue;
689
- raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber });
715
+ raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber, column: candidates[index].column });
690
716
  matchCount++;
691
717
  if (matchCount >= effectiveLimit) {
692
718
  matchLimitReached = true;
@@ -714,7 +740,8 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
714
740
  if (seenMatches.has(matchKey)) return true;
715
741
  seenMatches.add(matchKey);
716
742
  const bytes = rgBytes(data.lines);
717
- batch.push({ filePath, lineNumber: data.line_number, line: bytes });
743
+ batch.push({ filePath, lineNumber: data.line_number, line: bytes,
744
+ column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length });
718
745
  batchBytes += bytes.length;
719
746
  if (predicates.length === 0 || batch.length >= FILTER_BATCH_SIZE || batchBytes >= FILTER_BATCH_BYTES) {
720
747
  return flushBatch();
@@ -722,28 +749,26 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
722
749
  return true;
723
750
  });
724
751
  if (signal?.aborted) throw new Error("Operation aborted");
725
- if (!run.stopped && run.code !== 0 && run.code !== 1) {
726
- throw new Error(run.stderr.trim() || `ripgrep exited with code ${run.code}`);
727
- }
752
+ recordSearchDiagnostics(run, warnings);
728
753
  if (batch.length && matchCount < effectiveLimit) await flushBatch();
729
754
  }
730
755
 
731
756
  if (raw.length === 0) {
757
+ if (warnings.length) throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
732
758
  return {
733
- content: [{ type: "text" as const, text: literalFallback
734
- ? `No matches found\n\n[${LITERAL_FALLBACK_NOTICE}]` : "No matches found" }],
759
+ content: [{ type: "text" as const, text: "No matches found" + (literalFallback ? `\n\n[${LITERAL_FALLBACK_NOTICE}]` : "") }],
735
760
  details: undefined,
736
761
  };
737
762
  }
738
763
 
739
764
  // Group by file, matches sorted by line number (Map keeps rg's discovery order).
740
- const byFile = new Map<string, number[]>();
765
+ const byFile = new Map<string, RgMatch[]>();
741
766
  for (const match of raw) {
742
767
  const lines = byFile.get(match.filePath) ?? [];
743
- lines.push(match.lineNumber);
768
+ lines.push(match);
744
769
  byFile.set(match.filePath, lines);
745
770
  }
746
- for (const lines of byFile.values()) lines.sort((a, b) => a - b);
771
+ for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
747
772
 
748
773
  // Read each file once; only hash the selected match/context rows below.
749
774
  const getFile = async (filePath: string) => {
@@ -752,7 +777,8 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
752
777
  bytes = await readFile(filePath);
753
778
  } catch (error) {
754
779
  if (strictIdentities) throw error;
755
- bytes = Buffer.alloc(0);
780
+ warnings.push(`Could not read ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
781
+ return undefined;
756
782
  }
757
783
  const content = decodeEditableText(bytes);
758
784
  if (strictIdentities) {
@@ -776,10 +802,12 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
776
802
  if (outputMode === "content") {
777
803
  for (const [filePath, matchLines] of byFile) {
778
804
  const lines = await getFile(filePath);
805
+ if (!lines) continue;
806
+ const columns = new Map(matchLines.map(match => [match.lineNumber, match.column]));
779
807
  // Context windows are rebuilt from surviving matches so context
780
808
  // lines of a filtered-out match never leak.
781
809
  const windowSet = new Set<number>();
782
- for (const lineNumber of matchLines) {
810
+ for (const { lineNumber } of matchLines) {
783
811
  for (
784
812
  let n = Math.max(1, lineNumber - ctx);
785
813
  n <= Math.min(lines.length, lineNumber + ctx);
@@ -790,10 +818,9 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
790
818
  const rows: string[] = [];
791
819
  for (const n of [...windowSet].sort((a, b) => a - b)) {
792
820
  const content = lines[n - 1] ?? "";
793
- const hash = n <= lines.length ? computeLineHash(n, content, hashLen) : "";
794
- const { text: display, wasTruncated } = truncateLine(content.replace(/\r/g, ""));
821
+ const { text: display, wasTruncated } = previewLine(displayCarriageReturns(content), columns.get(n));
795
822
  if (wasTruncated) linesTruncated = true;
796
- rows.push(`${n}#${hash}│${display}`);
823
+ rows.push(anchors.row(n, content, display));
797
824
  }
798
825
  blocks.push(`${header}${rows.join("\n")}`);
799
826
  }
@@ -810,6 +837,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
810
837
  );
811
838
  }
812
839
 
840
+ if (!blocks.length && warnings.length) throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
813
841
  let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
814
842
  const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
815
843
  output = truncation.content;
@@ -823,14 +851,15 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
823
851
  if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
824
852
  if (linesTruncated) {
825
853
  notices.push(
826
- `Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read to see full lines`,
854
+ `Partial line previews show up to ${GREP_MAX_LINE_LENGTH} characters near a match (context-only lines show the start). Columns are 1-based UTF-16 positions; anchors hash full lines. Use read for full content`,
827
855
  );
828
856
  }
829
857
  if (notices.length) output += `\n\n[${notices.join(". ")}]`;
858
+ output += formatSearchWarnings(warnings);
830
859
 
831
860
  return {
832
861
  content: [{ type: "text" as const, text: output }],
833
- details: undefined,
862
+ details: warnings.length ? { incomplete: true } : undefined,
834
863
  };
835
864
  },
836
865
  };