@criogaid/pi-hashline-edit 0.9.0 → 0.11.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 (131) hide show
  1. package/README.md +12 -12
  2. package/README.zh-CN.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +0 -6
  4. package/package.json +1 -1
  5. package/src/core/AGENTS.md +4 -5
  6. package/src/core/apply.test.ts +96 -271
  7. package/src/core/apply.ts +62 -169
  8. package/src/core/case-fold.ts +8 -67
  9. package/src/core/character-set.test.ts +2 -3
  10. package/src/core/character-set.ts +5 -5
  11. package/src/core/errors.test.ts +23 -7
  12. package/src/core/errors.ts +32 -5
  13. package/src/core/hash.test.ts +8 -16
  14. package/src/core/hash.ts +3 -23
  15. package/src/core/lines.ts +2 -4
  16. package/src/core/ranges.test.ts +2 -1
  17. package/src/core/ranges.ts +1 -1
  18. package/src/core/regex.ts +3 -4
  19. package/src/core/replace.test.ts +47 -1
  20. package/src/core/replace.ts +19 -13
  21. package/src/core/search-analysis.test.ts +24 -27
  22. package/src/core/search-analysis.ts +34 -65
  23. package/src/core/search-matrix.testing.ts +0 -2
  24. package/src/core/search.ts +1 -1
  25. package/src/core/text.test.ts +5 -5
  26. package/src/core/text.ts +5 -12
  27. package/src/core/types.ts +8 -44
  28. package/src/index.ts +8 -8
  29. package/src/integration/config-registration.test.ts +8 -10
  30. package/src/integration/fusion-dispatch.test.ts +4 -7
  31. package/src/integration/grep-errors.test.ts +3 -3
  32. package/src/integration/grep-flags.test.ts +5 -19
  33. package/src/integration/grep-js-completeness.test.ts +45 -18
  34. package/src/integration/grep-line-candidates.test.ts +7 -10
  35. package/src/integration/grep-matrix.test.ts +6 -9
  36. package/src/integration/grep-order.test.ts +4 -4
  37. package/src/integration/grep-path-matrix.test.ts +10 -9
  38. package/src/integration/grep-prefilter-coverage.test.ts +5 -8
  39. package/src/integration/grep-process-limits.test.ts +76 -0
  40. package/src/integration/grep-regex.test.ts +10 -10
  41. package/src/integration/grep-rg.test.ts +166 -66
  42. package/src/integration/grep-scan-budget.test.ts +9 -9
  43. package/src/integration/grep-translation.test.ts +18 -32
  44. package/src/integration/large-text.test.ts +6 -52
  45. package/src/integration/model-budget-lifecycle.test.ts +10 -9
  46. package/src/integration/mutation-file-types.testing.ts +4 -4
  47. package/src/integration/npm-package.testing.ts +3 -3
  48. package/src/integration/publication-read-changes.test.ts +161 -83
  49. package/src/integration/read-changes.test.ts +4 -4
  50. package/src/integration/replace-worker-boundary.test.ts +22 -12
  51. package/src/integration/report-replay.test.ts +23 -26
  52. package/src/integration/utf8-errors.test.ts +4 -4
  53. package/src/pi/AGENTS.md +18 -17
  54. package/src/pi/action-fusion.test.ts +241 -353
  55. package/src/pi/action-fusion.testing.ts +38 -0
  56. package/src/pi/action-fusion.ts +150 -125
  57. package/src/pi/anchor-format.test.ts +9 -9
  58. package/src/pi/anchor-format.ts +6 -8
  59. package/src/pi/argument-diagnostics.ts +25 -28
  60. package/src/pi/argument-error.ts +2 -1
  61. package/src/pi/argument-format.test.ts +19 -18
  62. package/src/pi/argument-validation.test.ts +334 -283
  63. package/src/pi/argument-validation.ts +5 -8
  64. package/src/pi/budgets.ts +6 -8
  65. package/src/pi/codemode.test.ts +7 -2
  66. package/src/pi/config.test.ts +7 -3
  67. package/src/pi/config.ts +12 -9
  68. package/src/pi/diagnostic-buffer.test.ts +34 -13
  69. package/src/pi/diagnostic-buffer.ts +1 -2
  70. package/src/pi/directory-sync.test.ts +0 -1
  71. package/src/pi/edit-tool.ts +86 -211
  72. package/src/pi/error-text.ts +10 -9
  73. package/src/pi/execute.test.ts +249 -345
  74. package/src/pi/failure-context.test.ts +146 -127
  75. package/src/pi/failure-context.ts +45 -94
  76. package/src/pi/failure-path.test.ts +182 -155
  77. package/src/pi/file-commit.test.ts +156 -71
  78. package/src/pi/file-commit.ts +126 -146
  79. package/src/pi/file-snapshot.test.ts +3 -5
  80. package/src/pi/fusion-card.test.ts +26 -22
  81. package/src/pi/fusion-card.ts +16 -24
  82. package/src/pi/grep-candidates.test.ts +19 -120
  83. package/src/pi/grep-candidates.ts +25 -76
  84. package/src/pi/grep-matrix.test.ts +5 -5
  85. package/src/pi/grep-order.test.ts +16 -15
  86. package/src/pi/grep-output.ts +94 -107
  87. package/src/pi/grep-render.ts +1 -1
  88. package/src/pi/grep-reread.ts +97 -0
  89. package/src/pi/grep-rg.testing.ts +70 -0
  90. package/src/pi/grep-scope.ts +41 -43
  91. package/src/pi/grep-search.ts +27 -39
  92. package/src/pi/grep-tool.ts +63 -106
  93. package/src/pi/grep.test.ts +177 -156
  94. package/src/pi/model-budgets.test.ts +27 -24
  95. package/src/pi/model-budgets.ts +6 -38
  96. package/src/pi/mutation-outcome.testing.ts +0 -1
  97. package/src/pi/mutation-result.test.ts +44 -35
  98. package/src/pi/mutation-result.ts +52 -21
  99. package/src/pi/mutation-runner.ts +134 -74
  100. package/src/pi/output-budgets.test.ts +86 -42
  101. package/src/pi/path.ts +1 -1
  102. package/src/pi/pi.test.ts +18 -13
  103. package/src/pi/read-tool.ts +18 -23
  104. package/src/pi/read.test.ts +22 -41
  105. package/src/pi/regex-worker-contract.ts +3 -13
  106. package/src/pi/regex-worker.ts +1 -10
  107. package/src/pi/registration.test.ts +85 -51
  108. package/src/pi/render.test.ts +88 -59
  109. package/src/pi/render.ts +64 -65
  110. package/src/pi/replace-regex.ts +14 -2
  111. package/src/pi/replace-tool.ts +22 -94
  112. package/src/pi/replace-worker.ts +1 -1
  113. package/src/pi/replace.test.ts +53 -38
  114. package/src/pi/report-cause.ts +3 -8
  115. package/src/pi/report-failure.testing.ts +10 -3
  116. package/src/pi/report-schema.ts +251 -148
  117. package/src/pi/report.test.ts +215 -67
  118. package/src/pi/report.ts +50 -98
  119. package/src/pi/result-safety.test.ts +241 -247
  120. package/src/pi/rg-process.test.ts +77 -63
  121. package/src/pi/rg-process.ts +53 -75
  122. package/src/pi/rg-regex.ts +40 -400
  123. package/src/pi/schema.ts +35 -0
  124. package/src/pi/text-stream.test.ts +0 -21
  125. package/src/pi/text-stream.ts +14 -21
  126. package/src/pi/tool-factories.testing.ts +59 -0
  127. package/src/pi/write-tool.ts +36 -71
  128. package/src/pi/write.test.ts +31 -34
  129. package/src/testing/regex-translation-corpus.ts +12 -12
  130. package/src/testing/run-tests.ts +1 -1
  131. package/src/pi/replace-worker-contract.ts +0 -10
package/src/core/types.ts CHANGED
@@ -11,7 +11,7 @@ export interface Anchor {
11
11
  }
12
12
 
13
13
  /** Public anchor field names shared by preparation, verification, and recovery. */
14
- export const EDIT_ANCHOR_FIELDS = ["anchor", "end", "before", "after"] as const;
14
+ export const EDIT_ANCHOR_FIELDS = ["anchor", "end"] as const;
15
15
  type AnchorField = (typeof EDIT_ANCHOR_FIELDS)[number];
16
16
 
17
17
  /**
@@ -27,28 +27,20 @@ export type Edit =
27
27
  readonly body: string[];
28
28
  }
29
29
  | { readonly op: "delete"; readonly anchor: Anchor; readonly end?: Anchor }
30
- | ({ readonly op: "copy" | "move"; readonly anchor: Anchor; readonly end?: Anchor } & (
31
- | { readonly before: Anchor; readonly after?: never }
32
- | { readonly after: Anchor; readonly before?: never }
33
- ))
34
30
  | { readonly op: "insert_after"; readonly anchor: Anchor; readonly body: string[] }
35
31
  | { readonly op: "insert_before"; readonly anchor: Anchor; readonly body: string[] }
36
32
  | { readonly op: "append"; readonly body: string[] }
37
33
  | { readonly op: "prepend"; readonly body: string[] };
38
34
 
39
- export type LineEnding = "lf" | "crlf";
40
-
41
35
  /**
42
36
  * Outcome of shifted-anchor recovery. Search ±radius first; only if there are
43
37
  * no candidates, search the rest of the file. Radius 0 disables recovery.
44
38
  * Candidate checksums hold the ORIGINAL line number fixed. Because checksums
45
39
  * can collide, a match is a candidate rather than proof of identity. Returned
46
40
  * anchors use each candidate's actual line number and freshly computed hash.
47
- * Candidate `scope` records the completed search: local results leave matches
48
- * outside the window unchecked; full-file results cover the entire snapshot.
49
41
  *
50
- * - `found` — exactly one line matches in the selected search scope; the caller
51
- * checks its content before resending with the provided anchor.
42
+ * - `found` — exactly one line matches; the caller checks its content before
43
+ * resending with the provided anchor.
52
44
  * - `ambiguous` — several lines match; the caller inspects the candidates
53
45
  * and chooses the intended target.
54
46
  * - `none` — no candidate found, or recovery disabled; the caller checks the
@@ -57,13 +49,11 @@ export type LineEnding = "lf" | "crlf";
57
49
  export type AnchorRecovery =
58
50
  | {
59
51
  readonly kind: "found";
60
- readonly scope: "local" | "full-file";
61
52
  readonly newLine: number;
62
53
  readonly newHash: string;
63
54
  }
64
55
  | {
65
56
  readonly kind: "ambiguous";
66
- readonly scope: "local" | "full-file";
67
57
  readonly candidates: ReadonlyArray<{ readonly line: number; readonly hash: string }>;
68
58
  }
69
59
  | { readonly kind: "none" };
@@ -71,10 +61,8 @@ export type AnchorRecovery =
71
61
  /**
72
62
  * A single anchor that failed verification, with its recovery attempt.
73
63
  *
74
- * `opIndex` is the 0-based position in the input `edits[]`; `which` names the
75
- * op's source/insertion anchor, range end, or before/after destination; `op` is the op kind.
76
- * `current` is the cited line's live content (null if the line number is
77
- * out of range) — surfaced when recovery is `none` so the model can self-diagnose.
64
+ * `opIndex` is the 0-based position in the input `steps[]`; `which` names the
65
+ * op's target or insertion anchor, or its range end; `op` is the op kind.
78
66
  */
79
67
  export interface AnchorFailure {
80
68
  readonly opIndex: number;
@@ -82,40 +70,16 @@ export interface AnchorFailure {
82
70
  readonly op: Edit["op"];
83
71
  readonly cited: Anchor;
84
72
  readonly recovery: AnchorRecovery;
85
- readonly current: { readonly content: string } | null;
86
- }
87
-
88
- /** Record for one supplied anchor in the immutable apply snapshot. */
89
- export interface AnchorCheck {
90
- readonly opIndex: number;
91
- readonly which: AnchorField;
92
- readonly status: "matched" | "mismatched";
93
73
  }
94
74
 
95
- /** Batch-level failure. Anchor checks describe only checksum validation in this snapshot. */
96
- export type ApplyFailure =
97
- | {
98
- readonly kind: "anchor";
99
- readonly failures: readonly AnchorFailure[];
100
- readonly checks: readonly AnchorCheck[];
101
- }
102
- | {
103
- readonly kind: "range";
104
- /** INVALID_RANGE for a reversed range or a move into itself; OVERLAPPING_EDITS for overlap or a repeated insertion position. */
105
- readonly code: "INVALID_RANGE" | "OVERLAPPING_EDITS";
106
- readonly message: string;
107
- readonly checks: readonly AnchorCheck[];
108
- };
109
-
110
75
  /**
111
76
  * Apply result. Byte-identical output is a success; the commit layer detects the no-op.
112
- * On failure, `failure` is either the collected set of anchor failures
113
- * (each with recovery) or a range error, plus per-input anchor checks.
114
- * Nothing is written on failure.
77
+ * On failure, `failures` is the collected set of anchor failures, each with recovery;
78
+ * the tool layer bounds and formats them. Nothing is written on failure.
115
79
  */
116
80
  export type ApplyResult =
117
81
  | {
118
82
  readonly ok: true;
119
83
  readonly text: string;
120
84
  }
121
- | { readonly ok: false; readonly failure: ApplyFailure };
85
+ | { readonly ok: false; readonly failures: readonly AnchorFailure[] };
package/src/index.ts CHANGED
@@ -35,9 +35,7 @@ export default function (pi: ExtensionAPI) {
35
35
  const budgets = registerModelBudgets(pi);
36
36
  // Saved then_run cards render even when Action Fusion is now off.
37
37
  const reportProgress = registerFusionCards(pi);
38
- const fusion = config.actionFusion
39
- ? createActionFusionExecutor(undefined, reportProgress)
40
- : undefined;
38
+ const fusion = config.actionFusion ? createActionFusionExecutor(reportProgress) : undefined;
41
39
  // Every tool returns a report; Pi prints this shared guideline once.
42
40
  const register = <TParams extends TSchema, TDetails, TState>(
43
41
  tool: ToolDefinition<TParams, TDetails, TState>,
@@ -49,11 +47,13 @@ export default function (pi: ExtensionAPI) {
49
47
  const registerMutation = <TParams extends TSchema, TDetails>(
50
48
  tool: ToolDefinition<TParams, TDetails>,
51
49
  ) => register(fusion ? withMutationStatus(tool) : tool);
52
- registerMutation(makeWriteOverride(cwd, fusion, budgets));
53
- registerMutation(makeEditOverride(cwd, config, fusion, budgets));
54
- registerMutation(makeReplaceTool(cwd, config, fusion, budgets));
50
+ const env = { cwd, config, budgets };
51
+ const mutationEnv = { ...env, fusion };
52
+ registerMutation(makeWriteOverride(mutationEnv));
53
+ registerMutation(makeEditOverride(mutationEnv));
54
+ registerMutation(makeReplaceTool(mutationEnv));
55
55
 
56
- register(makeReadOverride(cwd, config, budgets));
57
- register(makeGrepOverride(cwd, config, budgets));
56
+ register(makeReadOverride(env));
57
+ register(makeGrepOverride(env));
58
58
  }
59
59
  }
@@ -7,7 +7,8 @@ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-age
7
7
  import registerHashline from "../index.ts";
8
8
  import { computeLineHash } from "../core/hash.ts";
9
9
  import { callTool } from "../pi/tool-call.testing.ts";
10
- import { DEFAULT_CONFIG, type HashlineEditConfig } from "../pi/config.ts";
10
+ import { type HashlineEditConfig } from "../pi/config.ts";
11
+ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
11
12
  import { reportOf } from "../pi/report.ts";
12
13
  import { formatByteSize } from "../pi/budgets.ts";
13
14
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
@@ -73,11 +74,11 @@ test("registered tools retain their configuration when another tool set is regis
73
74
  grep: { path, pattern: "before", literal: true },
74
75
  edit: {
75
76
  path,
76
- edits: [
77
+ steps: [
77
78
  {
78
79
  action: "replace",
79
80
  anchor: `1#${computeLineHash(1, "before", hashLen)}`,
80
- body: ["after"],
81
+ lines: ["after"],
81
82
  },
82
83
  ],
83
84
  },
@@ -104,7 +105,7 @@ test("registered tools retain their configuration when another tool set is regis
104
105
  await expectToolFailure(
105
106
  callTool(tool, {
106
107
  path,
107
- edits: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
108
+ steps: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
108
109
  }),
109
110
  "ANCHOR_MISMATCH",
110
111
  (report) => {
@@ -134,7 +135,7 @@ test("registered tools retain their configuration when another tool set is regis
134
135
  `${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`,
135
136
  ),
136
137
  );
137
- assert.equal(reportOf(result, "read")?.pagination?.nextOffset, read.defaultLimit + 1);
138
+ assert.equal(reportOf(result, "read")?.nextOffset, read.defaultLimit + 1);
138
139
 
139
140
  const wide = "界".repeat(500);
140
141
  await writeFile(join(directory, path), `${wide}\n`);
@@ -142,17 +143,14 @@ test("registered tools retain their configuration when another tool set is regis
142
143
  assert.equal(bounded.content[0].type, "text");
143
144
  if (read.maxKiB === 1) {
144
145
  const maxBytes = read.maxKiB * 1024;
145
- assert.deepEqual(reportOf(bounded, "read")?.lineTooLong, {
146
- line: 1,
147
- limit: formatByteSize(maxBytes),
148
- });
146
+ assert.equal(reportOf(bounded, "read")?.lineTooLong, formatByteSize(maxBytes));
149
147
  assert.doesNotMatch(bounded.content[0].text, /^\d+#/m);
150
148
  } else {
151
149
  assert.ok(
152
150
  bounded.content[0].text.includes(`1#${computeLineHash(1, wide, hashLen)}│${wide}`),
153
151
  );
154
152
  assert.equal(reportOf(bounded, "read")?.outputLimit, undefined);
155
- assert.equal(reportOf(bounded, "read")?.pagination, undefined);
153
+ assert.equal(reportOf(bounded, "read")?.nextOffset, undefined);
156
154
  }
157
155
  },
158
156
  );
@@ -6,12 +6,9 @@ import { Type } from "typebox";
6
6
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
7
7
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import { openTestSession, responseStream } from "../testing/session.testing.ts";
9
- import {
10
- createActionFusionExecutor,
11
- type ActionFusionProgress,
12
- type ThenRunInput,
13
- } from "../pi/action-fusion.ts";
14
- import { makeWriteOverride } from "../pi/write-tool.ts";
9
+ import type { ActionFusionProgress } from "../pi/report-schema.ts";
10
+ import { createActionFusionExecutor, type ThenRunInput } from "../pi/action-fusion.ts";
11
+ import { makeWriteOverride } from "../pi/tool-factories.testing.ts";
15
12
  import { commandText } from "../pi/mutation-result.ts";
16
13
  import { reportOf } from "../pi/report.ts";
17
14
  import type { CommandStatus } from "../pi/report-schema.ts";
@@ -34,7 +31,7 @@ async function openSession(
34
31
  pi.registerTool(
35
32
  makeWriteOverride(
36
33
  cwd,
37
- createActionFusionExecutor(undefined, (event) => {
34
+ createActionFusionExecutor((event) => {
38
35
  progress.push(event);
39
36
  onProgress?.(event);
40
37
  }),
@@ -3,8 +3,8 @@ import { chmod, mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/pro
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
6
- import { DEFAULT_CONFIG } from "../pi/config.ts";
7
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
6
+ const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
7
+
8
8
  import { callTool } from "../pi/tool-call.testing.ts";
9
9
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
10
10
 
@@ -36,7 +36,7 @@ for (const condition of ["permission denied", "symlink loop"] as const) {
36
36
  code = "ELOOP";
37
37
  }
38
38
  await assert.rejects(stat(path), { code });
39
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
39
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
40
40
  await expectToolFailure(
41
41
  callTool(tool, { path, pattern: "needle", literal: true, ignoreCase: false }),
42
42
  "FILESYSTEM_ERROR",
@@ -3,12 +3,11 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
6
- import { DEFAULT_CONFIG } from "../pi/config.ts";
7
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
6
+ const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
7
+
8
8
  import { reportOf } from "../pi/report.ts";
9
- import { grepCounts } from "../pi/grep-output.testing.ts";
9
+ const { grepCounts } = await import("../pi/grep-output.testing.ts");
10
10
  import { callTool } from "../pi/tool-call.testing.ts";
11
- import { rejectsArgument } from "../pi/argument-error.testing.ts";
12
11
 
13
12
  const cases = [
14
13
  {
@@ -217,7 +216,7 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
217
216
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-flags-"));
218
217
  t.after(() => rm(directory, { recursive: true, force: true }));
219
218
  const path = join(directory, "input.txt");
220
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
219
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
221
220
  for (const scenario of cases) {
222
221
  await t.test(scenario.name, async () => {
223
222
  await writeFile(path, scenario.source);
@@ -239,19 +238,6 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
239
238
  }
240
239
  });
241
240
 
242
- test("grep flags: invalid Unicode syntax rejects the pattern argument", async () => {
243
- const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
244
- await assert.rejects(
245
- callTool(tool, {
246
- path: "missing.txt",
247
- pattern: "\\p{NotAProperty}",
248
- literal: false,
249
- flags: "u",
250
- }),
251
- rejectsArgument("pattern"),
252
- );
253
- });
254
-
255
241
  test("grep flags: valid V8 patterns exceeding translator parser depth still execute", async (t) => {
256
242
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-parser-depth-"));
257
243
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -259,7 +245,7 @@ test("grep flags: valid V8 patterns exceeding translator parser depth still exec
259
245
  await writeFile(path, "A\na\n");
260
246
  const pattern = `${"(?:".repeat(3_000)}A${")".repeat(3_000)}`;
261
247
  assert.equal(new RegExp(pattern).test("A"), true);
262
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
248
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
263
249
  for (const flags of [undefined, "m"]) {
264
250
  const result = await callTool(tool, {
265
251
  path,
@@ -1,13 +1,14 @@
1
+ import { makeMockGrep } from "../pi/grep-rg.testing.ts";
1
2
  import assert from "node:assert/strict";
2
3
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { test } from "node:test";
6
- import { DEFAULT_CONFIG } from "../pi/config.ts";
7
- import { MAX_MULTILINE_SEARCH_BYTES } from "../pi/grep-search.ts";
8
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
7
+ const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
8
+ const MAX_MULTILINE_SEARCH_BYTES = 64 * 1024 * 1024;
9
+
9
10
  import { reportOf } from "../pi/report.ts";
10
- import { grepCounts } from "../pi/grep-output.testing.ts";
11
+ const { grepCounts } = await import("../pi/grep-output.testing.ts");
11
12
  import { COMMON_RG_ARGS, runRgLines, runRgPaths } from "../pi/rg-process.ts";
12
13
  import { searchText } from "../core/search.ts";
13
14
  import { callTool } from "../pi/tool-call.testing.ts";
@@ -28,7 +29,7 @@ test("JS grep: rg discovery retains ignore, hidden, glob, and binary rules", asy
28
29
  await writeFile(join(directory, name), "😀\n");
29
30
  await writeFile(join(directory, ".ignore"), "ignored.txt\n");
30
31
  await writeFile(join(directory, "binary.txt"), "😀\n\0");
31
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
32
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
32
33
  const result = await callTool(tool, {
33
34
  ...query,
34
35
  path: directory,
@@ -55,7 +56,7 @@ test("JS grep: physical rows, context, and limits agree across output modes", as
55
56
  t.after(() => rm(directory, { recursive: true, force: true }));
56
57
  const path = join(directory, "input.txt");
57
58
  await writeFile(path, "head\r\n😀\r\nab\ntail\n");
58
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
59
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
59
60
  for (const outputMode of ["content", "files", "count"] as const) {
60
61
  const result = await callTool(tool, { ...query, path, outputMode, limit: 1, context: 1 });
61
62
  assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
@@ -79,7 +80,7 @@ test("JS grep: malformed UTF-8 matches the preview text without editable anchors
79
80
  t.after(() => rm(directory, { recursive: true, force: true }));
80
81
  const path = join(directory, "invalid.txt");
81
82
  await writeFile(path, Buffer.from([0x61, 0xff, 0x62, 0x0a]));
82
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
83
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
83
84
  const result = await callTool(tool, { path, pattern: "a.b", literal: false });
84
85
  assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
85
86
  assert.equal(grepCounts(result).matches, 1);
@@ -97,7 +98,7 @@ test("oversized line or multiline input → explicit incomplete-search diagnosti
97
98
  const good = join(directory, "good.txt");
98
99
  const oversized = Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1, 0x61);
99
100
  await writeFile(good, "a\n");
100
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
101
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
101
102
  for (const finalNewline of [false, true]) {
102
103
  await writeFile(path, finalNewline ? Buffer.concat([oversized, Buffer.from("\n")]) : oversized);
103
104
  for (const multiline of [false, true]) {
@@ -147,36 +148,34 @@ test("real rg candidates → include every JS row and preserve confirmed output
147
148
  ] as const) {
148
149
  await t.test(`${pattern} /${flags} → identical confirmed results`, async () => {
149
150
  const candidates = new Map<string, readonly number[] | undefined>();
150
- const filtered = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
151
- runRgPaths(rg, args, signal, onPath) {
152
- return runRgPaths(rg, args, signal, (path) => {
151
+ const filtered = makeMockGrep(directory, DEFAULT_CONFIG, {
152
+ runRgPaths(args, signal, onPath) {
153
+ return runRgPaths(args, signal, (path) => {
153
154
  candidates.set(path, undefined);
154
155
  return onPath(path);
155
156
  });
156
157
  },
157
- runRgLines(rg, args, signal, maxLines, onFile) {
158
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
158
+ runRgLines(args, signal, maxLines, onFile) {
159
+ return runRgLines(args, signal, maxLines, (path, lines) => {
159
160
  candidates.set(path, lines);
160
161
  return onFile(path, lines);
161
162
  });
162
163
  },
163
164
  });
164
- const full = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
165
- runRgPaths(rg, args, signal, onPath) {
165
+ const full = makeMockGrep(directory, DEFAULT_CONFIG, {
166
+ runRgPaths(args, signal, onPath) {
166
167
  const scopeStart = args.indexOf("--null");
167
168
  assert.ok(scopeStart >= 0);
168
169
  return runRgPaths(
169
- rg,
170
170
  [...COMMON_RG_ARGS, "--files", ...args.slice(scopeStart)],
171
171
  signal,
172
172
  onPath,
173
173
  );
174
174
  },
175
- runRgLines(rg, args, signal, _maxLines, onFile) {
175
+ runRgLines(args, signal, _maxLines, onFile) {
176
176
  const scopeStart = args.indexOf("--hidden");
177
177
  assert.ok(scopeStart >= 0);
178
178
  return runRgPaths(
179
- rg,
180
179
  [...COMMON_RG_ARGS, "--files", "--null", ...args.slice(scopeStart)],
181
180
  signal,
182
181
  (path) => onFile(path, undefined),
@@ -216,3 +215,31 @@ test("real rg candidates → include every JS row and preserve confirmed output
216
215
  });
217
216
  }
218
217
  });
218
+
219
+ test("NUL past a search limit → skips oversized line and multiline files without diagnostics", async (t) => {
220
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-nul-limit-"));
221
+ t.after(() => rm(directory, { recursive: true, force: true }));
222
+ const path = join(directory, "large-nul.txt");
223
+ // Place NUL beyond the chunk that first exceeds the search limit.
224
+ const bytes = Buffer.alloc(MAX_MULTILINE_SEARCH_BYTES + 1024 * 1024, 0x61);
225
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
226
+ for (const hasNul of [true, false]) {
227
+ bytes[bytes.length - 1] = hasNul ? 0 : 0x61;
228
+ await writeFile(path, bytes);
229
+ for (const multiline of [false, true]) {
230
+ await t.test(`multiline=${multiline}, NUL=${hasNul}`, async () => {
231
+ const result = await callTool(tool, { path, pattern: "a", literal: true, multiline });
232
+ const report = reportOf(result, "grep");
233
+ if (hasNul) {
234
+ assert.equal(result.isError, undefined, JSON.stringify(report));
235
+ assert.deepEqual(grepCounts(result), { matches: 0, files: 0 });
236
+ assert.equal(report?.diagnostics, undefined);
237
+ } else {
238
+ assert.equal(result.isError, true);
239
+ assert.equal(report?.error, "SEARCH_INCOMPLETE");
240
+ assert.match(report?.diagnostics ?? "", multiline ? /MiB/ : /UTF-16 code units/);
241
+ }
242
+ });
243
+ }
244
+ }
245
+ });
@@ -1,12 +1,12 @@
1
+ import { searchWithMockRg } from "../pi/grep-rg.testing.ts";
1
2
  import assert from "node:assert/strict";
2
3
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { test } from "node:test";
6
- import { rgPath } from "@vscode/ripgrep";
7
7
  import { acceptsNative } from "../core/search-matrix.testing.ts";
8
8
  import { searchText, type GrepQuery } from "../core/search.ts";
9
- import { searchFiles, type GrepFileMatch } from "../pi/grep-search.ts";
9
+ import type { GrepFileMatch } from "../pi/grep-search.ts";
10
10
  import { lineCandidatePatterns } from "../pi/rg-regex.ts";
11
11
  import { runRgLines } from "../pi/rg-process.ts";
12
12
  import { REGEX_TRANSLATION_CORPUS } from "../testing/regex-translation-corpus.ts";
@@ -183,30 +183,27 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
183
183
  const translated = lineCandidatePatterns(query);
184
184
  assert.ok(translated, JSON.stringify(query));
185
185
  const candidates = new Map<string, readonly number[] | undefined>();
186
- const warnings: string[] = [];
187
- const actual = await searchFiles({
186
+ const actual = await searchWithMockRg({
188
187
  backend: {
189
188
  async runRgPaths() {
190
189
  assert.fail(`unexpected file fallback: ${JSON.stringify(query)}`);
191
190
  },
192
- runRgLines: (rg, args, signal, maxLines, onFile) => {
191
+ runRgLines: (args, signal, maxLines, onFile) => {
193
192
  assert.equal(maxLines, candidateLineLimit);
194
193
  const emitted = args.flatMap((arg, index) => (arg === "-e" ? [args[index + 1]] : []));
195
194
  assert.deepEqual(emitted, translated);
196
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
195
+ return runRgLines(args, signal, maxLines, (path, lines) => {
197
196
  candidates.set(path, lines);
198
197
  listedRows += lines?.length ?? 0;
199
198
  return onFile(path, lines);
200
199
  });
201
200
  },
202
201
  },
203
- rgPath,
204
- scope: { globs: [], noIgnore: false, follow: false, searchPaths: [directory] },
202
+ scope: { globs: [], searchPaths: [directory] },
205
203
  query,
206
204
  limit,
207
205
  timeoutMs: processTimeoutMs,
208
206
  signal: AbortSignal.timeout(processTimeoutMs),
209
- warnings,
210
207
  });
211
208
  const expected = inputs.map(({ filePath, bytes }) => {
212
209
  const result = searchText({ source: bytes.toString("utf8"), query, limit });
@@ -218,7 +215,7 @@ test("Cartesian adversarial bytes × syntax × flags × assertion positions →
218
215
  }
219
216
  return { filePath, rows: result.lines };
220
217
  });
221
- assert.deepEqual(warnings, [], JSON.stringify(query));
218
+ assert.deepEqual(actual.warnings, [], JSON.stringify(query));
222
219
  assert.deepEqual(sortedRows(actual.files), sortedRows(expected), JSON.stringify(query));
223
220
  assert.equal(actual.matchLimitReached, false);
224
221
  nativeRows += expected.reduce((sum, file) => sum + file.rows.length, 0);
@@ -3,7 +3,6 @@ import { test, type TestContext } from "node:test";
3
3
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { basename, join } from "node:path";
6
- import { rgPath } from "@vscode/ripgrep";
7
6
  import { extractPrefilter, type Prefilter } from "../core/search-analysis.ts";
8
7
  import { searchText, type GrepQuery } from "../core/search.ts";
9
8
  import {
@@ -13,10 +12,11 @@ import {
13
12
  MATRIX_INPUTS,
14
13
  } from "../core/search-matrix.testing.ts";
15
14
  import { runRgPaths } from "../pi/rg-process.ts";
16
- import { runCandidatePaths } from "../pi/grep-candidates.ts";
15
+ import { fileCandidateArgs } from "../pi/grep-rg.testing.ts";
17
16
 
18
17
  interface CandidateCase {
19
18
  readonly prefilter: Prefilter;
19
+ readonly query: GrepQuery;
20
20
  readonly required: Map<string, GrepQuery>;
21
21
  }
22
22
 
@@ -44,7 +44,7 @@ async function checkCandidates(t: TestContext, queries: Iterable<{ readonly quer
44
44
  const key = JSON.stringify(prefilter);
45
45
  let group = groups.get(key);
46
46
  if (!group) {
47
- group = { prefilter, required: new Map() };
47
+ group = { prefilter, query, required: new Map() };
48
48
  groups.set(key, group);
49
49
  }
50
50
  for (const input of inputs) {
@@ -64,13 +64,10 @@ async function checkCandidates(t: TestContext, queries: Iterable<{ readonly quer
64
64
  const workers = await Promise.allSettled(
65
65
  Array.from({ length: concurrency }, async () => {
66
66
  while (next < cases.length) {
67
- const { prefilter, required } = cases[next++];
67
+ const { prefilter, query, required } = cases[next++];
68
68
  const actual = new Set<string>();
69
- const result = await runCandidatePaths(
70
- runRgPaths,
71
- rgPath,
72
- prefilter,
73
- ["--null", "--", directory],
69
+ const result = await runRgPaths(
70
+ [...(await fileCandidateArgs(query)), "--null", "--", directory],
74
71
  AbortSignal.timeout(processTimeoutMs),
75
72
  (path) => {
76
73
  actual.add(basename(path));
@@ -4,9 +4,9 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
6
6
  import { computeLineHash } from "../core/hash.ts";
7
- import { DEFAULT_CONFIG } from "../pi/config.ts";
8
- import { parseFileHeader } from "../pi/grep-output.ts";
9
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
7
+ const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
8
+ const { parseFileHeader } = await import("../pi/grep-output.ts");
9
+
10
10
  import { reportOf } from "../pi/report.ts";
11
11
  import { callTool } from "../pi/tool-call.testing.ts";
12
12
 
@@ -20,7 +20,7 @@ test("repeated real-rg query with increasing limits → stable traversal order a
20
20
  for (const name of names) {
21
21
  await writeFile(join(dir, name), `${sourceLine(name, 1)}\n${sourceLine(name, 2)}\n`);
22
22
  }
23
- const tool = makeGrepOverrideWithBackend(dir, DEFAULT_CONFIG, {});
23
+ const tool = makeGrepOverride(dir, DEFAULT_CONFIG);
24
24
  for (const [roots, expectedNames] of [
25
25
  [["."], ["a.txt", "sub/b.txt", "sub.txt", "z.txt"]],
26
26
  [
@@ -1,13 +1,14 @@
1
+ import { makeMockGrep } from "../pi/grep-rg.testing.ts";
1
2
  import assert from "node:assert/strict";
2
3
  import { test } from "node:test";
3
4
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
4
5
  import { tmpdir } from "node:os";
5
6
  import { basename, join } from "node:path";
6
7
  import { DEFAULT_GREP_FLAGS, searchText } from "../core/search.ts";
7
- import { DEFAULT_CONFIG } from "../pi/config.ts";
8
- import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
+ const { DEFAULT_CONFIG } = await import("../pi/tool-factories.testing.ts");
9
+
9
10
  import { reportOf } from "../pi/report.ts";
10
- import { grepCounts } from "../pi/grep-output.testing.ts";
11
+ const { grepCounts } = await import("../pi/grep-output.testing.ts");
11
12
  import { runRgLines, runRgPaths } from "../pi/rg-process.ts";
12
13
  import { callTool } from "../pi/tool-call.testing.ts";
13
14
  import { acceptsNative } from "../core/search-matrix.testing.ts";
@@ -28,15 +29,15 @@ test("Cartesian literal mode × flags × case override × line mode × bytes →
28
29
  for (const input of inputs) await writeFile(join(directory, input.name), input.bytes);
29
30
  const limit = inputs.reduce((sum, input) => sum + input.bytes.length, 0);
30
31
  const candidates = new Map<string, readonly number[] | undefined>();
31
- const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {
32
- runRgPaths(rg, args, signal, onPath) {
33
- return runRgPaths(rg, args, signal, (path) => {
32
+ const tool = makeMockGrep(directory, DEFAULT_CONFIG, {
33
+ runRgPaths(args, signal, onPath) {
34
+ return runRgPaths(args, signal, (path) => {
34
35
  candidates.set(basename(path), undefined);
35
36
  return onPath(path);
36
37
  });
37
38
  },
38
- runRgLines(rg, args, signal, maxLines, onFile) {
39
- return runRgLines(rg, args, signal, maxLines, (path, lines) => {
39
+ runRgLines(args, signal, maxLines, onFile) {
40
+ return runRgLines(args, signal, maxLines, (path, lines) => {
40
41
  candidates.set(basename(path), lines);
41
42
  return onFile(path, lines);
42
43
  });
@@ -68,7 +69,7 @@ test("Cartesian literal mode × flags × case override × line mode × bytes →
68
69
  const context = JSON.stringify(params);
69
70
  candidates.clear();
70
71
  if (!literal && !acceptsNative(query)) {
71
- await assert.rejects(callTool(tool, params), rejectsArgument("pattern"), context);
72
+ await assert.rejects(callTool(tool, params), rejectsArgument("pattern[0]"), context);
72
73
  assert.equal(candidates.size, 0, context);
73
74
  rejected++;
74
75
  continue;