@criogaid/pi-hashline-edit 0.11.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 (94) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +73 -17
  3. package/README.zh-CN.md +74 -18
  4. package/package.json +8 -7
  5. package/src/core/AGENTS.md +2 -2
  6. package/src/core/apply.test.ts +15 -2
  7. package/src/core/apply.ts +6 -10
  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 -32
  13. package/src/core/replace.test.ts +51 -0
  14. package/src/core/replace.ts +10 -4
  15. package/src/core/search-analysis.test.ts +66 -61
  16. package/src/core/search-analysis.ts +24 -39
  17. package/src/core/search-matrix.test.ts +2 -2
  18. package/src/core/search-matrix.testing.ts +6 -16
  19. package/src/core/search-schema.ts +0 -1
  20. package/src/core/search.test.ts +6 -19
  21. package/src/core/search.ts +10 -8
  22. package/src/index.ts +28 -3
  23. package/src/integration/config-registration.test.ts +77 -4
  24. package/src/integration/fusion-dispatch.test.ts +47 -2
  25. package/src/integration/grep-errors.test.ts +31 -0
  26. package/src/integration/grep-flags.test.ts +13 -196
  27. package/src/integration/grep-js-completeness.test.ts +41 -8
  28. package/src/integration/grep-line-candidates.test.ts +4 -33
  29. package/src/integration/grep-matrix.test.ts +1 -1
  30. package/src/integration/grep-path-matrix.test.ts +59 -65
  31. package/src/integration/grep-prefilter-coverage.test.ts +26 -8
  32. package/src/integration/grep-process-limits.test.ts +46 -0
  33. package/src/integration/grep-regex.test.ts +7 -2
  34. package/src/integration/grep-rg.test.ts +106 -12
  35. package/src/integration/grep-translation.test.ts +14 -7
  36. package/src/integration/model-budget-lifecycle.test.ts +41 -2
  37. package/src/integration/npm-package.test.ts +12 -10
  38. package/src/integration/npm-package.testing.ts +147 -1
  39. package/src/integration/replace-package.testing.ts +2 -2
  40. package/src/integration/report-replay.test.ts +4 -0
  41. package/src/pi/AGENTS.md +23 -15
  42. package/src/pi/action-fusion.test.ts +38 -4
  43. package/src/pi/action-fusion.ts +23 -19
  44. package/src/pi/argument-diagnostics.ts +28 -48
  45. package/src/pi/argument-validation.test.ts +103 -6
  46. package/src/pi/argument-validation.ts +55 -31
  47. package/src/pi/budgets.ts +19 -10
  48. package/src/pi/config.test.ts +1 -1
  49. package/src/pi/diagnostic-buffer.test.ts +1 -0
  50. package/src/pi/edit-tool.ts +3 -3
  51. package/src/pi/execute.test.ts +4 -0
  52. package/src/pi/failure-context.test.ts +24 -3
  53. package/src/pi/failure-context.ts +36 -42
  54. package/src/pi/failure-path.test.ts +8 -3
  55. package/src/pi/file-commit.test.ts +109 -52
  56. package/src/pi/file-commit.ts +62 -56
  57. package/src/pi/fusion-card.ts +12 -7
  58. package/src/pi/grep-candidates.test.ts +5 -5
  59. package/src/pi/grep-candidates.ts +80 -48
  60. package/src/pi/grep-matrix.test.ts +14 -29
  61. package/src/pi/grep-order.test.ts +132 -9
  62. package/src/pi/grep-output.ts +173 -48
  63. package/src/pi/grep-render.ts +40 -34
  64. package/src/pi/grep-rg.testing.ts +9 -6
  65. package/src/pi/grep-scope.ts +51 -29
  66. package/src/pi/grep-search.ts +96 -71
  67. package/src/pi/grep-tool.ts +28 -34
  68. package/src/pi/grep.test.ts +348 -83
  69. package/src/pi/model-budgets.test.ts +56 -6
  70. package/src/pi/model-budgets.ts +7 -4
  71. package/src/pi/mutation-result.test.ts +25 -1
  72. package/src/pi/mutation-result.ts +7 -2
  73. package/src/pi/mutation-runner.ts +4 -5
  74. package/src/pi/output-budgets.test.ts +3 -1
  75. package/src/pi/path.ts +18 -4
  76. package/src/pi/pi.test.ts +22 -0
  77. package/src/pi/read-delegation.test.ts +119 -0
  78. package/src/pi/read-tool.ts +109 -61
  79. package/src/pi/read.test.ts +351 -17
  80. package/src/pi/regex-worker.test.ts +42 -0
  81. package/src/pi/regex-worker.ts +17 -11
  82. package/src/pi/registration.test.ts +157 -102
  83. package/src/pi/render.test.ts +97 -0
  84. package/src/pi/render.ts +9 -9
  85. package/src/pi/replace-tool.ts +5 -2
  86. package/src/pi/report-schema.ts +75 -37
  87. package/src/pi/report.test.ts +73 -31
  88. package/src/pi/report.ts +12 -5
  89. package/src/pi/rg-process.ts +41 -5
  90. package/src/pi/rg-regex.test.ts +12 -39
  91. package/src/pi/rg-regex.ts +31 -79
  92. package/src/pi/text-stream.test.ts +3 -0
  93. package/src/pi/text-stream.ts +1 -1
  94. package/src/testing/regex-translation-corpus.ts +39 -96
@@ -9,6 +9,7 @@ import type {
9
9
  ExtensionAPI,
10
10
  ExtensionContext,
11
11
  ToolDefinition,
12
+ ToolRenderers,
12
13
  } from "@earendil-works/pi-coding-agent";
13
14
  import {
14
15
  createBashToolDefinition,
@@ -131,15 +132,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
131
132
  });
132
133
  pi.on("session_tree", (_event, ctx) => restore(ctx));
133
134
 
134
- pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, { expanded }):
135
+ pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, function renderCard(entry, options):
135
136
  | Component
136
137
  | undefined {
138
+ const { expanded } = options;
137
139
  const initial = entry.data;
138
140
  if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
139
141
  if (!tui) {
140
142
  // Pi may rebuild history before session_start supplies its UI context.
141
143
  let component: Component | undefined;
142
- const ready = () => (component ??= tui ? renderCard(entry, { expanded }) : undefined);
144
+ const ready = () => (component ??= tui ? renderCard(entry, options) : undefined);
143
145
  return {
144
146
  render: (width) => ready()?.render(width) ?? [],
145
147
  invalidate: () => component?.invalidate(),
@@ -155,15 +157,16 @@ export function registerFusionCards(pi: ExtensionAPI) {
155
157
  let box = new Box(outputPadding, 1);
156
158
  let call: Component | undefined;
157
159
  let result: Component | undefined;
158
- const renderers: Pick<typeof bash, "renderShell" | "renderCall" | "renderResult"> = {
160
+ const renderers: ToolRenderers = {
159
161
  renderShell: "self",
160
- renderCall(args, theme, context) {
162
+ renderCall(_args, theme, context) {
161
163
  const padding = SettingsManager.inMemory(pi.getSettings()).getOutputPad();
162
164
  if (padding !== outputPadding) {
163
165
  outputPadding = padding;
164
166
  box = new Box(outputPadding, 1);
165
167
  }
166
168
  const value = current();
169
+ const args = { command: value.commandText, timeout: value.timing?.timeoutSeconds };
167
170
  const pending = commandPending(value);
168
171
  const interrupted = pending && !active.has(value.toolCallId);
169
172
  const status = interrupted ? "interrupted (final status unknown)" : value.command;
@@ -192,7 +195,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
192
195
  statusText.setText(
193
196
  `${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
194
197
  );
195
- call = bash.renderCall!(args, theme, { ...context, lastComponent: call });
198
+ call = bash.renderCall!(args, theme, { ...context, args, lastComponent: call });
196
199
  box.clear();
197
200
  box.addChild(statusText);
198
201
  box.addChild(call);
@@ -205,6 +208,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
205
208
  if (current().result) {
206
209
  result = bash.renderResult!(value, options, theme, {
207
210
  ...context,
211
+ args: { command: current().commandText, timeout: current().timing?.timeoutSeconds },
208
212
  lastComponent: result,
209
213
  });
210
214
  box.addChild(result);
@@ -286,7 +290,8 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
286
290
  ...tool,
287
291
  renderShell: "self",
288
292
  renderCall(args, theme, context) {
289
- const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
293
+ const shell = (context.state.mutationShell ??= { box: new Box(context.outputPad, 1) });
294
+ shell.box.setPaddingX(context.outputPad);
290
295
  shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
291
296
  shell.box.clear();
292
297
  shell.box.addChild(shell.call);
@@ -303,7 +308,7 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
303
308
  return shell.box;
304
309
  },
305
310
  renderResult(result, options, theme, context) {
306
- const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
311
+ const shell = (context.state.mutationShell ??= { box: new Box(context.outputPad, 1) });
307
312
  // Fusion updates carry progress alongside TDetails; final results carry only the outcome.
308
313
  const details = result.details as { actionFusion?: MutationCardProgress } | undefined;
309
314
  const file = details?.actionFusion ?? shell.fileState;
@@ -4,14 +4,14 @@ import assert from "node:assert/strict";
4
4
  import { COMMON_RG_ARGS } from "./rg-process.ts";
5
5
 
6
6
  test("candidate literals → rg lists files with escaped byte-preserving alternatives", async () => {
7
- const query = { patterns: ["."], literal: false, flags: "", multiline: true };
7
+ const query = { patterns: ["."], literal: false, ignoreCase: false, multiline: true };
8
8
  assert.deepEqual(await fileCandidateArgs(query), [...COMMON_RG_ARGS, "--files"]);
9
- for (const [patterns, literal, flags, pattern] of [
10
- [["a.b", "-é"], true, "", "a\\x{2e}b|\\x{2d}\\x{e9}"],
11
- [["k_9"], true, "iu", "[Kk\\x{212a}]_9"],
9
+ for (const [patterns, literal, ignoreCase, pattern] of [
10
+ [["a.b", "-é"], true, false, "a\\x{2e}b|\\x{2d}\\x{e9}"],
11
+ [["k_9"], true, true, "[Kk]_9"],
12
12
  ] as const) {
13
13
  assert.deepEqual(
14
- await fileCandidateArgs({ patterns: [...patterns], literal, flags, multiline: true }),
14
+ await fileCandidateArgs({ patterns: [...patterns], literal, ignoreCase, multiline: true }),
15
15
  [
16
16
  ...COMMON_RG_ARGS,
17
17
  "--files-with-matches",
@@ -9,12 +9,16 @@
9
9
  import { stat } from "node:fs/promises";
10
10
  import { resolve } from "node:path";
11
11
  import type { GrepQuery } from "../core/search.ts";
12
- import { extractPrefilter, type Literal, type Prefilter } from "../core/search-analysis.ts";
13
- import { scopeArgs, type SearchScope } from "./grep-scope.ts";
12
+ import { extractPrefilter, type Literal } from "../core/search-analysis.ts";
13
+ import { ListedFiles, scopeArgs, type SearchScope } from "./grep-scope.ts";
14
14
  import {
15
15
  COMMON_RG_ARGS,
16
+ isRgArgumentLimit,
16
17
  LINE_LISTING_ARGS,
17
18
  MAX_RG_PATTERN_UNITS,
19
+ RG_PATTERN_FLAG,
20
+ rgPatternArgUnits,
21
+ rgRejectsPatterns,
18
22
  runRgLines,
19
23
  runRgPaths,
20
24
  type RgRunResult,
@@ -48,32 +52,17 @@ function literalPattern(literal: Literal): string {
48
52
  const literalAlternation = (literals: readonly Literal[]): string =>
49
53
  literals.map(literalPattern).join("|");
50
54
 
51
- /** Necessary literals too long for rg's command line widen to every file in scope. */
52
- function boundedPrefilter(prefilter: Prefilter): Prefilter {
53
- return prefilter.kind === "literals" &&
54
- literalAlternation(prefilter.literals).length > MAX_RG_PATTERN_UNITS
55
- ? { kind: "all" }
56
- : prefilter;
55
+ /** A listing that narrows candidates with rg patterns; the next stage replaces it when rg cannot run them. */
56
+ interface PatternStage {
57
+ readonly patternArgs: readonly string[];
58
+ readonly list: () => Promise<RgRunResult>;
57
59
  }
58
60
 
59
- /**
60
- * List candidate files: those whose original bytes contain a prefilter literal, or every
61
- * file in scope. Literals never contain a line break, so line-oriented matching finds them.
62
- */
63
- function candidateArgs(prefilter: Prefilter): string[] {
64
- if (prefilter.kind === "all") return [...COMMON_RG_ARGS, "--files"];
65
- return [
66
- ...COMMON_RG_ARGS,
67
- "--files-with-matches",
68
- ...BYTE_PATTERN_ARGS,
69
- "-e",
70
- literalAlternation(prefilter.literals),
71
- ];
61
+ function widenOnArgumentLimit(error: unknown): undefined {
62
+ if (isRgArgumentLimit(error)) return undefined;
63
+ throw error;
72
64
  }
73
65
 
74
- /** How candidates were selected: rg's candidate lines, or whole files (see Prefilter). */
75
- type CandidateSource = "lines" | "files" | "all";
76
-
77
66
  /**
78
67
  * Await each consumer for backpressure; false stops listing. The caller owns worker cleanup.
79
68
  * An empty scope lists nothing, because rg would search the working directory instead.
@@ -90,18 +79,18 @@ export async function listCandidates(options: {
90
79
  }> {
91
80
  const { scope, query, signal, stopped, onCandidate } = options;
92
81
  if (scope.searchPaths.length === 0) return { scanLimitReached: false };
93
- let candidates: CandidateSource = "lines";
82
+ let scanAll = false;
94
83
  let listedAny = false;
95
84
  let scanned = 0;
96
85
  let scanLimitReached = false;
97
- const seen = new Set<string>();
86
+ const seen = new ListedFiles();
98
87
  const offer = async (path: string, lines?: readonly number[]) => {
99
88
  listedAny = true;
100
89
  if (stopped()) return false;
101
90
  const filePath = resolve(path);
102
- if (seen.has(filePath)) return true;
91
+ if (await seen.has(filePath)) return true;
103
92
  seen.add(filePath);
104
- if (candidates === "all") {
93
+ if (scanAll) {
105
94
  if (scanned >= MAX_UNNARROWED_SCAN_BYTES) {
106
95
  scanLimitReached = true;
107
96
  return false;
@@ -115,26 +104,69 @@ export async function listCandidates(options: {
115
104
  return onCandidate({ filePath, lines });
116
105
  };
117
106
  const scoped = [...scopeArgs(scope), "--", ...scope.searchPaths];
118
- const patterns = query.multiline ? undefined : lineCandidatePatterns(query);
119
- let listing = patterns
120
- ? await runRgLines(
121
- [
122
- ...COMMON_RG_ARGS,
123
- ...BYTE_PATTERN_ARGS,
124
- ...LINE_LISTING_ARGS,
125
- ...patterns.flatMap((pattern) => ["-e", pattern]),
126
- ...scoped,
127
- ],
128
- signal,
129
- MAX_CANDIDATE_LINES,
130
- offer,
131
- )
132
- : undefined;
133
- // rg reports a pattern it cannot compile, such as one beyond its size limit, before any file.
134
- if (!listing || (listing.code === 2 && !listedAny)) {
135
- const prefilter = boundedPrefilter(extractPrefilter(query));
136
- candidates = prefilter.kind === "all" ? "all" : "files";
137
- listing = await runRgPaths([...candidateArgs(prefilter), "--null", ...scoped], signal, offer);
107
+
108
+ /** Narrowing listings, most selective first; each is derived only when the one before gives way. */
109
+ function* patternStages(): Generator<PatternStage> {
110
+ const patterns = query.multiline ? undefined : lineCandidatePatterns(query);
111
+ if (patterns) {
112
+ const patternArgs = patterns.flatMap((pattern) => [RG_PATTERN_FLAG, pattern]);
113
+ yield {
114
+ patternArgs,
115
+ list: () =>
116
+ runRgLines(
117
+ [
118
+ ...COMMON_RG_ARGS,
119
+ ...BYTE_PATTERN_ARGS,
120
+ ...LINE_LISTING_ARGS,
121
+ ...patternArgs,
122
+ ...scoped,
123
+ ],
124
+ signal,
125
+ MAX_CANDIDATE_LINES,
126
+ offer,
127
+ ),
128
+ };
129
+ }
130
+ const prefilter = extractPrefilter(query);
131
+ if (prefilter.kind !== "literals") return;
132
+ const pattern = literalAlternation(prefilter.literals);
133
+ if (rgPatternArgUnits(pattern) > MAX_RG_PATTERN_UNITS) return;
134
+ const patternArgs = [RG_PATTERN_FLAG, pattern];
135
+ yield {
136
+ patternArgs,
137
+ list: () =>
138
+ runRgPaths(
139
+ [
140
+ ...COMMON_RG_ARGS,
141
+ "--files-with-matches",
142
+ ...BYTE_PATTERN_ARGS,
143
+ ...patternArgs,
144
+ "--null",
145
+ ...scoped,
146
+ ],
147
+ signal,
148
+ offer,
149
+ ),
150
+ };
151
+ }
152
+
153
+ // A stage gives way when its arguments exceed the command line, or when rg exits with code 2
154
+ // before offering any candidate because it rejects the patterns. A completed listing that only
155
+ // hit unreadable paths also exits with 2, and stands.
156
+ for (const { patternArgs, list } of patternStages()) {
157
+ const listing = await list().catch(widenOnArgumentLimit);
158
+ const givesWay =
159
+ !listing ||
160
+ (listing.code === 2 &&
161
+ !listedAny &&
162
+ (await rgRejectsPatterns([...BYTE_PATTERN_ARGS, ...patternArgs], signal)));
163
+ if (!givesWay) return { listing, scanLimitReached };
138
164
  }
165
+ scanAll = true;
166
+ const listing = await runRgPaths(
167
+ [...COMMON_RG_ARGS, "--files", "--null", ...scoped],
168
+ signal,
169
+ offer,
170
+ );
139
171
  return { listing, scanLimitReached };
140
172
  }
@@ -1,13 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { MATRIX_FLAGS, MATRIX_SYNTAX } from "../core/search-matrix.testing.ts";
3
+ import { MATRIX_SYNTAX } from "../core/search-matrix.testing.ts";
4
+ import { GREP_FLAGS } from "../core/search.ts";
4
5
  import { makeMockGrep } from "./grep-rg.testing.ts";
5
6
  const { DEFAULT_CONFIG } = await import("./tool-factories.testing.ts");
6
7
  import { reportOf } from "./report.ts";
7
8
  import { rejectsArgument } from "./argument-error.testing.ts";
8
9
  import { callTool } from "./tool-call.testing.ts";
9
10
 
10
- test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8 before discovery", async (t) => {
11
+ test("Cartesian JS syntax × case override → tool entry agrees with V8 before discovery", async (t) => {
11
12
  let discoveries = 0;
12
13
  const discover = async () => {
13
14
  discoveries++;
@@ -17,17 +18,6 @@ test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8
17
18
  runRgPaths: discover,
18
19
  runRgLines: discover,
19
20
  });
20
- const flagsCases = [
21
- ...["", "d", "g", "dg"].flatMap((prefix) => MATRIX_FLAGS.map((flags) => prefix + flags)),
22
- "uv",
23
- "imuv",
24
- "x",
25
- "I",
26
- "u v",
27
- "gg",
28
- "ii",
29
- "mmuu",
30
- ];
31
21
  const patterns = [
32
22
  ...MATRIX_SYNTAX.map(([, pattern]) => pattern),
33
23
  "(",
@@ -38,26 +28,22 @@ test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8
38
28
  let accepted = 0;
39
29
  let rejected = 0;
40
30
  for (const pattern of patterns) {
41
- for (const flags of flagsCases) {
42
- const normalizedFlags = [...new Set(flags)].join("");
43
- let field: "flags" | "pattern[0]" | undefined;
31
+ for (const ignoreCase of [undefined, false, true]) {
32
+ let field: "pattern[0]" | undefined;
44
33
  try {
45
- new RegExp("", normalizedFlags);
34
+ new RegExp(pattern, GREP_FLAGS);
46
35
  } catch (error) {
47
36
  if (!(error instanceof SyntaxError)) throw error;
48
- field = "flags";
49
- }
50
- if (!field) {
51
- try {
52
- new RegExp(pattern, normalizedFlags);
53
- } catch (error) {
54
- if (!(error instanceof SyntaxError)) throw error;
55
- field = "pattern[0]";
56
- }
37
+ field = "pattern[0]";
57
38
  }
58
39
  const before = discoveries;
59
- const result = callTool(tool, { pattern, flags, literal: false });
60
- const context = JSON.stringify({ pattern, flags });
40
+ const params = {
41
+ pattern,
42
+ literal: false,
43
+ ...(ignoreCase === undefined ? {} : { ignoreCase }),
44
+ };
45
+ const result = callTool(tool, params);
46
+ const context = JSON.stringify(params);
61
47
  if (field) {
62
48
  rejected++;
63
49
  await assert.rejects(result, rejectsArgument(field), context);
@@ -74,7 +60,6 @@ test("Cartesian JS syntax × all flag combinations → tool entry agrees with V8
74
60
  t.diagnostic(
75
61
  JSON.stringify({
76
62
  syntaxInputs: patterns.length,
77
- flagInputs: flagsCases.length,
78
63
  accepted,
79
64
  rejected,
80
65
  }),
@@ -15,6 +15,12 @@ import type { MockRg } from "./grep-rg.testing.ts";
15
15
  import type { WorkerError } from "./report-cause.ts";
16
16
  import { callTool } from "./tool-call.testing.ts";
17
17
 
18
+ const REGEX_TIMEOUT: WorkerError = {
19
+ code: "REGEX_TIMEOUT",
20
+ message: "Regex evaluation timed out.",
21
+ facts: { timeoutMs: DEFAULT_CONFIG.grep.regexTimeoutMs },
22
+ };
23
+
18
24
  test("out-of-order file completions → listing order fixes rows, warnings, and the limit cutoff", {
19
25
  timeout: 15_000,
20
26
  }, async (t) => {
@@ -205,16 +211,11 @@ test("file-associated failure → listing position decides failure or cutoff, wh
205
211
  t.after(() => fs.rm(dir, { recursive: true, force: true }));
206
212
  const names = ["a.txt", "z.txt"];
207
213
  for (const name of names) await fs.writeFile(join(dir, name), `needle ${name}\n`);
208
- const timeout: WorkerError = {
209
- code: "REGEX_TIMEOUT",
210
- message: "Regex evaluation timed out.",
211
- facts: { timeoutMs: DEFAULT_CONFIG.grep.regexTimeoutMs },
212
- };
213
214
  const failures = [
214
215
  {
215
216
  name: "timeout",
216
- code: timeout.code,
217
- finish: (worker: Worker) => worker.emit("message", { error: timeout }),
217
+ code: REGEX_TIMEOUT.code,
218
+ finish: (worker: Worker) => worker.emit("message", { error: REGEX_TIMEOUT }),
218
219
  },
219
220
  {
220
221
  name: "worker error",
@@ -222,11 +223,11 @@ test("file-associated failure → listing position decides failure or cutoff, wh
222
223
  finish: (worker: Worker) => worker.emit("error", new Error("Worker crashed")),
223
224
  },
224
225
  {
225
- name: "inconsistent rows",
226
+ name: "invalid reply schema",
226
227
  code: "REGEX_WORKER_FAILED",
227
228
  finish: (worker: Worker) =>
228
229
  worker.emit("message", {
229
- result: { totalLines: 2, lines: [{ lineNumber: 1, column: 0 }] },
230
+ result: { lines: [{ lineNumber: 0, column: 0 }] },
230
231
  }),
231
232
  },
232
233
  ] as const;
@@ -322,3 +323,125 @@ test("file-associated failure → listing position decides failure or cutoff, wh
322
323
  }
323
324
  }
324
325
  });
326
+
327
+ test("partial budget consumed by an earlier file → later file has the same regex timeout in either completion order", {
328
+ timeout: 15_000,
329
+ }, async (t) => {
330
+ t.mock.method(os, "availableParallelism", () => 3);
331
+ syncBuiltinESMExports();
332
+ const { makeMockGrep } = await import("./grep-rg.testing.ts");
333
+ t.mock.restoreAll();
334
+ syncBuiltinESMExports();
335
+
336
+ const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-chunk-order-"));
337
+ t.after(() => fs.rm(dir, { recursive: true, force: true }));
338
+ const early = join(dir, "a.txt");
339
+ const late = join(dir, "z.txt");
340
+ // End the later file's first regex request after its first match.
341
+ const chunkUnits = 1024 * 1024;
342
+ await fs.writeFile(early, "needle early\n");
343
+ await fs.writeFile(late, `${"needle late".padEnd(chunkUnits - 1)}\nslow tail\n`);
344
+ const backend: MockRg = {
345
+ runRgPaths: async () => assert.fail("This query uses line candidates"),
346
+ runRgLines: async (_args, _signal, _maxLines, onFile) => {
347
+ for (const file of [early, late]) if (!(await onFile(file, undefined))) break;
348
+ return { code: 0, stderr: "", stopped: false };
349
+ },
350
+ };
351
+
352
+ for (const earlyFirst of [false, true]) {
353
+ await t.test(
354
+ earlyFirst ? "earlier file commits first" : "later file times out first",
355
+ async (t) => {
356
+ type Held = { worker: Worker; finish: () => void };
357
+ const earlyRequest = Promise.withResolvers<Held>();
358
+ const lateRequest = Promise.withResolvers<Held>();
359
+ const stopped = new Map<Worker, () => void>();
360
+ const terminate = Worker.prototype.terminate;
361
+ t.mock.method(Worker.prototype, "terminate", function (this: Worker) {
362
+ stopped.get(this)?.();
363
+ return terminate.call(this);
364
+ });
365
+ t.mock.method(
366
+ Worker.prototype,
367
+ "postMessage",
368
+ function (this: Worker, input: SearchInput | LineSearchInput) {
369
+ assert.ok("source" in input);
370
+ if (input.source === "slow tail\n") {
371
+ this.emit("message", { error: REGEX_TIMEOUT });
372
+ } else {
373
+ const request = input.source.startsWith("needle early") ? earlyRequest : lateRequest;
374
+ request.resolve({
375
+ worker: this,
376
+ finish: () => this.emit("message", { result: searchText(input) }),
377
+ });
378
+ }
379
+ },
380
+ );
381
+ const controller = new AbortController();
382
+ const running = callTool(
383
+ makeMockGrep(dir, DEFAULT_CONFIG, backend),
384
+ { path: dir, pattern: "needle", literal: true, limit: 2, outputMode: "files" },
385
+ { signal: controller.signal },
386
+ );
387
+ try {
388
+ const [a, z] = await Promise.race([
389
+ Promise.all([earlyRequest.promise, lateRequest.promise]),
390
+ running.then(() => assert.fail("Search finished before both requests were held")),
391
+ ]);
392
+ const [first, second] = earlyFirst ? [a, z] : [z, a];
393
+ const firstSettled = new Promise<void>((resolve) => stopped.set(first.worker, resolve));
394
+ first.finish();
395
+ await firstSettled;
396
+ second.finish();
397
+ const result = await running;
398
+ const report = reportOf(result, "grep");
399
+ assert.equal(report?.error, REGEX_TIMEOUT.code, JSON.stringify(report));
400
+ assert.equal(result.isError, true);
401
+ } finally {
402
+ controller.abort();
403
+ await running;
404
+ }
405
+ },
406
+ );
407
+ }
408
+ });
409
+
410
+ test("regex request fails before a later NUL → skip that file and search the next candidate", async (t) => {
411
+ const { makeMockGrep } = await import("./grep-rg.testing.ts");
412
+ const dir = await fs.mkdtemp(join(os.tmpdir(), "hl-grep-late-nul-"));
413
+ t.after(() => fs.rm(dir, { recursive: true, force: true }));
414
+ const binaries = Array.from({ length: 4 }, (_, index) => join(dir, `binary-${index}.txt`));
415
+ const text = join(dir, "text.txt");
416
+ const binarySource = `${"binary request\n".repeat(100_000)}\0`;
417
+ await Promise.all(binaries.map((file) => fs.writeFile(file, binarySource)));
418
+ await fs.writeFile(text, "needle\n");
419
+ t.mock.method(
420
+ Worker.prototype,
421
+ "postMessage",
422
+ function (this: Worker, input: SearchInput | LineSearchInput) {
423
+ assert.ok("source" in input);
424
+ this.emit(
425
+ "message",
426
+ input.source.startsWith("binary request")
427
+ ? { error: REGEX_TIMEOUT }
428
+ : { result: searchText(input) },
429
+ );
430
+ },
431
+ );
432
+ const tool = makeMockGrep(dir, DEFAULT_CONFIG, {
433
+ runRgLines: async (_args, _signal, _maxLines, onFile) => {
434
+ for (const file of [...binaries, text]) if (!(await onFile(file, undefined))) break;
435
+ return { code: 0, stderr: "", stopped: false };
436
+ },
437
+ });
438
+ const result = await callTool(tool, {
439
+ path: dir,
440
+ pattern: "needle",
441
+ literal: true,
442
+ outputMode: "files",
443
+ });
444
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
445
+ assert.deepEqual(result.content[0], { type: "text", text: "text.txt" });
446
+ assert.equal(reportOf(result, "grep")?.diagnostics, undefined);
447
+ });