@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
@@ -1,15 +1,15 @@
1
1
  /** JavaScript matching on the LF view, returning bounded physical rows rather than match objects. */
2
- import { countLines, normalizeLineEndings } from "./lines.ts";
2
+ import { normalizeLineEndings } from "./lines.ts";
3
3
  import { buildRegex } from "./regex.ts";
4
4
  import type { SearchResult } from "./search-schema.ts";
5
5
 
6
- /** Explicit flags replace this default. */
7
- export const DEFAULT_GREP_FLAGS = "m";
6
+ /** Every grep regex uses these flags; ignoreCase adds i. */
7
+ export const GREP_FLAGS = "m";
8
8
 
9
9
  export interface GrepQuery {
10
10
  readonly patterns: readonly string[];
11
11
  readonly literal: boolean;
12
- readonly flags: string;
12
+ readonly ignoreCase: boolean;
13
13
  readonly multiline: boolean;
14
14
  }
15
15
  export interface SearchInput {
@@ -74,8 +74,10 @@ function multilineRows(source: string, regex: RegExp, limit: number): Rows {
74
74
  return rows;
75
75
  }
76
76
 
77
- const queryRegexes = (query: GrepQuery) =>
78
- query.patterns.map((pattern) => buildRegex(pattern, query.literal, query.flags));
77
+ const queryRegexes = ({ patterns, literal, ignoreCase }: GrepQuery) =>
78
+ patterns.map((pattern) =>
79
+ buildRegex(pattern, literal, ignoreCase ? `${GREP_FLAGS}i` : GREP_FLAGS),
80
+ );
79
81
 
80
82
  /** The first match column of one physical line, or undefined when no pattern matches it. */
81
83
  function lineColumn(regexes: readonly RegExp[], text: string): number | undefined {
@@ -110,10 +112,10 @@ export function searchText({ source: raw, query, limit }: SearchInput): SearchRe
110
112
  for (const regex of regexes)
111
113
  lines = mergeRows(lines, multilineRows(source, regex, limit), limit);
112
114
  } else lines = lineRows(source, regexes, limit);
113
- return { lines, totalLines: countLines(source) };
115
+ return { lines };
114
116
  }
115
117
 
116
118
  /** Line-mode matching of selected lines; a row's lineNumber is the line's 1-based position. */
117
119
  export function searchLines({ lines, query, limit }: LineSearchInput): SearchResult {
118
- return { lines: lineRows(lines, queryRegexes(query), limit), totalLines: countLines(lines) };
120
+ return { lines: lineRows(lines, queryRegexes(query), limit) };
119
121
  }
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  * @module pi-hashline-edit
11
11
  */
12
12
 
13
+ import { isAbsolute, join } from "node:path";
13
14
  import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
14
15
  import type { TSchema } from "typebox";
15
16
  import { loadConfig } from "./pi/config.ts";
@@ -23,8 +24,32 @@ import { createActionFusionExecutor } from "./pi/action-fusion.ts";
23
24
  import { registerFusionCards, withMutationStatus } from "./pi/fusion-card.ts";
24
25
  import { NEXT_GUIDELINE } from "./pi/report-schema.ts";
25
26
 
26
- export default function (pi: ExtensionAPI) {
27
- const cwd = process.cwd();
27
+ export default async function (pi: ExtensionAPI) {
28
+ // Pi runs exec in the extension loader's workspace, even before session_start.
29
+ // Replay on reload needs tools and entry renderers registered before that event.
30
+ // Ask the OS directly so a second Node runtime cannot rerun the host's preloads.
31
+ const windows = process.platform === "win32";
32
+ const result = windows
33
+ ? await pi.exec(
34
+ join(
35
+ process.env.SystemRoot ?? "C:\\Windows",
36
+ "System32/WindowsPowerShell/v1.0/powershell.exe",
37
+ ),
38
+ [
39
+ "-NoProfile",
40
+ "-NonInteractive",
41
+ "-Command",
42
+ "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); [Console]::Write([Environment]::CurrentDirectory)",
43
+ ],
44
+ )
45
+ : await pi.exec("/bin/pwd", ["-P"]);
46
+ const { stderr, code, killed, truncated } = result;
47
+ const cwd = windows ? result.stdout : result.stdout.replace(/\n$/, "");
48
+ if (code !== 0 || killed || truncated || !isAbsolute(cwd)) {
49
+ throw new Error(`Unable to resolve the Pi workspace (exit ${code})`, {
50
+ cause: stderr || undefined,
51
+ });
52
+ }
28
53
 
29
54
  // Tools capture this snapshot at registration; a reload registers them again.
30
55
  const config = loadConfig(cwd);
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
6
6
  import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
7
8
  import registerHashline from "../index.ts";
8
9
  import { computeLineHash } from "../core/hash.ts";
9
10
  import { callTool } from "../pi/tool-call.testing.ts";
@@ -12,20 +13,93 @@ import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
12
13
  import { reportOf } from "../pi/report.ts";
13
14
  import { formatByteSize } from "../pi/budgets.ts";
14
15
  import { expectToolFailure } from "../pi/report-failure.testing.ts";
16
+ import { openTestSession } from "../testing/session.testing.ts";
17
+
18
+ test("relative Node preload → registration uses the workspace", async (t) => {
19
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-workspace-"));
20
+ t.after(() => rm(cwd, { recursive: true, force: true }));
21
+ const previous = process.env.NODE_OPTIONS;
22
+ process.env.NODE_OPTIONS = "--require=./package.json";
23
+ try {
24
+ const { session } = await openTestSession(t, {
25
+ cwd,
26
+ tools: ["read"],
27
+ configure: registerHashline,
28
+ });
29
+ assert.ok(session.getToolDefinition("read")?.prepareArguments);
30
+ } finally {
31
+ if (previous === undefined) delete process.env.NODE_OPTIONS;
32
+ else process.env.NODE_OPTIONS = previous;
33
+ }
34
+ });
35
+
36
+ test("SDK cwd differs from process cwd → project settings and relative tools use the workspace", async (t) => {
37
+ const cwd = await mkdtemp(join(tmpdir(), "hashline-workspace-"));
38
+ t.after(() => rm(cwd, { recursive: true, force: true }));
39
+ const settings = join(cwd, ".pi", "settings.json");
40
+ await mkdir(join(cwd, ".pi"));
41
+ await writeFile(settings, JSON.stringify({ hashlineEdit: { hashLen: 8, actionFusion: false } }));
42
+ await writeFile(join(cwd, "workspace.txt"), "from the SDK workspace\n");
43
+ const hostCwd = process.cwd();
44
+ assert.notEqual(cwd, hostCwd);
45
+ const { session } = await openTestSession(t, {
46
+ cwd,
47
+ tools: ["read", "write", "edit"],
48
+ configure: registerHashline,
49
+ });
50
+ const read = session.getToolDefinition("read");
51
+ assert.ok(read);
52
+ const result = await callTool(read, { path: "workspace.txt" }, { ctx: { cwd } });
53
+ const anchor = `1#${computeLineHash(1, "from the SDK workspace", 8)}`;
54
+ assert.ok(
55
+ result.content.some((block) => block.type === "text" && block.text.includes(anchor)),
56
+ JSON.stringify(result.content),
57
+ );
58
+ const write = session.getToolDefinition("write");
59
+ assert.ok(write && Type.IsObject(write.parameters));
60
+ assert.ok(!("then_run" in write.parameters.properties));
61
+ const written = await callTool(
62
+ write,
63
+ { path: "workspace.txt", content: "written\n", mode: "overwrite" },
64
+ { ctx: { cwd } },
65
+ );
66
+ assert.equal(reportOf(written, "write")?.publication, "PUBLISHED");
67
+ assert.equal(await readFile(join(cwd, "workspace.txt"), "utf8"), "written\n");
68
+
69
+ await session.reload({
70
+ beforeSessionStart: () => {
71
+ assert.ok(session.getToolDefinition("edit")?.prepareArguments);
72
+ assert.ok(session.extensionRunner.getEntryRenderer("hashline-then-run"));
73
+ },
74
+ });
75
+
76
+ await writeFile(settings, JSON.stringify({ hashlineEdit: { enabled: false } }));
77
+ await session.reload({
78
+ beforeSessionStart: () => {
79
+ assert.equal(session.getToolDefinition("replace"), undefined);
80
+ assert.equal(session.extensionRunner.getEntryRenderer("hashline-then-run"), undefined);
81
+ },
82
+ });
83
+ const builtin = session.getToolDefinition("edit");
84
+ assert.ok(builtin && Type.IsObject(builtin.parameters));
85
+ assert.ok("edits" in builtin.parameters.properties);
86
+ assert.equal(process.cwd(), hostCwd);
87
+ });
15
88
 
16
89
  test("registered tools retain their configuration when another tool set is registered", async (t) => {
17
90
  const directory = await mkdtemp(join(tmpdir(), "hashline-config-registration-"));
18
- const previousCwd = process.cwd();
19
91
  try {
20
92
  await mkdir(join(directory, ".pi"));
21
- process.chdir(directory);
22
93
  const register = async (config: HashlineEditConfig) => {
23
94
  await writeFile(
24
95
  join(directory, ".pi", "settings.json"),
25
96
  JSON.stringify({ hashlineEdit: config }),
26
97
  );
27
98
  const tools = new Map<string, ToolDefinition>();
28
- registerHashline({
99
+ await registerHashline({
100
+ async exec() {
101
+ return { stdout: directory, stderr: "", code: 0, killed: false, truncated: false };
102
+ },
29
103
  on() {},
30
104
  registerEntryRenderer() {},
31
105
  registerTool(tool: ToolDefinition) {
@@ -212,7 +286,6 @@ test("registered tools retain their configuration when another tool set is regis
212
286
  );
213
287
  }
214
288
  } finally {
215
- process.chdir(previousCwd);
216
289
  await rm(directory, { recursive: true, force: true });
217
290
  }
218
291
  });
@@ -44,7 +44,7 @@ async function openSession(
44
44
  calls,
45
45
  progress,
46
46
  abort: () => session.abort(),
47
- async run(thenRun: ThenRunInput) {
47
+ async run(thenRun: ThenRunInput, expectedFile: string | null = "saved\n") {
48
48
  let responses = 0;
49
49
  session.agent.streamFunction = () => {
50
50
  const first = responses++ === 0;
@@ -75,7 +75,9 @@ async function openSession(
75
75
  );
76
76
  assert.ok(result?.role === "toolResult");
77
77
  assert.equal(result.isError, false, "A command failure must not fail the completed mutation");
78
- assert.equal(await readFile(join(cwd, "saved.txt"), "utf8"), "saved\n");
78
+ const saved = readFile(join(cwd, "saved.txt"), "utf8");
79
+ if (expectedFile === null) await assert.rejects(saved, { code: "ENOENT" });
80
+ else assert.equal(await saved, expectedFile);
79
81
  return {
80
82
  modelRequests: responses,
81
83
  report: reportOf(result, "write"),
@@ -140,6 +142,24 @@ for (const { name, source, timeout, command, diagnostic } of commandCases) {
140
142
  });
141
143
  }
142
144
 
145
+ for (const [freshness, source, expectedFile, status] of [
146
+ ["changed", "fs.writeFileSync('saved.txt', 'after'); process.exitCode = 7;", "after", "failed"],
147
+ ["missing", "fs.unlinkSync('saved.txt');", null, "succeeded"],
148
+ ] as const) {
149
+ test(`real session command leaves target ${freshness} → reports publication, command status and final freshness`, async (t) => {
150
+ const f = await openSession(t);
151
+ await writeFile(join(f.cwd, "command.mjs"), `import fs from 'node:fs';\n${source}`);
152
+ const result = await f.run({ command: "node command.mjs" }, expectedFile);
153
+ assert.equal(result.report?.publication, "PUBLISHED");
154
+ assert.equal(result.report.then_run?.status, status);
155
+ assert.equal(result.report.freshness, freshness);
156
+ const wire = reportOf({ content: [{ type: "text", text: result.text }] }, "write");
157
+ assert.equal(wire?.freshness, freshness);
158
+ if (freshness === "changed") assert.match(wire.next ?? "", /Read the file/);
159
+ else assert.equal(wire.next, undefined);
160
+ });
161
+ }
162
+
143
163
  test("cancelling a real session Bash command → reports cancellation and keeps the published mutation", {
144
164
  timeout: 15_000,
145
165
  }, async (t) => {
@@ -273,3 +293,28 @@ test("session Bash override and tool_result hook → then_run uses their final r
273
293
  await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
274
294
  assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
275
295
  });
296
+
297
+ test("session Bash override writes the target through a nested call → fails without waiting on its own queue", {
298
+ timeout: 3_000,
299
+ }, async (t) => {
300
+ const f = await openSession(t, (pi) => {
301
+ pi.registerTool({
302
+ name: "bash",
303
+ label: "bash",
304
+ description: "Session Bash override",
305
+ parameters: Type.Object({ command: Type.String() }),
306
+ async execute(_id, _args, _signal, _onUpdate, ctx) {
307
+ const nested = await ctx.executeTool("write", {
308
+ path: "./saved.txt",
309
+ mode: "overwrite",
310
+ content: "nested write\n",
311
+ });
312
+ return { ...nested.result, isError: nested.isError };
313
+ },
314
+ });
315
+ });
316
+ const result = await f.run({ command: "check" });
317
+ assert.equal(result.report?.publication, "PUBLISHED");
318
+ assert.equal(result.report?.then_run?.status, "failed");
319
+ assert.ok(f.calls.some((call) => call.name === "write" && call.parent === "fused/1"));
320
+ });
@@ -1,3 +1,4 @@
1
+ import { listCandidates } from "../pi/grep-candidates.ts";
1
2
  import assert from "node:assert/strict";
2
3
  import { chmod, mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/promises";
3
4
  import { tmpdir } from "node:os";
@@ -48,3 +49,33 @@ for (const condition of ["permission denied", "symlink loop"] as const) {
48
49
  );
49
50
  });
50
51
  }
52
+
53
+ test("prefilter hits an unreadable path without matches → preserves the diagnostic and offers no unfiltered candidates", {
54
+ skip: process.getuid?.() === 0 ? "POSIX permission fixture requires a non-root user" : false,
55
+ }, async (t) => {
56
+ const directory = await mkdtemp(join(tmpdir(), "hashline-grep-prefilter-error-"));
57
+ t.after(() => rm(directory, { recursive: true, force: true }));
58
+ await writeFile(join(directory, "nonmatch.txt"), "other text\n");
59
+ const inaccessible = join(directory, "inaccessible");
60
+ if (process.platform === "win32") {
61
+ await symlink(join(directory, "missing"), inaccessible, "junction");
62
+ } else {
63
+ await writeFile(inaccessible, "needle\n");
64
+ await chmod(inaccessible, 0);
65
+ }
66
+
67
+ const offered: string[] = [];
68
+ const { listing } = await listCandidates({
69
+ scope: { searchPaths: [directory], globs: [] },
70
+ query: { patterns: ["needle"], literal: true, ignoreCase: false, multiline: true },
71
+ signal: new AbortController().signal,
72
+ stopped: () => false,
73
+ onCandidate: async ({ filePath }) => {
74
+ offered.push(filePath);
75
+ return true;
76
+ },
77
+ });
78
+ assert.deepEqual(offered, []);
79
+ assert.equal(listing?.code, 2);
80
+ assert.match(listing.stderr, /inaccessible/);
81
+ });
@@ -11,208 +11,34 @@ import { callTool } from "../pi/tool-call.testing.ts";
11
11
 
12
12
  const cases = [
13
13
  {
14
- name: "u counts Unicode code points",
15
- pattern: "^.$",
16
- flags: "mu",
17
- source: "😀\na\nab\n",
18
- lines: [1, 2],
19
- },
20
- {
21
- name: "v counts Unicode code points",
22
- pattern: "^.$",
23
- flags: "mv",
24
- source: "😀\na\nab\n",
25
- lines: [1, 2],
26
- },
27
- {
28
- name: "Unicode property escape",
29
- pattern: "^\\p{Letter}+$",
30
- flags: "mu",
31
- source: "é\nabc\n12\n",
32
- lines: [1, 2],
33
- },
34
- {
35
- name: "Unicode set intersection",
36
- pattern: "^[\\p{ASCII}&&\\p{Letter}]+$",
37
- flags: "mv",
38
- source: "é\nabc\n12\n",
39
- lines: [2],
40
- },
41
- {
42
- name: "Unicode set subtraction",
43
- pattern: "^[\\p{Letter}--[a-z]]+$",
44
- flags: "mv",
45
- source: "é\nabc\nΩ\n",
46
- lines: [1, 3],
47
- },
48
- {
49
- name: "Unicode string set",
50
- pattern: "^[\\q{ab|cd}]$",
51
- flags: "mv",
52
- source: "ab\ncd\na\n",
53
- lines: [1, 2],
54
- },
55
- {
56
- name: "Unicode property of strings",
57
- pattern: "^\\p{RGI_Emoji}$",
58
- flags: "mv",
59
- source: "👨‍👩‍👧‍👦\n😀\nx\n",
60
- lines: [1, 2],
61
- },
62
- {
63
- name: "Unicode case folding includes Kelvin",
64
- pattern: "^k$",
65
- flags: "miu",
66
- source: "k\nK\nK\n",
67
- lines: [1, 2, 3],
68
- },
69
- {
70
- name: "non-Unicode case folding excludes Kelvin",
71
- pattern: "^k$",
72
- flags: "mi",
73
- source: "k\nK\nK\n",
74
- lines: [1, 2],
75
- },
76
- {
77
- name: "Unicode caseless word set",
78
- pattern: "^\\w$",
79
- flags: "miu",
80
- source: "ſ\nK\nk\né\n",
81
- lines: [1, 2, 3],
82
- },
83
- {
84
- name: "dotAll crosses physical lines when enabled",
85
- pattern: "^a.b$",
86
- flags: "s",
87
- source: "a\nb",
88
- multiline: true,
89
- lines: [1, 2],
90
- },
91
- {
92
- name: "dotAll does not override line mode",
93
- pattern: "^a.b$",
94
- flags: "s",
95
- source: "a\nb",
96
- lines: [],
97
- },
98
- {
99
- name: "explicit flags can disable m",
100
- pattern: "^a$",
101
- flags: "",
102
- source: "x\na",
103
- multiline: true,
104
- lines: [],
105
- },
106
- {
107
- name: "explicit m restores line anchors",
108
- pattern: "^a$",
109
- flags: "m",
110
- source: "x\na",
111
- multiline: true,
112
- lines: [2],
113
- },
114
- {
115
- name: "sticky matching starts at each physical line",
116
- pattern: "a",
117
- flags: "y",
118
- source: "ba\na\n",
119
- lines: [2],
120
- },
121
- {
122
- name: "sticky whole-file matching stops at first failure",
123
- pattern: "a",
124
- flags: "y",
125
- source: "ba\na\n",
126
- multiline: true,
127
- lines: [],
128
- },
129
- {
130
- name: "global sticky matches remain contiguous",
131
- pattern: "a",
132
- flags: "gy",
133
- source: "aa\nba\n",
134
- multiline: true,
135
- lines: [1],
136
- },
137
- {
138
- name: "global and indices flags reset between physical lines",
139
- pattern: "a",
140
- flags: "gd",
141
- source: "a\na",
142
- lines: [1, 2],
143
- },
144
- {
145
- name: "Unicode zero-width advancement",
146
- pattern: "(?=.)",
147
- flags: "u",
148
- source: "😀\nx",
149
- multiline: true,
14
+ name: "lowercase pattern → smart-case ignores case",
15
+ pattern: "^foo$",
16
+ source: "FOO\nfoo\n",
150
17
  lines: [1, 2],
151
18
  },
152
19
  {
153
- name: "Unicode mode cannot split a surrogate pair",
154
- pattern: "\\uDE00",
155
- flags: "u",
156
- source: "😀x",
157
- lines: [],
158
- },
159
- ...["s", "m"].flatMap((flags) => [
160
- {
161
- name: `lowercase pattern with ${flags} → smart-case ignores case`,
162
- pattern: "^foo$",
163
- flags,
164
- source: "FOO\nfoo\n",
165
- lines: [1, 2],
166
- },
167
- {
168
- name: `uppercase pattern with ${flags} → smart-case is case-sensitive`,
169
- pattern: "^FOO$",
170
- flags,
171
- source: "FOO\nfoo\n",
172
- lines: [1],
173
- },
174
- ]),
175
- {
176
- name: "explicit i overrides uppercase smart-case",
20
+ name: "uppercase pattern → smart-case is case-sensitive",
177
21
  pattern: "^FOO$",
178
- flags: "i",
179
22
  source: "FOO\nfoo\n",
180
- lines: [1, 2],
23
+ lines: [1],
181
24
  },
182
25
  {
183
- name: "ignoreCase false overrides i",
26
+ name: "ignoreCase false with lowercase pattern → matches case-sensitively",
184
27
  pattern: "^foo$",
185
- flags: "mi",
186
28
  ignoreCase: false,
187
29
  source: "FOO\nfoo\n",
188
30
  lines: [2],
189
31
  },
190
32
  {
191
- name: "ignoreCase true enables i",
33
+ name: "ignoreCase true with uppercase pattern → matches case-insensitively",
192
34
  pattern: "^FOO$",
193
- flags: "m",
194
35
  ignoreCase: true,
195
36
  source: "FOO\nfoo\n",
196
37
  lines: [1, 2],
197
38
  },
198
- {
199
- name: "literal Unicode case folding",
200
- pattern: "k",
201
- literal: true,
202
- flags: "iu",
203
- source: "k\nK\nK\n",
204
- lines: [1, 2, 3],
205
- },
206
- {
207
- name: "flag lists deduplicate",
208
- pattern: "^foo$",
209
- flags: "mmi",
210
- source: "FOO\nfoo\n",
211
- lines: [1, 2],
212
- },
213
39
  ];
214
40
 
215
- test("grep flags: JavaScript modes preserve native matching through the real search pipeline", async (t) => {
41
+ test("grep case options → preserve native matching through the real search pipeline", async (t) => {
216
42
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-flags-"));
217
43
  t.after(() => rm(directory, { recursive: true, force: true }));
218
44
  const path = join(directory, "input.txt");
@@ -223,9 +49,7 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
223
49
  const result = await callTool(tool, {
224
50
  path,
225
51
  pattern: scenario.pattern,
226
- literal: scenario.literal ?? false,
227
- flags: scenario.flags,
228
- multiline: scenario.multiline ?? false,
52
+ literal: false,
229
53
  ...(scenario.ignoreCase === undefined ? {} : { ignoreCase: scenario.ignoreCase }),
230
54
  });
231
55
  assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
@@ -238,7 +62,7 @@ test("grep flags: JavaScript modes preserve native matching through the real sea
238
62
  }
239
63
  });
240
64
 
241
- test("grep flags: valid V8 patterns exceeding translator parser depth still execute", async (t) => {
65
+ test("valid V8 patterns exceeding translator parser depth → still execute", async (t) => {
242
66
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-parser-depth-"));
243
67
  t.after(() => rm(directory, { recursive: true, force: true }));
244
68
  const path = join(directory, "input.txt");
@@ -246,14 +70,7 @@ test("grep flags: valid V8 patterns exceeding translator parser depth still exec
246
70
  const pattern = `${"(?:".repeat(3_000)}A${")".repeat(3_000)}`;
247
71
  assert.equal(new RegExp(pattern).test("A"), true);
248
72
  const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
249
- for (const flags of [undefined, "m"]) {
250
- const result = await callTool(tool, {
251
- path,
252
- pattern,
253
- literal: false,
254
- ...(flags === undefined ? {} : { flags }),
255
- });
256
- assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
257
- assert.equal(grepCounts(result).matches, 1);
258
- }
73
+ const result = await callTool(tool, { path, pattern, literal: false });
74
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
75
+ assert.equal(grepCounts(result).matches, 1);
259
76
  });
@@ -91,6 +91,33 @@ test("JS grep: malformed UTF-8 matches the preview text without editable anchors
91
91
  assert.doesNotMatch(body.text, /\d+#[0-9A-Z]+/);
92
92
  });
93
93
 
94
+ test("line length at the limit → only LF and CRLF terminators are excluded", async (t) => {
95
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-line-bound-"));
96
+ t.after(() => rm(directory, { recursive: true, force: true }));
97
+ const path = join(directory, "large.txt");
98
+ const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
99
+ const maxLineUnits = 64 * 1024 * 1024;
100
+ const body = Buffer.alloc(maxLineUnits, 0x61);
101
+ // Put CR at the end of a 64 KiB scan chunk in the split case.
102
+ const prefix = "x".repeat(64 * 1024 - 2) + "\n";
103
+ for (const [leading, ending, accepted] of [
104
+ ["", "\n", true],
105
+ ["", "\r\n", true],
106
+ [prefix, "\r\n", true],
107
+ ["", "\r", false],
108
+ ["", "a\r\n", false],
109
+ ] as const) {
110
+ await writeFile(path, Buffer.concat([Buffer.from(leading), body, Buffer.from(ending)]));
111
+ const result = await callTool(tool, { path, pattern: "a", literal: true, outputMode: "count" });
112
+ if (accepted) {
113
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result, "grep")));
114
+ assert.equal(grepCounts(result).matches, 1);
115
+ } else {
116
+ assert.equal(reportOf(result, "grep")?.error, "SEARCH_INCOMPLETE");
117
+ }
118
+ }
119
+ });
120
+
94
121
  test("oversized line or multiline input → explicit incomplete-search diagnostics", async (t) => {
95
122
  const directory = await mkdtemp(join(tmpdir(), "hl-grep-js-bound-"));
96
123
  t.after(() => rm(directory, { recursive: true, force: true }));
@@ -140,13 +167,12 @@ test("real rg candidates → include every JS row and preserve confirmed output
140
167
  ["miss.txt", Buffer.from("unrelated\n")],
141
168
  ] as const;
142
169
  for (const [name, bytes] of fixtures) await writeFile(join(directory, name), bytes);
143
- for (const [pattern, flags, multiline, matches] of [
144
- ["colou?r", "mi", false, 2],
145
- ["a\\uFFFDb", "m", false, 1],
146
- ["k", "miu", false, 2],
147
- ["alpha\\nbeta", "m", true, 2],
170
+ for (const [pattern, ignoreCase, multiline, matches] of [
171
+ ["colou?r", true, false, 2],
172
+ ["a\\uFFFDb", false, false, 1],
173
+ ["alpha\\nbeta", false, true, 2],
148
174
  ] as const) {
149
- await t.test(`${pattern} /${flags} → identical confirmed results`, async () => {
175
+ await t.test(`${pattern} ignoreCase=${ignoreCase} → identical confirmed results`, async () => {
150
176
  const candidates = new Map<string, readonly number[] | undefined>();
151
177
  const filtered = makeMockGrep(directory, DEFAULT_CONFIG, {
152
178
  runRgPaths(args, signal, onPath) {
@@ -183,7 +209,14 @@ test("real rg candidates → include every JS row and preserve confirmed output
183
209
  },
184
210
  });
185
211
  for (const outputMode of ["content", "files", "count"] as const) {
186
- const params = { path: directory, pattern, flags, multiline, literal: false, outputMode };
212
+ const params = {
213
+ path: directory,
214
+ pattern,
215
+ ignoreCase,
216
+ multiline,
217
+ literal: false,
218
+ outputMode,
219
+ };
187
220
  const actual = await callTool(filtered, params);
188
221
  const expected = await callTool(full, params);
189
222
  assert.equal(actual.isError, undefined, JSON.stringify(reportOf(actual, "grep")));
@@ -200,7 +233,7 @@ test("real rg candidates → include every JS row and preserve confirmed output
200
233
  const path = join(directory, name);
201
234
  const rows = searchText({
202
235
  source: bytes.toString("utf8"),
203
- query: { patterns: [pattern], literal: false, flags, multiline },
236
+ query: { patterns: [pattern], literal: false, ignoreCase, multiline },
204
237
  limit: bytes.length,
205
238
  }).lines;
206
239
  if (!rows.length) continue;