@criogaid/pi-hashline-edit 0.5.1 → 0.6.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 (51) hide show
  1. package/README.md +51 -15
  2. package/package.json +6 -6
  3. package/src/core/apply.test.ts +66 -16
  4. package/src/core/apply.ts +36 -19
  5. package/src/core/lines.ts +3 -3
  6. package/src/index.ts +2 -0
  7. package/src/integration/forget-grep.test.ts +98 -0
  8. package/src/integration/fusion-dispatch.test.ts +343 -0
  9. package/src/integration/grep-rg.test.ts +269 -33
  10. package/src/integration/mutation-file-types.test.ts +44 -0
  11. package/src/pi/action-fusion.test.ts +71 -128
  12. package/src/pi/action-fusion.ts +83 -45
  13. package/src/pi/argument-validation.test.ts +136 -0
  14. package/src/pi/argument-validation.ts +103 -0
  15. package/src/pi/budgets.ts +4 -1
  16. package/src/pi/config.test.ts +1 -0
  17. package/src/pi/config.ts +4 -0
  18. package/src/pi/directory-sync.test.ts +1 -1
  19. package/src/pi/edit-tool.ts +55 -36
  20. package/src/pi/execute.test.ts +185 -645
  21. package/src/pi/failure-context.test.ts +4 -3
  22. package/src/pi/failure-path.test.ts +3 -3
  23. package/src/pi/file-commit.test.ts +24 -17
  24. package/src/pi/file-commit.ts +36 -9
  25. package/src/pi/file-snapshot.test.ts +24 -0
  26. package/src/pi/forget-tool.ts +268 -0
  27. package/src/pi/forget.test.ts +343 -0
  28. package/src/pi/forget.testing.ts +273 -0
  29. package/src/pi/grep-output.ts +57 -28
  30. package/src/pi/grep-search.ts +35 -12
  31. package/src/pi/grep-tool.ts +28 -9
  32. package/src/pi/grep.test.ts +173 -152
  33. package/src/pi/mutation-result.test.ts +23 -0
  34. package/src/pi/mutation-runner.ts +8 -4
  35. package/src/pi/path.ts +16 -2
  36. package/src/pi/pi.test.ts +3 -2
  37. package/src/pi/read-tool.ts +58 -26
  38. package/src/pi/read.test.ts +361 -0
  39. package/src/pi/registration.test.ts +115 -2
  40. package/src/pi/render.test.ts +45 -14
  41. package/src/pi/replace-tool.ts +18 -27
  42. package/src/pi/replace.test.ts +8 -107
  43. package/src/pi/result-safety.test.ts +123 -149
  44. package/src/pi/rg-match-bytes.ts +95 -0
  45. package/src/pi/rg-process.test.ts +40 -59
  46. package/src/pi/rg-text-view.ts +52 -5
  47. package/src/pi/tool-call.testing.ts +50 -0
  48. package/src/pi/tool-prompts.ts +15 -0
  49. package/src/pi/write-tool.ts +17 -26
  50. package/src/pi/write.test.ts +70 -61
  51. package/src/pi/e2e-scenarios.test.ts +0 -361
@@ -1,12 +1,13 @@
1
1
  import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
2
2
  import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
3
3
  import { createHash } from "node:crypto";
4
- import { isAbsolute, relative, resolve, sep } from "node:path";
5
4
  import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
6
5
  import { fileReadWarning, type RgMatch, type SearchFileSnapshot } from "./grep-search.ts";
7
- import { scanTextLines } from "./text-stream.ts";
6
+ import { scanTextFile, scanTextLines } from "./text-stream.ts";
8
7
  import { GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
9
8
  import { searchChangedError } from "./error-text.ts";
9
+ import { serializePath } from "./path.ts";
10
+ import { rawMatchVerifier } from "./rg-match-bytes.ts";
10
11
 
11
12
  /** UTF-16 units kept before the match column when a preview window is cut. */
12
13
  const GREP_PREVIEW_LEAD = 100;
@@ -70,17 +71,13 @@ export async function formatMatches(options: FormatMatchesOptions) {
70
71
  byFile.set(match.filePath, lines);
71
72
  }
72
73
  for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
73
- const formatPath = (filePath: string): string => {
74
- const absolute = resolve(cwd, filePath);
75
- const rel = relative(cwd, absolute);
76
- return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
77
- ? rel.replace(/\\/g, "/")
78
- : absolute;
79
- };
74
+ const formatPath = (filePath: string): string => serializePath(cwd, filePath);
80
75
  const blocks: string[] = [];
81
76
  let linesTruncated = false;
82
- if (outputMode === "content") {
83
- const fileEntries = [...byFile.entries()];
77
+ const fileEntries = [...byFile.entries()].filter(
78
+ ([, matches]) => outputMode === "content" || matches.some((match) => match.rawMatch),
79
+ );
80
+ if (fileEntries.length) {
84
81
  const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
85
82
  let nextIndex = 0;
86
83
  const workerAbort = new AbortController();
@@ -94,19 +91,40 @@ export async function formatMatches(options: FormatMatchesOptions) {
94
91
  while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
95
92
  const current = nextIndex++;
96
93
  const [filePath, matchLines] = fileEntries[current];
97
- const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
98
- const matchedTexts = new Map(
99
- matchLines.map((match) => [match.lineNumber, match.matchedText]),
94
+ const verifyRaw = rawMatchVerifier(
95
+ new Set(matchLines.flatMap((match) => (match.rawMatch ? [match.rawMatch] : []))),
100
96
  );
101
- const windowSet = new Set<number>();
102
- for (const { lineNumber } of matchLines) {
103
- for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
104
- windowSet.add(n);
105
- }
106
- const rows: string[] = [];
107
- const matchedRows = new Set<number>();
108
- const hash = createHash("sha256");
109
97
  try {
98
+ if (outputMode !== "content") {
99
+ const hash = createHash("sha256");
100
+ await scanTextFile(
101
+ filePath,
102
+ undefined,
103
+ scanSignal,
104
+ (bytes) => {
105
+ hash.update(bytes);
106
+ verifyRaw.write(bytes);
107
+ },
108
+ "lossy",
109
+ );
110
+ verifyRaw.end();
111
+ if (hash.digest("hex") !== searchSnapshots.get(filePath)!.revision)
112
+ throw searchChangedError();
113
+ fileResults[current] = {};
114
+ continue;
115
+ }
116
+ const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
117
+ const matchedTexts = new Map(
118
+ matchLines.map((match) => [match.lineNumber, match.matchedText]),
119
+ );
120
+ const windowSet = new Set<number>();
121
+ for (const { lineNumber } of matchLines) {
122
+ for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
123
+ windowSet.add(n);
124
+ }
125
+ const rows: string[] = [];
126
+ const matchedRows = new Set<number>();
127
+ const hash = createHash("sha256");
110
128
  // Content-mode search snapshots every file before recording its matches.
111
129
  const snapshot = searchSnapshots.get(filePath)!;
112
130
  const stats = await scanTextLines(
@@ -130,8 +148,16 @@ export async function formatMatches(options: FormatMatchesOptions) {
130
148
  : plainRow(line.number, display),
131
149
  );
132
150
  },
133
- { signal: scanSignal, onBytes: (bytes) => hash.update(bytes), decoding: "lossy" },
151
+ {
152
+ signal: scanSignal,
153
+ onBytes: (bytes) => {
154
+ hash.update(bytes);
155
+ verifyRaw.write(bytes);
156
+ },
157
+ decoding: "lossy",
158
+ },
134
159
  );
160
+ verifyRaw.end();
135
161
  if (stats.hasNul) throw searchChangedError();
136
162
  if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
137
163
  throw searchChangedError();
@@ -159,13 +185,16 @@ export async function formatMatches(options: FormatMatchesOptions) {
159
185
  );
160
186
  await Promise.all(workers);
161
187
  if (failed) throw failure;
162
- for (const result of fileResults) {
163
- if (result.warning) warnings.push(result.warning);
164
- else if (result.block) blocks.push(result.block);
188
+ for (const [index, result] of fileResults.entries()) {
189
+ if (result.warning) {
190
+ warnings.push(result.warning);
191
+ byFile.delete(fileEntries[index][0]);
192
+ } else if (result.block) blocks.push(result.block);
165
193
  }
166
- } else if (outputMode === "files") {
194
+ }
195
+ if (outputMode === "files") {
167
196
  for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
168
- } else {
197
+ } else if (outputMode === "count" && byFile.size) {
169
198
  let total = 0;
170
199
  for (const [filePath, matchLines] of byFile) {
171
200
  blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
@@ -13,7 +13,8 @@ import {
13
13
  type SearchModes,
14
14
  } from "./rg-process.ts";
15
15
  import { submatchesToLineRanges } from "./rg-line-ranges.ts";
16
- import { throwIfCancelled } from "./error-text.ts";
16
+ import { rawMatchRevision, type RawMatchRevision } from "./rg-match-bytes.ts";
17
+ import { searchChangedError, throwIfCancelled } from "./error-text.ts";
17
18
 
18
19
  /** Surface incomplete search diagnostics without discarding confirmed matches. */
19
20
  export function recordSearchDiagnostics(result: RgRunResult, warnings?: string[]): void {
@@ -32,6 +33,8 @@ export interface RgMatch {
32
33
  lineNumber: number;
33
34
  column?: number;
34
35
  matchedText?: string;
36
+ /** Shared whole-event digest: a limited row still depends on every byte in its raw match. */
37
+ rawMatch?: RawMatchRevision;
35
38
  }
36
39
 
37
40
  interface RgJsonEvent {
@@ -40,6 +43,7 @@ interface RgJsonEvent {
40
43
  path?: Parameters<typeof rgText>[0];
41
44
  lines?: Parameters<typeof rgBytes>[0];
42
45
  line_number?: number;
46
+ absolute_offset?: number;
43
47
  submatches?: { start: number; end: number }[];
44
48
  };
45
49
  }
@@ -55,15 +59,19 @@ export interface SearchScope {
55
59
  export interface SearchRequest {
56
60
  /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
57
61
  readonly matcher: readonly string[];
62
+ /** Original patterns for raw-byte files; omitted when they equal the LF-view patterns. */
63
+ readonly rawMatcher?: readonly string[];
58
64
  readonly scope: SearchScope;
59
65
  }
60
66
 
67
+ export type SearchTextView = { kind: "lf" } | { kind: "raw"; snapshot: SearchFileSnapshot };
68
+
61
69
  /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
62
70
  export type SearchRunner = (
63
71
  rgPath: string,
64
72
  request: SearchRequest,
65
73
  signal: AbortSignal | undefined,
66
- onLine: (line: string) => boolean | Promise<boolean>,
74
+ onLine: (line: string, view: SearchTextView) => boolean | Promise<boolean>,
67
75
  ) => Promise<RgRunResult>;
68
76
 
69
77
  /** @internal — injectable process boundary for deterministic tests. */
@@ -141,13 +149,17 @@ export async function searchMatches(options: SearchMatchesOptions) {
141
149
  // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
142
150
  const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
143
151
  for (const group of patternGroups) {
144
- const matcher = [
145
- ...matcherArgs(modes),
146
- "--json",
147
- "--line-number",
148
- ...group.flatMap((pattern) => ["-e", pattern]),
149
- ];
150
- const run = await backend.search(rgPath, { matcher, scope }, signal, async (line) => {
152
+ const args = [...matcherArgs(modes), "--json", "--line-number"];
153
+ const normalized = group.map(normalizeLineEndings);
154
+ const matcher = [...args, ...normalized.flatMap((pattern) => ["-e", pattern])];
155
+ const request: SearchRequest = {
156
+ matcher,
157
+ scope,
158
+ ...(group.some((pattern, index) => pattern !== normalized[index])
159
+ ? { rawMatcher: [...args, ...group.flatMap((pattern) => ["-e", pattern])] }
160
+ : {}),
161
+ };
162
+ const run = await backend.search(rgPath, request, signal, async (line, view) => {
151
163
  if (raw.length >= limit) return false;
152
164
  let event: RgJsonEvent;
153
165
  try {
@@ -167,6 +179,11 @@ export async function searchMatches(options: SearchMatchesOptions) {
167
179
  const filePath = resolve(rgText(data.path));
168
180
  if (unreadableFiles.has(filePath)) return true;
169
181
  let snapshot = snapshots.get(filePath);
182
+ if (view.kind === "raw") {
183
+ if (snapshot && snapshot.revision !== view.snapshot.revision) throw searchChangedError();
184
+ snapshot = view.snapshot;
185
+ snapshots.set(filePath, snapshot);
186
+ }
170
187
  if (!snapshot && needsSnapshot) {
171
188
  try {
172
189
  snapshot = await scanFileSnapshot(filePath, signal);
@@ -183,13 +200,17 @@ export async function searchMatches(options: SearchMatchesOptions) {
183
200
  return true;
184
201
  }
185
202
  }
203
+ if (snapshot && snapshot.validUtf8 !== (view.kind === "lf")) throw searchChangedError();
186
204
  const startLine = data.line_number;
187
205
  const bytes = rgBytes(data.lines);
188
206
  const text = bytes.toString("utf8");
207
+ const rawMatch =
208
+ view.kind === "raw" ? rawMatchRevision(bytes, startLine, data.absolute_offset) : undefined;
189
209
  // Valid text is already the LF view; normalizing it twice would strip a content CR.
190
- const matchedText = (
191
- snapshot?.validUtf8 === false ? normalizeLineEndings(text) : text
192
- ).replace(/\n$/, "");
210
+ const matchedText = (view.kind === "raw" ? normalizeLineEndings(text) : text).replace(
211
+ /\n$/,
212
+ "",
213
+ );
193
214
  const addMatch = (match: RgMatch) => {
194
215
  const matchKey = `${filePath}\0${match.lineNumber}`;
195
216
  if (seenMatches.has(matchKey)) return true;
@@ -207,6 +228,7 @@ export async function searchMatches(options: SearchMatchesOptions) {
207
228
  lineNumber: startLine,
208
229
  column: bytes.subarray(0, data.submatches?.[0]?.start ?? 0).toString("utf8").length,
209
230
  matchedText,
231
+ rawMatch,
210
232
  });
211
233
  }
212
234
  if (!Array.isArray(data.submatches)) throw new Error("Invalid rg multiline match event");
@@ -229,6 +251,7 @@ export async function searchMatches(options: SearchMatchesOptions) {
229
251
  lineNumber,
230
252
  column: columns.get(lineNumber),
231
253
  matchedText: texts[lineNumber - startLine],
254
+ rawMatch,
232
255
  })
233
256
  )
234
257
  return false;
@@ -12,6 +12,7 @@ import { rgPath as bundledRgPath } from "@vscode/ripgrep";
12
12
  import { Type, type Static } from "typebox";
13
13
  import { Text } from "@earendil-works/pi-tui";
14
14
  import { renderOutputPreview, renderToolError } from "./render.ts";
15
+ import { type ForgetReceiptDetails, grepReceipt, withResultTag } from "./forget-tool.ts";
15
16
  import { normalizeLineEndings } from "../core/lines.ts";
16
17
  import { createAnchorFormatter } from "./anchor-format.ts";
17
18
  import { assembleGrepOutput, formatMatches, formatSearchWarnings } from "./grep-output.ts";
@@ -34,6 +35,7 @@ import { runRgTextView } from "./rg-text-view.ts";
34
35
  import { GREP_CONTEXT_RANGE, POSITIVE_SAFE_INTEGER } from "./schema.ts";
35
36
  import { throwIfCancelled } from "./error-text.ts";
36
37
  import type { HashlineEditConfig } from "./config.ts";
38
+ import { createArgumentPreparer } from "./argument-validation.ts";
37
39
 
38
40
  /** Grep parameters; descriptions state the configured defaults. */
39
41
  function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["grep"]) {
@@ -54,7 +56,7 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
54
56
  ],
55
57
  {
56
58
  description:
57
- "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded; use glob.",
59
+ "Existing file or directory, or an array of them; omit to search the working directory. Wildcards are not expanded.",
58
60
  },
59
61
  ),
60
62
  ),
@@ -109,7 +111,10 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
109
111
  );
110
112
  }
111
113
  type GrepSchema = ReturnType<typeof createGrepSchema>;
112
- type GrepTool = ToolDefinition<GrepSchema, { incomplete?: true } | undefined>;
114
+ type GrepTool = ToolDefinition<
115
+ GrepSchema,
116
+ ({ incomplete?: true } & ForgetReceiptDetails) | undefined
117
+ >;
113
118
 
114
119
  /** Build the production grep override (a ToolDefinition fragment for registerTool). */
115
120
  export function makeGrepOverride(cwd: string, config: HashlineEditConfig) {
@@ -136,17 +141,18 @@ export function makeGrepOverrideWithBackend(
136
141
  name: "grep" as const,
137
142
  label: "grep",
138
143
  description:
139
- "Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8; invalid UTF-8 uses replacement characters and plain line numbers. NUL-containing files are skipped. Files/count modes return paths or matching-line counts. Valid UTF-8 CRLF is searched as LF; invalid UTF-8 is searched as raw bytes. Directory searches respect ignore rules and skip linked directories.",
144
+ "Search file contents with ripgrep. Content mode returns LINE#HASH edit anchors for valid UTF-8 and plain line numbers without anchors otherwise; files/count modes return paths or matching-line counts. Valid UTF-8 CRLF is searched as LF; invalid UTF-8 is searched as raw bytes. NUL-containing files are skipped. Directory searches respect ignore rules and skip linked directories.",
140
145
  promptSnippet: "Search file contents with ripgrep",
141
146
  promptGuidelines: [
142
147
  "Prefer grep for file-content searches; use another tool for ignored or linked directories.",
143
- 'In grep, omit path to search the working directory (never pass ""); use glob for filename wildcards.',
144
- "In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional ripgrep (Rust) regex, which has no lookaround or backreferences.",
148
+ "In grep, use glob for filename wildcards.",
149
+ "In grep, use literal:true for exact text, including names, paths, and code snippets; use literal:false only for intentional regex.",
145
150
  "In grep, use a pattern array for alternatives instead of joining them with |, and context:3-5 when searching code to edit.",
146
151
  "In grep, use multiline:true for cross-line matches and outputMode files or count when only paths or counts are needed.",
147
152
  "Copy grep anchors directly into edit; read the full line before rewriting from a partial preview.",
148
153
  ],
149
154
  parameters: grepSchema,
155
+ prepareArguments: createArgumentPreparer("grep", grepSchema),
150
156
 
151
157
  renderShell: "default" as const,
152
158
 
@@ -184,7 +190,7 @@ export function makeGrepOverrideWithBackend(
184
190
  },
185
191
 
186
192
  async execute(
187
- _toolCallId: string,
193
+ toolCallId: string,
188
194
  params: Static<GrepSchema>,
189
195
  signal: AbortSignal | undefined,
190
196
  _onUpdate: Parameters<GrepTool["execute"]>[3],
@@ -193,7 +199,7 @@ export function makeGrepOverrideWithBackend(
193
199
  const anchors = createAnchorFormatter(hashLen);
194
200
  const warnings: string[] = [];
195
201
 
196
- const patterns = toArray(params.pattern).map(normalizeLineEndings);
202
+ const patterns = toArray(params.pattern);
197
203
  const effectiveLimit = params.limit ?? config.grep.defaultLimit;
198
204
  const context = params.context ?? config.grep.defaultContext;
199
205
  const rgPath = bundledRgPath;
@@ -201,7 +207,12 @@ export function makeGrepOverrideWithBackend(
201
207
  const multiline = params.multiline ?? false;
202
208
  const globs = toArray(params.glob);
203
209
  const { literal } = params;
204
- if (!literal) await assertValidRegex(patterns, multiline, rgPath, backend, signal);
210
+ if (!literal) {
211
+ await assertValidRegex(patterns, multiline, rgPath, backend, signal);
212
+ const normalized = patterns.map(normalizeLineEndings);
213
+ if (patterns.some((pattern, index) => pattern !== normalized[index]))
214
+ await assertValidRegex(normalized, multiline, rgPath, backend, signal);
215
+ }
205
216
  const matcherIgnoreCase = await backend.resolveIgnoreCase(
206
217
  rgPath,
207
218
  patterns,
@@ -266,7 +277,7 @@ export function makeGrepOverrideWithBackend(
266
277
  warnings,
267
278
  searchSnapshots: result.snapshots,
268
279
  });
269
- return assembleGrepOutput({
280
+ const output = assembleGrepOutput({
270
281
  blocks,
271
282
  warnings,
272
283
  outputMode,
@@ -274,6 +285,14 @@ export function makeGrepOverrideWithBackend(
274
285
  effectiveLimit,
275
286
  linesTruncated,
276
287
  });
288
+ // Only content mode returns file text; paths and counts have nothing to forget.
289
+ if (outputMode !== "content") return output;
290
+ return withResultTag(toolCallId, output, config.forget, () =>
291
+ grepReceipt(patterns, raw.length, new Set(raw.map((match) => match.filePath)).size, {
292
+ limitReached: matchLimitReached,
293
+ incomplete: warnings.length > 0,
294
+ }),
295
+ );
277
296
  },
278
297
  } satisfies GrepTool;
279
298
  }