@criogaid/pi-hashline-edit 0.2.0 → 0.3.1

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.
package/src/pi/render.ts CHANGED
@@ -128,7 +128,7 @@ export function renderMutationResult(
128
128
  if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
129
129
  const content = result.content?.[0];
130
130
  if (context.isError) return renderToolError(result, theme);
131
- const diff: string | undefined = result.details?.diff;
131
+ const diff: string | undefined = result.details?.displayDiff ?? result.details?.diff;
132
132
  // Refresh in place: invalidation inside a renderer re-enters updateDisplay.
133
133
  publishDiffCounts(diff, context, (counts) => {
134
134
  context.state?.callText?.setText(header(context.args, theme, counts));
@@ -157,9 +157,19 @@ export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDef
157
157
  renderResult(result, options, theme, context) {
158
158
  const shell = context.state.mutationShell;
159
159
  const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
160
- shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
160
+ // Fused errors retain combined details for the model; show the mutation's summary here.
161
+ const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
162
+ shell.result = fusedError ? renderToolError(result, theme)
163
+ : tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
161
164
  // Pi runs renderCall first; update its box in place without invalidating the tool row.
162
165
  shell.box.addChild(shell.result);
166
+ const file = result.details?.actionFusion ?? shell.fileState;
167
+ if (file) {
168
+ shell.fileState = { freshness: file.freshness };
169
+ if (file.freshness === "changed" || file.freshness === "missing") {
170
+ shell.box.addChild(new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0));
171
+ }
172
+ }
163
173
  shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
164
174
  return new Container();
165
175
  },
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `replace`: powerful bulk text replacement — literal substring (replaceAll) or
2
+ * `replace`: bulk literal text replacement or
3
3
  * full JavaScript regex with capture-group substitution.
4
4
  *
5
5
  * Distinct from the anchor-verified `edit`. `replace` is **location-blind**:
@@ -8,10 +8,8 @@
8
8
  * otherwise need many individual edits. For a single surgical, verified change,
9
9
  * prefer `edit`.
10
10
  *
11
- * - Literal mode (`regex` false): `find` is a substring, matched verbatim;
12
- * `replace` is inserted as-is (no `$` expansion).
13
- * - Regex mode (`regex` true): `find` is a JS pattern source; `replace` supports
14
- * `$1`, `$2`, `$&`, etc.
11
+ * - Both modes match the shared LF view and restore original line separators.
12
+ * - Literal mode keeps `$` verbatim; regex mode expands JavaScript replacement tokens.
15
13
  * - `flags` adds regex flags in either mode; `g` is always forced so every
16
14
  * occurrence is replaced. `i` (case-insensitive), `m` (per-line ^/$),
17
15
  * `s` (dotall), `u` (unicode) all work.
@@ -30,12 +28,12 @@ import {
30
28
  } from "@earendil-works/pi-coding-agent";
31
29
  import { Type, type Static } from "typebox";
32
30
  import { escapeRegex } from "../core/text.ts";
33
- import { splitLines } from "../core/index.ts";
31
+ import { createLfTextView, detectLineEnding, normalizeLineEndings, restoreLineEndings, splitLines } from "../core/lines.ts";
34
32
  import { findSortedRangeConflict } from "../core/ranges.ts";
35
33
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
36
34
  import { readEditableSnapshot, commitReplacement } from "./file-commit.ts";
37
35
  import { createAnchorFormatter, type AnchorFormatter } from "./anchor-format.ts";
38
- import { canonicalPath } from "./read-tool.ts";
36
+ import { canonicalPath } from "./path.ts";
39
37
  import { formatDiffCounts, renderMutationCall, renderMutationResult, type DiffCounts } from "./render.ts";
40
38
  import { appendMutationAnchors, finalizeMutationResult, formatMutationAnchors, generateMutationDetails, postProcessMutation } from "./mutation-result.ts";
41
39
 
@@ -45,8 +43,8 @@ const DEFAULT_MAX_MATCHES = 2000;
45
43
  const VALID_FLAGS = new Set(["g", "i", "m", "s", "u", "y", "d"]);
46
44
 
47
45
  const replacementSchema = Type.Object({
48
- find: Type.String({ description: "Text to find. Literal substring by default; a JavaScript regex source when regex is true." }),
49
- replace: Type.String({ description: "Replacement text. Literal mode inserts verbatim; regex mode supports JavaScript $ substitutions." }),
46
+ find: Type.String({ description: "Text or JavaScript regex to find in the shared LF view. Actual CRLF in the file and query normalizes to LF; standalone CR stays content. In literal mode (default), an actual LF matches a line boundary, while backslash followed by n matches those two source characters. In regex mode, \\n in the pattern matches LF." }),
47
+ replace: Type.String({ description: "Replacement text in the shared LF view. Restores original line endings; extra lines use the last matched ending or the file style. Literal mode keeps $ verbatim; regex mode expands JavaScript $ substitutions against the LF snapshot. Use write for explicit whole-file line-ending conversion." }),
50
48
  regex: Type.Optional(Type.Boolean({ description: "Interpret find as a JavaScript regex (default false)." })),
51
49
  flags: Type.Optional(Type.String({ description: "Regex flags in either mode; g is always added." })),
52
50
  maxMatches: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: `Per-rule match cap (default ${DEFAULT_MAX_MATCHES}); exceeding it rejects the entire call.` })),
@@ -81,11 +79,7 @@ function replacementRules(params: ReplaceParams): Replacement[] {
81
79
  return rules as Replacement[];
82
80
  }
83
81
 
84
- /**
85
- * Build the matcher. `find` is escaped in literal mode; `flags` (validated) get
86
- * `g` forced so all occurrences replace. Invalid patterns or unsupported flags
87
- * surface as a friendly message rather than a raw `SyntaxError`.
88
- */
82
+ /** Both matcher modes operate on the shared LF view. */
89
83
  function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined): RegExp {
90
84
  for (const c of flagsRaw ?? "") {
91
85
  if (!VALID_FLAGS.has(c)) throw new Error(`invalid regex flag '${c}' (valid: g i m s u y d)`);
@@ -93,7 +87,8 @@ function buildRegex(find: string, isRegex: boolean, flagsRaw: string | undefined
93
87
  const set = new Set((flagsRaw ?? "").split(""));
94
88
  set.add("g");
95
89
  const flagStr = [...set].join("");
96
- const source = isRegex ? find : escapeRegex(find);
90
+ const logical = normalizeLineEndings(find);
91
+ const source = isRegex ? logical : escapeRegex(logical);
97
92
  try {
98
93
  return new RegExp(source, flagStr);
99
94
  } catch (e) {
@@ -123,16 +118,21 @@ function expandReplacement(template: string, match: RegExpMatchArray, source: st
123
118
 
124
119
  function applyReplacements(source: string, rules: readonly Replacement[]): { text: string; count: number } {
125
120
  const changes: { start: number; end: number; text: string; rule: number }[] = [];
121
+ const view = createLfTextView(source);
122
+ const fallbackEnding = detectLineEnding(source) === "crlf" ? "\r\n" : "\n";
126
123
  for (const [index, rule] of rules.entries()) {
127
124
  try {
128
125
  const regex = buildRegex(rule.find, rule.regex === true, rule.flags);
129
126
  const maxMatches = rule.maxMatches ?? DEFAULT_MAX_MATCHES;
130
127
  let count = 0;
131
- for (const match of source.matchAll(regex)) {
128
+ const replacement = normalizeLineEndings(rule.replace);
129
+ for (const match of view.text.matchAll(regex)) {
132
130
  if (++count > maxMatches) throw new Error(`${count}+ matches exceed \`maxMatches\` (${maxMatches}). Raise \`maxMatches\` if intentional, or narrow \`find\`.`);
131
+ const start = view.sourceOffset(match.index!);
132
+ const end = view.sourceOffset(match.index! + match[0].length);
133
133
  changes.push({
134
- start: match.index!, end: match.index! + match[0].length, rule: index,
135
- text: rule.regex ? expandReplacement(rule.replace, match, source) : rule.replace,
134
+ start, end, rule: index,
135
+ text: restoreLineEndings(rule.regex ? expandReplacement(replacement, match, view.text) : replacement, source.slice(start, end), fallbackEnding),
136
136
  });
137
137
  }
138
138
  if (count === 0) throw new Error(`no matches for ${rule.regex ? `/${rule.find}/` : JSON.stringify(rule.find)}.`);
@@ -41,6 +41,14 @@ const stubTheme = { fg: (_k: string, s: string) => s, bold: (s: string) => s };
41
41
  // singleton — initialize it once for this test process (watcher off by default).
42
42
  initTheme();
43
43
 
44
+ test("replace guidance distinguishes literal LF from a visible escape", () => {
45
+ const tool = makeReplaceTool(process.cwd());
46
+ const description = JSON.stringify(tool.parameters.properties.find);
47
+ assert.match(description, /In literal mode \(default\), an actual LF matches a line boundary/);
48
+ assert.match(description, /backslash followed by n matches those two source characters/);
49
+ assert.match(description, /In regex mode/);
50
+ });
51
+
44
52
  test("replace literal: replaces all occurrences", async () => {
45
53
  await withDir(async (dir) => {
46
54
  const f = join(dir, "f.txt");
@@ -52,6 +60,63 @@ test("replace literal: replaces all occurrences", async () => {
52
60
  });
53
61
  });
54
62
 
63
+ test("literal multiline replace matches LF and CRLF while retaining local separators", async () => withDir(async (dir) => {
64
+ const file = join(dir, "mixed.txt");
65
+ await writeFile(file, "\uFEFFhead\r\nold\r\none\r\nmid\nold\none\nend\r\n");
66
+ const result: any = await call(makeReplaceTool(dir), { path: "mixed.txt", find: "old\none", replace: "NEW\nX" });
67
+ assert.match(result.content[0].text, /2 matches/);
68
+ assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\nNEW\r\nX\r\nmid\nNEW\nX\nend\r\n");
69
+ await call(makeReplaceTool(dir), { path: "mixed.txt", find: "NEW\r\nX", replace: "done" });
70
+ assert.equal(await readFile(file, "utf8"), "\uFEFFhead\r\ndone\r\nmid\ndone\nend\r\n");
71
+ }));
72
+
73
+ test("both replacement modes preserve each matched separator", async () => withDir(async (dir) => {
74
+ const file = join(dir, "mixed.txt");
75
+ for (const regex of [false, true]) {
76
+ await writeFile(file, "a\r\nb\nc\r\ntail\n");
77
+ await call(makeReplaceTool(dir), { path: "mixed.txt", find: "a\nb\nc", replace: "x\ny\nz\nextra", regex });
78
+ assert.equal(await readFile(file, "utf8"), "x\r\ny\nz\nextra\r\ntail\n");
79
+ }
80
+ }));
81
+
82
+ test("literal replacement uses one LF view and preserves raw bytes across query styles", async () => withDir(async (dir) => {
83
+ const file = join(dir, "f.txt");
84
+ for (const find of ["a\nb\nc", "a\r\nb\r\nc", "a\r\nb\nc"]) {
85
+ const before = "\uFEFFhead\r\na\r\nb\nc\rtail";
86
+ await writeFile(file, before);
87
+ const result = await call(makeReplaceTool(dir), { path: file, find, replace: find });
88
+ assert.equal(await readFile(file, "utf8"), before);
89
+ assert.match(result.content[0].text, /no net change/);
90
+ }
91
+ for (const [before, find, replacement, expected] of [
92
+ ["a\r\nb", "a", "A\nextra", "A\r\nextra\r\nb"],
93
+ ["a\nb", "a\r\nb", "A\r\nB", "A\nB"],
94
+ ["a\r\nb", "\n", "", "ab"],
95
+ ["a\r\nb", "\n", "\n", "a\r\nb"],
96
+ ["a\rb\r\r\nc", "a\rb\r\r\nc", "x\ry\r\r\nz", "x\ry\r\r\nz"],
97
+ ]) {
98
+ await writeFile(file, before);
99
+ await call(makeReplaceTool(dir), { path: file, find, replace: replacement });
100
+ assert.equal(await readFile(file, "utf8"), expected);
101
+ }
102
+ }));
103
+
104
+ test("mixed literal and regex batches share raw offsets after CRLF normalization", async () => withDir(async (dir) => {
105
+ const file = join(dir, "f.txt");
106
+ await writeFile(file, "😀\r\na\r\nb\r\nc");
107
+ await call(makeReplaceTool(dir), { path: file, replacements: [
108
+ { find: "a\nb", replace: "A\nB" },
109
+ { find: "(c)$", replace: "$1!", regex: true },
110
+ ] });
111
+ assert.equal(await readFile(file, "utf8"), "😀\r\nA\r\nB\r\nc!");
112
+ const before = await readFile(file, "utf8");
113
+ await assert.rejects(call(makeReplaceTool(dir), { path: file, replacements: [
114
+ { find: "A\nB", replace: "x" },
115
+ { find: "\\nB", replace: "y", regex: true },
116
+ ] }), /overlap/);
117
+ assert.equal(await readFile(file, "utf8"), before);
118
+ }));
119
+
55
120
  test("replace literal: $ in replacement stays literal (no expansion)", async () => {
56
121
  await withDir(async (dir) => {
57
122
  const f = join(dir, "f.txt");
@@ -402,3 +467,13 @@ test("successful batches run one command against the complete result", async ()
402
467
  assert.equal(result.details.actionFusion.command, "succeeded");
403
468
  assert.match(result.content[0].text, /Updated anchors/);
404
469
  }));
470
+
471
+ test("regex captures and zero-width insertions use logical offsets without consuming CRLF bytes", async () => withDir(async (dir) => {
472
+ const path = join(dir, "f.txt");
473
+ const before = "a\r\nb\rc\r\r\n";
474
+ await writeFile(path, before);
475
+ await call(makeReplaceTool(dir), { path, find: "(b\rc\r)\\n", replace: "$1\n", regex: true });
476
+ assert.equal(await readFile(path, "utf8"), before);
477
+ await call(makeReplaceTool(dir), { path, find: "(?=\\n)", replace: "!", regex: true });
478
+ assert.equal(await readFile(path, "utf8"), "a!\r\nb\rc\r!\r\n");
479
+ }));
@@ -2,7 +2,7 @@ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import type { Readable } from "node:stream";
3
3
  import { escapeRegex } from "../core/text.ts";
4
4
 
5
- export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--crlf"];
5
+ export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--no-crlf"];
6
6
  export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
7
7
 
8
8
  export interface SearchModes {
@@ -0,0 +1,88 @@
1
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { normalizeLineEndings } from "../core/lines.ts";
5
+ import { decodeUtf8 } from "../core/text.ts";
6
+ import { COMMON_RG_ARGS, rgText, runRg, runRgPaths, type RgRunResult } from "./rg-line-filter.ts";
7
+
8
+ /** Search bounded LF snapshots while reporting original paths and logical match offsets. */
9
+ export const runRgTextView: typeof runRg = async (rgPath, args, signal, onLine) => {
10
+ let boundary = args.length;
11
+ const scope: string[] = [];
12
+ const matcher: string[] = [];
13
+ for (let i = 0; i < args.length; i++) {
14
+ const arg = args[i];
15
+ if (arg === "--") { boundary = i; break; }
16
+ if (arg === "--glob") scope.push(arg, args[++i]);
17
+ else if (["--hidden", "--no-ignore", "--follow"].includes(arg)) scope.push(arg);
18
+ else {
19
+ matcher.push(arg);
20
+ if (arg === "-e") matcher.push(args[++i]);
21
+ }
22
+ }
23
+ if (boundary === args.length || args[boundary + 1] === "-") return runRg(rgPath, args, signal, onLine);
24
+ // ponytail: bounded snapshots add disk I/O; use a streaming backend if large scans dominate.
25
+ const directory = await mkdtemp(join(tmpdir(), "hashline-grep-"));
26
+ const result: RgRunResult = { code: 1, stderr: "", stopped: false };
27
+ const paths = new Map<string, string>();
28
+ let snapshotBytes = 0;
29
+ const record = (run: RgRunResult) => {
30
+ result.stderr = (result.stderr + run.stderr).slice(0, 65536);
31
+ if (run.code !== 0 && run.code !== 1 && !run.stopped) result.code = run.code;
32
+ else if (run.code === 0 && result.code === 1) result.code = 0;
33
+ result.stopped ||= run.stopped;
34
+ };
35
+ const flush = async () => {
36
+ if (!paths.size) return !result.stopped;
37
+ // Scope filtering belongs to the original paths. Snapshot names have no ignore/glob semantics.
38
+ const searchArgs = [
39
+ ...matcher, "--encoding=none", "--no-ignore", "--hidden", "--", ...paths.keys(),
40
+ ];
41
+ const run = await runRg(rgPath, searchArgs, signal, async (line) => {
42
+ const event = JSON.parse(line);
43
+ if (event.data?.path) {
44
+ const original = paths.get(resolve(rgText(event.data.path)));
45
+ if (!original) throw new Error("ripgrep returned an unexpected snapshot path");
46
+ event.data.path = { text: original };
47
+ }
48
+ return onLine(JSON.stringify(event));
49
+ });
50
+ record(run);
51
+ for (const path of paths.keys()) await rm(path);
52
+ paths.clear();
53
+ snapshotBytes = 0;
54
+ return !result.stopped;
55
+ };
56
+ try {
57
+ const listArgs = [
58
+ ...COMMON_RG_ARGS, ...scope, "--files", "--null", "--", ...args.slice(boundary + 1),
59
+ ];
60
+ const listed = await runRgPaths(rgPath, listArgs, signal, async (path) => {
61
+ signal?.throwIfAborted();
62
+ const original = resolve(path);
63
+ if (original.startsWith(directory + sep)) return true;
64
+ let text: string | Buffer;
65
+ try {
66
+ const bytes = await readFile(original, { signal });
67
+ // Let rg decide whether a NUL file matches; the result reader rejects confirmed binary hits.
68
+ text = bytes.includes(0) ? bytes : normalizeLineEndings(decodeUtf8(bytes));
69
+ } catch (error) {
70
+ signal?.throwIfAborted();
71
+ const message = error instanceof Error ? error.message : String(error);
72
+ record({ code: 2, stopped: false, stderr: `${original}: ${message}\n` });
73
+ return true;
74
+ }
75
+ const snapshot = join(directory, String(paths.size));
76
+ await writeFile(snapshot, text, { signal });
77
+ paths.set(snapshot, original);
78
+ snapshotBytes += Buffer.byteLength(text);
79
+ return (paths.size < 64 && snapshotBytes < 8 * 1024 * 1024) || await flush();
80
+ });
81
+ // A successful listing is not itself a text match.
82
+ record({ ...listed, code: listed.code === 0 ? 1 : listed.code });
83
+ if (!result.stopped) await flush();
84
+ return result;
85
+ } finally {
86
+ await rm(directory, { recursive: true, force: true });
87
+ }
88
+ };
@@ -3,12 +3,12 @@ import { createWriteToolDefinition, withFileMutationQueue } from "@earendil-work
3
3
  import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
4
4
  import { commitFile, type CommitMode } from "./file-commit.ts";
5
5
  import { postProcessMutation } from "./mutation-result.ts";
6
- import { canonicalPath } from "./read-tool.ts";
6
+ import { canonicalPath } from "./path.ts";
7
7
 
8
8
  function createWriteSchema(actionFusion: boolean) {
9
9
  return Type.Object({
10
10
  path: Type.String({ description: "Path to the file to write" }),
11
- content: Type.String({ description: "Complete file content" }),
11
+ content: Type.String({ description: "Complete file content, including the exact desired line endings. Source-code escape sequences remain literal text." }),
12
12
  mode: Type.Optional(Type.Union([
13
13
  Type.Literal("create", { description: "Fail if the target already exists" }),
14
14
  Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
@@ -27,7 +27,7 @@ export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof create
27
27
  return {
28
28
  name: "write" as const,
29
29
  label: "write",
30
- description: "Write complete file content. By default, creates missing files and overwrites existing files.",
30
+ description: "Write complete file content exactly as supplied, including LF/CRLF choices. Use for intentional whole-file line-ending conversion. By default, creates missing files and overwrites existing files.",
31
31
  promptSnippet: "Write complete file content to a path",
32
32
  promptGuidelines: fusion ? ACTION_FUSION_GUIDELINES : [],
33
33
  parameters,