@criogaid/pi-hashline-edit 0.6.0 → 0.7.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 (148) hide show
  1. package/README.md +161 -304
  2. package/THIRD_PARTY_NOTICES.md +80 -0
  3. package/package.json +10 -6
  4. package/src/core/AGENTS.md +20 -0
  5. package/src/core/apply.test.ts +189 -60
  6. package/src/core/apply.ts +110 -74
  7. package/src/core/case-fold.test.ts +40 -0
  8. package/src/core/case-fold.ts +81 -0
  9. package/src/core/character-set.test.ts +103 -0
  10. package/src/core/character-set.ts +170 -0
  11. package/src/core/errors.test.ts +23 -0
  12. package/src/core/errors.ts +70 -4
  13. package/src/core/lines.ts +7 -0
  14. package/src/core/regex.ts +21 -0
  15. package/src/core/replace-schema.ts +34 -0
  16. package/src/core/replace.ts +37 -54
  17. package/src/core/search-analysis.test.ts +199 -0
  18. package/src/core/search-analysis.ts +375 -0
  19. package/src/core/search-matrix.test.ts +64 -0
  20. package/src/core/search-matrix.testing.ts +183 -0
  21. package/src/core/search-schema.ts +18 -0
  22. package/src/core/search.test.ts +145 -0
  23. package/src/core/search.ts +119 -0
  24. package/src/core/text.test.ts +16 -8
  25. package/src/core/text.ts +26 -6
  26. package/src/core/types.ts +16 -11
  27. package/src/index.ts +25 -15
  28. package/src/integration/config-registration.test.ts +30 -24
  29. package/src/integration/forget-grep.test.ts +52 -2
  30. package/src/integration/fusion-dispatch.test.ts +21 -105
  31. package/src/integration/grep-errors.test.ts +50 -0
  32. package/src/integration/grep-flags.test.ts +280 -0
  33. package/src/integration/grep-js-completeness.test.ts +208 -0
  34. package/src/integration/grep-line-candidates.test.ts +233 -0
  35. package/src/integration/grep-matrix.test.ts +121 -0
  36. package/src/integration/grep-path-matrix.test.ts +132 -0
  37. package/src/integration/grep-prefilter-coverage.test.ts +189 -0
  38. package/src/integration/grep-regex.test.ts +410 -0
  39. package/src/integration/grep-rg.test.ts +220 -402
  40. package/src/integration/grep-scan-budget.test.ts +89 -0
  41. package/src/integration/grep-translation.test.ts +206 -0
  42. package/src/integration/large-text.test.ts +57 -1
  43. package/src/integration/model-budget-lifecycle.test.ts +128 -0
  44. package/src/integration/mutation-file-types.test.ts +12 -25
  45. package/src/integration/mutation-file-types.testing.ts +33 -0
  46. package/src/integration/npm-package.test.ts +17 -0
  47. package/src/integration/npm-package.testing.ts +123 -0
  48. package/src/integration/publication-read-changes.test.ts +344 -0
  49. package/src/integration/read-changes.test.ts +98 -0
  50. package/src/integration/replace-package.test.ts +17 -36
  51. package/src/integration/replace-package.testing.ts +33 -0
  52. package/src/integration/replace-worker-boundary.test.ts +107 -0
  53. package/src/integration/report-replay.test.ts +90 -0
  54. package/src/integration/utf8-errors.test.ts +46 -0
  55. package/src/pi/AGENTS.md +55 -0
  56. package/src/pi/action-fusion.test.ts +253 -103
  57. package/src/pi/action-fusion.ts +116 -290
  58. package/src/pi/anchor-format.ts +9 -0
  59. package/src/pi/argument-diagnostics.ts +478 -0
  60. package/src/pi/argument-error.testing.ts +43 -0
  61. package/src/pi/argument-error.ts +78 -0
  62. package/src/pi/argument-format.test.ts +208 -0
  63. package/src/pi/argument-validation.test.ts +742 -45
  64. package/src/pi/argument-validation.ts +56 -59
  65. package/src/pi/budgets.ts +45 -16
  66. package/src/pi/codemode.test.ts +96 -0
  67. package/src/pi/config.test.ts +14 -10
  68. package/src/pi/config.ts +21 -7
  69. package/src/pi/diagnostic-buffer.test.ts +52 -16
  70. package/src/pi/diagnostic-buffer.ts +11 -14
  71. package/src/pi/directory-sync.test.ts +4 -1
  72. package/src/pi/edit-tool.ts +100 -93
  73. package/src/pi/error-text.ts +39 -16
  74. package/src/pi/execute.test.ts +362 -315
  75. package/src/pi/extension-loading.test.ts +14 -0
  76. package/src/pi/extension-loading.testing.ts +3 -0
  77. package/src/pi/failure-context.test.ts +220 -88
  78. package/src/pi/failure-context.ts +161 -180
  79. package/src/pi/failure-path.test.ts +85 -88
  80. package/src/pi/file-commit.test.ts +78 -45
  81. package/src/pi/file-commit.ts +218 -151
  82. package/src/pi/file-read.test.ts +29 -0
  83. package/src/pi/file-read.ts +60 -0
  84. package/src/pi/file-snapshot.test.ts +1 -1
  85. package/src/pi/forget-tool.ts +189 -90
  86. package/src/pi/forget.test.ts +309 -22
  87. package/src/pi/forget.testing.ts +41 -113
  88. package/src/pi/fusion-card.test.ts +40 -14
  89. package/src/pi/fusion-card.ts +84 -50
  90. package/src/pi/grep-candidates.test.ts +127 -0
  91. package/src/pi/grep-candidates.ts +193 -0
  92. package/src/pi/grep-matrix.test.ts +83 -0
  93. package/src/pi/grep-output.ts +181 -138
  94. package/src/pi/grep-render.ts +28 -25
  95. package/src/pi/grep-scope.ts +61 -53
  96. package/src/pi/grep-search.ts +299 -242
  97. package/src/pi/grep-tool.ts +150 -140
  98. package/src/pi/grep-worker.mjs +4 -0
  99. package/src/pi/grep-worker.ts +14 -0
  100. package/src/pi/grep.test.ts +631 -632
  101. package/src/pi/model-budgets.test.ts +43 -0
  102. package/src/pi/model-budgets.ts +44 -0
  103. package/src/pi/mutation-outcome.testing.ts +5 -5
  104. package/src/pi/mutation-result.test.ts +21 -74
  105. package/src/pi/mutation-result.ts +74 -87
  106. package/src/pi/mutation-runner.ts +83 -75
  107. package/src/pi/output-budgets.test.ts +166 -0
  108. package/src/pi/path.ts +7 -0
  109. package/src/pi/read-tool.ts +151 -137
  110. package/src/pi/read.test.ts +39 -33
  111. package/src/pi/regex-worker-contract.ts +73 -0
  112. package/src/pi/regex-worker.ts +101 -0
  113. package/src/pi/registration.test.ts +111 -92
  114. package/src/pi/render.test.ts +193 -19
  115. package/src/pi/render.ts +137 -29
  116. package/src/pi/replace-regex.ts +11 -44
  117. package/src/pi/replace-tool.ts +38 -145
  118. package/src/pi/replace-worker-contract.ts +19 -0
  119. package/src/pi/replace-worker.ts +12 -8
  120. package/src/pi/replace.test.ts +93 -160
  121. package/src/pi/report-cause.ts +99 -0
  122. package/src/pi/report-failure.testing.ts +20 -0
  123. package/src/pi/report-schema.ts +512 -0
  124. package/src/pi/report.test.ts +276 -0
  125. package/src/pi/report.ts +288 -0
  126. package/src/pi/result-safety.test.ts +122 -427
  127. package/src/pi/rg-process.test.ts +78 -79
  128. package/src/pi/rg-process.ts +124 -177
  129. package/src/pi/rg-regex.test.ts +50 -0
  130. package/src/pi/rg-regex.ts +709 -0
  131. package/src/pi/text-stream.test.ts +67 -38
  132. package/src/pi/text-stream.ts +96 -75
  133. package/src/pi/tool-call.testing.ts +3 -39
  134. package/src/pi/write-tool.ts +45 -34
  135. package/src/pi/write.test.ts +45 -37
  136. package/src/testing/extension-loader.testing.ts +24 -0
  137. package/src/testing/installation.testing.ts +77 -0
  138. package/src/testing/process.testing.ts +33 -0
  139. package/src/testing/regex-host.testing.ts +20 -0
  140. package/src/testing/regex-translation-corpus.ts +308 -0
  141. package/src/testing/rg-line-listing.fixture.mjs +7 -0
  142. package/src/testing/run-tests.ts +47 -0
  143. package/src/testing/session.testing.ts +127 -0
  144. package/src/pi/rg-line-ranges.test.ts +0 -66
  145. package/src/pi/rg-line-ranges.ts +0 -75
  146. package/src/pi/rg-match-bytes.ts +0 -95
  147. package/src/pi/rg-text-view.ts +0 -192
  148. package/src/pi/tool-prompts.ts +0 -15
@@ -14,6 +14,7 @@ import {
14
14
  toolResponse,
15
15
  toolResult,
16
16
  } from "../pi/forget.testing.ts";
17
+ import { reportOf } from "../pi/report.ts";
17
18
 
18
19
  for (const encoding of ["UTF-8", "invalid UTF-8"] as const) {
19
20
  test(`real grep of ${encoding} logs then forget → matched content is absent from the next request`, {
@@ -59,9 +60,10 @@ for (const encoding of ["UTF-8", "invalid UTF-8"] as const) {
59
60
  assert.ok(receipt.type === "text" && !receipt.text.includes("needle"));
60
61
  assert.ok(receipt.type === "text" && !receipt.text.includes("search.log"));
61
62
  const displayReceipt = `grep /needle/ Ā· ${rows.length} matches in 1 file`;
62
- assert.deepEqual(f.rawResult("forget-call").details, {
63
+ assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
63
64
  forgotten: [{ id, receipt: displayReceipt }],
64
65
  });
66
+ assert.deepEqual(reportOf(f.rawResult("forget-call"))?.forgotten, [id]);
65
67
  assert.ok(f.renderForgetCard().includes(displayReceipt));
66
68
  });
67
69
  }
@@ -92,7 +94,55 @@ test("real grep reaches its limit across files → forget card reports the retur
92
94
  const id = taggedResultId(toolResult(f.requests[1], "search"));
93
95
  assert.ok(id);
94
96
  const receipt = `grep /needle | backup/ Ā· ${limit} matches in ${paths.length} files Ā· limit reached`;
95
- assert.deepEqual(f.rawResult("forget-call").details, { forgotten: [{ id, receipt }] });
97
+ assert.partialDeepStrictEqual(f.rawResult("forget-call").details, {
98
+ forgotten: [{ id, receipt }],
99
+ });
100
+ assert.deepEqual(reportOf(f.rawResult("forget-call"))?.forgotten, [id]);
96
101
  assert.ok(f.renderForgetCard().includes(receipt));
97
102
  assertForgotten(toolResult(f.requests[2], "search"), id);
98
103
  });
104
+
105
+ for (const outputMode of [undefined, "content", null, "files", "count"] as const) {
106
+ test(`codemode grep outputMode=${String(outputMode)} → only content output can be forgotten`, {
107
+ timeout: SESSION_TIMEOUT_MS,
108
+ }, async (t) => {
109
+ const f = await openForgetSession(t);
110
+ const path = join(f.cwd, "search.log");
111
+ await writeFile(path, `needle ${"x".repeat(FORGET_MIN_BYTES)}\n`);
112
+ const args = { path, pattern: "needle", literal: true, outputMode };
113
+ const eligible = outputMode === undefined || outputMode === null || outputMode === "content";
114
+ await f.prompt(
115
+ toolResponse({
116
+ type: "toolCall",
117
+ id: "script-search",
118
+ name: "codemode",
119
+ arguments: {
120
+ code: `text(await tools.grep(${JSON.stringify(args)})); text("padding".repeat(${FORGET_MIN_BYTES}));`,
121
+ },
122
+ }),
123
+ (messages) => {
124
+ const result = toolResult(messages, "script-search");
125
+ assert.equal(result.isError, false);
126
+ const id = taggedResultId(result);
127
+ if (eligible) {
128
+ assert.ok(id, "Content-mode inspection output needs a parent tag");
129
+ return toolResponse(forgetCall(messages, "script-search"));
130
+ }
131
+ assert.equal(id, undefined, "Summary-only grep must not make a script forgettable");
132
+ return finish;
133
+ },
134
+ ...(eligible ? [finish] : []),
135
+ );
136
+ const original = toolResult(f.requests[1], "script-search");
137
+ const text = original.content
138
+ .filter((block) => block.type === "text")
139
+ .map((block) => block.text)
140
+ .join("\n");
141
+ assert.equal([...text.matchAll(/"resultId": "r[0-9a-f]{5}"/g)].length, eligible ? 1 : 0);
142
+ if (eligible) {
143
+ const id = taggedResultId(original);
144
+ assert.ok(id);
145
+ assertForgotten(toolResult(f.requests[2], "script-search"), id);
146
+ }
147
+ });
148
+ }
@@ -1,19 +1,10 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
2
+ import { readFile, writeFile } from "node:fs/promises";
4
3
  import { join } from "node:path";
5
4
  import { test, type TestContext } from "node:test";
6
5
  import { Type } from "typebox";
7
- import type { AssistantMessage } from "@earendil-works/pi-ai";
8
- import { AssistantMessageEventStream } from "@earendil-works/pi-ai/utils/event-stream";
9
- import {
10
- createAgentSession,
11
- DefaultResourceLoader,
12
- type ExtensionAPI,
13
- ModelRuntime,
14
- SessionManager,
15
- SettingsManager,
16
- } from "@earendil-works/pi-coding-agent";
6
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
7
+ import { openTestSession, responseStream } from "../testing/session.testing.ts";
17
8
  import {
18
9
  createActionFusionExecutor,
19
10
  type ActionFusionDetails,
@@ -28,84 +19,26 @@ async function openSession(
28
19
  configure?: (pi: ExtensionAPI) => void,
29
20
  onProgress?: (event: ActionFusionProgress) => void,
30
21
  ) {
31
- const cwd = await mkdtemp(join(tmpdir(), "hashline-fusion-session-"));
32
- let dispose: (() => void) | undefined;
33
- t.after(async () => {
34
- dispose?.();
35
- await rm(cwd, { recursive: true, force: true });
36
- });
37
- const modelRuntime = await ModelRuntime.create({
38
- authPath: join(cwd, "auth.json"),
39
- modelsPath: null,
40
- modelsStorePath: join(cwd, "models.json"),
41
- refreshOnCreate: false,
42
- allowModelNetwork: false,
43
- });
44
- modelRuntime.registerProvider("fusion-test", {
45
- api: "openai-completions",
46
- baseUrl: "https://unused.invalid",
47
- apiKey: "local-test-placeholder",
48
- models: [
49
- {
50
- id: "test",
51
- name: "Test",
52
- input: ["text"],
53
- reasoning: false,
54
- contextWindow: 100_000,
55
- maxTokens: 1000,
56
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
57
- },
58
- ],
59
- });
60
- const model = modelRuntime.getModel("fusion-test", "test");
61
- assert.ok(model);
62
22
  const calls: { name: string; parent?: string }[] = [];
63
23
  const progress: ActionFusionProgress[] = [];
64
- const settingsManager = SettingsManager.inMemory({
65
- compaction: { enabled: false },
66
- retry: { enabled: false },
67
- });
68
- const loader = new DefaultResourceLoader({
69
- cwd,
70
- agentDir: cwd,
71
- settingsManager,
72
- noExtensions: true,
73
- noSkills: true,
74
- noPromptTemplates: true,
75
- noThemes: true,
76
- noContextFiles: true,
77
- extensionFactories: [
78
- (pi) => {
79
- pi.on("tool_call", (event) => {
80
- calls.push({ name: event.toolName, parent: event.parentToolCallId });
81
- });
82
- configure?.(pi);
83
- pi.registerTool(
84
- makeWriteOverride(
85
- cwd,
86
- createActionFusionExecutor(undefined, (event) => {
87
- progress.push(event);
88
- onProgress?.(event);
89
- }),
90
- ),
91
- );
92
- },
93
- ],
94
- });
95
- await loader.reload();
96
- const { session, extensionsResult } = await createAgentSession({
97
- cwd,
98
- agentDir: cwd,
99
- modelRuntime,
100
- model,
101
- settingsManager,
102
- resourceLoader: loader,
103
- sessionManager: SessionManager.inMemory(cwd),
24
+ const { cwd, session, model } = await openTestSession(t, {
104
25
  tools: ["write", "bash"],
26
+ configure(pi, cwd) {
27
+ pi.on("tool_call", (event) => {
28
+ calls.push({ name: event.toolName, parent: event.parentToolCallId });
29
+ });
30
+ configure?.(pi);
31
+ pi.registerTool(
32
+ makeWriteOverride(
33
+ cwd,
34
+ createActionFusionExecutor(undefined, (event) => {
35
+ progress.push(event);
36
+ onProgress?.(event);
37
+ }),
38
+ ),
39
+ );
40
+ },
105
41
  });
106
- dispose = () => session.dispose();
107
- assert.deepEqual(extensionsResult.errors, []);
108
- await session.bindExtensions({});
109
42
  return {
110
43
  cwd,
111
44
  calls,
@@ -116,8 +49,7 @@ async function openSession(
116
49
  session.agent.streamFunction = () => {
117
50
  const first = responses++ === 0;
118
51
  assert.ok(responses <= 2, "Unexpected model request");
119
- const message: AssistantMessage = {
120
- role: "assistant",
52
+ return responseStream(model, {
121
53
  content: first
122
54
  ? [
123
55
  {
@@ -134,23 +66,7 @@ async function openSession(
134
66
  ]
135
67
  : [{ type: "text", text: "Done." }],
136
68
  stopReason: first ? "toolUse" : "stop",
137
- api: model.api,
138
- provider: model.provider,
139
- model: model.id,
140
- timestamp: Date.now(),
141
- usage: {
142
- input: 0,
143
- output: 0,
144
- cacheRead: 0,
145
- cacheWrite: 0,
146
- totalTokens: 0,
147
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
148
- },
149
- };
150
- const stream = new AssistantMessageEventStream();
151
- stream.push({ type: "start", partial: message });
152
- stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });
153
- return stream;
69
+ });
154
70
  };
155
71
  await session.prompt("Run the requested local command after the mutation.");
156
72
  assert.equal(session.agent.state.errorMessage, undefined);
@@ -0,0 +1,50 @@
1
+ import assert from "node:assert/strict";
2
+ import { chmod, mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
7
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
+ import { callTool } from "../pi/tool-call.testing.ts";
9
+ import { expectToolFailure } from "../pi/report-failure.testing.ts";
10
+
11
+ for (const condition of ["permission denied", "symlink loop"] as const) {
12
+ test(`existing search path has ${condition} → grep retains the real filesystem error`, {
13
+ skip:
14
+ process.platform === "win32" ||
15
+ (condition === "permission denied" && process.getuid?.() === 0)
16
+ ? "Requires POSIX traversal permissions and symlinks; permission case requires a non-root user"
17
+ : false,
18
+ }, async (t) => {
19
+ const directory = await mkdtemp(join(tmpdir(), "hashline-grep-scope-"));
20
+ const denied = join(directory, "denied");
21
+ t.after(async () => {
22
+ if (condition === "permission denied") await chmod(denied, 0o700);
23
+ await rm(directory, { recursive: true, force: true });
24
+ });
25
+ let path: string;
26
+ let code: string;
27
+ if (condition === "permission denied") {
28
+ await mkdir(denied);
29
+ path = join(denied, "source.txt");
30
+ await writeFile(path, "needleäø­ę–‡\n");
31
+ await chmod(denied, 0);
32
+ code = "EACCES";
33
+ } else {
34
+ path = join(directory, "loop");
35
+ await symlink("loop", path);
36
+ code = "ELOOP";
37
+ }
38
+ await assert.rejects(stat(path), { code });
39
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
40
+ await expectToolFailure(
41
+ callTool(tool, { path, pattern: "needle", literal: true, ignoreCase: false }),
42
+ "FILESYSTEM_ERROR",
43
+ (report) => {
44
+ assert.doesNotMatch(report.message ?? "", /Path not found/);
45
+ assert.ok(report.message?.includes(code));
46
+ assert.equal(report.cause, undefined);
47
+ },
48
+ );
49
+ });
50
+ }
@@ -0,0 +1,280 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import { DEFAULT_CONFIG } from "../pi/config.ts";
7
+ import { makeGrepOverrideWithBackend } from "../pi/grep-tool.ts";
8
+ import { reportOf } from "../pi/report.ts";
9
+ import { callTool } from "../pi/tool-call.testing.ts";
10
+ import { rejectsArgument } from "../pi/argument-error.testing.ts";
11
+
12
+ const cases = [
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,
150
+ lines: [1, 2],
151
+ },
152
+ {
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",
177
+ pattern: "^FOO$",
178
+ flags: "i",
179
+ source: "FOO\nfoo\n",
180
+ lines: [1, 2],
181
+ },
182
+ {
183
+ name: "ignoreCase false overrides i",
184
+ pattern: "^foo$",
185
+ flags: "mi",
186
+ ignoreCase: false,
187
+ source: "FOO\nfoo\n",
188
+ lines: [2],
189
+ },
190
+ {
191
+ name: "ignoreCase true enables i",
192
+ pattern: "^FOO$",
193
+ flags: "m",
194
+ ignoreCase: true,
195
+ source: "FOO\nfoo\n",
196
+ lines: [1, 2],
197
+ },
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
+ ];
214
+
215
+ test("grep flags: JavaScript modes preserve native matching through the real search pipeline", async (t) => {
216
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-flags-"));
217
+ t.after(() => rm(directory, { recursive: true, force: true }));
218
+ const path = join(directory, "input.txt");
219
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
220
+ for (const scenario of cases) {
221
+ await t.test(scenario.name, async () => {
222
+ await writeFile(path, scenario.source);
223
+ const result = await callTool(tool, {
224
+ path,
225
+ pattern: scenario.pattern,
226
+ literal: scenario.literal ?? false,
227
+ flags: scenario.flags,
228
+ multiline: scenario.multiline ?? false,
229
+ ...(scenario.ignoreCase === undefined ? {} : { ignoreCase: scenario.ignoreCase }),
230
+ });
231
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
232
+ assert.equal(reportOf(result)?.matches, scenario.lines.length);
233
+ const body = result.content[0];
234
+ assert.ok(body.type === "text");
235
+ const lines = [...body.text.matchAll(/^(\d+)#[0-9A-Z]+│/gm)].map((match) => Number(match[1]));
236
+ assert.deepEqual(lines, scenario.lines);
237
+ });
238
+ }
239
+ });
240
+
241
+ test("grep flags: native flag and Unicode syntax errors reject the corresponding argument", async () => {
242
+ const tool = makeGrepOverrideWithBackend(process.cwd(), DEFAULT_CONFIG, {});
243
+ for (const literal of [false, true]) {
244
+ for (const flags of ["x", "uv"]) {
245
+ await assert.rejects(
246
+ callTool(tool, { path: "missing.txt", pattern: "a", literal, flags }),
247
+ rejectsArgument("flags"),
248
+ );
249
+ }
250
+ }
251
+ await assert.rejects(
252
+ callTool(tool, {
253
+ path: "missing.txt",
254
+ pattern: "\\p{NotAProperty}",
255
+ literal: false,
256
+ flags: "u",
257
+ }),
258
+ rejectsArgument("pattern"),
259
+ );
260
+ });
261
+
262
+ test("grep flags: valid V8 patterns exceeding translator parser depth still execute", async (t) => {
263
+ const directory = await mkdtemp(join(tmpdir(), "hl-grep-parser-depth-"));
264
+ t.after(() => rm(directory, { recursive: true, force: true }));
265
+ const path = join(directory, "input.txt");
266
+ await writeFile(path, "A\na\n");
267
+ const pattern = `${"(?:".repeat(3_000)}A${")".repeat(3_000)}`;
268
+ assert.equal(new RegExp(pattern).test("A"), true);
269
+ const tool = makeGrepOverrideWithBackend(directory, DEFAULT_CONFIG, {});
270
+ for (const flags of [undefined, "m"]) {
271
+ const result = await callTool(tool, {
272
+ path,
273
+ pattern,
274
+ literal: false,
275
+ ...(flags === undefined ? {} : { flags }),
276
+ });
277
+ assert.equal(result.isError, undefined, JSON.stringify(reportOf(result)));
278
+ assert.equal(reportOf(result)?.matches, 1);
279
+ }
280
+ });