@criogaid/pi-hashline-edit 0.4.0 → 0.5.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 (60) hide show
  1. package/README.md +116 -20
  2. package/package.json +3 -3
  3. package/src/core/apply.test.ts +194 -104
  4. package/src/core/apply.ts +6 -37
  5. package/src/core/errors.ts +9 -0
  6. package/src/core/hash.test.ts +8 -8
  7. package/src/core/hash.ts +5 -5
  8. package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
  9. package/src/core/text.ts +1 -3
  10. package/src/core/types.ts +4 -7
  11. package/src/index.ts +9 -11
  12. package/src/integration/config-registration.test.ts +206 -0
  13. package/src/integration/grep-rg.test.ts +73 -60
  14. package/src/integration/large-text.test.ts +9 -8
  15. package/src/integration/replace-package.test.ts +11 -7
  16. package/src/pi/action-fusion.test.ts +110 -34
  17. package/src/pi/action-fusion.ts +77 -114
  18. package/src/pi/anchor-format.test.ts +43 -22
  19. package/src/pi/anchor-format.ts +23 -8
  20. package/src/pi/budgets.ts +7 -2
  21. package/src/pi/config.test.ts +153 -40
  22. package/src/pi/config.ts +87 -41
  23. package/src/pi/e2e-scenarios.test.ts +12 -11
  24. package/src/pi/edit-tool.ts +20 -156
  25. package/src/pi/error-text.ts +10 -5
  26. package/src/pi/execute.test.ts +299 -175
  27. package/src/pi/failure-context.test.ts +7 -2
  28. package/src/pi/failure-context.ts +155 -8
  29. package/src/pi/failure-path.test.ts +33 -26
  30. package/src/pi/file-commit.ts +2 -1
  31. package/src/pi/fusion-card.ts +83 -2
  32. package/src/pi/grep-output.ts +26 -9
  33. package/src/pi/grep-render.ts +6 -5
  34. package/src/pi/grep-scope.ts +2 -15
  35. package/src/pi/grep-search.ts +29 -15
  36. package/src/pi/grep-tool.ts +94 -78
  37. package/src/pi/grep.test.ts +357 -320
  38. package/src/pi/mutation-outcome.testing.ts +22 -0
  39. package/src/pi/mutation-result.test.ts +51 -2
  40. package/src/pi/mutation-result.ts +62 -55
  41. package/src/pi/mutation-runner.ts +16 -33
  42. package/src/pi/pi.test.ts +10 -5
  43. package/src/pi/read-tool.ts +61 -33
  44. package/src/pi/registration.test.ts +1 -5
  45. package/src/pi/render.test.ts +16 -8
  46. package/src/pi/render.ts +4 -91
  47. package/src/pi/replace-regex.ts +54 -0
  48. package/src/pi/replace-tool.ts +24 -58
  49. package/src/pi/replace-worker.ts +2 -2
  50. package/src/pi/replace.test.ts +62 -58
  51. package/src/pi/result-safety.test.ts +124 -84
  52. package/src/pi/rg-line-ranges.ts +3 -2
  53. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  54. package/src/pi/{rg-line-filter.ts → rg-process.ts} +35 -4
  55. package/src/pi/rg-text-view.ts +17 -33
  56. package/src/pi/schema.ts +2 -10
  57. package/src/pi/write-tool.ts +1 -2
  58. package/src/pi/write.test.ts +10 -9
  59. package/src/core/index.ts +0 -14
  60. package/src/pi/state.ts +0 -26
@@ -89,7 +89,7 @@ test("ambiguous context preserves complete rows at the byte budget", () => {
89
89
  const exact = "x".repeat(16 * 1024 - Buffer.byteLength("1#XXXX│\n"));
90
90
  const lines = [exact, "target", "last"];
91
91
  const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
92
- assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact)}│${exact}\n`));
92
+ assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact, 4)}│${exact}\n`));
93
93
  assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
94
94
  assert.match(byteLimited, /truncated: byte limit/);
95
95
  assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
@@ -131,7 +131,12 @@ test("unique candidates inside ambiguous neighborhoods retain the candidate row
131
131
  const lines = ["prefix", "x".repeat(4096), "match", "match"];
132
132
  const output = format(lines.join("\n"), [
133
133
  ambiguous(lines, [3, 4]),
134
- failure({ kind: "found", scope: "local", newLine: 2, newHash: computeLineHash(2, lines[1]) }),
134
+ failure({
135
+ kind: "found",
136
+ scope: "local",
137
+ newLine: 2,
138
+ newHash: computeLineHash(2, lines[1], 4),
139
+ }),
135
140
  ]).text;
136
141
  assert.match(output, /truncated: candidate row limit/);
137
142
  assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
@@ -1,11 +1,24 @@
1
+ /**
2
+ * Bounded anchor-failure diagnostics for edit: failure details with recovery
3
+ * candidates, input-anchor checks, and ambiguous-candidate neighborhoods.
4
+ *
5
+ * @module pi-hashline-edit/pi
6
+ */
7
+
8
+ import { truncateHead } from "@earendil-works/pi-coding-agent";
1
9
  import type { AnchorFormatter } from "./anchor-format.ts";
2
10
  import { splitLines } from "../core/lines.ts";
3
- import type { AnchorFailure } from "../core/types.ts";
11
+ import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
4
12
  import { mergeRanges } from "../core/ranges.ts";
5
- import { MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
13
+ import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
6
14
 
7
15
  const CONTEXT_RADIUS = 3;
8
- export const MAX_AMBIGUOUS_CANDIDATES = 8;
16
+ const MAX_AMBIGUOUS_CANDIDATES = 8;
17
+
18
+ /** Select the shared candidate prefix for detail lists and observation neighborhoods. */
19
+ export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
20
+ return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
21
+ }
9
22
 
10
23
  type Interval = { lo: number; hi: number };
11
24
  type ContextRow = { line: number; text: string };
@@ -82,9 +95,7 @@ export function formatAmbiguousCandidateNeighborhoods(
82
95
  ): { text: string; shownLines: ReadonlySet<number> } {
83
96
  const centers = failures.flatMap((failure) =>
84
97
  failure.recovery.kind === "ambiguous"
85
- ? failure.recovery.candidates
86
- .slice(0, MAX_AMBIGUOUS_CANDIDATES)
87
- .map((candidate) => candidate.line)
98
+ ? selectAmbiguousCandidates(failure.recovery.candidates).map((candidate) => candidate.line)
88
99
  : [],
89
100
  );
90
101
  if (centers.length === 0) return { text: "", shownLines: new Set() };
@@ -95,7 +106,7 @@ export function formatAmbiguousCandidateNeighborhoods(
95
106
  if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
96
107
  }
97
108
  const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
98
- const body = ["Ambiguous-candidate neighborhoods (+/-3; observation only):"];
109
+ const body = [`Ambiguous-candidate neighborhoods (+/-${CONTEXT_RADIUS}; observation only):`];
99
110
  if (rows.length === 0) {
100
111
  body.push("No complete neighborhood row fits the limits.");
101
112
  } else {
@@ -106,8 +117,144 @@ export function formatAmbiguousCandidateNeighborhoods(
106
117
  `Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`,
107
118
  );
108
119
  body.push(
109
- `Candidate neighborhoods truncated: ${truncatedBy} (16384 bytes; candidate row 4096 bytes; lowest lines first).`,
120
+ `Candidate neighborhoods truncated: ${truncatedBy} (${formatKiB(MAX_BLOCK_BYTES)}; candidate row ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}; lowest lines first).`,
110
121
  );
111
122
  }
112
123
  return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
113
124
  }
125
+
126
+ /** Keep independent byte budgets for failure details and input-anchor checks. */
127
+ function boundDiagnostic(message: string, notice: string): string {
128
+ const bounded = truncateHead(message, { maxBytes: MAX_BLOCK_BYTES - Buffer.byteLength(notice) });
129
+ return bounded.content + (bounded.truncated ? notice : "");
130
+ }
131
+ /** Format failure mappings and complete unique-candidate rows within the detail budget. */
132
+ function formatFailureDetails(
133
+ failure: ApplyFailure,
134
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
135
+ candidateLines: ReadonlySet<number>,
136
+ ): string {
137
+ if (failure.kind !== "anchor") return failure.message;
138
+
139
+ const lines: string[] = [];
140
+ const currentLines = splitLines(snapshot.currentText);
141
+ const shownCandidates = new Set(candidateLines);
142
+ let found = 0;
143
+ let ambiguous = 0;
144
+ let none = 0;
145
+ for (const f of failure.failures) {
146
+ if (f.recovery.kind === "found") found++;
147
+ else if (f.recovery.kind === "ambiguous") ambiguous++;
148
+ else none++;
149
+ const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
150
+ const search =
151
+ f.recovery.kind === "none"
152
+ ? ""
153
+ : f.recovery.scope === "local"
154
+ ? "Search: local; matches outside the window were not checked."
155
+ : "Search: full file.";
156
+ switch (f.recovery.kind) {
157
+ case "found": {
158
+ const content = currentLines[f.recovery.newLine - 1];
159
+ const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
160
+ const row =
161
+ content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
162
+ let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
163
+ if (!shownCandidates.has(f.recovery.newLine)) {
164
+ if (
165
+ content !== undefined &&
166
+ Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES
167
+ ) {
168
+ detail += `\n${row}`;
169
+ shownCandidates.add(f.recovery.newLine);
170
+ } else {
171
+ detail += ` Candidate content exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`;
172
+ }
173
+ }
174
+ lines.push(detail);
175
+ break;
176
+ }
177
+ case "ambiguous": {
178
+ const candidates = selectAmbiguousCandidates(f.recovery.candidates);
179
+ const list = candidates
180
+ .map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`)
181
+ .join(" / ");
182
+ const omitted = f.recovery.candidates.length - candidates.length;
183
+ const more = omitted ? ` (${omitted} more candidates omitted)` : "";
184
+ lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
185
+ break;
186
+ }
187
+ case "none": {
188
+ const row =
189
+ f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
190
+ if (row !== null && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
191
+ lines.push(
192
+ `• ${where}: no checksum-matching candidate found. Current cited line (validation snapshot; observation only):\n${row}\nConfirm this is the intended target before reusing its anchor directly; retries revalidate.`,
193
+ );
194
+ } else {
195
+ lines.push(
196
+ `• ${where}: no checksum-matching candidate found. Use read or grep to inspect the current file before retrying.` +
197
+ (f.current === null
198
+ ? " Cited line is out of range."
199
+ : ` Current row exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`),
200
+ );
201
+ }
202
+ break;
203
+ }
204
+ }
205
+ }
206
+ const parts: string[] = [];
207
+ if (found) parts.push(`${found} shifted`);
208
+ if (ambiguous) parts.push(`${ambiguous} ambiguous`);
209
+ if (none) parts.push(`${none} unresolved`);
210
+ const message = [
211
+ `Anchor mismatch: ${parts.join(", ")}.`,
212
+ "No changes written by this edit batch.",
213
+ ...lines,
214
+ ].join("\n");
215
+ return boundDiagnostic(
216
+ message,
217
+ `\nDiagnostic output truncated at ${formatKiB(MAX_BLOCK_BYTES)}.`,
218
+ );
219
+ }
220
+
221
+ function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
222
+ const rows = failure.checks.map(
223
+ (check) =>
224
+ `op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
225
+ );
226
+ const message = [
227
+ "Input-anchor checks (this snapshot):",
228
+ ...rows,
229
+ "Anchor checks only; retries revalidate.",
230
+ ].join("\n");
231
+ return boundDiagnostic(
232
+ message,
233
+ `\nAnchor-check output truncated at ${formatKiB(MAX_BLOCK_BYTES)}; omitted entries are not implied matched.`,
234
+ );
235
+ }
236
+
237
+ /** Keep validation status and observation context visible even when failure details are truncated. */
238
+ export function formatFailure(
239
+ failure: ApplyFailure,
240
+ snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
241
+ isBatch: boolean,
242
+ ): string {
243
+ const candidateNeighborhoods =
244
+ failure.kind === "anchor"
245
+ ? formatAmbiguousCandidateNeighborhoods(
246
+ snapshot.currentText,
247
+ failure.failures,
248
+ snapshot.anchors,
249
+ )
250
+ : { text: "", shownLines: new Set<number>() };
251
+ const guidance =
252
+ failure.kind === "anchor"
253
+ ? "\nCheck the intended target before retrying; use read or grep for omitted or additional context."
254
+ : "";
255
+ const anchorChecks =
256
+ isBatch && failure.checks.length > 0
257
+ ? `\n${formatAnchorChecks(failure, snapshot.anchors)}`
258
+ : "";
259
+ return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}${anchorChecks}${candidateNeighborhoods.text}${guidance}`;
260
+ }
@@ -3,8 +3,15 @@ import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import assert from "node:assert/strict";
5
5
  import { test } from "node:test";
6
- import { createActionFusionExecutor, ActionFusionError } from "./action-fusion.ts";
7
- import { byteRevision, FileMutationError } from "./file-commit.ts";
6
+ import {
7
+ createActionFusionExecutor,
8
+ ActionFusionError,
9
+ THEN_RUN_STALE,
10
+ THEN_RUN_SUCCEEDED,
11
+ } from "./action-fusion.ts";
12
+ import { FileMutationError } from "./file-commit.ts";
13
+ import { staleTargetNotice } from "./mutation-result.ts";
14
+ import { publishedMutation } from "./mutation-outcome.testing.ts";
8
15
 
9
16
  async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
10
17
  const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
@@ -16,10 +23,11 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
16
23
  }
17
24
 
18
25
  const context = (cwd: string) => ({ cwd }) as any;
19
- const result = (content: string) => ({
20
- content: [{ type: "text" as const, text: "mutation" }],
21
- details: { publication: "PUBLISHED", publishedRevision: byteRevision(content) },
22
- });
26
+ const result = (content: string) =>
27
+ publishedMutation(content, {
28
+ content: [{ type: "text", text: "mutation" }],
29
+ details: undefined,
30
+ });
23
31
 
24
32
  test("published post-processing failure skips command and preserves publication state", async () =>
25
33
  withTemp(async (dir) => {
@@ -82,8 +90,9 @@ test("command failure still reports final changed freshness", async () =>
82
90
  command: "failed",
83
91
  freshness: "changed",
84
92
  });
85
- assert.equal((outcome.content[1].text.match(/Re-read/g) ?? []).length, 1);
86
- assert.match(outcome.content[1].text, /then_run:stale/);
93
+ assert.deepEqual(outcome.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
94
+ assert.equal(outcome.content.length, 3);
95
+ assert.match(outcome.content[2].text, /command failed/);
87
96
  }));
88
97
 
89
98
  test("timeout and cancellation do not rerun mutation and still inspect freshness", async () =>
@@ -154,7 +163,7 @@ test("queue is released after a failed command", async () =>
154
163
  );
155
164
  }));
156
165
 
157
- test("result generation failure cannot overwrite an already successful command", async () =>
166
+ test("successful command finalizes anchors and retains completed progress", async () =>
158
167
  withTemp(async (dir) => {
159
168
  const target = join(dir, "finalize.txt");
160
169
  const progress: any[] = [];
@@ -162,23 +171,21 @@ test("result generation failure cannot overwrite an already successful command",
162
171
  async () => "command finished",
163
172
  (event) => progress.push(event),
164
173
  );
165
- await assert.rejects(
166
- fusion({
167
- toolCallId: "finalize",
168
- absolutePath: target,
169
- thenRun: { command: "check" },
170
- signal: undefined,
171
- ctx: context(dir),
172
- mutate: async () => {
173
- await writeFile(target, "saved\n");
174
- return result("saved\n");
175
- },
176
- finalizeMutation: () => {
177
- throw new Error("mutation result failure");
178
- },
179
- }),
180
- /mutation result failure/,
181
- );
174
+ const completed = await fusion({
175
+ toolCallId: "finalize",
176
+ absolutePath: target,
177
+ thenRun: { command: "check" },
178
+ signal: undefined,
179
+ ctx: context(dir),
180
+ mutate: async () => {
181
+ await writeFile(target, "saved\n");
182
+ return { ...result("saved\n"), anchors: " ANCHOR" };
183
+ },
184
+ });
185
+ assert.deepEqual(completed.content, [
186
+ { type: "text", text: "mutation ANCHOR" },
187
+ { type: "text", text: `${THEN_RUN_SUCCEEDED}\ncommand finished` },
188
+ ]);
182
189
  assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
183
190
  assert.equal(progress.at(-1).publication, "PUBLISHED");
184
191
  assert.equal(progress.at(-1).freshness, "unchanged");
@@ -14,7 +14,8 @@ import {
14
14
  import { dirname, join } from "node:path";
15
15
  import { createHash } from "node:crypto";
16
16
  import { decodeEditableText, unwritableTextReason } from "../core/text.ts";
17
- import { errorMessage, OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
17
+ import { errorMessage } from "../core/errors.ts";
18
+ import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
18
19
 
19
20
  export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
20
21
  export type CommitMode = "create" | "overwrite";
@@ -1,7 +1,21 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
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.
5
+ *
6
+ * @module pi-hashline-edit/pi
7
+ */
8
+
9
+ import type {
10
+ ExtensionAPI,
11
+ ExtensionContext,
12
+ ToolDefinition,
13
+ } from "@earendil-works/pi-coding-agent";
2
14
  import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
3
- import { Box, Text, type Component } from "@earendil-works/pi-tui";
15
+ import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
16
+ import type { TSchema } from "typebox";
4
17
  import type { ActionFusionProgress } from "./action-fusion.ts";
18
+ import { renderToolError, type MutationRenderState } from "./render.ts";
5
19
 
6
20
  const CARD_TYPE = "hashline-then-run";
7
21
  const RESULT_TYPE = "hashline-then-run-result";
@@ -135,3 +149,70 @@ export function registerFusionCards(pi: ExtensionAPI) {
135
149
  if (!pending) pi.appendEntry(RESULT_TYPE, data);
136
150
  };
137
151
  }
152
+
153
+ /** Mutation render state plus the shell that keeps the card status independent of then_run. */
154
+ interface FusedMutationRenderState extends MutationRenderState {
155
+ mutationShell?: {
156
+ box: Box;
157
+ call?: Component;
158
+ result?: Component;
159
+ fileState?: { freshness?: string };
160
+ };
161
+ }
162
+
163
+ /** Keep the mutation card's background independent of the fused command's lifetime. */
164
+ export function withMutationStatus<TParams extends TSchema, TDetails>(
165
+ tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
166
+ ): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
167
+ return {
168
+ ...tool,
169
+ renderShell: "self",
170
+ renderCall(args, theme, context) {
171
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
172
+ shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
173
+ shell.box.clear();
174
+ shell.box.addChild(shell.call);
175
+ shell.box.setBgFn((line: string) =>
176
+ theme.bg(
177
+ context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
178
+ line,
179
+ ),
180
+ );
181
+ return shell.box;
182
+ },
183
+ renderResult(result, options, theme, context) {
184
+ const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
185
+ const details = result.details as
186
+ | { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
187
+ | undefined;
188
+ const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
189
+ // Fused errors retain combined details for the model; show the mutation's summary here.
190
+ const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
191
+ shell.result = fusedError
192
+ ? renderToolError(result, theme)
193
+ : tool.renderResult!(result, { ...options, isPartial }, theme, {
194
+ ...context,
195
+ isPartial,
196
+ lastComponent: shell.result,
197
+ });
198
+ // Pi runs renderCall first; update its box in place without invalidating the tool row.
199
+ shell.box.addChild(shell.result);
200
+ const file = details?.actionFusion ?? shell.fileState;
201
+ if (file) {
202
+ shell.fileState = { freshness: file.freshness };
203
+ if (file.freshness === "changed" || file.freshness === "missing") {
204
+ shell.box.addChild(
205
+ new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
206
+ );
207
+ }
208
+ }
209
+ shell.box.setBgFn((line: string) =>
210
+ theme.bg(
211
+ isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
212
+ line,
213
+ ),
214
+ );
215
+ return new Container();
216
+ },
217
+ };
218
+ }
@@ -1,16 +1,33 @@
1
1
  import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
2
2
  import { createHash } from "node:crypto";
3
3
  import { isAbsolute, relative, resolve, sep } from "node:path";
4
- import { UNSUPPORTED_TEXT_NUL } from "../core/text.ts";
4
+ import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
5
5
  import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
6
6
  import { fileReadWarning, type RgMatch } from "./grep-search.ts";
7
7
  import { scanTextLines } from "./text-stream.ts";
8
- import { formatKiB, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
8
+ import { formatKiB, GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
9
+ import { searchChangedError } from "./error-text.ts";
9
10
 
10
- /** Maximum UTF-16 units in a line preview, excluding its partial-line label. */
11
- const GREP_MAX_LINE_LENGTH = 500;
11
+ /** UTF-16 units kept before the match column when a preview window is cut. */
12
+ const GREP_PREVIEW_LEAD = 100;
12
13
  const MAX_CONCURRENT_FILE_READS = 16;
13
14
 
15
+ /** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
16
+ function formatFileHeader(path: string, matches: number): string {
17
+ return `${path} · ${matches} match${matches !== 1 ? "es" : ""}`;
18
+ }
19
+ const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/;
20
+
21
+ export function parseFileHeader(line: string): { path: string; summary: string } | undefined {
22
+ const match = FILE_HEADER.exec(line);
23
+ return match ? { path: match[1], summary: match[2] } : undefined;
24
+ }
25
+
26
+ /** Notices and search diagnostics open with `[` (see assembleGrepOutput and formatSearchWarnings). */
27
+ export function isNoticeLine(line: string): boolean {
28
+ return line.startsWith("[");
29
+ }
30
+
14
31
  export function formatSearchWarnings(warnings: readonly string[]): string {
15
32
  if (!warnings.length) return "";
16
33
  const summary = truncateHead([...new Set(warnings)].join("\n"), {
@@ -21,7 +38,7 @@ export function formatSearchWarnings(warnings: readonly string[]): string {
21
38
 
22
39
  function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
23
40
  if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
24
- let start = Math.max(0, Math.min(column - 100, text.length - GREP_MAX_LINE_LENGTH));
41
+ let start = Math.max(0, Math.min(column - GREP_PREVIEW_LEAD, text.length - GREP_MAX_LINE_LENGTH));
25
42
  // Slice at UTF-16 boundaries without splitting an astral character.
26
43
  if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
27
44
  let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
@@ -96,7 +113,7 @@ export async function formatMatches(options: FormatMatchesOptions) {
96
113
  if (line.text === undefined) return;
97
114
  const matchedText = matchedTexts.get(line.number);
98
115
  if (matchedText !== undefined && matchedText !== line.text) {
99
- throw new Error("File changed during search; rerun the query.");
116
+ throw searchChangedError();
100
117
  }
101
118
  if (matchedTexts.has(line.number)) matchedRows.add(line.number);
102
119
  const { text: display, wasTruncated } = previewLine(
@@ -110,13 +127,13 @@ export async function formatMatches(options: FormatMatchesOptions) {
110
127
  );
111
128
  if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
112
129
  if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
113
- throw new Error("File changed during search; rerun the query.");
130
+ throw searchChangedError();
114
131
  }
115
132
  const searchRevision = searchRevisions.get(filePath);
116
133
  if (searchRevision && searchRevision !== hash.digest("hex")) {
117
- throw new Error("File changed during search; rerun the query.");
134
+ throw searchChangedError();
118
135
  }
119
- const header = `${formatPath(filePath)} · ${matchLines.length} match${matchLines.length !== 1 ? "es" : ""}\n`;
136
+ const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
120
137
  fileResults[current] = { block: header + rows.join("\n") };
121
138
  } catch (error) {
122
139
  const warning = fileReadWarning(filePath, error, scanSignal);
@@ -1,5 +1,6 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { parseHashline } from "./render.ts";
2
+ import { parseHashline } from "./anchor-format.ts";
3
+ import { isNoticeLine, parseFileHeader } from "./grep-output.ts";
3
4
 
4
5
  /**
5
6
  * Convert the anchored grep output (grouped, `LINE#HASH│`) into a human-readable
@@ -24,9 +25,9 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
24
25
  let i = 0;
25
26
  while (i < lines.length) {
26
27
  const line = lines[i];
27
- const h = line.match(/^(.+?) · (\d+ match(?:es)?)$/);
28
- if (h) {
29
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
28
+ const header = parseFileHeader(line);
29
+ if (header) {
30
+ out.push(theme.fg("success", header.path) + theme.fg("dim", ` · ${header.summary}`));
30
31
  // collect the anchor lines in this file group
31
32
  const group: { lineNo: string; content: string }[] = [];
32
33
  let j = i + 1;
@@ -50,7 +51,7 @@ export function toDisplayLines(raw: string, theme: Theme): string[] {
50
51
  i = j;
51
52
  continue;
52
53
  }
53
- if (line.startsWith("[")) out.push(theme.fg("warning", line));
54
+ if (isNoticeLine(line)) out.push(theme.fg("warning", line));
54
55
  else out.push(theme.fg("toolOutput", line));
55
56
  i++;
56
57
  }
@@ -1,7 +1,7 @@
1
1
  import { stat } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { canonicalPath } from "./path.ts";
4
- import { COMMON_RG_ARGS } from "./rg-line-filter.ts";
4
+ import { COMMON_RG_ARGS } from "./rg-process.ts";
5
5
  import {
6
6
  recordSearchDiagnostics,
7
7
  scopeArgs,
@@ -50,20 +50,7 @@ export async function resolveLiteralMode(
50
50
  if (explicit === undefined && !patterns.some((pattern) => REGEX_SYNTAX.test(pattern)))
51
51
  return true;
52
52
 
53
- const result = await backend.runRg(
54
- rgPath,
55
- [
56
- ...COMMON_RG_ARGS,
57
- "--engine=default",
58
- multiline ? "--multiline" : "--no-multiline",
59
- "--quiet",
60
- ...patterns.flatMap((pattern) => ["-e", pattern]),
61
- "--",
62
- "-",
63
- ],
64
- signal,
65
- () => true,
66
- );
53
+ const result = await backend.probeRegex(rgPath, patterns, multiline, signal);
67
54
  throwIfCancelled(signal);
68
55
  if (result.code === 0 || result.code === 1) return false;
69
56
  if (result.code === 2 && REGEX_PARSE_ERROR.test(result.stderr)) {
@@ -1,17 +1,17 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { resolve } from "node:path";
3
- import { UNSUPPORTED_TEXT_NUL } from "../core/text.ts";
3
+ import { UNSUPPORTED_TEXT_NUL } from "../core/errors.ts";
4
4
  import { scanTextFile } from "./text-stream.ts";
5
5
  import {
6
6
  type RgRunResult,
7
7
  matcherArgs,
8
+ probeRegex,
8
9
  resolveIgnoreCase,
9
10
  rgBytes,
10
11
  rgText,
11
- runRg,
12
12
  runRgPaths,
13
13
  type SearchModes,
14
- } from "./rg-line-filter.ts";
14
+ } from "./rg-process.ts";
15
15
  import { submatchesToLineRanges } from "./rg-line-ranges.ts";
16
16
  import { throwIfCancelled } from "./error-text.ts";
17
17
 
@@ -44,13 +44,6 @@ interface RgJsonEvent {
44
44
  };
45
45
  }
46
46
 
47
- /** @internal — injectable process boundary for deterministic tests. */
48
- export interface GrepBackend {
49
- runRg: typeof runRg;
50
- runRgPaths: typeof runRgPaths;
51
- resolveIgnoreCase: typeof resolveIgnoreCase;
52
- }
53
-
54
47
  export interface SearchScope {
55
48
  globs: readonly string[];
56
49
  noIgnore: boolean;
@@ -58,6 +51,30 @@ export interface SearchScope {
58
51
  searchPaths: readonly string[];
59
52
  }
60
53
 
54
+ /** One JSONL content search, kept structured so the backend never re-parses rg arguments. */
55
+ export interface SearchRequest {
56
+ /** Matcher and output arguments, including `-e` patterns; no scope flags or paths. */
57
+ readonly matcher: readonly string[];
58
+ readonly scope: SearchScope;
59
+ }
60
+
61
+ /** Runs a search request and streams rg JSONL lines to `onLine`; returning false stops rg. */
62
+ export type SearchRunner = (
63
+ rgPath: string,
64
+ request: SearchRequest,
65
+ signal: AbortSignal | undefined,
66
+ onLine: (line: string) => boolean | Promise<boolean>,
67
+ ) => Promise<RgRunResult>;
68
+
69
+ /** @internal — injectable process boundary for deterministic tests. */
70
+ export interface GrepBackend {
71
+ search: SearchRunner;
72
+ runRgPaths: typeof runRgPaths;
73
+ resolveIgnoreCase: typeof resolveIgnoreCase;
74
+ probeRegex: typeof probeRegex;
75
+ }
76
+
77
+ /** The only place scope becomes rg flags. */
61
78
  export function scopeArgs(scope: SearchScope): string[] {
62
79
  return [
63
80
  "--hidden",
@@ -105,16 +122,13 @@ export async function searchMatches(options: SearchMatchesOptions) {
105
122
  // rg reports non-overlapping spans, so overlapping multiline OR patterns need separate scans.
106
123
  const patternGroups = modes.multiline ? patterns.map((pattern) => [pattern]) : [patterns];
107
124
  for (const group of patternGroups) {
108
- const args = [
125
+ const matcher = [
109
126
  ...matcherArgs(modes),
110
127
  "--json",
111
128
  "--line-number",
112
- ...scopeArgs(scope),
113
129
  ...group.flatMap((pattern) => ["-e", pattern]),
114
- "--",
115
- ...scope.searchPaths,
116
130
  ];
117
- const run = await backend.runRg(rgPath, args, signal, async (line) => {
131
+ const run = await backend.search(rgPath, { matcher, scope }, signal, async (line) => {
118
132
  if (raw.length >= limit) return false;
119
133
  let event: RgJsonEvent;
120
134
  try {