@criogaid/pi-hashline-edit 0.12.0 → 0.13.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 (88) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +59 -16
  3. package/README.zh-CN.md +59 -16
  4. package/package.json +2 -2
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +13 -0
  7. package/src/core/apply.ts +5 -9
  8. package/src/core/case-fold.test.ts +16 -25
  9. package/src/core/case-fold.ts +4 -4
  10. package/src/core/character-set.test.ts +1 -6
  11. package/src/core/character-set.ts +7 -61
  12. package/src/core/regex.ts +2 -36
  13. package/src/core/search-analysis.test.ts +66 -61
  14. package/src/core/search-analysis.ts +24 -39
  15. package/src/core/search-matrix.test.ts +2 -2
  16. package/src/core/search-matrix.testing.ts +6 -16
  17. package/src/core/search-schema.ts +0 -1
  18. package/src/core/search.test.ts +6 -19
  19. package/src/core/search.ts +10 -8
  20. package/src/index.ts +27 -2
  21. package/src/integration/config-registration.test.ts +77 -4
  22. package/src/integration/fusion-dispatch.test.ts +47 -2
  23. package/src/integration/grep-errors.test.ts +31 -0
  24. package/src/integration/grep-flags.test.ts +13 -196
  25. package/src/integration/grep-js-completeness.test.ts +41 -8
  26. package/src/integration/grep-line-candidates.test.ts +3 -33
  27. package/src/integration/grep-matrix.test.ts +1 -1
  28. package/src/integration/grep-path-matrix.test.ts +59 -65
  29. package/src/integration/grep-prefilter-coverage.test.ts +15 -8
  30. package/src/integration/grep-process-limits.test.ts +46 -0
  31. package/src/integration/grep-regex.test.ts +7 -2
  32. package/src/integration/grep-rg.test.ts +63 -12
  33. package/src/integration/grep-translation.test.ts +14 -7
  34. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  35. package/src/integration/npm-package.testing.ts +2 -3
  36. package/src/integration/replace-package.testing.ts +2 -2
  37. package/src/pi/AGENTS.md +21 -13
  38. package/src/pi/action-fusion.test.ts +38 -4
  39. package/src/pi/action-fusion.ts +23 -19
  40. package/src/pi/argument-diagnostics.ts +28 -48
  41. package/src/pi/argument-validation.test.ts +61 -27
  42. package/src/pi/argument-validation.ts +34 -0
  43. package/src/pi/budgets.ts +19 -10
  44. package/src/pi/config.test.ts +1 -1
  45. package/src/pi/diagnostic-buffer.test.ts +1 -0
  46. package/src/pi/edit-tool.ts +1 -1
  47. package/src/pi/failure-context.test.ts +23 -2
  48. package/src/pi/failure-context.ts +36 -42
  49. package/src/pi/failure-path.test.ts +8 -3
  50. package/src/pi/file-commit.test.ts +109 -52
  51. package/src/pi/file-commit.ts +62 -56
  52. package/src/pi/fusion-card.ts +3 -2
  53. package/src/pi/grep-candidates.test.ts +5 -5
  54. package/src/pi/grep-candidates.ts +81 -50
  55. package/src/pi/grep-matrix.test.ts +14 -29
  56. package/src/pi/grep-order.test.ts +132 -9
  57. package/src/pi/grep-output.ts +169 -51
  58. package/src/pi/grep-render.ts +40 -34
  59. package/src/pi/grep-rg.testing.ts +9 -6
  60. package/src/pi/grep-scope.ts +51 -29
  61. package/src/pi/grep-search.ts +96 -71
  62. package/src/pi/grep-tool.ts +13 -22
  63. package/src/pi/grep.test.ts +310 -84
  64. package/src/pi/model-budgets.test.ts +56 -6
  65. package/src/pi/model-budgets.ts +7 -4
  66. package/src/pi/mutation-result.test.ts +25 -1
  67. package/src/pi/mutation-result.ts +7 -2
  68. package/src/pi/mutation-runner.ts +3 -4
  69. package/src/pi/output-budgets.test.ts +3 -1
  70. package/src/pi/path.ts +18 -4
  71. package/src/pi/pi.test.ts +22 -0
  72. package/src/pi/read-delegation.test.ts +119 -0
  73. package/src/pi/read-tool.ts +109 -61
  74. package/src/pi/read.test.ts +306 -17
  75. package/src/pi/regex-worker.test.ts +42 -0
  76. package/src/pi/regex-worker.ts +17 -11
  77. package/src/pi/registration.test.ts +157 -102
  78. package/src/pi/render.test.ts +54 -0
  79. package/src/pi/render.ts +9 -9
  80. package/src/pi/replace-tool.ts +5 -2
  81. package/src/pi/report-schema.ts +52 -31
  82. package/src/pi/report.test.ts +60 -10
  83. package/src/pi/rg-process.ts +41 -5
  84. package/src/pi/rg-regex.test.ts +12 -52
  85. package/src/pi/rg-regex.ts +29 -77
  86. package/src/pi/text-stream.test.ts +3 -0
  87. package/src/pi/text-stream.ts +1 -1
  88. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -14,7 +14,7 @@ import { searchDiagnostic } from "./rg-process.ts";
14
14
  import type { SearchScope } from "./grep-scope.ts";
15
15
  import { listCandidates, type Candidate } from "./grep-candidates.ts";
16
16
  import { withRegexWorker } from "./regex-worker.ts";
17
- import { invalidWorkerResult, workerReplyDecoder } from "./regex-worker-contract.ts";
17
+ import { workerReplyDecoder } from "./regex-worker-contract.ts";
18
18
  import { fileReadWarning, throwIfCancelled, type SearchWarning } from "./error-text.ts";
19
19
  import { formatByteSize } from "./budgets.ts";
20
20
 
@@ -69,11 +69,10 @@ type Settled =
69
69
  /**
70
70
  * The candidate lines among the next lines of a request source, as the LF view shows them.
71
71
  * `next` indexes the first candidate in source; a returned line number is 1-based in source.
72
- * `lengths` holds each selected line's length, and `lines` the lines a worker matches.
72
+ * `lines` holds the lines a worker matches.
73
73
  */
74
74
  function selectLines(source: string, offset: number, wanted: readonly number[], next: number) {
75
75
  const numbers: number[] = [];
76
- const lengths: number[] = [];
77
76
  const texts: string[] = [];
78
77
  let start = 0;
79
78
  let line = offset + 1;
@@ -88,37 +87,26 @@ function selectLines(source: string, offset: number, wanted: readonly number[],
88
87
  // A CRLF line feeds its view without the CR; a CR before the end of the file stays.
89
88
  const end = lf === -1 ? source.length : source[lf - 1] === "\r" ? lf - 1 : lf;
90
89
  numbers.push(line - offset);
91
- lengths.push(end - start);
92
90
  texts.push(source.slice(start, end), "\n");
93
91
  }
94
- return { numbers, lengths, lines: texts.join("") };
92
+ return { numbers, lines: texts.join("") };
95
93
  }
96
94
 
97
95
  /**
98
96
  * Match one file. Without multiline each line matches alone, so requests split after a
99
- * line feed; a multiline query sends the whole file. Undefined when the file has NUL.
97
+ * line feed; a multiline query sends the whole file. A skipped NUL file can leave a failed worker.
100
98
  */
101
99
  async function searchFile(
102
100
  { filePath, lines: wanted }: Candidate,
103
101
  query: GrepQuery,
104
- room: () => number,
102
+ fileLimit: number,
105
103
  run: Run,
106
104
  signal: AbortSignal,
107
- ): Promise<{ rows: Rows; snapshot: SearchFileSnapshot } | undefined> {
105
+ ): Promise<GrepFileMatch | "restart" | undefined> {
108
106
  const rows: Rows = [];
109
107
  let lineOffset = 0;
110
108
  let nextWanted = 0;
111
- const check = async (input: SearchInput | LineSearchInput, lines: number) => {
112
- const result = await run(input);
113
- if (result.totalLines !== lines || result.lines.length > input.limit)
114
- throw invalidWorkerResult();
115
- let previous = 0;
116
- for (const row of result.lines) {
117
- if (row.lineNumber <= previous || row.lineNumber > lines) throw invalidWorkerResult();
118
- previous = row.lineNumber;
119
- }
120
- return result.lines;
121
- };
109
+ let evaluationFailure: { error: unknown } | undefined;
122
110
  const send = async (source: string) => {
123
111
  const lines = countLines(source);
124
112
  let candidates = lines;
@@ -127,22 +115,21 @@ async function searchFile(
127
115
  while (end < wanted.length && wanted[end] <= lineOffset + lines) end++;
128
116
  candidates = end - nextWanted;
129
117
  }
130
- const limit = room() - rows.length;
118
+ const limit = fileLimit - rows.length;
131
119
  if (candidates > 0 && limit > 0) {
132
120
  // Selecting most lines costs more than matching them all, with the same results.
133
- if (wanted && candidates * 2 <= lines) {
134
- const selected = selectLines(source, lineOffset, wanted, nextWanted);
135
- const found = await check({ lines: selected.lines, query, limit }, candidates);
136
- for (const { lineNumber, column } of found) {
137
- if (column > selected.lengths[lineNumber - 1]) throw invalidWorkerResult();
138
- rows.push({ lineNumber: lineOffset + selected.numbers[lineNumber - 1], column });
139
- }
140
- } else {
141
- for (const { lineNumber, column } of await check({ source, query, limit }, lines)) {
142
- if (column > source.length) throw invalidWorkerResult();
143
- rows.push({ lineNumber: lineOffset + lineNumber, column });
144
- }
145
- }
121
+ const selected =
122
+ wanted && candidates * 2 <= lines
123
+ ? selectLines(source, lineOffset, wanted, nextWanted)
124
+ : undefined;
125
+ const found = await run(
126
+ selected ? { lines: selected.lines, query, limit } : { source, query, limit },
127
+ );
128
+ for (const { lineNumber, column } of found.lines)
129
+ rows.push({
130
+ lineNumber: lineOffset + (selected ? selected.numbers[lineNumber - 1] : lineNumber),
131
+ column,
132
+ });
146
133
  }
147
134
  if (wanted) nextWanted += candidates;
148
135
  lineOffset += lines;
@@ -156,7 +143,8 @@ async function searchFile(
156
143
  let oversized = false;
157
144
  const stats = await scanTextFile(filePath, {
158
145
  onChunk: async (text, bytesRead) => {
159
- if (oversized) return;
146
+ // A later NUL makes earlier regex results and failures irrelevant.
147
+ if (oversized || evaluationFailure) return;
160
148
  if (query.multiline) {
161
149
  oversized = bytesRead > MAX_MULTILINE_SEARCH_BYTES;
162
150
  pending = oversized ? "" : pending + text;
@@ -165,8 +153,16 @@ async function searchFile(
165
153
  let start = 0;
166
154
  for (;;) {
167
155
  const lf = text.indexOf("\n", start);
168
- lineUnits += (lf === -1 ? text.length : lf) - start;
169
- if (lineUnits > MAX_SEARCH_LINE_UNITS) {
156
+ const end = lf === -1 ? text.length : lf;
157
+ lineUnits += end - start;
158
+ // One extra CR can belong to the terminator, including across scan chunks.
159
+ if (
160
+ lineUnits > MAX_SEARCH_LINE_UNITS &&
161
+ !(
162
+ lineUnits === MAX_SEARCH_LINE_UNITS + 1 &&
163
+ (end === 0 ? pending.endsWith("\r") : text[end - 1] === "\r")
164
+ )
165
+ ) {
170
166
  oversized = true;
171
167
  pending = "";
172
168
  return;
@@ -181,16 +177,31 @@ async function searchFile(
181
177
  const source = pending.slice(0, complete);
182
178
  pending = pending.slice(complete);
183
179
  complete = 0;
184
- await send(source);
180
+ try {
181
+ await send(source);
182
+ } catch (error) {
183
+ throwIfCancelled(signal);
184
+ evaluationFailure = { error };
185
+ pending = "";
186
+ }
185
187
  }
186
188
  },
187
189
  signal,
188
190
  decoding: "lossy",
191
+ }).catch((error: unknown) => {
192
+ throwIfCancelled(signal);
193
+ // A failed scan cannot clear the earlier worker failure.
194
+ if (evaluationFailure) throw evaluationFailure.error;
195
+ throw error;
189
196
  });
190
- if (stats.hasNul) return undefined;
191
- if (oversized) throw new SearchFileLimitError(query.multiline);
197
+ if (stats.hasNul) return evaluationFailure ? "restart" : undefined;
198
+ if (evaluationFailure) throw evaluationFailure.error;
199
+ if (oversized || lineUnits > MAX_SEARCH_LINE_UNITS)
200
+ throw new SearchFileLimitError(query.multiline);
192
201
  await send(pending);
202
+ if (!rows.length) return undefined;
193
203
  return {
204
+ filePath,
194
205
  rows,
195
206
  snapshot: { revision: stats.revision, validUtf8: stats.validUtf8 },
196
207
  };
@@ -213,7 +224,7 @@ export async function searchFiles(options: {
213
224
  const files: GrepFileMatch[] = [];
214
225
  /** File warnings in listing order, then the listing's own diagnostic. */
215
226
  const warnings: SearchWarning[] = [];
216
- /** Committed matches; a file still searching gets at most the remaining room. */
227
+ /** Matches committed in listing order. */
217
228
  let matches = 0;
218
229
  let matchLimitReached = false;
219
230
  let failure: { error: unknown } | undefined;
@@ -244,7 +255,8 @@ export async function searchFiles(options: {
244
255
  const settled = new Map<number, Settled>();
245
256
  let enqueued = 0;
246
257
  let committed = 0;
247
- const commit = () => {
258
+ const commit = (position: number, outcome: Settled) => {
259
+ settled.set(position, outcome);
248
260
  for (let result = settled.get(committed); result && !stopped(); ) {
249
261
  settled.delete(committed++);
250
262
  if ("error" in result) fail(result.error);
@@ -260,42 +272,55 @@ export async function searchFiles(options: {
260
272
  releaseAll();
261
273
  };
262
274
 
263
- const searchPath = async ({ candidate, position }: Queued, run: Run) => {
264
- const { filePath } = candidate;
265
- let result: Settled;
266
- try {
267
- const found = await searchFile(candidate, query, () => limit - matches, run, poolSignal);
268
- result = found?.rows.length ? { file: { filePath, ...found } } : {};
269
- } catch (error) {
270
- throwIfCancelled(poolSignal);
271
- const warning: SearchWarning | undefined =
272
- error instanceof SearchFileLimitError
273
- ? { path: filePath, reason: error.message }
274
- : fileReadWarning(filePath, error);
275
- result = warning ? { warning } : { error };
275
+ // A fatal result ends this slot; only a failed worker on a skipped file needs replacing.
276
+ const consume = async (run: Run): Promise<"restart" | void> => {
277
+ for (let item = await next(); item !== undefined; item = await next()) {
278
+ const { candidate, position } = item;
279
+ let found: Awaited<ReturnType<typeof searchFile>>;
280
+ try {
281
+ // Use a fixed file budget so earlier commits cannot change which regex requests run.
282
+ found = await searchFile(candidate, query, limit, run, poolSignal);
283
+ } catch (error) {
284
+ throwIfCancelled(poolSignal);
285
+ const warning =
286
+ error instanceof SearchFileLimitError
287
+ ? { path: candidate.filePath, reason: error.message }
288
+ : fileReadWarning(candidate.filePath, error);
289
+ commit(position, warning ? { warning } : { error });
290
+ if (!warning) return;
291
+ continue;
292
+ }
293
+ if (found === "restart") {
294
+ commit(position, {});
295
+ return found;
296
+ }
297
+ commit(position, { file: found });
276
298
  }
277
- settled.set(position, result);
278
- commit();
279
- // Nothing after a fatal candidate can be needed; retire its worker without reusing a failure.
280
- return !("error" in result);
281
299
  };
282
300
 
283
301
  const workers: Promise<void>[] = [];
284
- const startWorker = () =>
285
- withRegexWorker<SearchInput | LineSearchInput, SearchResult, void>(
286
- new URL("./grep-worker.mjs", import.meta.url),
287
- decodeReply,
288
- timeoutMs,
289
- poolSignal,
290
- async (run) => {
291
- for (let file = await next(); file !== undefined; file = await next())
292
- if (!(await searchPath(file, run))) break;
293
- },
294
- { maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
295
- ).catch((error) => {
302
+ const startWorker = async () => {
303
+ try {
304
+ while (!stopped()) {
305
+ const outcome = await withRegexWorker<
306
+ SearchInput | LineSearchInput,
307
+ SearchResult,
308
+ Awaited<ReturnType<typeof consume>>
309
+ >(
310
+ new URL("./grep-worker.mjs", import.meta.url),
311
+ decodeReply,
312
+ timeoutMs,
313
+ poolSignal,
314
+ consume,
315
+ { maxOldGenerationSizeMb: MAX_SEARCH_HEAP_MB },
316
+ );
317
+ if (outcome !== "restart") break;
318
+ }
319
+ } catch (error) {
296
320
  fail(error);
297
321
  releaseAll();
298
- });
322
+ }
323
+ };
299
324
 
300
325
  const enqueue = async (candidate: Candidate) => {
301
326
  if (stopped()) return false;
@@ -16,8 +16,7 @@ import { filterExplicitFilesByGlob, resolveSearchPaths } from "./grep-scope.ts";
16
16
  import { searchFiles } from "./grep-search.ts";
17
17
  import { toDisplayLines } from "./grep-render.ts";
18
18
  import { smartIgnoreCase } from "../core/search-analysis.ts";
19
- import { checkRegexArguments } from "../core/regex.ts";
20
- import { DEFAULT_GREP_FLAGS } from "../core/search.ts";
19
+ import { GREP_FLAGS } from "../core/search.ts";
21
20
  import {
22
21
  GREP_CONTEXT_RANGE,
23
22
  literalUnion,
@@ -27,7 +26,11 @@ import {
27
26
  import { throwIfCancelled } from "./error-text.ts";
28
27
  import { reportResult, runTool, type ReportDetails } from "./report.ts";
29
28
  import type { HashlineEditConfig, ToolEnvironment } from "./config.ts";
30
- import { createArgumentPreparer, type ReportArgumentIssue } from "./argument-validation.ts";
29
+ import {
30
+ checkRegexArguments,
31
+ createArgumentPreparer,
32
+ type ReportArgumentIssue,
33
+ } from "./argument-validation.ts";
31
34
 
32
35
  /** A list field: arrays only, because strict sampling cannot take a string-or-array union. */
33
36
  const nonEmptyStrings = (description: string) =>
@@ -62,15 +65,10 @@ function createGrepSchema({ defaultLimit, defaultContext }: HashlineEditConfig["
62
65
  description:
63
66
  "true: match the text exactly, including regex punctuation; use it for names, paths, and code snippets. false: JavaScript regex, where foo(0) matches foo0; use it only for an intentional regex.",
64
67
  }),
65
- flags: Type.Optional(
66
- Type.String({
67
- description: `JavaScript regex flags (default ${DEFAULT_GREP_FLAGS}); given flags replace the default, so in a multiline search without m, ^ and $ anchor to the file's start and end. g is always enabled and repeated flags are ignored. Use u or v for Unicode mode, s for dotAll, and y for sticky matching.`,
68
- }),
69
- ),
70
68
  ignoreCase: Type.Optional(
71
69
  Type.Boolean({
72
70
  description:
73
- "true ignores case, false matches case; overrides the i flag. When omitted, the i flag ignores case; without it, case is ignored only when no pattern contains an uppercase letter (a pattern that cannot be analyzed counts as uppercase).",
71
+ "true ignores case, false matches case. When omitted, case is ignored only when no pattern contains an uppercase letter (a pattern that cannot be analyzed counts as uppercase).",
74
72
  }),
75
73
  ),
76
74
  multiline: Type.Optional(
@@ -107,12 +105,11 @@ function streamedList(value: string | readonly string[] | null | undefined): rea
107
105
 
108
106
  /** Validate JavaScript syntax once; the search never rejects a pattern V8 accepts. */
109
107
  function checkGrepArguments(args: unknown, report: ReportArgumentIssue): void {
110
- const { pattern, literal, flags } = (args ?? {}) as Record<string, unknown>;
111
- if (flags !== undefined && typeof flags !== "string") return;
108
+ const { pattern, literal } = (args ?? {}) as Record<string, unknown>;
112
109
  const fields = Array.isArray(pattern)
113
110
  ? pattern.map((value, index) => [`pattern[${index}]`, value] as const)
114
111
  : [];
115
- checkRegexArguments("flags", flags ?? DEFAULT_GREP_FLAGS, literal !== false, fields, report);
112
+ checkRegexArguments("flags", GREP_FLAGS, literal !== false, fields, report);
116
113
  }
117
114
 
118
115
  /** Build the grep override (a ToolDefinition fragment for registerTool). */
@@ -128,7 +125,6 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
128
125
  promptSnippet: "Search file contents",
129
126
  promptGuidelines: [
130
127
  "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
131
- "Copy grep anchors directly into edit.",
132
128
  ],
133
129
  parameters: grepSchema,
134
130
  prepareArguments: createArgumentPreparer("grep", grepSchema, checkGrepArguments, budgets),
@@ -144,7 +140,7 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
144
140
  const globs = streamedList(args?.glob);
145
141
  let text =
146
142
  theme.fg("toolTitle", theme.bold("grep ")) +
147
- theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/${args?.flags ?? ""}`) +
143
+ theme.fg("accent", `/${streamedList(args?.pattern).join(" | ")}/`) +
148
144
  theme.fg("toolOutput", ` in ${paths.length ? paths.join(" ") : "."}`);
149
145
  if (globs.length) text += theme.fg("toolOutput", ` (${globs.join(", ")})`);
150
146
  if (args?.outputMode && args.outputMode !== "content")
@@ -190,20 +186,14 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
190
186
  const effectiveLimit = params.limit ?? config.grep.defaultLimit;
191
187
  const outputMode = params.outputMode ?? "content";
192
188
  const { literal } = params;
193
- const flags = new Set(params.flags ?? DEFAULT_GREP_FLAGS);
194
- const ignoreCase =
195
- params.ignoreCase ??
196
- (flags.has("i") || smartIgnoreCase(patterns, literal, [...flags].join("")));
197
- if (ignoreCase) flags.add("i");
198
- else flags.delete("i");
199
189
  const query = {
200
190
  patterns,
201
191
  literal,
202
- flags: [...flags].join(""),
192
+ ignoreCase: params.ignoreCase ?? smartIgnoreCase(patterns, literal),
203
193
  multiline: params.multiline ?? false,
204
194
  };
205
195
  const globs = params.glob ?? [];
206
- const paths = await resolveSearchPaths(cwd, params.path);
196
+ const { paths, missing } = await resolveSearchPaths(cwd, params.path);
207
197
  const admitted = await filterExplicitFilesByGlob(globs, paths, signal);
208
198
  const { warnings: searchWarnings, ...search } = await searchFiles({
209
199
  scope: { globs, searchPaths: admitted.searchPaths },
@@ -221,6 +211,7 @@ export function makeGrepOverride({ cwd, config, budgets }: ToolEnvironment) {
221
211
  signal,
222
212
  // Each stage returns its warnings in order; the report states them in stage order.
223
213
  warnings: [...admitted.warnings, ...searchWarnings],
214
+ missing,
224
215
  effectiveLimit,
225
216
  literalPipe: literal && patterns.some((pattern) => pattern.includes("|")),
226
217
  budget,