@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
@@ -0,0 +1,9 @@
1
+ /** Error-code messages shared by core validation and the tool layer. */
2
+ export const UNSUPPORTED_ENCODING = "UNSUPPORTED_ENCODING: expected valid UTF-8.";
3
+ export const UNSUPPORTED_TEXT_NUL = "UNSUPPORTED_TEXT: NUL bytes are not editable.";
4
+ export const INVALID_UNICODE = "INVALID_UNICODE: content cannot be encoded losslessly as UTF-8.";
5
+
6
+ /** Message text for a caught value; non-Error throws are stringified. */
7
+ export function errorMessage(error: unknown): string {
8
+ return error instanceof Error ? error.message : String(error);
9
+ }
@@ -13,16 +13,16 @@ test("computeLineHash is stable and base32", () => {
13
13
  });
14
14
 
15
15
  test("different line number → different hash (even for identical content)", () => {
16
- assert.notEqual(computeLineHash(2, ""), computeLineHash(5, ""));
17
- assert.notEqual(computeLineHash(1, "}"), computeLineHash(2, "}"));
16
+ assert.notEqual(computeLineHash(2, "", 4), computeLineHash(5, "", 4));
17
+ assert.notEqual(computeLineHash(1, "}", 4), computeLineHash(2, "}", 4));
18
18
  });
19
19
 
20
20
  test("different content → different hash", () => {
21
- assert.notEqual(computeLineHash(1, "a"), computeLineHash(1, "b"));
21
+ assert.notEqual(computeLineHash(1, "a", 4), computeLineHash(1, "b", 4));
22
22
  });
23
23
 
24
24
  test("same (line, content) → same hash", () => {
25
- assert.equal(computeLineHash(7, "x"), computeLineHash(7, "x"));
25
+ assert.equal(computeLineHash(7, "x", 4), computeLineHash(7, "x", 4));
26
26
  });
27
27
 
28
28
  test("base32 alphabet (without I/L/O/U) in bulk", () => {
@@ -33,16 +33,16 @@ test("base32 alphabet (without I/L/O/U) in bulk", () => {
33
33
  });
34
34
 
35
35
  test("hashFileLines length equals line count", () => {
36
- assert.equal(hashFileLines(["a", "b", "c"]).length, 3);
36
+ assert.equal(hashFileLines(["a", "b", "c"], 4).length, 3);
37
37
  });
38
38
 
39
39
  test("hashFileLines empty file", () => {
40
- assert.deepEqual(hashFileLines([]), []);
40
+ assert.deepEqual(hashFileLines([], 4), []);
41
41
  });
42
42
 
43
43
  test("hashFileLines normally disambiguates repeated content without changing hash length", () => {
44
44
  const lines = ["", "", "", "", "", "}", "}", "}", "return", "return", ",", ","];
45
- const hashes = hashFileLines(lines);
45
+ const hashes = hashFileLines(lines, 4);
46
46
  assert.equal(new Set(hashes).size, hashes.length, "unexpected collision in fixture");
47
47
  for (const h of hashes) assert.equal(h.length, 4, `hash ${h} is not 4 chars`);
48
48
  });
@@ -66,7 +66,7 @@ test("hashLen 8 has a leading zero due to the 32-bit hash limit", () => {
66
66
  });
67
67
 
68
68
  test("computeLineHash produces output identical to hashing full interpolated string", () => {
69
- function referenceHash(line: number, content: string, len = 4): string {
69
+ function referenceHash(line: number, content: string, len: number): string {
70
70
  let h = 0x811c9dc5;
71
71
  const str = `${line}\n${content}`;
72
72
  for (let i = 0; i < str.length; i++) {
package/src/core/hash.ts CHANGED
@@ -21,7 +21,7 @@
21
21
  */
22
22
 
23
23
  /** Crockford base32 alphabet (without I/L/O/U to avoid ambiguous characters). Exactly 32 characters. */
24
- const BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
24
+ export const HASH_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
25
25
 
26
26
  /**
27
27
  * FNV-1a 32-bit. Stable (same input always yields the same output), evenly
@@ -66,7 +66,7 @@ function fnv1a32Line(line: number, content: string): number {
66
66
  function toBase32(n: number, len: number): string {
67
67
  let encoded = "";
68
68
  for (let i = 0; i < len; i++) {
69
- encoded = BASE32[n & 31] + encoded;
69
+ encoded = HASH_ALPHABET[n & 31] + encoded;
70
70
  n >>>= 5;
71
71
  }
72
72
  return encoded;
@@ -81,13 +81,13 @@ export const HASH_LEN_MAX = 8;
81
81
  *
82
82
  * @param line 1-based line number
83
83
  * @param content the line's content (no line terminator)
84
- * @param len hash length (default 4, 20 bits ≈ 1M values)
84
+ * @param len caller-selected hash length
85
85
  */
86
- export function computeLineHash(line: number, content: string, len = 4): string {
86
+ export function computeLineHash(line: number, content: string, len: number): string {
87
87
  return toBase32(fnv1a32Line(line, content), len);
88
88
  }
89
89
 
90
90
  /** Compute compact per-line checksums; callers must treat collisions as possible. */
91
- export function hashFileLines(lines: readonly string[], len = 4): string[] {
91
+ export function hashFileLines(lines: readonly string[], len: number): string[] {
92
92
  return lines.map((content, i) => computeLineHash(i + 1, content, len));
93
93
  }
@@ -1,12 +1,12 @@
1
- import { escapeRegex } from "../core/text.ts";
1
+ import { escapeRegex } from "./text.ts";
2
2
  import {
3
3
  createLfTextView,
4
4
  detectLineEnding,
5
5
  normalizeLineEndings,
6
6
  restoreLineEndings,
7
- } from "../core/lines.ts";
8
- import { findSortedRangeConflict } from "../core/ranges.ts";
9
- import { errorMessage } from "./error-text.ts";
7
+ } from "./lines.ts";
8
+ import { findSortedRangeConflict } from "./ranges.ts";
9
+ import { errorMessage } from "./errors.ts";
10
10
 
11
11
  export interface Replacement {
12
12
  find: string;
package/src/core/text.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  import { TextDecoder } from "node:util";
2
2
 
3
- export const UNSUPPORTED_ENCODING = "UNSUPPORTED_ENCODING: expected valid UTF-8.";
4
- export const UNSUPPORTED_TEXT_NUL = "UNSUPPORTED_TEXT: NUL bytes are not editable.";
5
- export const INVALID_UNICODE = "INVALID_UNICODE: content cannot be encoded losslessly as UTF-8.";
3
+ import { INVALID_UNICODE, UNSUPPORTED_ENCODING, UNSUPPORTED_TEXT_NUL } from "./errors.ts";
6
4
 
7
5
  /** Why text cannot be written as editable UTF-8 (NUL or unpaired surrogates); undefined when it can. */
8
6
  export function unwritableTextReason(text: string): string | undefined {
package/src/core/types.ts CHANGED
@@ -76,16 +76,13 @@ export interface AnchorFailure {
76
76
  readonly current: { readonly hash: string; readonly content: string } | null;
77
77
  }
78
78
 
79
- /**
80
- * Record for one supplied anchor in the immutable apply snapshot.
81
- * not_checked means input validation rejected the batch before hashing.
82
- */
79
+ /** Record for one supplied anchor in the immutable apply snapshot. */
83
80
  export interface AnchorCheck {
84
81
  readonly opIndex: number;
85
82
  readonly which: "anchor" | "end";
86
83
  readonly op: Edit["op"];
87
84
  readonly cited: Anchor;
88
- readonly status: "matched" | "mismatched" | "not_checked";
85
+ readonly status: "matched" | "mismatched";
89
86
  }
90
87
 
91
88
  /** Batch-level failure. Anchor checks describe only checksum validation in this snapshot. */
@@ -96,7 +93,7 @@ export type ApplyFailure =
96
93
  readonly checks: readonly AnchorCheck[];
97
94
  }
98
95
  | {
99
- readonly kind: "input" | "range";
96
+ readonly kind: "range";
100
97
  readonly message: string;
101
98
  readonly checks: readonly AnchorCheck[];
102
99
  };
@@ -107,7 +104,7 @@ export type ApplyFailure =
107
104
  * callers retain their content while compacting anchors for caller-supplied rows.
108
105
  * Byte-identical output succeeds with changed=false and empty anchor lists.
109
106
  * On failure, `failure` is either the collected set of anchor failures
110
- * (each with recovery) or an input/range error, plus per-input anchor checks.
107
+ * (each with recovery) or a range error, plus per-input anchor checks.
111
108
  * Nothing is written on failure.
112
109
  */
113
110
  export type ApplyResult =
package/src/index.ts CHANGED
@@ -15,37 +15,35 @@
15
15
  import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
16
16
  import type { TSchema } from "typebox";
17
17
  import { loadConfig } from "./pi/config.ts";
18
- import { getState } from "./pi/state.ts";
19
18
  import { makeEditOverride } from "./pi/edit-tool.ts";
20
19
  import { makeReadOverride } from "./pi/read-tool.ts";
21
20
  import { makeGrepOverride } from "./pi/grep-tool.ts";
22
21
  import { makeReplaceTool } from "./pi/replace-tool.ts";
23
22
  import { makeWriteOverride } from "./pi/write-tool.ts";
24
23
  import { createActionFusionExecutor } from "./pi/action-fusion.ts";
25
- import { registerFusionCards } from "./pi/fusion-card.ts";
26
- import { withMutationStatus } from "./pi/render.ts";
24
+ import { registerFusionCards, withMutationStatus } from "./pi/fusion-card.ts";
27
25
 
28
26
  export default function (pi: ExtensionAPI) {
29
27
  const cwd = process.cwd();
30
28
 
31
- const state = getState();
32
- state.config = loadConfig(cwd);
29
+ // Tools capture this snapshot at registration; a reload registers them again.
30
+ const config = loadConfig(cwd);
33
31
 
34
32
  // `enabled: false` leaves the extension fully inert — pi's built-in
35
33
  // read/edit/grep/replace/write stay in place, as if this package were not installed.
36
- if (state.config.enabled) {
34
+ if (config.enabled) {
37
35
  const reportProgress = registerFusionCards(pi);
38
- const fusion = state.config.actionFusion
36
+ const fusion = config.actionFusion
39
37
  ? createActionFusionExecutor(undefined, reportProgress)
40
38
  : undefined;
41
39
  const registerMutation = <TParams extends TSchema, TDetails>(
42
40
  tool: ToolDefinition<TParams, TDetails>,
43
41
  ) => pi.registerTool(fusion ? withMutationStatus(tool) : tool);
44
42
  registerMutation(makeWriteOverride(cwd, fusion));
45
- registerMutation(makeEditOverride(cwd, fusion));
46
- registerMutation(makeReplaceTool(cwd, fusion));
43
+ registerMutation(makeEditOverride(cwd, config, fusion));
44
+ registerMutation(makeReplaceTool(cwd, config, fusion));
47
45
 
48
- pi.registerTool(makeReadOverride(cwd));
49
- pi.registerTool(makeGrepOverride(cwd));
46
+ pi.registerTool(makeReadOverride(cwd, config));
47
+ pi.registerTool(makeGrepOverride(cwd, config));
50
48
  }
51
49
  }
@@ -0,0 +1,206 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { test } from "node:test";
6
+ import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
7
+ import registerHashline from "../index.ts";
8
+ import { computeLineHash } from "../core/hash.ts";
9
+ import { callTool } from "../pi/tool-call.testing.ts";
10
+ import { DEFAULT_CONFIG, type HashlineEditConfig } from "../pi/config.ts";
11
+
12
+ test("registered tools retain their configuration when another tool set is registered", async (t) => {
13
+ const directory = await mkdtemp(join(tmpdir(), "hashline-config-registration-"));
14
+ const previousCwd = process.cwd();
15
+ try {
16
+ await mkdir(join(directory, ".pi"));
17
+ process.chdir(directory);
18
+ const register = async (config: HashlineEditConfig) => {
19
+ await writeFile(
20
+ join(directory, ".pi", "settings.json"),
21
+ JSON.stringify({ hashlineEdit: config }),
22
+ );
23
+ const tools = new Map<string, ToolDefinition>();
24
+ registerHashline({
25
+ on() {},
26
+ registerEntryRenderer() {},
27
+ registerTool(tool: ToolDefinition) {
28
+ tools.set(tool.name, tool);
29
+ },
30
+ } as unknown as ExtensionAPI);
31
+ return { tools, config };
32
+ };
33
+ const registrations = [
34
+ {
35
+ ...(await register({
36
+ ...DEFAULT_CONFIG,
37
+ actionFusion: false,
38
+ hashLen: 6,
39
+ shiftRadius: 1,
40
+ read: { defaultLimit: 1, maxKiB: 1 },
41
+ grep: { defaultLimit: 1, defaultContext: 1 },
42
+ replace: { regexTimeoutMs: 1_000 },
43
+ })),
44
+ expectedGrepLines: [1, 2, 3],
45
+ },
46
+ {
47
+ ...(await register({
48
+ ...DEFAULT_CONFIG,
49
+ actionFusion: false,
50
+ hashLen: 8,
51
+ shiftRadius: 0,
52
+ read: { defaultLimit: 2, maxKiB: 2 },
53
+ grep: { defaultLimit: 2, defaultContext: 0 },
54
+ replace: { regexTimeoutMs: 1_500 },
55
+ })),
56
+ expectedGrepLines: [2, 6],
57
+ },
58
+ ];
59
+
60
+ for (const { tools, config, expectedGrepLines } of registrations) {
61
+ const { hashLen, shiftRadius, read, grep, replace } = config;
62
+ for (const name of ["read", "grep", "replace", "edit"] as const) {
63
+ await t.test(`${name} retains the registered hash length ${hashLen}`, async () => {
64
+ const tool = tools.get(name);
65
+ assert.ok(tool);
66
+ const path = `${hashLen}-${name}.txt`;
67
+ await writeFile(join(directory, path), "before\n");
68
+ const params = {
69
+ read: { path },
70
+ grep: { path, pattern: "before", literal: true },
71
+ replace: { path, replacements: [{ find: "before", replace: "after" }] },
72
+ edit: {
73
+ path,
74
+ edits: [
75
+ {
76
+ op: "replace",
77
+ anchor: `1#${computeLineHash(1, "before", hashLen)}`,
78
+ body: ["after"],
79
+ },
80
+ ],
81
+ },
82
+ }[name];
83
+ const result = await callTool(tool, params);
84
+ const expected = name === "read" || name === "grep" ? "before" : "after";
85
+ const anchor = `1#${computeLineHash(1, expected, hashLen)}`;
86
+ assert.match(result.content[0].text, new RegExp(`^${anchor}(?:│|$)`, "m"));
87
+ assert.equal(await readFile(join(directory, path), "utf8"), `${expected}\n`);
88
+ });
89
+ }
90
+
91
+ await t.test(`edit retains the registered recovery radius ${shiftRadius}`, async () => {
92
+ const tool = tools.get("edit");
93
+ assert.ok(tool);
94
+ const path = `${hashLen}-recovery.txt`;
95
+ const text = "changed\ntarget\n";
96
+ await writeFile(join(directory, path), text);
97
+ await assert.rejects(
98
+ callTool(tool, {
99
+ path,
100
+ edits: [{ op: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
101
+ }),
102
+ shiftRadius === 0
103
+ ? /no checksum-matching candidate found/
104
+ : /checksum-matching candidate 2#/,
105
+ );
106
+ assert.equal(await readFile(join(directory, path), "utf8"), text);
107
+ });
108
+
109
+ await t.test(
110
+ `read retains registered limit ${read.defaultLimit} and budget ${read.maxKiB} KiB`,
111
+ async () => {
112
+ const tool = tools.get("read");
113
+ assert.ok(tool);
114
+ const path = `${hashLen}-read-settings.txt`;
115
+ const lines = ["first", "second", "third"];
116
+ await writeFile(join(directory, path), `${lines.join("\n")}\n`);
117
+ const result = await callTool(tool, { path });
118
+ assert.deepEqual(
119
+ result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
120
+ lines
121
+ .slice(0, read.defaultLimit)
122
+ .map(
123
+ (content, index) =>
124
+ `${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`,
125
+ ),
126
+ );
127
+ assert.equal(result.details.pagination.nextOffset, read.defaultLimit + 1);
128
+
129
+ const wide = "界".repeat(500);
130
+ await writeFile(join(directory, path), `${wide}\n`);
131
+ const bounded = await callTool(tool, { path });
132
+ if (read.maxKiB === 1) {
133
+ assert.match(bounded.content[0].text, /line 1 exceeds 1 KiB/);
134
+ assert.equal(bounded.details.truncation.maxBytes, 1024);
135
+ assert.equal(bounded.details.truncation.outputBytes, 0);
136
+ } else {
137
+ assert.ok(
138
+ bounded.content[0].text.includes(`1#${computeLineHash(1, wide, hashLen)}│${wide}`),
139
+ );
140
+ assert.equal(bounded.details, undefined);
141
+ }
142
+ },
143
+ );
144
+
145
+ await t.test(
146
+ `grep retains registered limit ${grep.defaultLimit} and context ${grep.defaultContext}`,
147
+ async () => {
148
+ const tool = tools.get("grep");
149
+ assert.ok(tool);
150
+ const path = `${hashLen}-grep-settings.txt`;
151
+ const lines = [
152
+ "before one",
153
+ "needle one",
154
+ "after one",
155
+ "gap",
156
+ "before two",
157
+ "needle two",
158
+ "after two",
159
+ "gap",
160
+ "before three",
161
+ "needle three",
162
+ "after three",
163
+ ];
164
+ await writeFile(join(directory, path), `${lines.join("\n")}\n`);
165
+ const result = await callTool(tool, { path, pattern: "needle", literal: true });
166
+ assert.deepEqual(
167
+ result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
168
+ expectedGrepLines.map(
169
+ (line) =>
170
+ `${line}#${computeLineHash(line, lines[line - 1], hashLen)}│${lines[line - 1]}`,
171
+ ),
172
+ );
173
+ assert.match(
174
+ result.content[0].text,
175
+ new RegExp(`${grep.defaultLimit} matches limit reached`),
176
+ );
177
+ },
178
+ );
179
+
180
+ await t.test(
181
+ `replace retains registered regex timeout ${replace.regexTimeoutMs}ms`,
182
+ async () => {
183
+ const tool = tools.get("replace");
184
+ assert.ok(tool);
185
+ const path = `${hashLen}-replace-settings.txt`;
186
+ const original = `${"a".repeat(35)}!`;
187
+ await writeFile(join(directory, path), original);
188
+ await assert.rejects(
189
+ callTool(tool, {
190
+ path,
191
+ replacements: [{ find: "^(a+)+$", replace: "changed", regex: true }],
192
+ }),
193
+ (error: unknown) =>
194
+ error instanceof Error &&
195
+ error.message ===
196
+ `Replace ${path}: regex evaluation timed out after ${replace.regexTimeoutMs}ms`,
197
+ );
198
+ assert.equal(await readFile(join(directory, path), "utf8"), original);
199
+ },
200
+ );
201
+ }
202
+ } finally {
203
+ process.chdir(previousCwd);
204
+ await rm(directory, { recursive: true, force: true });
205
+ }
206
+ });