@criogaid/pi-hashline-edit 0.1.2 → 0.2.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 (39) hide show
  1. package/README.md +67 -21
  2. package/package.json +1 -1
  3. package/src/core/apply.test.ts +85 -8
  4. package/src/core/apply.ts +99 -79
  5. package/src/core/ranges.test.ts +28 -0
  6. package/src/core/ranges.ts +25 -0
  7. package/src/core/text.ts +5 -0
  8. package/src/core/types.ts +37 -20
  9. package/src/integration/grep-rg.test.ts +76 -1
  10. package/src/pi/action-fusion.test.ts +1 -1
  11. package/src/pi/action-fusion.ts +9 -21
  12. package/src/pi/anchor-format.test.ts +30 -0
  13. package/src/pi/anchor-format.ts +28 -0
  14. package/src/pi/config.test.ts +6 -9
  15. package/src/pi/config.ts +4 -4
  16. package/src/pi/edit-tool.ts +90 -99
  17. package/src/pi/execute.test.ts +240 -14
  18. package/src/pi/failure-context.test.ts +99 -62
  19. package/src/pi/failure-context.ts +67 -64
  20. package/src/pi/failure-path.test.ts +3 -2
  21. package/src/pi/file-commit.test.ts +21 -0
  22. package/src/pi/file-commit.ts +35 -3
  23. package/src/pi/grep-tool.ts +75 -48
  24. package/src/pi/grep.test.ts +67 -3
  25. package/src/pi/mutation-result.ts +46 -9
  26. package/src/pi/read-tool.ts +7 -10
  27. package/src/pi/registration.test.ts +15 -2
  28. package/src/pi/render.test.ts +24 -0
  29. package/src/pi/render.ts +18 -4
  30. package/src/pi/replace-tool.ts +134 -130
  31. package/src/pi/replace.test.ts +118 -1
  32. package/src/pi/result-safety.test.ts +241 -8
  33. package/src/pi/rg-line-filter.test.ts +7 -1
  34. package/src/pi/rg-line-filter.ts +9 -11
  35. package/src/pi/rg-line-ranges.test.ts +10 -0
  36. package/src/pi/rg-line-ranges.ts +21 -15
  37. package/src/pi/state.ts +2 -3
  38. package/src/pi/write-tool.ts +10 -44
  39. package/src/pi/write.test.ts +25 -36
@@ -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
37
  import { splitLines } from "../core/lines.ts";
40
38
  import { decodeEditableText } from "../core/text.ts";
41
- import { getState } from "./state.ts";
39
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
42
40
  import { canonicalPath } from "./read-tool.ts";
43
- import { parseHashline } from "./render.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,
@@ -57,7 +56,7 @@ import {
57
56
  import { intersectRanges, normalizeRanges, subtractRanges, unionRanges, submatchesToLineRanges, type LineRange, type RgSubmatch } from "./rg-line-ranges.ts";
58
57
 
59
58
  const DEFAULT_LIMIT = 100;
60
- /** Max chars per result line for display (mirrors pi's truncate.ts; not exported there). */
59
+ /** Maximum UTF-16 units in a line preview, excluding its partial-line label. */
61
60
  const GREP_MAX_LINE_LENGTH = 500;
62
61
  const GREP_CONTEXT_MAX = 20;
63
62
  const MAX_ALL_PATTERNS = 16;
@@ -67,10 +66,35 @@ const FILTER_BATCH_BYTES = 1024 * 1024;
67
66
  const FILE_BATCH_SIZE = 64;
68
67
  const FILE_BATCH_ARG_BYTES = 16 * 1024;
69
68
  const MAX_PENDING_RANGES = 262_144;
70
- const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched all patterns as literal text";
69
+ const LITERAL_FALLBACK_NOTICE = "Invalid regex; searched the pattern as literal text";
71
70
  const REGEX_SYNTAX = /[.*+?^${}()|[\]\\]/;
72
71
  const REGEX_PARSE_ERROR = /^(?:rg: )?regex parse error:/m;
73
72
 
73
+ /** Exclusion scans must succeed: incomplete exclusions could admit false matches. */
74
+ function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
75
+ const message = result.stderr.trim() || (!result.stopped && result.code !== 0 && result.code !== 1
76
+ ? `ripgrep exited with code ${result.code}` : "");
77
+ if (!message) return;
78
+ if (!warnings) throw new Error(message);
79
+ warnings.push(message);
80
+ }
81
+
82
+ function formatSearchWarnings(warnings: readonly string[]): string {
83
+ if (!warnings.length) return "";
84
+ const summary = truncateHead([...new Set(warnings)].join("\n"), { maxBytes: 4 * 1024 });
85
+ return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? "\nAdditional search diagnostics omitted (4 KiB limit)." : ""}]`;
86
+ }
87
+
88
+ function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
89
+ if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
90
+ let start = Math.max(0, Math.min(column - 100, text.length - GREP_MAX_LINE_LENGTH));
91
+ // Slice at UTF-16 boundaries without splitting an astral character.
92
+ if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
93
+ let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
94
+ if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
95
+ return { text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`, wasTruncated: true };
96
+ }
97
+
74
98
  async function resolveLiteralMode(
75
99
  patterns: readonly string[],
76
100
  explicit: boolean | undefined,
@@ -78,6 +102,7 @@ async function resolveLiteralMode(
78
102
  backend: GrepBackend,
79
103
  modes: Pick<SearchModes, "engine" | "multiline">,
80
104
  signal: AbortSignal | undefined,
105
+ allowFallback: boolean,
81
106
  ): Promise<boolean> {
82
107
  if (modes.engine === "pcre2") return false;
83
108
  if (explicit === true) return true;
@@ -101,6 +126,7 @@ async function resolveLiteralMode(
101
126
  if (result.code === 0 || result.code === 1) return false;
102
127
  if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
103
128
  if (explicit === false) throw new Error(result.stderr.trim());
129
+ 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
130
  return true;
105
131
  }
106
132
  throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
@@ -155,7 +181,7 @@ const grepOverrideSchema = Type.Object({
155
181
  ),
156
182
  literal: Type.Optional(
157
183
  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.",
184
+ description: "true: literal; false: regex, no fallback. Shared by pattern/excludePattern. Default: literal unless any pattern has regex syntax; invalid regex falls back only for one inclusion pattern without exclusions.",
159
185
  }),
160
186
  ),
161
187
  noIgnore: Type.Optional(Type.Boolean({
@@ -185,6 +211,7 @@ const grepOverrideSchema = Type.Object({
185
211
  interface RgMatch {
186
212
  filePath: string;
187
213
  lineNumber: number;
214
+ column?: number;
188
215
  }
189
216
 
190
217
  /** @internal — injectable process boundary for deterministic tests. */
@@ -235,6 +262,7 @@ async function filterExplicitFilesByGlob(
235
262
  scope: SearchScope,
236
263
  paths: readonly SearchPathInfo[],
237
264
  signal: AbortSignal | undefined,
265
+ warnings: string[],
238
266
  ): Promise<string[]> {
239
267
  const explicitFiles = paths.filter(({ isFile }) => isFile);
240
268
  if (scope.globs.length === 0 || explicitFiles.length === 0) return paths.map(({ path }) => path);
@@ -255,9 +283,7 @@ async function filterExplicitFilesByGlob(
255
283
  allowed.add(fileKey(path));
256
284
  return true;
257
285
  });
258
- if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
259
- throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
260
- }
286
+ recordSearchDiagnostics(listed, warnings);
261
287
  return paths
262
288
  .filter(({ path, isFile }) => !isFile || allowed.has(fileKey(path)))
263
289
  .map(({ path }) => path);
@@ -306,6 +332,8 @@ async function scanPatternRanges(
306
332
  word: boolean,
307
333
  signal: AbortSignal | undefined,
308
334
  lineCounts: Map<string, number>,
335
+ warnings?: string[],
336
+ columns?: Map<string, Map<number, number>>,
309
337
  ): Promise<Map<string, LineRange[]>> {
310
338
  if (files.length === 0) return new Map();
311
339
  const args = [
@@ -339,14 +367,14 @@ async function scanPatternRanges(
339
367
  if (!Array.isArray(data.submatches)) throw new Error("Invalid rg submatch protocol");
340
368
  if (data.submatches.length === 0) submatches = [{ start: bytes.length, end: bytes.length }];
341
369
  else submatches = data.submatches.map((match: any) => ({ start: match.start, end: match.end }));
342
- const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount);
370
+ const fileColumns = columns?.get(filePath) ?? new Map<number, number>();
371
+ const ranges = submatchesToLineRanges(bytes, data.line_number, submatches, lineCount, columns ? fileColumns : undefined);
372
+ columns?.set(filePath, fileColumns);
343
373
  result.set(filePath, unionRanges(result.get(filePath) ?? [], ranges));
344
374
  if (rangeCount(result) > MAX_PENDING_RANGES) throw new Error("Search produced too many pending line ranges; refine the query");
345
375
  return true;
346
376
  });
347
- if (!run.stopped && run.code !== 0 && run.code !== 1) {
348
- throw new Error(run.stderr.trim() || `ripgrep exited with code ${run.code}`);
349
- }
377
+ recordSearchDiagnostics(run, warnings);
350
378
  return result;
351
379
  }
352
380
 
@@ -361,10 +389,11 @@ interface ComplexSearchOptions {
361
389
  word: boolean;
362
390
  limit: number;
363
391
  signal?: AbortSignal;
392
+ warnings: string[];
364
393
  }
365
394
 
366
395
  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;
396
+ const { backend, rgPath, scope, patterns, excludes, matchMode, modes, word, limit, signal, warnings } = options;
368
397
  const raw: RgMatch[] = [];
369
398
  const identities = new Map<string, FileIdentity>();
370
399
  const seen = new Set<string>();
@@ -379,11 +408,12 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
379
408
  if (files.length === 0) return true;
380
409
  for (const file of files) identities.set(file, await fileIdentity(file));
381
410
  const lineCounts = new Map<string, number>();
411
+ const columns = new Map<string, Map<number, number>>();
382
412
 
383
413
  let included = new Map<string, LineRange[]>();
384
414
  for (let index = 0; index < patterns.length; index++) {
385
415
  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);
416
+ const ranges = await scanPatternRanges(backend, rgPath, candidates, patterns[index], modes, word, signal, lineCounts, warnings, columns);
387
417
  included = index === 0 ? ranges : combineRangeMaps(included, ranges, matchMode === "all" ? "intersect" : "union");
388
418
  if (matchMode === "all" && included.size === 0) break;
389
419
  }
@@ -406,7 +436,7 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
406
436
  }
407
437
  for (const [start, end] of included.get(file) ?? []) {
408
438
  for (let lineNumber = start; lineNumber < end; lineNumber++) {
409
- raw.push({ filePath: file, lineNumber });
439
+ raw.push({ filePath: file, lineNumber, column: columns.get(file)?.get(lineNumber) });
410
440
  if (raw.length >= limit) {
411
441
  matchLimitReached = true;
412
442
  return false;
@@ -434,9 +464,7 @@ async function complexSearch(options: ComplexSearchOptions): Promise<{ raw: RgMa
434
464
  batchBytes += Buffer.byteLength(filePath) + 1;
435
465
  return batch.length >= FILE_BATCH_SIZE || batchBytes >= FILE_BATCH_ARG_BYTES ? processBatch() : true;
436
466
  });
437
- if (!listed.stopped && listed.code !== 0 && listed.code !== 1) {
438
- throw new Error(listed.stderr.trim() || `ripgrep exited with code ${listed.code}`);
439
- }
467
+ recordSearchDiagnostics(listed, warnings);
440
468
  if (!matchLimitReached && batch.length) await processBatch();
441
469
  return { raw, matchLimitReached, identities };
442
470
  }
@@ -557,11 +585,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
557
585
 
558
586
  renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
559
587
  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
- }
588
+ if (context?.isError) return renderToolError(result, theme);
565
589
  const out = result.content?.[0]?.type === "text" ? result.content[0].text : "";
566
590
  const styled = toDisplayLines(out, theme);
567
591
  const maxLines = expanded ? styled.length : 15;
@@ -579,8 +603,9 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
579
603
  signal: AbortSignal | undefined,
580
604
  _onUpdate: any,
581
605
  ): Promise<any> {
582
- const state = getState();
583
606
  if (signal?.aborted) throw new Error("Operation aborted");
607
+ const anchors = createAnchorFormatter();
608
+ const warnings: string[] = [];
584
609
 
585
610
  const patterns = toArray(params.pattern);
586
611
  if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
@@ -600,7 +625,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
600
625
  }
601
626
  const allPatterns = [...patterns, ...excludes];
602
627
  const literal = await resolveLiteralMode(
603
- allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal,
628
+ allPatterns, params.literal, rgPath, backend, { engine, multiline }, signal, patterns.length === 1 && excludes.length === 0,
604
629
  );
605
630
  const literalFallback = !params.pcre2 && params.literal === undefined && literal &&
606
631
  allPatterns.some((pattern) => REGEX_SYNTAX.test(pattern));
@@ -620,7 +645,6 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
620
645
  follow: params.follow === true,
621
646
  searchPaths,
622
647
  };
623
- const hashLen = state.config.hashLen;
624
648
 
625
649
  const pathInfo: SearchPathInfo[] = [];
626
650
  for (const searchPath of searchPaths) {
@@ -629,7 +653,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
629
653
  }
630
654
  scope = {
631
655
  ...scope,
632
- searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal),
656
+ searchPaths: await filterExplicitFilesByGlob(backend, rgPath, scope, pathInfo, signal, warnings),
633
657
  };
634
658
  if (matchMode === "all" && patterns.length > MAX_ALL_PATTERNS) {
635
659
  throw new Error(`matchMode:"all" supports at most ${MAX_ALL_PATTERNS} patterns`);
@@ -650,7 +674,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
650
674
  await backend.validatePatterns(rgPath, excludes, modes, false, signal);
651
675
  const result = await complexSearch({
652
676
  backend, rgPath, scope, patterns, excludes, matchMode, modes,
653
- word: !!wordMatch, limit: effectiveLimit, signal,
677
+ word: !!wordMatch, limit: effectiveLimit, signal, warnings,
654
678
  });
655
679
  raw = result.raw;
656
680
  matchLimitReached = result.matchLimitReached;
@@ -675,7 +699,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
675
699
  ? backend.createLinePredicate(rgPath, excludes, modes, false, signal)
676
700
  : undefined;
677
701
  const predicates: LinePredicate[] = [...andPredicates, ...(exclusionPredicate ? [exclusionPredicate] : [])];
678
- const batch: { filePath: string; lineNumber: number; line: Buffer }[] = [];
702
+ const batch: { filePath: string; lineNumber: number; line: Buffer; column: number }[] = [];
679
703
  let batchBytes = 0;
680
704
  const flushBatch = async (): Promise<boolean> => {
681
705
  const candidates = batch.splice(0);
@@ -686,7 +710,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
686
710
  if (!decisions.every((results, predicate) =>
687
711
  predicate < andPredicates.length ? results[index] : !results[index],
688
712
  )) continue;
689
- raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber });
713
+ raw.push({ filePath: candidates[index].filePath, lineNumber: candidates[index].lineNumber, column: candidates[index].column });
690
714
  matchCount++;
691
715
  if (matchCount >= effectiveLimit) {
692
716
  matchLimitReached = true;
@@ -714,7 +738,8 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
714
738
  if (seenMatches.has(matchKey)) return true;
715
739
  seenMatches.add(matchKey);
716
740
  const bytes = rgBytes(data.lines);
717
- batch.push({ filePath, lineNumber: data.line_number, line: bytes });
741
+ batch.push({ filePath, lineNumber: data.line_number, line: bytes,
742
+ column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length });
718
743
  batchBytes += bytes.length;
719
744
  if (predicates.length === 0 || batch.length >= FILTER_BATCH_SIZE || batchBytes >= FILTER_BATCH_BYTES) {
720
745
  return flushBatch();
@@ -722,28 +747,26 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
722
747
  return true;
723
748
  });
724
749
  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
- }
750
+ recordSearchDiagnostics(run, warnings);
728
751
  if (batch.length && matchCount < effectiveLimit) await flushBatch();
729
752
  }
730
753
 
731
754
  if (raw.length === 0) {
755
+ if (warnings.length) throw new Error(`No matches confirmed.${formatSearchWarnings(warnings)}`);
732
756
  return {
733
- content: [{ type: "text" as const, text: literalFallback
734
- ? `No matches found\n\n[${LITERAL_FALLBACK_NOTICE}]` : "No matches found" }],
757
+ content: [{ type: "text" as const, text: "No matches found" + (literalFallback ? `\n\n[${LITERAL_FALLBACK_NOTICE}]` : "") }],
735
758
  details: undefined,
736
759
  };
737
760
  }
738
761
 
739
762
  // Group by file, matches sorted by line number (Map keeps rg's discovery order).
740
- const byFile = new Map<string, number[]>();
763
+ const byFile = new Map<string, RgMatch[]>();
741
764
  for (const match of raw) {
742
765
  const lines = byFile.get(match.filePath) ?? [];
743
- lines.push(match.lineNumber);
766
+ lines.push(match);
744
767
  byFile.set(match.filePath, lines);
745
768
  }
746
- for (const lines of byFile.values()) lines.sort((a, b) => a - b);
769
+ for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
747
770
 
748
771
  // Read each file once; only hash the selected match/context rows below.
749
772
  const getFile = async (filePath: string) => {
@@ -752,7 +775,8 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
752
775
  bytes = await readFile(filePath);
753
776
  } catch (error) {
754
777
  if (strictIdentities) throw error;
755
- bytes = Buffer.alloc(0);
778
+ warnings.push(`Could not read ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
779
+ return undefined;
756
780
  }
757
781
  const content = decodeEditableText(bytes);
758
782
  if (strictIdentities) {
@@ -776,10 +800,12 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
776
800
  if (outputMode === "content") {
777
801
  for (const [filePath, matchLines] of byFile) {
778
802
  const lines = await getFile(filePath);
803
+ if (!lines) continue;
804
+ const columns = new Map(matchLines.map(match => [match.lineNumber, match.column]));
779
805
  // Context windows are rebuilt from surviving matches so context
780
806
  // lines of a filtered-out match never leak.
781
807
  const windowSet = new Set<number>();
782
- for (const lineNumber of matchLines) {
808
+ for (const { lineNumber } of matchLines) {
783
809
  for (
784
810
  let n = Math.max(1, lineNumber - ctx);
785
811
  n <= Math.min(lines.length, lineNumber + ctx);
@@ -790,10 +816,9 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
790
816
  const rows: string[] = [];
791
817
  for (const n of [...windowSet].sort((a, b) => a - b)) {
792
818
  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, ""));
819
+ const { text: display, wasTruncated } = previewLine(displayCarriageReturns(content), columns.get(n));
795
820
  if (wasTruncated) linesTruncated = true;
796
- rows.push(`${n}#${hash}│${display}`);
821
+ rows.push(anchors.row(n, content, display));
797
822
  }
798
823
  blocks.push(`${header}${rows.join("\n")}`);
799
824
  }
@@ -810,6 +835,7 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
810
835
  );
811
836
  }
812
837
 
838
+ if (!blocks.length && warnings.length) throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
813
839
  let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
814
840
  const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
815
841
  output = truncation.content;
@@ -823,14 +849,15 @@ export function makeGrepOverrideWithBackend(cwd: string, overrides: Partial<Grep
823
849
  if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
824
850
  if (linesTruncated) {
825
851
  notices.push(
826
- `Some lines truncated to ${GREP_MAX_LINE_LENGTH} chars. Use read to see full lines`,
852
+ `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
853
  );
828
854
  }
829
855
  if (notices.length) output += `\n\n[${notices.join(". ")}]`;
856
+ output += formatSearchWarnings(warnings);
830
857
 
831
858
  return {
832
859
  content: [{ type: "text" as const, text: output }],
833
- details: undefined,
860
+ details: warnings.length ? { incomplete: true } : undefined,
834
861
  };
835
862
  },
836
863
  };
@@ -338,8 +338,14 @@ test("auto-detects modes with rg validation while preserving explicit overrides"
338
338
  const fallback = makeGrepOverrideWithBackend(dir, invalid.backend);
339
339
 
340
340
  const result = await call(fallback, { pattern: "queueTool(" });
341
- assert.match(text(result), /Invalid regex; searched all patterns as literal text/);
342
- await call(fallback, { pattern: ["plain", "broken("] });
341
+ assert.match(text(result), /Invalid regex; searched the pattern as literal text/);
342
+ for (const params of [
343
+ { pattern: ["plain", "broken("] },
344
+ { pattern: "broken(", excludePattern: "^\\s*//" },
345
+ { pattern: "plain", excludePattern: "broken(" },
346
+ ]) {
347
+ await assert.rejects(call(fallback, params), /Invalid regex in compound query; automatic literal fallback is disabled/);
348
+ }
343
349
  await call(tool, { pattern: "value.*" });
344
350
  await call(tool, { pattern: "plain", literal: false });
345
351
  await call(tool, { pattern: "value.*", literal: true });
@@ -347,7 +353,7 @@ test("auto-detects modes with rg validation while preserving explicit overrides"
347
353
  assert.deepEqual(
348
354
  [...invalid.calls, ...valid.calls].filter(({ args }) => !args.includes("--quiet"))
349
355
  .map(({ args }) => args.includes("--fixed-strings")),
350
- [true, true, false, false, true],
356
+ [true, false, false, true],
351
357
  );
352
358
  assert.equal(valid.calls.filter(({ args }) => args.includes("--quiet")).length, 2);
353
359
  assert.deepEqual(invalid.calls[0].args, [
@@ -558,3 +564,61 @@ test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text"
558
564
  }),
559
565
  );
560
566
  });
567
+
568
+ test("partial searches retain matches and surface stderr across output modes", async () => {
569
+ await withDir(async dir => {
570
+ const file = join(dir, "found.txt");
571
+ await writeFile(file, "needle\n");
572
+ for (const outputMode of ["content", "files", "count"]) {
573
+ for (const limit of [1, 10]) {
574
+ const fake = fakeBackend({ lines: [rgMatch(file, 1, "needle\n")], code: 2, stderr: "unreadable.txt: Permission denied" });
575
+ const result = await call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle", outputMode, limit });
576
+ assert.match(text(result), /found\.txt/);
577
+ assert.match(text(result), /Search incomplete; results and counts cover only confirmed matches/);
578
+ assert.match(text(result), /unreadable\.txt: Permission denied/);
579
+ assert.equal(result.details.incomplete, true);
580
+ }
581
+ }
582
+ const fake = fakeBackend({ code: 2, stderr: "Permission denied" });
583
+ await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "needle" }), /No matches confirmed.*Search incomplete/s);
584
+ });
585
+ });
586
+
587
+ test("failed result reads report incomplete coverage while retaining readable files", async () => {
588
+ await withDir(async dir => {
589
+ const good = join(dir, "good.txt");
590
+ const gone = join(dir, "gone.txt");
591
+ await writeFile(good, "needle\n");
592
+ await writeFile(gone, "needle\n");
593
+ const fake = fakeBackend({ lines: [rgMatch(gone, 1, "needle\n"), rgMatch(good, 1, "needle\n")] });
594
+ const result = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
595
+ const result = await fake.backend.runRg(...args);
596
+ await rm(gone);
597
+ return result;
598
+ } }), { pattern: "needle" });
599
+ assert.match(text(result), /good\.txt · 1 match/);
600
+ assert.doesNotMatch(text(result), /gone\.txt · 1 match/);
601
+ assert.match(text(result), /Search incomplete/);
602
+ assert.match(text(result), /Could not read.*gone\.txt/);
603
+ });
604
+ });
605
+
606
+ test("complex searches report listing errors but reject incomplete exclusion scans", async () => {
607
+ await withDir(async dir => {
608
+ const file = join(dir, "fixture.txt");
609
+ await writeFile(file, "needle\n");
610
+ const event = JSON.stringify({ type: "match", data: { path: { text: file }, line_number: 1, lines: { text: "needle\n" }, submatches: [{ start: 0, end: 6 }] } });
611
+ const fake = fakeBackend({ paths: [file], lines: [event] });
612
+ const listing = await call(makeGrepOverrideWithBackend(dir, { ...fake.backend, runRgPaths: async (...args) => {
613
+ const result = await fake.backend.runRgPaths(...args);
614
+ return { ...result, code: 2, stderr: "directory: Permission denied" };
615
+ } }), { pattern: "needle", multiline: true });
616
+ assert.match(text(listing), /1#[0-9A-Z]+│needle/);
617
+ assert.match(text(listing), /Search incomplete/);
618
+ const tool = makeGrepOverrideWithBackend(dir, { ...fake.backend, runRg: async (...args) => {
619
+ const result = await fake.backend.runRg(...args);
620
+ return args[1].includes("exclude") ? { ...result, code: 2, stderr: "exclusion scan failed" } : result;
621
+ } });
622
+ await assert.rejects(call(tool, { pattern: "needle", excludePattern: "exclude", multiline: true }), /exclusion scan failed/);
623
+ });
624
+ });
@@ -1,6 +1,36 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
2
  import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
3
- import { computeLineHash } from "../core/hash.ts";
3
+ import { generateDiffString, generateUnifiedPatch } from "@earendil-works/pi-coding-agent";
4
+ import { displayCarriageReturns, type AnchorFormatter } from "./anchor-format.ts";
5
+
6
+ /** Diff raw text so line numbers and patches retain LF boundaries and all source bytes. */
7
+ export function generateMutationDetails(path: string, before: string, after: string, versions: MutationVersions, publication: PublicationStatus) {
8
+ const { diff, firstChangedLine } = generateDiffString(before, after);
9
+ return {
10
+ diff: displayCarriageReturns(diff),
11
+ firstChangedLine,
12
+ patch: generateUnifiedPatch(path, before, after),
13
+ publication,
14
+ ...versions,
15
+ revision: versions.publishedRevision,
16
+ };
17
+ }
18
+
19
+ /** Keep result-building failures distinct from file publication failures. */
20
+ export function postProcessMutation<T>(tool: string, publication: PublicationStatus, build: () => T): T {
21
+ try { return build(); } catch (error) {
22
+ throw new FileMutationError("post_process", publication, `${tool} result generation failed; publication=${publication}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
23
+ }
24
+ }
25
+
26
+ /** Append only to the summary block after the caller confirms anchor freshness. */
27
+ export function appendMutationAnchors<T>(result: AgentToolResult<T>, anchors: string, publish: boolean): AgentToolResult<T> {
28
+ return {
29
+ ...result,
30
+ content: result.content.map((block, index) => index === 0 && block.type === "text"
31
+ ? { ...block, text: `${block.text}${publish ? anchors : ""}` } : block),
32
+ };
33
+ }
4
34
 
5
35
  export function observedFreshness(result: AgentToolResult<unknown>): "unchanged" | "changed" | "unknown" {
6
36
  const versions = result.details as Partial<MutationVersions> | undefined;
@@ -13,12 +43,13 @@ export function finalizeMutationResult<T>(
13
43
  result: AgentToolResult<T>,
14
44
  finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
15
45
  publishAnchors = observedFreshness(result) === "unchanged",
46
+ staleNotice = "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits.",
16
47
  ): AgentToolResult<T> {
17
48
  try {
18
49
  const finalized = finalize(result, publishAnchors);
19
50
  return publishAnchors ? finalized : {
20
51
  ...finalized,
21
- content: [...finalized.content, { type: "text", text: "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits." }],
52
+ content: [...finalized.content, { type: "text", text: staleNotice }],
22
53
  };
23
54
  } catch (error) {
24
55
  const publication = (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
@@ -26,20 +57,26 @@ export function finalizeMutationResult<T>(
26
57
  }
27
58
  }
28
59
 
29
- /** Bound complete anchor rows before hashing or constructing their output strings. */
30
- export function formatMutationAnchors(lines: readonly string[], indices: Iterable<number>, hashLen: number, heading: string): string {
31
- const notice = "\n… (additional anchors omitted: 40-row/16 KiB limit; use read for full content)";
60
+ /** Return compact changed-position anchors; selected context rows retain full content within the byte budget. */
61
+ export function formatMutationAnchors(
62
+ beforeLines: readonly string[], lines: readonly string[], indices: Iterable<number>, anchors: AnchorFormatter, heading: string,
63
+ contentIndices?: ReadonlySet<number>,
64
+ ): string {
65
+ const notice = "\n… (additional anchors omitted: 16 KiB limit; use read for omitted positions)";
32
66
  const rows: string[] = [];
33
67
  let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
34
68
  let omitted = false;
35
69
  for (const index of indices) {
36
70
  const content = lines[index];
37
- const rowBytes = Buffer.byteLength(`${index + 1}#${"X".repeat(hashLen)}│`) + Buffer.byteLength(content) + 1;
38
- if (rows.length >= 40 || bytes + rowBytes > 16 * 1024) {
71
+ // Compare source content, not short hashes: a collision must not suppress a changed row.
72
+ if (beforeLines[index] === content) continue;
73
+ const row = contentIndices?.has(index) ? anchors.row(index + 1, content) : anchors.token(index + 1, content);
74
+ const rowBytes = Buffer.byteLength(row) + 1;
75
+ if (bytes + rowBytes > 16 * 1024) {
39
76
  omitted = true;
40
- break;
77
+ continue;
41
78
  }
42
- rows.push(`${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`);
79
+ rows.push(row);
43
80
  bytes += rowBytes;
44
81
  }
45
82
  return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
@@ -14,10 +14,10 @@ import { Text } from "@earendil-works/pi-tui";
14
14
  import { readFile } from "node:fs/promises";
15
15
  import { join, resolve } from "node:path";
16
16
  import { homedir } from "node:os";
17
- import { decodeUtf8, computeLineHash } from "../core/index.ts";
17
+ import { decodeUtf8 } from "../core/index.ts";
18
18
  import { hasFinalNewline, splitLines } from "../core/lines.ts";
19
- import { getState } from "./state.ts";
20
- import { parseHashline } from "./render.ts";
19
+ import { createAnchorFormatter } from "./anchor-format.ts";
20
+ import { parseHashline, renderToolError } from "./render.ts";
21
21
 
22
22
  const MAX_LINES = 2000;
23
23
  const MAX_BYTES = 256 * 1024;
@@ -117,10 +117,7 @@ export function makeReadOverride(cwd: string) {
117
117
  renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
118
118
  if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
119
119
  const content = result.content?.[0];
120
- if (context?.isError) {
121
- const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
122
- return new Text(theme.fg("error", t), 0, 0);
123
- }
120
+ if (context?.isError) return renderToolError(result, theme);
124
121
  // Collapsed (not expanded): show nothing — the call line carries the
125
122
  // title, matching the built-in read's fold behavior.
126
123
  if (!expanded) return new Text("", 0, 0);
@@ -131,6 +128,7 @@ export function makeReadOverride(cwd: string) {
131
128
  async execute(toolCallId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx?: any) {
132
129
  // User cancelled → delegate to the built-in (builtin handles abort itself)
133
130
  if (signal?.aborted) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
131
+ const anchors = createAnchorFormatter();
134
132
 
135
133
  const absPath = canonicalPath(cwd, params.path as string);
136
134
  let buf: Buffer;
@@ -147,7 +145,6 @@ export function makeReadOverride(cwd: string) {
147
145
  const text = decodeUtf8(buf);
148
146
  const allLines = splitLines(text);
149
147
  const totalLines = allLines.length;
150
- const hashLen = getState().config.hashLen;
151
148
 
152
149
  // offset/limit
153
150
  const offset = (params.offset as number | undefined) ?? 1;
@@ -155,7 +152,7 @@ export function makeReadOverride(cwd: string) {
155
152
  const startIdx = Math.max(0, offset - 1);
156
153
  const endIdx = Math.min(totalLines, startIdx + limit);
157
154
 
158
- const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${computeLineHash(startIdx + index + 1, line, hashLen)}│${line}`);
155
+ const rows = allLines.slice(startIdx, endIdx).map((line, index) => anchors.row(startIdx + index + 1, line));
159
156
  const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
160
157
 
161
158
  const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
@@ -164,7 +161,7 @@ export function makeReadOverride(cwd: string) {
164
161
  // never copies into an edit `body`.
165
162
  const noFinalNewline = hasFinalNewline(text) ? "" : " · no trailing newline";
166
163
  const tail = truncation.firstLineExceedsLimit
167
- ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row)`
164
+ ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
168
165
  : truncation.truncated ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)` : "";
169
166
  const header = `${params.path} · ${totalLines} lines${shownFrom}${noFinalNewline}\n`;
170
167
  const body = truncation.content;
@@ -9,14 +9,14 @@ import { initTheme } from "@earendil-works/pi-coding-agent";
9
9
  import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
10
10
  import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
11
11
 
12
- test("registered mutation cards finish independently of fused command cards", async () => {
12
+ test("mutation cards use Fusion by default and explicit false removes command support", async () => {
13
13
  const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
14
14
  const previousCwd = process.cwd();
15
15
  const state = getState();
16
16
  const previousConfig = state.config;
17
17
  try {
18
18
  await mkdir(join(dir, ".pi"));
19
- await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true, actionFusion: true } }));
19
+ await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true } }));
20
20
  process.chdir(dir);
21
21
  const tools: any[] = [];
22
22
  const entries: any[] = [];
@@ -80,6 +80,19 @@ test("registered mutation cards finish independently of fused command cards", as
80
80
  });
81
81
  }
82
82
  assert.deepEqual(entries.map((entry) => entry.data.command), cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]));
83
+ await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion: false } }));
84
+ const disabledTools: any[] = [];
85
+ registerHashline({
86
+ on() {},
87
+ registerEntryRenderer() {},
88
+ registerTool(tool: any) { disabledTools.push(tool); },
89
+ } as any);
90
+ assert.equal(disabledTools.length, 5);
91
+ for (const tool of disabledTools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
92
+ assert.equal(tool.parameters.properties.then_run, undefined);
93
+ assert.equal(tool.renderShell, "default");
94
+ await assert.rejects(tool.execute("disabled", { path: "published.txt", then_run: { command: "exit 0" } }, undefined, undefined, { cwd: dir }), /then_run is unavailable/);
95
+ }
83
96
  } finally {
84
97
  process.chdir(previousCwd);
85
98
  state.config = previousConfig;