@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
@@ -9,19 +9,13 @@ const theme = {
9
9
  bg: (_color: string, text: string) => text,
10
10
  bold: (text: string) => text,
11
11
  };
12
- const themeKeys = [
13
- Symbol.for("@earendil-works/pi-coding-agent:theme"),
14
- Symbol.for("@mariozechner/pi-coding-agent:theme"),
15
- ];
16
- const originalThemes = themeKeys.map((key) => Object.getOwnPropertyDescriptor(globalThis, key));
12
+ const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
13
+ const originalTheme = Object.getOwnPropertyDescriptor(globalThis, themeKey);
17
14
  before(() => initTheme("dark"));
18
- after(() =>
19
- themeKeys.forEach((key, index) => {
20
- const original = originalThemes[index];
21
- if (original) Object.defineProperty(globalThis, key, original);
22
- else Reflect.deleteProperty(globalThis, key);
23
- }),
24
- );
15
+ after(() => {
16
+ if (originalTheme) Object.defineProperty(globalThis, themeKey, originalTheme);
17
+ else Reflect.deleteProperty(globalThis, themeKey);
18
+ });
25
19
 
26
20
  function harness(entries: any[] = []) {
27
21
  const renderers = new Map<string, any>();
@@ -126,12 +120,15 @@ test("skips and cancellations stay neutral and restore their own reason", () =>
126
120
  for (const command of ["skipped", "cancelled"] as const) {
127
121
  const h = harness();
128
122
  h.report(waiting);
129
- h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
123
+ h.report({ ...waiting, command, mutationCompleted: false });
130
124
  for (const restored of [false, true]) {
131
125
  const view = restored ? harness(h.entries) : h;
132
126
  if (restored) view.restore();
133
127
  const output = view.card(h.entries[0], true).render(160).join("\n");
134
- assert.match(output, /Not run because the mutation did not complete/);
128
+ assert.match(
129
+ output,
130
+ command === "skipped" ? /Not run: the mutation did not complete/ : /Not run: cancelled/,
131
+ );
135
132
  assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
136
133
  assert.ok(!view.backgrounds.includes("toolErrorBg"));
137
134
  assert.ok(!view.backgrounds.includes("toolSuccessBg"));
@@ -165,3 +162,32 @@ test("timed command cards show remaining seconds only while actively running", (
165
162
  restored.restore();
166
163
  assert.doesNotMatch(restored.card(h.entries[0]).render(160).join("\n"), /remaining/);
167
164
  });
165
+
166
+ test("invalid persisted command snapshots → do not replace valid progress or become executable cards", () => {
167
+ const original = harness();
168
+ original.report(waiting);
169
+ const initial = original.entries[0];
170
+ for (const invalid of [
171
+ ...["mutationCompleted", "freshness"].map((missing) =>
172
+ Object.fromEntries(
173
+ Object.entries({ ...initial.data, command: "succeeded" }).filter(
174
+ ([key]) => key !== missing,
175
+ ),
176
+ ),
177
+ ),
178
+ { ...initial.data, command: "not-a-command-status" },
179
+ { ...initial.data, freshness: "fresh" },
180
+ { ...initial.data, mutationCompleted: "yes" },
181
+ { ...initial.data, timing: { timeoutSeconds: -1, remainingSeconds: 2 } },
182
+ { ...initial.data, timing: { timeoutSeconds: 3, remainingSeconds: "2" } },
183
+ { ...initial.data, foreign: true },
184
+ ]) {
185
+ const malformed = { ...initial, data: invalid };
186
+ const resumed = harness([initial, { ...malformed, customType: "hashline-then-run-result" }]);
187
+ resumed.restore();
188
+ assert.equal(resumed.card(malformed), undefined);
189
+ const shown = resumed.card(initial).render(160).join("\n");
190
+ assert.match(shown, /interrupted \(final status unknown\)/);
191
+ assert.doesNotMatch(shown, /not-a-command-status|remaining/);
192
+ }
193
+ });
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Action Fusion presentation: the mutation card shell that keeps the file
3
- * result's status independent of the fused command, and the separate
4
- * transcript card for each then_run command.
2
+ * Action Fusion presentation: the mutation card follows file mutation completion;
3
+ * a separate transcript card follows each then_run command's output and outcome.
5
4
  *
6
5
  * @module pi-hashline-edit/pi
7
6
  */
@@ -13,36 +12,68 @@ import type {
13
12
  } from "@earendil-works/pi-coding-agent";
14
13
  import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
15
14
  import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
16
- import type { TSchema } from "typebox";
15
+ import { Type, type Static, type TSchema } from "typebox";
16
+ import { Value } from "typebox/value";
17
+ import { ACTION_FUSION_PROGRESS_SCHEMA } from "./report-schema.ts";
17
18
  import type { ActionFusionProgress } from "./action-fusion.ts";
18
- import { renderToolError, type MutationRenderState } from "./render.ts";
19
+ import type { MutationRenderState } from "./render.ts";
19
20
 
20
21
  const CARD_TYPE = "hashline-then-run";
21
22
  const RESULT_TYPE = "hashline-then-run-result";
22
23
 
23
- type CommandCardData = Pick<
24
- ActionFusionProgress,
25
- "toolCallId" | "commandText" | "command" | "output" | "reason" | "timing"
26
- >;
24
+ const CARD_PROPERTIES = ACTION_FUSION_PROGRESS_SCHEMA.properties;
25
+ const COMMAND_CARD_SCHEMA = Type.Object(
26
+ {
27
+ toolCallId: CARD_PROPERTIES.toolCallId,
28
+ commandText: CARD_PROPERTIES.commandText,
29
+ command: CARD_PROPERTIES.command,
30
+ output: CARD_PROPERTIES.output,
31
+ timing: CARD_PROPERTIES.timing,
32
+ mutationCompleted: CARD_PROPERTIES.mutationCompleted,
33
+ freshness: CARD_PROPERTIES.freshness,
34
+ },
35
+ { additionalProperties: false },
36
+ );
37
+ type CommandCardData = Static<typeof COMMAND_CARD_SCHEMA>;
27
38
 
28
39
  function commandCardData({
29
40
  toolCallId,
30
41
  commandText,
31
42
  command,
32
43
  output,
33
- reason,
34
44
  timing,
45
+ mutationCompleted,
46
+ freshness,
35
47
  }: ActionFusionProgress): CommandCardData {
36
48
  return {
37
49
  toolCallId,
38
50
  commandText,
39
51
  command,
40
52
  output,
41
- ...(reason ? { reason } : {}),
53
+ mutationCompleted,
54
+ freshness,
42
55
  ...(timing ? { timing } : {}),
43
56
  };
44
57
  }
45
58
 
59
+ const TARGET_STATE = {
60
+ changed: "the target changed after the mutation",
61
+ missing: "the target is missing after the mutation",
62
+ unknown: "the target revision could not be read",
63
+ } as const;
64
+
65
+ /**
66
+ * Why a command never started, derived from the same facts the mutation result
67
+ * states: whether the mutation completed and the target's freshness.
68
+ */
69
+ function notRunReason(card: CommandCardData): string | undefined {
70
+ if (card.command === "cancelled" && !card.output) return "Not run: cancelled.";
71
+ if (card.command !== "skipped") return undefined;
72
+ const { mutationCompleted, freshness } = card;
73
+ if (!mutationCompleted) return "Not run: the mutation did not complete.";
74
+ return freshness === "unchanged" ? undefined : `Not run: ${TARGET_STATE[freshness]}.`;
75
+ }
76
+
46
77
  /** Render one durable transcript card per fused command without adding model context. */
47
78
  export function registerFusionCards(pi: ExtensionAPI) {
48
79
  let currentCwd = process.cwd();
@@ -60,15 +91,8 @@ export function registerFusionCards(pi: ExtensionAPI) {
60
91
  (entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)
61
92
  )
62
93
  continue;
63
- const data = entry.data as ActionFusionProgress | undefined;
64
- if (
65
- data &&
66
- typeof data.toolCallId === "string" &&
67
- typeof data.commandText === "string" &&
68
- typeof data.output === "string"
69
- ) {
70
- states.set(data.toolCallId, commandCardData(data));
71
- }
94
+ const data = entry.data;
95
+ if (Value.Check(COMMAND_CARD_SCHEMA, data)) states.set(data.toolCallId, data);
72
96
  }
73
97
  };
74
98
  pi.on("session_start", (_event, ctx) => restore(ctx));
@@ -76,7 +100,7 @@ export function registerFusionCards(pi: ExtensionAPI) {
76
100
 
77
101
  pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
78
102
  const initial = entry.data;
79
- if (!initial) return undefined;
103
+ if (!Value.Check(COMMAND_CARD_SCHEMA, initial)) return undefined;
80
104
  const statusText = new Text("", 0, 0);
81
105
  const box = new Box(1, 1);
82
106
  let call: Component | undefined;
@@ -136,7 +160,8 @@ export function registerFusionCards(pi: ExtensionAPI) {
136
160
  box.clear();
137
161
  box.addChild(statusText);
138
162
  box.addChild(call);
139
- if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
163
+ const reason = notRunReason(current);
164
+ if (reason) box.addChild(new Text(theme.fg("dim", reason), 0, 0));
140
165
  if (current.output || current.command === "succeeded" || failed) {
141
166
  result = bash.renderResult!(
142
167
  { content: [{ type: "text", text: current.output }], details: undefined },
@@ -165,20 +190,36 @@ export function registerFusionCards(pi: ExtensionAPI) {
165
190
  };
166
191
  }
167
192
 
193
+ type MutationCardProgress = Partial<Pick<ActionFusionProgress, "mutationCompleted">>;
194
+
195
+ function mutationPending(isPartial: boolean, progress?: MutationCardProgress): boolean {
196
+ return isPartial && progress?.mutationCompleted !== true;
197
+ }
198
+
168
199
  /** Mutation render state plus the shell that keeps the card status independent of then_run. */
169
200
  interface FusedMutationRenderState extends MutationRenderState {
170
201
  mutationShell?: {
171
202
  box: Box;
172
203
  call?: Component;
173
204
  result?: Component;
174
- fileState?: { freshness?: string };
205
+ fileState?: MutationCardProgress;
175
206
  };
176
207
  }
177
208
 
178
- /** Keep the mutation card's background independent of the fused command's lifetime. */
179
- export function withMutationStatus<TParams extends TSchema, TDetails>(
180
- tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
181
- ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
209
+ type MutationCardTool<TParams extends TSchema, TDetails, TRenderDetails> = Omit<
210
+ ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
211
+ "renderResult"
212
+ > &
213
+ Pick<ToolDefinition<TParams, TRenderDetails, FusedMutationRenderState>, "renderResult">;
214
+
215
+ /** Finish the mutation card independently while the fused command remains active. */
216
+ export function withMutationStatus<
217
+ TParams extends TSchema,
218
+ TDetails extends TRenderDetails,
219
+ TRenderDetails,
220
+ >(
221
+ tool: MutationCardTool<TParams, TDetails, TRenderDetails>,
222
+ ): MutationCardTool<TParams, TDetails, TRenderDetails> {
182
223
  return {
183
224
  ...tool,
184
225
  renderShell: "self",
@@ -189,7 +230,11 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
189
230
  shell.box.addChild(shell.call);
190
231
  shell.box.setBgFn((line: string) =>
191
232
  theme.bg(
192
- context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
233
+ mutationPending(context.isPartial, shell.fileState)
234
+ ? "toolPendingBg"
235
+ : context.isError
236
+ ? "toolErrorBg"
237
+ : "toolSuccessBg",
193
238
  line,
194
239
  ),
195
240
  );
@@ -197,30 +242,19 @@ export function withMutationStatus<TParams extends TSchema, TDetails>(
197
242
  },
198
243
  renderResult(result, options, theme, context) {
199
244
  const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
200
- const details = result.details as
201
- | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
202
- | undefined;
203
- const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
204
- // Pi serializes fused failures into one diagnostic; retain it when the card expands.
205
- const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
206
- shell.result = fusedError
207
- ? renderToolError(result, theme, options.expanded)
208
- : tool.renderResult!(result, { ...options, isPartial }, theme, {
209
- ...context,
210
- isPartial,
211
- lastComponent: shell.result,
212
- });
245
+ // Fusion updates carry progress alongside TDetails; final results carry only the outcome.
246
+ const details = result.details as { actionFusion?: MutationCardProgress } | undefined;
247
+ const file = details?.actionFusion ?? shell.fileState;
248
+ const isPartial = mutationPending(options.isPartial, file);
249
+ // The tool's renderer shows failures and the report's freshness facts.
250
+ shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, {
251
+ ...context,
252
+ isPartial,
253
+ lastComponent: shell.result,
254
+ });
213
255
  // Pi runs renderCall first; update its box in place without invalidating the tool row.
214
256
  shell.box.addChild(shell.result);
215
- const file = details?.actionFusion ?? shell.fileState;
216
- if (file) {
217
- shell.fileState = { freshness: file.freshness };
218
- if (file.freshness === "changed" || file.freshness === "missing") {
219
- shell.box.addChild(
220
- new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
221
- );
222
- }
223
- }
257
+ if (file) shell.fileState = { mutationCompleted: file.mutationCompleted };
224
258
  shell.box.setBgFn((line: string) =>
225
259
  theme.bg(
226
260
  isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
@@ -0,0 +1,127 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { candidateArgs, runCandidatePaths, MAX_PREFILTER_PATH_BYTES } from "./grep-candidates.ts";
4
+ import { COMMON_RG_ARGS, type GrepBackend } from "./rg-process.ts";
5
+ import type { Prefilter } from "../core/search-analysis.ts";
6
+
7
+ test("candidate literals → rg lists files with escaped byte-preserving alternatives", () => {
8
+ assert.deepEqual(candidateArgs({ kind: "all" }), [...COMMON_RG_ARGS, "--files"]);
9
+ for (const [literals, pattern] of [
10
+ [
11
+ [
12
+ [["a"], ["."], ["b"]],
13
+ [["-"], ["é"]],
14
+ ],
15
+ "a\\x{2e}b|\\x{2d}\\x{e9}",
16
+ ],
17
+ [[[["K", "k", "K"], ["_"], ["9"]]], "[Kk\\x{212a}]_9"],
18
+ ] as const) {
19
+ assert.deepEqual(candidateArgs({ kind: "literals", literals }), [
20
+ ...COMMON_RG_ARGS,
21
+ "--files-with-matches",
22
+ "--engine=default",
23
+ "--case-sensitive",
24
+ "--encoding=none",
25
+ "-e",
26
+ pattern,
27
+ ]);
28
+ }
29
+ });
30
+
31
+ const conjunction: Prefilter = {
32
+ kind: "and",
33
+ filters: [
34
+ { kind: "literals", literals: [[["a"]]] },
35
+ { kind: "literals", literals: [[["b"]]] },
36
+ ],
37
+ };
38
+
39
+ test("AND file passes → intersect paths before emitting and preserve final callback stop", async () => {
40
+ let pass = 0;
41
+ const calls: string[][] = [];
42
+ const run: GrepBackend["runRgPaths"] = async (_rg, args, _signal, onPath) => {
43
+ calls.push([...args]);
44
+ for (const path of [
45
+ ["a-only", "both"],
46
+ ["b-only", "both", "later"],
47
+ ][pass++])
48
+ if (!(await onPath(path))) return { code: null, stderr: "", stopped: true };
49
+ return { code: 0, stderr: "", stopped: false };
50
+ };
51
+ const paths: string[] = [];
52
+ const result = await runCandidatePaths(
53
+ run,
54
+ "rg",
55
+ conjunction,
56
+ ["--", "root"],
57
+ undefined,
58
+ (path) => {
59
+ paths.push(path);
60
+ return false;
61
+ },
62
+ );
63
+ assert.deepEqual(paths, ["both"]);
64
+ assert.equal(result.stopped, true);
65
+ assert.equal(calls.length, 2);
66
+ for (const args of calls) assert.deepEqual(args.slice(-2), ["--", "root"]);
67
+ });
68
+
69
+ test("AND path retention fills → rerun one necessary clause without excluding its candidates", async () => {
70
+ let pass = 0;
71
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, _signal, onPath) => {
72
+ const keepGoing = await onPath(
73
+ pass++ === 0 ? "x".repeat(MAX_PREFILTER_PATH_BYTES + 1) : "candidate",
74
+ );
75
+ return { code: keepGoing ? 0 : null, stderr: "", stopped: !keepGoing };
76
+ };
77
+ const paths: string[] = [];
78
+ const result = await runCandidatePaths(
79
+ run,
80
+ "rg",
81
+ conjunction,
82
+ ["--", "root"],
83
+ undefined,
84
+ (path) => {
85
+ paths.push(path);
86
+ return true;
87
+ },
88
+ );
89
+ assert.deepEqual(paths, ["candidate"]);
90
+ assert.equal(pass, 2);
91
+ assert.equal(result.stopped, false);
92
+ });
93
+
94
+ test("incomplete intermediate pass → retain reported candidates and the failure diagnostics", async () => {
95
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, _signal, onPath) => {
96
+ await onPath("reported");
97
+ return { code: 2, stderr: "unreadable path", stopped: false };
98
+ };
99
+ const paths: string[] = [];
100
+ const result = await runCandidatePaths(run, "rg", conjunction, [], undefined, (path) => {
101
+ paths.push(path);
102
+ return true;
103
+ });
104
+ assert.deepEqual(paths, ["reported"]);
105
+ assert.equal(result.code, 2);
106
+ assert.match(result.stderr, /unreadable path/);
107
+ });
108
+
109
+ test("cancel between AND passes → propagate cancellation before emitting candidates", async () => {
110
+ const controller = new AbortController();
111
+ let pass = 0;
112
+ const run: GrepBackend["runRgPaths"] = async (_rg, _args, signal, onPath) => {
113
+ assert.equal(signal, controller.signal);
114
+ if (pass++) {
115
+ controller.abort(new Error("cancelled"));
116
+ signal?.throwIfAborted();
117
+ }
118
+ await onPath("candidate");
119
+ return { code: 0, stderr: "", stopped: false };
120
+ };
121
+ await assert.rejects(
122
+ runCandidatePaths(run, "rg", conjunction, [], controller.signal, () =>
123
+ assert.fail("cancelled candidate"),
124
+ ),
125
+ /cancelled/,
126
+ );
127
+ });
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Candidate selection: rg lists candidate lines through the rg-regex translation, or candidate
3
+ * files through the prefilter's necessary literals, with conservative fallback and a
4
+ * whole-scope scan budget. rg-process runs rg and parses its records; this module decides
5
+ * which rg runs to make.
6
+ *
7
+ * @module pi-hashline-edit/pi
8
+ */
9
+ import { stat } from "node:fs/promises";
10
+ import { resolve } from "node:path";
11
+ import type { GrepQuery } from "../core/search.ts";
12
+ import { extractPrefilter, type Literal, type Prefilter } from "../core/search-analysis.ts";
13
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
14
+ import { scopeArgs, type SearchScope } from "./grep-scope.ts";
15
+ import {
16
+ COMMON_RG_ARGS,
17
+ LINE_LISTING_ARGS,
18
+ MAX_RG_STDERR_BYTES,
19
+ type GrepBackend,
20
+ type RgRunResult,
21
+ } from "./rg-process.ts";
22
+ import { lineCandidatePatterns } from "./rg-regex.ts";
23
+
24
+ /** Beyond this many candidate lines, a file's every line is checked instead. */
25
+ const MAX_CANDIDATE_LINES = 64 * 1024;
26
+ /**
27
+ * When every file in scope is a candidate, files stop being listed once this many bytes of
28
+ * them were queued; README's search limits link here.
29
+ */
30
+ export const MAX_UNNARROWED_SCAN_BYTES = 256 * 1024 * 1024;
31
+ /** Maximum retained paths while intersecting necessary file conditions. */
32
+ export const MAX_PREFILTER_PATH_BYTES = 4 * 1024 * 1024;
33
+ /** Candidate patterns match original bytes exactly as written; JavaScript decides case and encoding. */
34
+ const BYTE_PATTERN_ARGS = ["--engine=default", "--case-sensitive", "--encoding=none"];
35
+
36
+ /** An absolute file path to check: only its ascending candidate lines, or every line when absent. */
37
+ export interface Candidate {
38
+ readonly filePath: string;
39
+ readonly lines?: readonly number[];
40
+ }
41
+
42
+ /** A literal's characters as one rg pattern; every non-word character is a code point escape. */
43
+ function literalPattern(literal: Literal): string {
44
+ const escape = (char: string) =>
45
+ /^[0-9A-Za-z_]$/.test(char) ? char : `\\x{${char.codePointAt(0)!.toString(16)}}`;
46
+ return literal
47
+ .map((chars) => (chars.length === 1 ? escape(chars[0]) : `[${chars.map(escape).join("")}]`))
48
+ .join("");
49
+ }
50
+
51
+ /**
52
+ * List candidate files: those whose original bytes contain a prefilter literal, or every
53
+ * file in scope. Literals never contain a line break, so line-oriented matching finds them.
54
+ */
55
+ export function candidateArgs(prefilter: Prefilter): string[] {
56
+ if (prefilter.kind === "and") return candidateArgs(prefilter.filters[0]);
57
+ if (prefilter.kind === "all") return [...COMMON_RG_ARGS, "--files"];
58
+ return [
59
+ ...COMMON_RG_ARGS,
60
+ "--files-with-matches",
61
+ ...BYTE_PATTERN_ARGS,
62
+ "-e",
63
+ prefilter.literals.map(literalPattern).join("|"),
64
+ ];
65
+ }
66
+
67
+ /** Execute AND-of-OR file conditions, falling back to one necessary clause if retention fills. */
68
+ export async function runCandidatePaths(
69
+ run: GrepBackend["runRgPaths"],
70
+ rgPath: string,
71
+ prefilter: Prefilter,
72
+ scopedArgs: readonly string[],
73
+ signal: AbortSignal | undefined,
74
+ onFile: (path: string) => boolean | Promise<boolean>,
75
+ ): Promise<RgRunResult> {
76
+ const filters = prefilter.kind === "and" ? prefilter.filters : [prefilter];
77
+ const diagnostics = new DiagnosticBuffer(MAX_RG_STDERR_BYTES);
78
+ let allowed: ReadonlySet<string> | undefined;
79
+ for (const [index, filter] of filters.entries()) {
80
+ const last = index === filters.length - 1;
81
+ const paths = new Set<string>();
82
+ let bytes = 0;
83
+ let overflow = false;
84
+ const result = await run(
85
+ rgPath,
86
+ [...candidateArgs(filter), "--null", ...scopedArgs],
87
+ signal,
88
+ async (path) => {
89
+ if (allowed && !allowed.has(path)) return true;
90
+ if (last) return onFile(path);
91
+ if (!paths.has(path)) {
92
+ paths.add(path);
93
+ bytes += Buffer.byteLength(path);
94
+ }
95
+ overflow = bytes > MAX_PREFILTER_PATH_BYTES;
96
+ return !overflow;
97
+ },
98
+ );
99
+ if (result.stderr) diagnostics.append(`${result.stderr}\n`);
100
+ if (overflow) {
101
+ const fallback = await run(
102
+ rgPath,
103
+ [...candidateArgs(filters[0]), "--null", ...scopedArgs],
104
+ signal,
105
+ onFile,
106
+ );
107
+ if (fallback.stderr) diagnostics.append(fallback.stderr);
108
+ return { ...fallback, stderr: diagnostics.toString() };
109
+ }
110
+ if (last || result.stopped || (result.code !== 0 && result.code !== 1)) {
111
+ // An incomplete intermediate listing cannot exclude its already reported candidates.
112
+ if (!last) for (const path of paths) if (!(await onFile(path))) break;
113
+ return { ...result, stderr: diagnostics.toString() };
114
+ }
115
+ if (!paths.size) return { code: 1, stderr: diagnostics.toString(), stopped: false };
116
+ allowed = paths;
117
+ }
118
+ return { code: 1, stderr: diagnostics.toString(), stopped: false };
119
+ }
120
+
121
+ /** How candidates were selected: rg's candidate lines, or whole files (see Prefilter). */
122
+ export type CandidateSource = "lines" | "files" | "all";
123
+
124
+ /**
125
+ * Await each consumer for backpressure; false stops listing. The caller owns worker cleanup.
126
+ * An empty scope lists nothing, because rg would search the working directory instead.
127
+ */
128
+ export async function listCandidates(options: {
129
+ readonly backend: GrepBackend;
130
+ readonly rgPath: string;
131
+ readonly scope: SearchScope;
132
+ readonly query: GrepQuery;
133
+ readonly signal: AbortSignal;
134
+ readonly onCandidate: (candidate: Candidate) => Promise<boolean>;
135
+ }): Promise<{
136
+ readonly listing?: RgRunResult;
137
+ readonly candidates: CandidateSource;
138
+ readonly scanLimitReached: boolean;
139
+ }> {
140
+ const { backend, rgPath, scope, query, signal, onCandidate } = options;
141
+ if (scope.searchPaths.length === 0) return { candidates: "lines", scanLimitReached: false };
142
+ let listedAny = false;
143
+ const offer = (path: string, lines?: readonly number[]) => {
144
+ listedAny = true;
145
+ return onCandidate({ filePath: resolve(path), lines });
146
+ };
147
+ let candidates: CandidateSource = "lines";
148
+ let scanned = 0;
149
+ let scanLimitReached = false;
150
+ const offerWithinBudget = async (path: string) => {
151
+ if (scanned >= MAX_UNNARROWED_SCAN_BYTES) {
152
+ scanLimitReached = true;
153
+ return false;
154
+ }
155
+ scanned += await stat(resolve(path)).then(
156
+ ({ size }) => size,
157
+ // The search reports unreadable files; a failed size probe must not exclude them.
158
+ () => 0,
159
+ );
160
+ return offer(path);
161
+ };
162
+ const scoped = [...scopeArgs(scope), "--", ...scope.searchPaths];
163
+ const patterns = query.multiline ? undefined : lineCandidatePatterns(query);
164
+ let listing = patterns
165
+ ? await backend.runRgLines(
166
+ rgPath,
167
+ [
168
+ ...COMMON_RG_ARGS,
169
+ ...BYTE_PATTERN_ARGS,
170
+ ...LINE_LISTING_ARGS,
171
+ ...patterns.flatMap((pattern) => ["-e", pattern]),
172
+ ...scoped,
173
+ ],
174
+ signal,
175
+ MAX_CANDIDATE_LINES,
176
+ offer,
177
+ )
178
+ : undefined;
179
+ // rg reports a pattern it cannot compile, such as one beyond its size limit, before any file.
180
+ if (!listing || (listing.code === 2 && !listedAny)) {
181
+ const prefilter = extractPrefilter(query);
182
+ candidates = prefilter.kind === "all" ? "all" : "files";
183
+ listing = await runCandidatePaths(
184
+ backend.runRgPaths,
185
+ rgPath,
186
+ prefilter,
187
+ scoped,
188
+ signal,
189
+ candidates === "all" ? offerWithinBudget : (path) => offer(path),
190
+ );
191
+ }
192
+ return { listing, candidates, scanLimitReached };
193
+ }