@criogaid/pi-hashline-edit 0.3.1 → 0.4.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 (69) hide show
  1. package/README.md +58 -49
  2. package/package.json +8 -3
  3. package/src/core/apply.test.ts +366 -310
  4. package/src/core/apply.ts +269 -202
  5. package/src/core/hash.test.ts +61 -23
  6. package/src/core/hash.ts +45 -16
  7. package/src/core/lines.test.ts +46 -27
  8. package/src/core/lines.ts +36 -28
  9. package/src/core/ranges.test.ts +73 -19
  10. package/src/core/ranges.ts +15 -15
  11. package/src/core/text.test.ts +3 -3
  12. package/src/core/text.ts +28 -9
  13. package/src/core/types.ts +54 -36
  14. package/src/index.ts +22 -16
  15. package/src/integration/grep-rg.test.ts +834 -219
  16. package/src/integration/large-text.test.ts +62 -0
  17. package/src/integration/replace-package.test.ts +37 -0
  18. package/src/pi/action-fusion.test.ts +535 -206
  19. package/src/pi/action-fusion.ts +469 -244
  20. package/src/pi/anchor-format.test.ts +30 -19
  21. package/src/pi/anchor-format.ts +27 -14
  22. package/src/pi/budgets.ts +20 -0
  23. package/src/pi/config.test.ts +60 -30
  24. package/src/pi/config.ts +45 -32
  25. package/src/pi/directory-sync.test.ts +55 -0
  26. package/src/pi/e2e-scenarios.test.ts +359 -0
  27. package/src/pi/edit-tool.ts +426 -262
  28. package/src/pi/error-text.ts +21 -0
  29. package/src/pi/execute.test.ts +1593 -712
  30. package/src/pi/failure-context.test.ts +105 -83
  31. package/src/pi/failure-context.ts +83 -71
  32. package/src/pi/failure-path.test.ts +171 -64
  33. package/src/pi/file-commit.test.ts +446 -233
  34. package/src/pi/file-commit.ts +347 -203
  35. package/src/pi/fusion-card.test.ts +118 -83
  36. package/src/pi/fusion-card.ts +120 -85
  37. package/src/pi/grep-output.ts +208 -0
  38. package/src/pi/grep-render.ts +58 -0
  39. package/src/pi/grep-scope.ts +152 -0
  40. package/src/pi/grep-search.ts +217 -0
  41. package/src/pi/grep-tool.ts +191 -766
  42. package/src/pi/grep.test.ts +562 -150
  43. package/src/pi/mutation-result.test.ts +37 -0
  44. package/src/pi/mutation-result.ts +107 -59
  45. package/src/pi/mutation-runner.ts +168 -0
  46. package/src/pi/path.ts +20 -12
  47. package/src/pi/pi.test.ts +95 -52
  48. package/src/pi/read-tool.ts +215 -132
  49. package/src/pi/registration.test.ts +274 -113
  50. package/src/pi/render.test.ts +218 -83
  51. package/src/pi/render.ts +152 -95
  52. package/src/pi/replace-apply.ts +109 -0
  53. package/src/pi/replace-tool.ts +280 -240
  54. package/src/pi/replace-worker.mjs +4 -0
  55. package/src/pi/replace-worker.ts +10 -0
  56. package/src/pi/replace.test.ts +773 -389
  57. package/src/pi/result-safety.test.ts +779 -342
  58. package/src/pi/rg-line-filter.test.ts +64 -36
  59. package/src/pi/rg-line-filter.ts +40 -124
  60. package/src/pi/rg-line-ranges.test.ts +57 -31
  61. package/src/pi/rg-line-ranges.ts +44 -82
  62. package/src/pi/rg-text-view.ts +106 -36
  63. package/src/pi/schema.ts +27 -0
  64. package/src/pi/state.ts +7 -7
  65. package/src/pi/text-stream.test.ts +118 -0
  66. package/src/pi/text-stream.ts +136 -0
  67. package/src/pi/tool-call.testing.ts +37 -0
  68. package/src/pi/write-tool.ts +115 -52
  69. package/src/pi/write.test.ts +248 -96
@@ -10,18 +10,25 @@
10
10
  */
11
11
 
12
12
  import {
13
- createReadToolDefinition, detectSupportedImageMimeTypeFromFile,
14
- getLanguageFromPath, highlightCode, truncateHead,
13
+ createReadToolDefinition,
14
+ detectSupportedImageMimeTypeFromFile,
15
+ getLanguageFromPath,
16
+ highlightCode,
17
+ type ReadToolInput,
18
+ type ReadToolDetails,
19
+ type ExtensionContext,
20
+ type Theme,
15
21
  } from "@earendil-works/pi-coding-agent";
22
+ import type { AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
16
23
  import { Text } from "@earendil-works/pi-tui";
17
- import { readFile } from "node:fs/promises";
18
- import { decodeUtf8 } from "../core/index.ts";
19
- import { hasFinalNewline, splitLines } from "../core/lines.ts";
20
- import { createAnchorFormatter } from "./anchor-format.ts";
24
+ import { scanTextLines } from "./text-stream.ts";
25
+ import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
21
26
  import { canonicalPath } from "./path.ts";
22
27
  import { parseHashline, renderToolError } from "./render.ts";
28
+ import { POSITIVE_SAFE_INTEGER } from "./schema.ts";
29
+ import { throwIfCancelled } from "./error-text.ts";
23
30
 
24
- const MAX_LINES = 2000;
31
+ const MAX_LINES = 500;
25
32
  const MAX_BYTES = 256 * 1024;
26
33
 
27
34
  /**
@@ -32,132 +39,208 @@ const MAX_BYTES = 256 * 1024;
32
39
  * line count diverges). Trailing notices (e.g. truncation) are shown in
33
40
  * `warning`.
34
41
  */
35
- function renderReadBody(raw: string, path: string, theme: any): string {
36
- const lines = raw.split("\n");
37
- if (lines.length === 0) return "";
38
- const out: string[] = [];
39
-
40
- // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
41
- // and/or " · no trailing newline".
42
- let bodyStart = 0;
43
- const h = lines[0].match(/^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/);
44
- if (h) {
45
- out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
46
- bodyStart = 1;
47
- }
48
-
49
- // Collect anchor rows (full content); the first non-anchor line begins the tail.
50
- const lineNos: string[] = [];
51
- const codeContents: string[] = [];
52
- let tailStart = lines.length;
53
- for (let i = bodyStart; i < lines.length; i++) {
54
- const row = parseHashline(lines[i]);
55
- if (!row) {
56
- tailStart = i;
57
- break;
58
- }
59
- lineNos.push(row.lineNo);
60
- codeContents.push(row.content);
61
- }
62
-
63
- // Syntax-highlight the whole block so multi-line constructs stay correct.
64
- const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
65
- const lang = getLanguageFromPath(path);
66
- let rendered: string[];
67
- if (lang) {
68
- const hl = highlightCode(detabbed.join("\n"), lang);
69
- // Guard against highlighters that reshape line count: fall back to plain.
70
- rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
71
- } else {
72
- rendered = detabbed.map((l) => theme.fg("toolOutput", l));
73
- }
74
- for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
75
- out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
76
- }
77
-
78
- for (let i = tailStart; i < lines.length; i++) {
79
- out.push(theme.fg("warning", lines[i]));
80
- }
81
- return out.join("\n");
42
+ function renderReadBody(raw: string, path: string, theme: Theme): string {
43
+ const lines = raw.split("\n");
44
+ if (lines.length === 0) return "";
45
+ const out: string[] = [];
46
+
47
+ // Header: "<path> · <N> lines", optionally followed by " (from line <offset>)"
48
+ // and/or " · no trailing newline".
49
+ let bodyStart = 0;
50
+ const h = lines[0].match(
51
+ /^(.+?) · (\d+ lines(?: \(from line \d+\))?(?: · no trailing newline)?)$/,
52
+ );
53
+ if (h) {
54
+ out.push(theme.fg("success", h[1]) + theme.fg("dim", ` · ${h[2]}`));
55
+ bodyStart = 1;
56
+ }
57
+
58
+ // Collect anchor rows (full content); the first non-anchor line begins the tail.
59
+ const lineNos: string[] = [];
60
+ const codeContents: string[] = [];
61
+ let tailStart = lines.length;
62
+ for (let i = bodyStart; i < lines.length; i++) {
63
+ const row = parseHashline(lines[i]);
64
+ if (!row) {
65
+ tailStart = i;
66
+ break;
67
+ }
68
+ lineNos.push(row.lineNo);
69
+ codeContents.push(row.content);
70
+ }
71
+
72
+ // Syntax-highlight the whole block so multi-line constructs stay correct.
73
+ const detabbed = codeContents.map((l) => l.replace(/\t/g, " "));
74
+ const lang = getLanguageFromPath(path);
75
+ let rendered: string[];
76
+ if (lang) {
77
+ const hl = highlightCode(detabbed.join("\n"), lang);
78
+ // Guard against highlighters that reshape line count: fall back to plain.
79
+ rendered = hl.length === detabbed.length ? hl : detabbed.map((l) => theme.fg("toolOutput", l));
80
+ } else {
81
+ rendered = detabbed.map((l) => theme.fg("toolOutput", l));
82
+ }
83
+ for (let i = 0; i < rendered.length && i < lineNos.length; i++) {
84
+ out.push(theme.fg("dim", ` ${lineNos[i]}: `) + rendered[i]);
85
+ }
86
+
87
+ for (let i = tailStart; i < lines.length; i++) {
88
+ out.push(theme.fg("warning", lines[i]));
89
+ }
90
+ return out.join("\n");
82
91
  }
83
92
 
84
93
  /** Build the read override (a ToolDefinition fragment for registerTool). */
85
- export function makeReadOverride(cwd: string) {
86
- const builtin = createReadToolDefinition(cwd);
87
-
88
- return {
89
- name: "read" as const,
90
- label: "read",
91
- description:
92
- "Read file contents. Text files display per-line content hashes (LINE#HASH│content) in the shared LF view for hashline-verified editing. CRLF line boundaries display as LF; source-code escape sequences remain literal text.",
93
- promptSnippet: "Read files with editable line anchors",
94
- promptGuidelines: [
95
- "Prefer read over shell output for files you intend to edit.",
96
- ],
97
- parameters: builtin.parameters,
98
- renderShell: "default" as const,
99
-
100
- renderCall: builtin.renderCall,
101
-
102
- renderResult(result: any, { isPartial, expanded }: any, theme: any, context: any) {
103
- if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
104
- const content = result.content?.[0];
105
- if (context?.isError) return renderToolError(result, theme);
106
- // Collapsed (not expanded): show nothing — the call line carries the
107
- // title, matching the built-in read's fold behavior.
108
- if (!expanded) return new Text("", 0, 0);
109
- const raw = content?.type === "text" ? content.text : "";
110
- return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
111
- },
112
-
113
- async execute(toolCallId: string, params: any, signal: AbortSignal | undefined, onUpdate: any, ctx?: any) {
114
- // User cancelled → delegate to the built-in (builtin handles abort itself)
115
- if (signal?.aborted) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
116
- const anchors = createAnchorFormatter();
117
-
118
- const absPath = canonicalPath(cwd, params.path as string);
119
- let buf: Buffer;
120
- try {
121
- if (await detectSupportedImageMimeTypeFromFile(absPath)) {
122
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
123
- }
124
- buf = await readFile(absPath);
125
- } catch {
126
- // read error → delegate to the built-in (it has polished error messages)
127
- return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
128
- }
129
-
130
- // NUL is a text-safety signal, not an exhaustive binary classifier.
131
- if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
132
-
133
- const text = decodeUtf8(buf);
134
- const allLines = splitLines(text);
135
- const totalLines = allLines.length;
136
-
137
- // offset/limit
138
- const offset = (params.offset as number | undefined) ?? 1;
139
- const limit = (params.limit as number | undefined) ?? MAX_LINES;
140
- const startIdx = Math.max(0, offset - 1);
141
- const endIdx = Math.min(totalLines, startIdx + limit);
142
-
143
- const rows = allLines.slice(startIdx, endIdx).map((line, index) => anchors.row(startIdx + index + 1, line));
144
- const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
145
-
146
- const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
147
- // A file whose last line carries no terminator is a byte-level fact that the
148
- // numbered rows cannot show; state it in the header, the one line the model
149
- // never copies into an edit `body`.
150
- const noFinalNewline = hasFinalNewline(text) ? "" : " · no trailing newline";
151
- const tail = truncation.firstLineExceedsLimit
152
- ? `\n… (line ${offset} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
153
- : truncation.truncated ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)` : "";
154
- const header = `${params.path} · ${totalLines} lines${shownFrom}${noFinalNewline}\n`;
155
- const body = truncation.content;
156
-
157
- return {
158
- content: [{ type: "text" as const, text: header + body + tail }],
159
- details: truncation.truncated ? { truncation } : undefined,
160
- };
161
- },
162
- };
94
+ export function makeReadOverride(cwd: string): ReturnType<typeof createReadToolDefinition> {
95
+ const builtin = createReadToolDefinition(cwd);
96
+ const parameters = {
97
+ ...builtin.parameters,
98
+ additionalProperties: false,
99
+ properties: {
100
+ ...builtin.parameters.properties,
101
+ path: { ...builtin.parameters.properties.path, minLength: 1 },
102
+ offset: {
103
+ ...builtin.parameters.properties.offset,
104
+ ...POSITIVE_SAFE_INTEGER,
105
+ description: "1-based line to start from (default 1).",
106
+ },
107
+ limit: {
108
+ ...builtin.parameters.properties.limit,
109
+ ...POSITIVE_SAFE_INTEGER,
110
+ description: "Maximum lines to read (default 500).",
111
+ },
112
+ },
113
+ };
114
+
115
+ return {
116
+ name: "read" as const,
117
+ label: "read",
118
+ description:
119
+ "Read a file. Text lines show as LINE#HASH│content anchors for edit; CRLF line endings show as LF.",
120
+ promptSnippet: "Read files with editable line anchors",
121
+ promptGuidelines: [
122
+ "Prefer read over shell output for files you intend to edit.",
123
+ "For large files, pass read offset and limit to read only the relevant section.",
124
+ ],
125
+ parameters: parameters as typeof builtin.parameters,
126
+ renderShell: "default" as const,
127
+
128
+ renderCall: builtin.renderCall,
129
+
130
+ renderResult(result, { isPartial, expanded }, theme, context) {
131
+ if (isPartial) return new Text(theme.fg("warning", "Reading…"), 0, 0);
132
+ const content = result.content?.[0];
133
+ if (context?.isError) return renderToolError(result, theme);
134
+ // Collapsed (not expanded): show nothing — the call line carries the
135
+ // title, matching the built-in read's fold behavior.
136
+ if (!expanded) return new Text("", 0, 0);
137
+ const raw = content?.type === "text" ? content.text : "";
138
+ return new Text(renderReadBody(raw, String(context?.args?.path ?? ""), theme), 0, 0);
139
+ },
140
+
141
+ async execute(
142
+ toolCallId: string,
143
+ params: ReadToolInput,
144
+ signal: AbortSignal | undefined,
145
+ onUpdate: AgentToolUpdateCallback<ReadToolDetails | undefined> | undefined,
146
+ ctx: ExtensionContext,
147
+ ) {
148
+ throwIfCancelled(signal);
149
+ const offset = params.offset ?? 1;
150
+ const limit = params.limit ?? MAX_LINES;
151
+ const anchors = createAnchorFormatter();
152
+
153
+ const absPath = canonicalPath(cwd, params.path as string);
154
+ try {
155
+ if (await detectSupportedImageMimeTypeFromFile(absPath)) {
156
+ return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
157
+ }
158
+ } catch {
159
+ return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
160
+ }
161
+
162
+ const start = offset;
163
+ const end = start + limit;
164
+ const rows: string[] = [];
165
+ const crExpansion = Buffer.byteLength(displayCarriageReturns("\r")) - 1;
166
+ let totalRows = 0;
167
+ let totalBytes = 0;
168
+ let outputBytes = 0;
169
+ let truncated = false;
170
+ let firstLineExceedsLimit = false;
171
+ let stats: Awaited<ReturnType<typeof scanTextLines>>;
172
+ try {
173
+ stats = await scanTextLines(
174
+ absPath,
175
+ (number) => number >= start && number < end,
176
+ (line) => {
177
+ const rowBytes =
178
+ line.byteLength +
179
+ line.carriageReturns * crExpansion +
180
+ Buffer.byteLength(anchors.row(line.number, ""));
181
+ totalBytes += rowBytes + (totalRows++ > 0 ? 1 : 0);
182
+ if (truncated) return;
183
+ const nextBytes = outputBytes + rowBytes + (rows.length > 0 ? 1 : 0);
184
+ if (nextBytes > MAX_BYTES) {
185
+ truncated = true;
186
+ firstLineExceedsLimit = rows.length === 0;
187
+ return;
188
+ }
189
+ rows.push(anchors.row(line.number, line.text!));
190
+ outputBytes = nextBytes;
191
+ },
192
+ { signal, maxLineBytes: MAX_BYTES },
193
+ );
194
+ } catch (error) {
195
+ // Keep native filesystem diagnostics without retrying decoding or cancellation failures.
196
+ if (!signal?.aborted && error instanceof Error && "code" in error) {
197
+ return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
198
+ }
199
+ throw error;
200
+ }
201
+ if (stats.hasNul) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
202
+ const pagination =
203
+ !truncated && rows.length > 0 && end <= stats.totalLines
204
+ ? {
205
+ start,
206
+ end: start + rows.length - 1,
207
+ totalLines: stats.totalLines,
208
+ nextOffset: start + rows.length,
209
+ }
210
+ : undefined;
211
+ const truncation = {
212
+ content: rows.join("\n"),
213
+ truncated,
214
+ truncatedBy: truncated ? ("bytes" as const) : null,
215
+ totalLines: totalRows,
216
+ totalBytes,
217
+ outputLines: rows.length,
218
+ outputBytes,
219
+ lastLinePartial: false,
220
+ firstLineExceedsLimit,
221
+ maxLines: totalRows,
222
+ maxBytes: MAX_BYTES,
223
+ };
224
+
225
+ const shownFrom = start > 1 ? ` (from line ${start})` : "";
226
+ // A file whose last line carries no terminator is a byte-level fact that the
227
+ // numbered rows cannot show; state it in the header, the one line the model
228
+ // never copies into an edit `body`.
229
+ const noFinalNewline = stats.finalNewline ? "" : " · no trailing newline";
230
+ const tail = truncation.firstLineExceedsLimit
231
+ ? `\n… (line ${start} exceeds ${MAX_BYTES >> 10}KB; cannot return a complete anchor row. Reducing limit cannot split a physical line; use bash to inspect it in chunks, or replace for a known literal/regex change)`
232
+ : truncation.truncated
233
+ ? `\n… (truncated at ${MAX_BYTES >> 10}KB; use offset/limit to read more)`
234
+ : pagination
235
+ ? `\n… (showing lines ${pagination.start}-${pagination.end} of ${pagination.totalLines}; use offset ${pagination.nextOffset} to continue)`
236
+ : "";
237
+ const header = `${params.path} · ${stats.totalLines} lines${shownFrom}${noFinalNewline}\n`;
238
+ const body = truncation.content;
239
+
240
+ return {
241
+ content: [{ type: "text" as const, text: header + body + tail }],
242
+ details: truncation.truncated ? { truncation } : pagination ? { pagination } : undefined,
243
+ };
244
+ },
245
+ };
163
246
  }