@criogaid/pi-hashline-edit 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +279 -0
  3. package/package.json +50 -0
  4. package/src/core/apply.test.ts +327 -0
  5. package/src/core/apply.ts +264 -0
  6. package/src/core/hash.test.ts +54 -0
  7. package/src/core/hash.ts +68 -0
  8. package/src/core/index.ts +13 -0
  9. package/src/core/lines.test.ts +33 -0
  10. package/src/core/lines.ts +52 -0
  11. package/src/core/types.ts +87 -0
  12. package/src/index.ts +44 -0
  13. package/src/integration/grep-rg.test.ts +390 -0
  14. package/src/pi/action-fusion.test.ts +244 -0
  15. package/src/pi/action-fusion.ts +284 -0
  16. package/src/pi/config.test.ts +22 -0
  17. package/src/pi/config.ts +56 -0
  18. package/src/pi/edit-tool.ts +367 -0
  19. package/src/pi/execute.test.ts +521 -0
  20. package/src/pi/failure-context.test.ts +88 -0
  21. package/src/pi/failure-context.ts +98 -0
  22. package/src/pi/failure-path.test.ts +60 -0
  23. package/src/pi/file-commit.test.ts +200 -0
  24. package/src/pi/file-commit.ts +185 -0
  25. package/src/pi/fusion-card.test.ts +69 -0
  26. package/src/pi/fusion-card.ts +78 -0
  27. package/src/pi/grep-tool.ts +795 -0
  28. package/src/pi/grep.test.ts +515 -0
  29. package/src/pi/pi.test.ts +19 -0
  30. package/src/pi/read-tool.ts +178 -0
  31. package/src/pi/registration.test.ts +41 -0
  32. package/src/pi/render.ts +103 -0
  33. package/src/pi/replace-tool.ts +303 -0
  34. package/src/pi/replace.test.ts +287 -0
  35. package/src/pi/rg-line-filter.test.ts +79 -0
  36. package/src/pi/rg-line-filter.ts +358 -0
  37. package/src/pi/rg-line-ranges.test.ts +30 -0
  38. package/src/pi/rg-line-ranges.ts +106 -0
  39. package/src/pi/state.ts +27 -0
  40. package/src/pi/write-tool.ts +83 -0
  41. package/src/pi/write.test.ts +126 -0
@@ -0,0 +1,358 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import type { Readable } from "node:stream";
3
+
4
+ export const COMMON_RG_ARGS = ["--no-config", "--color=never", "--crlf"];
5
+ export const MAX_RG_RECORD_BYTES = 16 * 1024 * 1024;
6
+
7
+ export interface SearchModes {
8
+ engine: "default" | "pcre2";
9
+ multiline: boolean;
10
+ literal: boolean;
11
+ ignoreCase: boolean;
12
+ }
13
+
14
+ export type LinePredicate = (lines: readonly Buffer[]) => Promise<boolean[]>;
15
+
16
+ interface ExitResult {
17
+ code: number | null;
18
+ stderr: string;
19
+ error?: Error;
20
+ }
21
+
22
+ interface RunningProcess {
23
+ child: ChildProcessWithoutNullStreams;
24
+ done: Promise<ExitResult>;
25
+ kill(): void;
26
+ }
27
+
28
+ export interface RgRunResult {
29
+ code: number | null;
30
+ stderr: string;
31
+ stopped: boolean;
32
+ }
33
+
34
+ function checkAbort(signal?: AbortSignal): void {
35
+ if (signal?.aborted) throw new Error("Operation aborted");
36
+ }
37
+
38
+ function startRg(rgPath: string, args: readonly string[], signal?: AbortSignal): RunningProcess {
39
+ checkAbort(signal);
40
+ const env = { ...process.env };
41
+ delete env.RIPGREP_CONFIG_PATH;
42
+ const child = spawn(rgPath, [...args], {
43
+ stdio: ["pipe", "pipe", "pipe"],
44
+ shell: false,
45
+ env,
46
+ });
47
+ let stderr = "";
48
+ let error: Error | undefined;
49
+ let closed = false;
50
+ let timer: ReturnType<typeof setTimeout> | undefined;
51
+ const kill = () => {
52
+ if (closed) return;
53
+ child.kill("SIGTERM");
54
+ timer ??= setTimeout(() => {
55
+ if (!closed) child.kill("SIGKILL");
56
+ }, 1000);
57
+ timer.unref();
58
+ };
59
+
60
+ child.stderr.on("data", (chunk: Buffer) => {
61
+ if (stderr.length < 65536) stderr += chunk.toString("utf8").slice(0, 65536 - stderr.length);
62
+ });
63
+ child.on("error", (cause) => {
64
+ error = cause;
65
+ });
66
+ child.stdin.on("error", (cause: NodeJS.ErrnoException) => {
67
+ if (cause.code !== "EPIPE") {
68
+ error = cause;
69
+ kill();
70
+ }
71
+ });
72
+ const done = new Promise<ExitResult>((resolve) => {
73
+ child.on("close", (code) => {
74
+ closed = true;
75
+ if (timer) clearTimeout(timer);
76
+ signal?.removeEventListener("abort", kill);
77
+ resolve({ code, stderr, error });
78
+ });
79
+ });
80
+ signal?.addEventListener("abort", kill, { once: true });
81
+ if (signal?.aborted) kill();
82
+ return { child, done, kill };
83
+ }
84
+
85
+ async function* delimitedRecords(stream: Readable, delimiter: number): AsyncGenerator<Buffer> {
86
+ let pending = Buffer.alloc(0);
87
+ for await (const value of stream) {
88
+ const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
89
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
90
+ let at: number;
91
+ while ((at = pending.indexOf(delimiter)) !== -1) {
92
+ if (at > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
93
+ yield pending.subarray(0, at);
94
+ pending = pending.subarray(at + 1);
95
+ }
96
+ if (pending.length > MAX_RG_RECORD_BYTES) throw new Error("ripgrep output record exceeds 16 MiB");
97
+ }
98
+ if (pending.length) yield pending;
99
+ }
100
+
101
+ async function runDelimited(
102
+ rgPath: string,
103
+ args: readonly string[],
104
+ input: Buffer | undefined,
105
+ delimiter: number,
106
+ signal: AbortSignal | undefined,
107
+ onRecord: (record: Buffer) => boolean | Promise<boolean>,
108
+ ): Promise<RgRunResult> {
109
+ const process = startRg(rgPath, args, signal);
110
+ let stopped = false;
111
+ process.child.stdin.end(input);
112
+ try {
113
+ for await (const record of delimitedRecords(process.child.stdout, delimiter)) {
114
+ checkAbort(signal);
115
+ if (!await onRecord(record)) {
116
+ stopped = true;
117
+ process.kill();
118
+ break;
119
+ }
120
+ }
121
+ const result = await process.done;
122
+ checkAbort(signal);
123
+ if (result.error) throw new Error(`Failed to run ripgrep: ${result.error.message}`);
124
+ return { code: result.code, stderr: result.stderr, stopped };
125
+ } finally {
126
+ process.kill();
127
+ await process.done;
128
+ }
129
+ }
130
+
131
+ /** @internal — shared process boundary for JSONL searches and regex validation. */
132
+ export function runRg(
133
+ rgPath: string,
134
+ args: string[],
135
+ signal: AbortSignal | undefined,
136
+ onLine: (line: string) => boolean | Promise<boolean>,
137
+ ): Promise<RgRunResult> {
138
+ return runDelimited(rgPath, args, undefined, 10, signal, (record) =>
139
+ record.length === 0 ? true : onLine(record.toString("utf8"))
140
+ );
141
+ }
142
+
143
+ /** @internal — read NUL-delimited UTF-8 paths from an owned rg process. */
144
+ export function runRgPaths(
145
+ rgPath: string,
146
+ args: string[],
147
+ signal: AbortSignal | undefined,
148
+ onPath: (path: string) => boolean | Promise<boolean>,
149
+ ): Promise<RgRunResult> {
150
+ return runDelimited(rgPath, args, undefined, 0, signal, (record) => {
151
+ const path = record.toString("utf8");
152
+ if (!Buffer.from(path, "utf8").equals(record)) throw new Error("Non-UTF-8 search paths are not supported");
153
+ return onPath(path);
154
+ });
155
+ }
156
+
157
+ function escapeRegex(text: string): string {
158
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
159
+ }
160
+
161
+ interface TextRunResult {
162
+ code: number | null;
163
+ stdout: string;
164
+ stderr: string;
165
+ }
166
+
167
+ export type RunText = (
168
+ rgPath: string,
169
+ args: readonly string[],
170
+ input: Buffer,
171
+ signal?: AbortSignal,
172
+ ) => Promise<TextRunResult>;
173
+
174
+ export const runText: RunText = async (rgPath, args, input, signal) => {
175
+ const process = startRg(rgPath, args, signal);
176
+ const chunks: Buffer[] = [];
177
+ let bytes = 0;
178
+ process.child.stdout.on("data", (chunk: Buffer) => {
179
+ bytes += chunk.length;
180
+ if (bytes <= 65536) chunks.push(chunk);
181
+ else process.kill();
182
+ });
183
+ process.child.stdin.end(input);
184
+ const result = await process.done;
185
+ checkAbort(signal);
186
+ if (result.error) throw result.error;
187
+ if (bytes > 65536) throw new Error("Unexpected ripgrep probe output overflow");
188
+ return {
189
+ code: result.code,
190
+ stderr: result.stderr,
191
+ stdout: Buffer.concat(chunks).toString("utf8"),
192
+ };
193
+ };
194
+
195
+ function modeArgs(modes: Pick<SearchModes, "engine" | "multiline">): string[] {
196
+ return [
197
+ ...COMMON_RG_ARGS,
198
+ `--engine=${modes.engine}`,
199
+ modes.multiline ? "--multiline" : "--no-multiline",
200
+ ];
201
+ }
202
+
203
+ export function matcherArgs(modes: SearchModes, word: boolean): string[] {
204
+ return [
205
+ ...modeArgs(modes),
206
+ modes.ignoreCase ? "--ignore-case" : "--case-sensitive",
207
+ ...(modes.literal ? ["--fixed-strings"] : []),
208
+ ...(word ? ["--word-regexp"] : []),
209
+ ];
210
+ }
211
+
212
+ function pcre2CaseCarrier(patterns: readonly string[]): string {
213
+ return ["(?x)", ...patterns.flatMap((pattern) => pattern.split("\n").map((line) => `#${line}`)), "\\x{41}", ""].join("\n");
214
+ }
215
+
216
+ /** Resolve rg's query-level default case flag; inline regex flags still apply normally. */
217
+ export async function resolveIgnoreCase(
218
+ rgPath: string,
219
+ patterns: readonly string[],
220
+ modes: Pick<SearchModes, "engine" | "multiline" | "literal">,
221
+ explicit: boolean | undefined,
222
+ signal?: AbortSignal,
223
+ run: RunText = runText,
224
+ ): Promise<boolean> {
225
+ checkAbort(signal);
226
+ if (explicit !== undefined) return explicit;
227
+ if (patterns.length === 0) throw new Error("pattern is required (got an empty array)");
228
+
229
+ if (modes.engine === "pcre2") {
230
+ const version = await run(rgPath, ["--version"], Buffer.alloc(0), signal);
231
+ if (version.code !== 0 || !/^ripgrep 15\.0\.0\b/m.test(version.stdout) || !/^features:\+pcre2$/m.test(version.stdout) || !/^PCRE2 10\.45 is available/m.test(version.stdout)) {
232
+ throw new Error("PCRE2 smart-case is not validated for this bundled ripgrep build; set ignoreCase explicitly");
233
+ }
234
+ const result = await run(
235
+ rgPath,
236
+ [...modeArgs(modes), "--smart-case", "--quiet", "-e", pcre2CaseCarrier(patterns), "--", "-"],
237
+ Buffer.from("a\n"),
238
+ signal,
239
+ );
240
+ checkAbort(signal);
241
+ if (result.code !== 0 && result.code !== 1) {
242
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
243
+ }
244
+ return result.code === 0;
245
+ }
246
+
247
+ const sources = patterns.map((pattern) => modes.literal ? escapeRegex(pattern) : pattern);
248
+ const result = await run(
249
+ rgPath,
250
+ [
251
+ ...modeArgs(modes),
252
+ "--smart-case",
253
+ "--encoding=none",
254
+ "--no-heading",
255
+ "--no-filename",
256
+ "--no-line-number",
257
+ "--only-matching",
258
+ "--replace",
259
+ "${1}",
260
+ "-e",
261
+ "(\\p{Lu})",
262
+ ...sources.flatMap((pattern) => ["-e", pattern]),
263
+ "--",
264
+ "-",
265
+ ],
266
+ Buffer.from("a\n"),
267
+ signal,
268
+ );
269
+ checkAbort(signal);
270
+ if (result.code !== 0 && result.code !== 1) {
271
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
272
+ }
273
+ const lines = result.stdout.replace(/\r\n/g, "\n").split("\n");
274
+ if (lines.some((line) => line !== "" && line !== "a")) throw new Error("Unexpected smart-case probe output");
275
+ return lines.includes("a");
276
+ }
277
+
278
+ export async function validatePatterns(
279
+ rgPath: string,
280
+ patterns: readonly string[],
281
+ modes: SearchModes,
282
+ word: boolean,
283
+ signal?: AbortSignal,
284
+ run: RunText = runText,
285
+ ): Promise<void> {
286
+ if (modes.literal) return;
287
+ for (const pattern of patterns) {
288
+ const result = await run(
289
+ rgPath,
290
+ [...matcherArgs(modes, word), "--quiet", "-e", pattern, "--", "-"],
291
+ Buffer.alloc(0),
292
+ signal,
293
+ );
294
+ checkAbort(signal);
295
+ if (result.code !== 0 && result.code !== 1) {
296
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
297
+ }
298
+ }
299
+ }
300
+
301
+ interface RgString {
302
+ text?: string;
303
+ bytes?: string;
304
+ }
305
+
306
+ export function rgBytes(value: RgString): Buffer {
307
+ if (typeof value.text === "string") return Buffer.from(value.text, "utf8");
308
+ if (typeof value.bytes === "string") return Buffer.from(value.bytes, "base64");
309
+ throw new Error("Invalid rg JSON string");
310
+ }
311
+
312
+ export function rgText(value: RgString): string {
313
+ if (typeof value.text === "string") return value.text;
314
+ throw new Error("Non-UTF-8 search paths are not supported");
315
+ }
316
+
317
+ export function createLinePredicate(
318
+ rgPath: string,
319
+ patterns: readonly string[],
320
+ modes: SearchModes,
321
+ word: boolean,
322
+ signal?: AbortSignal,
323
+ ): LinePredicate {
324
+ const args = [
325
+ ...matcherArgs(modes, word),
326
+ "--json",
327
+ "--line-number",
328
+ "--passthru",
329
+ "--text",
330
+ "--encoding=none",
331
+ ...patterns.flatMap((pattern) => ["-e", pattern]),
332
+ "--",
333
+ "-",
334
+ ];
335
+ return async (lines) => {
336
+ checkAbort(signal);
337
+ if (lines.length === 0) return [];
338
+ const records = lines.map((line) => {
339
+ const firstLf = line.indexOf(10);
340
+ if (firstLf >= 0 && firstLf !== line.length - 1) throw new Error("Expected exactly one physical candidate line");
341
+ return firstLf >= 0 ? line : Buffer.concat([line, Buffer.from("\n")]);
342
+ });
343
+ const matches: boolean[] = [];
344
+ const result = await runDelimited(rgPath, args, Buffer.concat(records), 10, signal, (record) => {
345
+ if (record.length === 0) return true;
346
+ const event = JSON.parse(record.toString("utf8"));
347
+ if (event.type !== "match" && event.type !== "context") return true;
348
+ if (event.data.line_number !== matches.length + 1) throw new Error("rg predicate line-number protocol mismatch");
349
+ matches.push(event.type === "match");
350
+ return true;
351
+ });
352
+ if (result.code !== 0 && result.code !== 1) {
353
+ throw new Error(result.stderr.trim() || `ripgrep exited with code ${result.code}`);
354
+ }
355
+ if (matches.length !== lines.length) throw new Error("rg predicate ended before all responses");
356
+ return matches;
357
+ };
358
+ }
@@ -0,0 +1,30 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { intersectRanges, normalizeRanges, submatchesToLineRanges, subtractRanges, unionRanges } from "./rg-line-ranges.ts";
4
+
5
+ test("normalizes and combines half-open physical line ranges", () => {
6
+ assert.deepEqual(normalizeRanges([[5, 7], [1, 3], [3, 5], [9, 10]]), [[1, 7], [9, 10]]);
7
+ assert.deepEqual(unionRanges([[1, 2], [5, 7]], [[2, 4], [8, 9]]), [[1, 4], [5, 7], [8, 9]]);
8
+ assert.deepEqual(intersectRanges([[1, 5], [8, 10]], [[3, 9]]), [[3, 5], [8, 9]]);
9
+ assert.deepEqual(subtractRanges([[1, 8]], [[2, 4], [6, 9]]), [[1, 2], [4, 6]]);
10
+ });
11
+
12
+ test("maps UTF-8 byte offsets and exact newline boundaries to physical lines", () => {
13
+ const bytes = Buffer.from("前alpha\nbeta\n", "utf8");
14
+ assert.deepEqual(submatchesToLineRanges(bytes, 4, [{ start: 3, end: 13 }], 10), [[4, 6]]);
15
+ assert.deepEqual(submatchesToLineRanges(Buffer.from("alpha\nbeta\n"), 2, [{ start: 0, end: 6 }], 5), [[2, 3]]);
16
+ assert.deepEqual(submatchesToLineRanges(Buffer.from("alpha\r\nbeta\r\n"), 2, [{ start: 0, end: 11 }], 5), [[2, 4]]);
17
+ });
18
+
19
+ test("resolves zero-width boundaries without inventing physical lines", () => {
20
+ const bytes = Buffer.from("a\nb\n");
21
+ assert.deepEqual(submatchesToLineRanges(bytes, 1, [{ start: 0, end: 0 }, { start: 2, end: 2 }], 2), [[1, 3]]);
22
+ assert.deepEqual(submatchesToLineRanges(bytes, 1, [{ start: 1, end: 1 }, { start: 3, end: 3 }], 2), [[1, 3]]);
23
+ assert.deepEqual(submatchesToLineRanges(Buffer.from("b"), 2, [{ start: 1, end: 1 }], 2), [[2, 3]]);
24
+ assert.deepEqual(submatchesToLineRanges(Buffer.alloc(0), 1, [{ start: 0, end: 0 }], 0), []);
25
+ });
26
+
27
+ test("rejects malformed ranges and rg byte offsets", () => {
28
+ assert.throws(() => normalizeRanges([[0, 1]]), /Invalid physical line range/);
29
+ assert.throws(() => submatchesToLineRanges(Buffer.from("a"), 1, [{ start: 0, end: 2 }], 1), /Invalid rg submatch/);
30
+ });
@@ -0,0 +1,106 @@
1
+ export type LineRange = readonly [start: number, endExclusive: number];
2
+
3
+ export interface RgSubmatch {
4
+ start: number;
5
+ end: number;
6
+ }
7
+
8
+ function assertRange(range: LineRange): void {
9
+ if (!Number.isSafeInteger(range[0]) || !Number.isSafeInteger(range[1]) || range[0] < 1 || range[1] <= range[0]) {
10
+ throw new Error("Invalid physical line range");
11
+ }
12
+ }
13
+
14
+ export function normalizeRanges(ranges: readonly LineRange[]): LineRange[] {
15
+ const sorted = ranges.map((range) => {
16
+ assertRange(range);
17
+ return range;
18
+ }).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
19
+ const result: LineRange[] = [];
20
+ for (const range of sorted) {
21
+ const previous = result[result.length - 1];
22
+ if (!previous || range[0] > previous[1]) result.push([range[0], range[1]]);
23
+ else if (range[1] > previous[1]) result[result.length - 1] = [previous[0], range[1]];
24
+ }
25
+ return result;
26
+ }
27
+
28
+ export function unionRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
29
+ return normalizeRanges([...left, ...right]);
30
+ }
31
+
32
+ export function intersectRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
33
+ const a = normalizeRanges(left);
34
+ const b = normalizeRanges(right);
35
+ const result: LineRange[] = [];
36
+ let i = 0;
37
+ let j = 0;
38
+ while (i < a.length && j < b.length) {
39
+ const start = Math.max(a[i][0], b[j][0]);
40
+ const end = Math.min(a[i][1], b[j][1]);
41
+ if (start < end) result.push([start, end]);
42
+ if (a[i][1] < b[j][1]) i++;
43
+ else j++;
44
+ }
45
+ return result;
46
+ }
47
+
48
+ export function subtractRanges(left: readonly LineRange[], right: readonly LineRange[]): LineRange[] {
49
+ const source = normalizeRanges(left);
50
+ const removed = normalizeRanges(right);
51
+ const result: LineRange[] = [];
52
+ let j = 0;
53
+ for (const [start, end] of source) {
54
+ let cursor = start;
55
+ while (j < removed.length && removed[j][1] <= cursor) j++;
56
+ let k = j;
57
+ while (k < removed.length && removed[k][0] < end) {
58
+ if (removed[k][0] > cursor) result.push([cursor, Math.min(removed[k][0], end)]);
59
+ cursor = Math.max(cursor, removed[k][1]);
60
+ if (cursor >= end) break;
61
+ k++;
62
+ }
63
+ if (cursor < end) result.push([cursor, end]);
64
+ }
65
+ return result;
66
+ }
67
+
68
+ function countLfBefore(bytes: Buffer, offset: number): number {
69
+ let count = 0;
70
+ for (let i = 0; i < offset; i++) if (bytes[i] === 10) count++;
71
+ return count;
72
+ }
73
+
74
+ function zeroWidthLine(bytes: Buffer, offset: number, eventStartLine: number, fileLineCount: number): number | undefined {
75
+ if (fileLineCount === 0) return undefined;
76
+ const candidate = eventStartLine + countLfBefore(bytes, offset);
77
+ return Math.min(candidate, fileLineCount);
78
+ }
79
+
80
+ /** Convert rg UTF-8 byte offsets into normalized 1-based physical line ranges. */
81
+ export function submatchesToLineRanges(
82
+ bytes: Buffer,
83
+ eventStartLine: number,
84
+ submatches: readonly RgSubmatch[],
85
+ fileLineCount: number,
86
+ ): LineRange[] {
87
+ if (!Number.isSafeInteger(eventStartLine) || eventStartLine < 1 || !Number.isSafeInteger(fileLineCount) || fileLineCount < 0) {
88
+ throw new Error("Invalid rg physical line metadata");
89
+ }
90
+ const ranges: LineRange[] = [];
91
+ for (const submatch of submatches) {
92
+ const { start, end } = submatch;
93
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end > bytes.length) {
94
+ throw new Error("Invalid rg submatch byte offsets");
95
+ }
96
+ if (start === end) {
97
+ const line = zeroWidthLine(bytes, start, eventStartLine, fileLineCount);
98
+ if (line !== undefined) ranges.push([line, line + 1]);
99
+ continue;
100
+ }
101
+ const first = eventStartLine + countLfBefore(bytes, start);
102
+ const last = eventStartLine + countLfBefore(bytes, end - 1);
103
+ if (first <= fileLineCount) ranges.push([first, Math.min(last, fileLineCount) + 1]);
104
+ }
105
+ return normalizeRanges(ranges);
106
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Session-level config holder.
3
+ *
4
+ * globalThis singleton (consistent with the repo's module-identity guidance).
5
+ * Config is loaded when the extension registers and read by the tool
6
+ * overrides.
7
+ *
8
+ * @module pi-hashline-edit/pi
9
+ */
10
+
11
+ import type { HashlineEditConfig } from "./config.ts";
12
+
13
+ const GLOBAL_KEY = "__piHashlineEdit";
14
+ const DEFAULT_CONFIG: HashlineEditConfig = { enabled: true, actionFusion: false, hashLen: 4, shiftRadius: 15 };
15
+
16
+ export interface HashlineEditState {
17
+ config: HashlineEditConfig;
18
+ }
19
+
20
+ export function getState(): HashlineEditState {
21
+ const g = globalThis as Record<string, unknown>;
22
+ const existing = g[GLOBAL_KEY];
23
+ if (existing) return existing as HashlineEditState;
24
+ const state: HashlineEditState = { config: DEFAULT_CONFIG };
25
+ g[GLOBAL_KEY] = state;
26
+ return state;
27
+ }
@@ -0,0 +1,83 @@
1
+ import { Type, type Static } from "typebox";
2
+ import { createWriteToolDefinition, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
3
+ import { getState } from "./state.ts";
4
+ import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
5
+ import { commitFile, FileMutationError, type CommitMode } from "./file-commit.ts";
6
+ import { canonicalPath } from "./read-tool.ts";
7
+ import { computeLineHash, splitLines } from "../core/index.ts";
8
+
9
+ function createWriteSchema(actionFusion: boolean) {
10
+ return Type.Object({
11
+ path: Type.String({ description: "Path to the file to write" }),
12
+ content: Type.String({ description: "Complete file content" }),
13
+ mode: Type.Optional(Type.Union([
14
+ Type.Literal("create", { description: "Fail if the target already exists" }),
15
+ Type.Literal("overwrite", { description: "Fail if the target does not exist" }),
16
+ ])),
17
+ expectedRevision: Type.Optional(Type.String({ description: "Expected SHA-256 revision of an existing target" })),
18
+ ...(actionFusion ? { then_run: createThenRunSchema("Command to run after write succeeds; failure does not roll back the write.") } : {}),
19
+ });
20
+ }
21
+
22
+ const writeSchema = createWriteSchema(false);
23
+ type WriteParams = Omit<Static<typeof writeSchema>, "then_run"> & { then_run?: ThenRunInput };
24
+
25
+ function formatAnchors(content: string, hashLen: number): string {
26
+ const lines = splitLines(content);
27
+ const shown = lines.slice(0, 40).map((line, index) => `${index + 1}#${computeLineHash(index + 1, line, hashLen)}`);
28
+ const suffix = lines.length > shown.length ? `\n… (${lines.length - shown.length} more; read again for full anchors)` : "";
29
+ return shown.length ? `\nFresh anchors: ${shown.join(", ")}${suffix}` : "";
30
+ }
31
+
32
+ export function makeWriteOverride(cwd: string, fusion?: ReturnType<typeof createActionFusionExecutor>): any {
33
+ const parameters = createWriteSchema(fusion !== undefined);
34
+ const builtin = createWriteToolDefinition(cwd);
35
+ return {
36
+ name: "write" as const,
37
+ label: "write",
38
+ description: "Write complete file content. By default, creates missing files and overwrites existing files.",
39
+ promptSnippet: "Write complete file content to a path",
40
+ promptGuidelines: fusion ? ACTION_FUSION_GUIDELINES : [],
41
+ parameters,
42
+ renderShell: "default" as const,
43
+ renderCall: builtin.renderCall,
44
+ renderResult: builtin.renderResult,
45
+ async execute(toolCallId: string, params: WriteParams, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
46
+ const { then_run, ...mutationParams } = params;
47
+ if (!fusion && then_run !== undefined) throw new Error("then_run is unavailable because hashlineEdit.actionFusion is disabled");
48
+ const absolutePath = canonicalPath(cwd, mutationParams.path);
49
+ const hashLen = getState().config.hashLen;
50
+ let mutationAnchors = "";
51
+ const mutate = () => withFileMutationQueue(absolutePath, async () => {
52
+ signal?.throwIfAborted();
53
+ const result = await commitFile(absolutePath, mutationParams.content, {
54
+ mode: mutationParams.mode as CommitMode | undefined,
55
+ expectedRevision: mutationParams.expectedRevision,
56
+ signal,
57
+ });
58
+ try {
59
+ mutationAnchors = formatAnchors(mutationParams.content, hashLen);
60
+ return {
61
+ content: [{ type: "text" as const, text: `${result.created ? "Created" : "Wrote"} ${mutationParams.path}.\nRevision: ${result.revision}` }],
62
+ details: { path: mutationParams.path, revision: result.revision, created: result.created, publication: result.publication },
63
+ };
64
+ } catch (error) {
65
+ throw new FileMutationError("post_process", "PUBLISHED", `file was published but write result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
66
+ }
67
+ });
68
+ const finalizeMutation = (result: any, publishAnchors: boolean) => {
69
+ const details = result.details as { path: string; revision: string; created: boolean };
70
+ const revisionLabel = publishAnchors ? "Revision" : "Mutation revision";
71
+ return {
72
+ ...result,
73
+ content: [{
74
+ type: "text" as const,
75
+ text: `${details.created ? "Created" : "Wrote"} ${details.path}.\n${revisionLabel}: ${details.revision}${publishAnchors ? mutationAnchors : ""}`,
76
+ }],
77
+ };
78
+ };
79
+ if (!fusion) return finalizeMutation(await mutate(), true);
80
+ return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, finalizeMutation, signal, ctx, onUpdate });
81
+ },
82
+ };
83
+ }