@criogaid/pi-hashline-edit 0.4.0 → 0.5.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.
Files changed (66) hide show
  1. package/README.md +134 -30
  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.test.ts +30 -1
  10. package/src/core/text.ts +9 -6
  11. package/src/core/types.ts +4 -7
  12. package/src/index.ts +9 -11
  13. package/src/integration/config-registration.test.ts +206 -0
  14. package/src/integration/grep-rg.test.ts +285 -153
  15. package/src/integration/large-text.test.ts +11 -12
  16. package/src/integration/replace-package.test.ts +11 -7
  17. package/src/pi/action-fusion.test.ts +251 -39
  18. package/src/pi/action-fusion.ts +113 -117
  19. package/src/pi/anchor-format.test.ts +91 -24
  20. package/src/pi/anchor-format.ts +43 -9
  21. package/src/pi/budgets.ts +7 -2
  22. package/src/pi/config.test.ts +153 -40
  23. package/src/pi/config.ts +87 -41
  24. package/src/pi/diagnostic-buffer.test.ts +58 -0
  25. package/src/pi/diagnostic-buffer.ts +59 -0
  26. package/src/pi/e2e-scenarios.test.ts +13 -11
  27. package/src/pi/edit-tool.ts +21 -157
  28. package/src/pi/error-text.ts +10 -5
  29. package/src/pi/execute.test.ts +299 -175
  30. package/src/pi/failure-context.test.ts +7 -2
  31. package/src/pi/failure-context.ts +155 -8
  32. package/src/pi/failure-path.test.ts +33 -26
  33. package/src/pi/file-commit.ts +2 -1
  34. package/src/pi/fusion-card.test.ts +26 -0
  35. package/src/pi/fusion-card.ts +102 -6
  36. package/src/pi/grep-output.ts +50 -35
  37. package/src/pi/grep-render.ts +13 -15
  38. package/src/pi/grep-scope.ts +8 -46
  39. package/src/pi/grep-search.ts +90 -63
  40. package/src/pi/grep-tool.ts +109 -121
  41. package/src/pi/grep.test.ts +597 -377
  42. package/src/pi/mutation-outcome.testing.ts +22 -0
  43. package/src/pi/mutation-result.test.ts +51 -2
  44. package/src/pi/mutation-result.ts +62 -55
  45. package/src/pi/mutation-runner.ts +16 -33
  46. package/src/pi/pi.test.ts +11 -6
  47. package/src/pi/read-tool.ts +62 -34
  48. package/src/pi/registration.test.ts +7 -7
  49. package/src/pi/render.test.ts +143 -9
  50. package/src/pi/render.ts +32 -96
  51. package/src/pi/replace-regex.ts +54 -0
  52. package/src/pi/replace-tool.ts +25 -59
  53. package/src/pi/replace-worker.ts +2 -2
  54. package/src/pi/replace.test.ts +62 -58
  55. package/src/pi/result-safety.test.ts +124 -84
  56. package/src/pi/rg-line-ranges.ts +3 -2
  57. package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
  58. package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
  59. package/src/pi/rg-text-view.ts +25 -38
  60. package/src/pi/schema.ts +2 -10
  61. package/src/pi/text-stream.test.ts +153 -0
  62. package/src/pi/text-stream.ts +33 -13
  63. package/src/pi/write-tool.ts +3 -2
  64. package/src/pi/write.test.ts +10 -9
  65. package/src/core/index.ts +0 -14
  66. package/src/pi/state.ts +0 -26
@@ -3,12 +3,45 @@ 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 { loadConfig } from "./config.ts";
6
+ import { DEFAULT_CONFIG, loadConfig } from "./config.ts";
7
7
 
8
- test("actionFusion defaults on and honors explicit disabling", async () => {
8
+ async function withSettings(
9
+ fn: (
10
+ write: (settings: unknown) => Promise<void>,
11
+ root: string,
12
+ agentDir: string,
13
+ ) => Promise<void>,
14
+ ) {
9
15
  const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
16
+ const agentDir = join(root, "agent");
17
+ const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
10
18
  try {
19
+ process.env.PI_CODING_AGENT_DIR = agentDir;
20
+ await mkdir(agentDir);
11
21
  await mkdir(join(root, ".pi"));
22
+ const path = join(root, ".pi", "settings.json");
23
+ await fn((settings) => writeFile(path, JSON.stringify(settings)), root, agentDir);
24
+ } finally {
25
+ if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
26
+ else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
27
+ await rm(root, { recursive: true, force: true });
28
+ }
29
+ }
30
+
31
+ test("defaults come from the settings schema", () => {
32
+ assert.deepEqual(DEFAULT_CONFIG, {
33
+ enabled: true,
34
+ actionFusion: true,
35
+ hashLen: 4,
36
+ shiftRadius: 15,
37
+ read: { defaultLimit: 500, maxKiB: 256 },
38
+ grep: { defaultLimit: 100, defaultContext: 0 },
39
+ replace: { regexTimeoutMs: 5_000 },
40
+ });
41
+ });
42
+
43
+ test("actionFusion defaults on and honors explicit disabling", () =>
44
+ withSettings(async (write, root) => {
12
45
  for (const [actionFusion, expected] of [
13
46
  [undefined, true],
14
47
  [false, false],
@@ -17,38 +50,16 @@ test("actionFusion defaults on and honors explicit disabling", async () => {
17
50
  ["false", true],
18
51
  [0, true],
19
52
  ]) {
20
- await writeFile(
21
- join(root, ".pi", "settings.json"),
22
- JSON.stringify({ hashlineEdit: { actionFusion } }),
23
- );
24
- assert.deepEqual(loadConfig(root), {
25
- enabled: true,
26
- actionFusion: expected,
27
- hashLen: 4,
28
- shiftRadius: 15,
29
- });
53
+ await write({ hashlineEdit: { actionFusion } });
54
+ assert.deepEqual(loadConfig(root), { ...DEFAULT_CONFIG, actionFusion: expected });
30
55
  }
31
- } finally {
32
- await rm(root, { recursive: true, force: true });
33
- }
34
- });
56
+ }));
35
57
 
36
- test("config rejects fractional values and tolerates malformed settings shapes", async () => {
37
- const root = await mkdtemp(join(tmpdir(), "hashline-config-"));
38
- try {
39
- await mkdir(join(root, ".pi"));
40
- const path = join(root, ".pi", "settings.json");
58
+ test("config rejects fractional values and tolerates malformed settings shapes", () =>
59
+ withSettings(async (write, root) => {
41
60
  for (const value of [3.5, -1, "4", null]) {
42
- await writeFile(
43
- path,
44
- JSON.stringify({ hashlineEdit: { hashLen: value, shiftRadius: value } }),
45
- );
46
- assert.deepEqual(loadConfig(root), {
47
- enabled: true,
48
- actionFusion: true,
49
- hashLen: 4,
50
- shiftRadius: 15,
51
- });
61
+ await write({ hashlineEdit: { hashLen: value, shiftRadius: value } });
62
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
52
63
  }
53
64
  for (const rootValue of [
54
65
  null,
@@ -58,15 +69,117 @@ test("config rejects fractional values and tolerates malformed settings shapes",
58
69
  { hashlineEdit: [] },
59
70
  { hashlineEdit: "invalid" },
60
71
  ]) {
61
- await writeFile(path, JSON.stringify(rootValue));
62
- const config = loadConfig(root);
63
- assert.ok(Number.isInteger(config.hashLen));
64
- assert.ok(Number.isInteger(config.shiftRadius));
72
+ await write(rootValue);
73
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
65
74
  }
66
- await writeFile(path, JSON.stringify({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } }));
75
+ await write({ hashlineEdit: { hashLen: 8, shiftRadius: 0 } });
67
76
  assert.equal(loadConfig(root).hashLen, 8);
68
77
  assert.equal(loadConfig(root).shiftRadius, 0);
69
- } finally {
70
- await rm(root, { recursive: true, force: true });
71
- }
72
- });
78
+ }));
79
+
80
+ test("tool groups resolve each setting independently", () =>
81
+ withSettings(async (write, root) => {
82
+ await write({
83
+ hashlineEdit: {
84
+ read: { defaultLimit: 50, maxKiB: 0 },
85
+ grep: { defaultContext: 21, defaultLimit: 7 },
86
+ replace: "fast",
87
+ },
88
+ });
89
+ assert.deepEqual(loadConfig(root), {
90
+ ...DEFAULT_CONFIG,
91
+ read: { defaultLimit: 50, maxKiB: DEFAULT_CONFIG.read.maxKiB },
92
+ grep: { defaultLimit: 7, defaultContext: DEFAULT_CONFIG.grep.defaultContext },
93
+ });
94
+ await write({ hashlineEdit: { replace: { regexTimeoutMs: 20_000 } } });
95
+ assert.equal(loadConfig(root).replace.regexTimeoutMs, 20_000);
96
+ }));
97
+
98
+ test("project settings replace global groups while absent project settings use global values", () =>
99
+ withSettings(async (write, root, agentDir) => {
100
+ const globalConfig = {
101
+ ...DEFAULT_CONFIG,
102
+ enabled: false,
103
+ actionFusion: false,
104
+ hashLen: 8,
105
+ shiftRadius: 0,
106
+ read: { defaultLimit: 7, maxKiB: 2 },
107
+ grep: { defaultLimit: 3, defaultContext: 2 },
108
+ replace: { regexTimeoutMs: 1_000 },
109
+ };
110
+ await writeFile(
111
+ join(agentDir, "settings.json"),
112
+ JSON.stringify({ hashlineEdit: globalConfig }),
113
+ );
114
+ assert.deepEqual(loadConfig(), globalConfig);
115
+ assert.deepEqual(loadConfig(root), globalConfig);
116
+ for (const settings of [{}, null, [], 42, "settings"]) {
117
+ await write(settings);
118
+ assert.deepEqual(loadConfig(root), globalConfig);
119
+ }
120
+ await write({ hashlineEdit: { read: { defaultLimit: 2 } } });
121
+ assert.deepEqual(loadConfig(root), {
122
+ ...DEFAULT_CONFIG,
123
+ read: { defaultLimit: 2, maxKiB: DEFAULT_CONFIG.read.maxKiB },
124
+ });
125
+ await write({ hashlineEdit: {} });
126
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
127
+ }));
128
+
129
+ test("invalid tool groups default independently without discarding valid sibling groups", () =>
130
+ withSettings(async (write, root) => {
131
+ const configured = {
132
+ ...DEFAULT_CONFIG,
133
+ enabled: false,
134
+ hashLen: 6,
135
+ shiftRadius: 0,
136
+ read: { defaultLimit: 2, maxKiB: 1 },
137
+ grep: { defaultLimit: 3, defaultContext: 2 },
138
+ replace: { regexTimeoutMs: 1_000 },
139
+ };
140
+ for (const group of ["read", "grep", "replace"] as const) {
141
+ for (const value of [null, [], 42, "invalid", true]) {
142
+ await write({ hashlineEdit: { ...configured, [group]: value } });
143
+ assert.deepEqual(loadConfig(root), { ...configured, [group]: DEFAULT_CONFIG[group] });
144
+ }
145
+ }
146
+ }));
147
+
148
+ test("tool settings accept their boundary values and default invalid leaves", () =>
149
+ withSettings(async (write, root) => {
150
+ const cases = [
151
+ {
152
+ group: "read",
153
+ key: "defaultLimit",
154
+ valid: [1, Number.MAX_SAFE_INTEGER],
155
+ invalid: [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "2", null],
156
+ },
157
+ { group: "read", key: "maxKiB", valid: [1, 4096], invalid: [0, 4097, 1.5, "2", null] },
158
+ {
159
+ group: "grep",
160
+ key: "defaultLimit",
161
+ valid: [1, Number.MAX_SAFE_INTEGER],
162
+ invalid: [0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1, "2", null],
163
+ },
164
+ { group: "grep", key: "defaultContext", valid: [0, 20], invalid: [-1, 21, 1.5, "2", null] },
165
+ {
166
+ group: "replace",
167
+ key: "regexTimeoutMs",
168
+ valid: [1_000, 300_000],
169
+ invalid: [999, 300_001, 1000.5, "1000", null],
170
+ },
171
+ ] as const;
172
+ for (const { group, key, valid, invalid } of cases) {
173
+ for (const value of valid) {
174
+ await write({ hashlineEdit: { [group]: { [key]: value } } });
175
+ assert.deepEqual(loadConfig(root), {
176
+ ...DEFAULT_CONFIG,
177
+ [group]: { ...DEFAULT_CONFIG[group], [key]: value },
178
+ });
179
+ }
180
+ for (const value of invalid) {
181
+ await write({ hashlineEdit: { [group]: { [key]: value } } });
182
+ assert.deepEqual(loadConfig(root), DEFAULT_CONFIG);
183
+ }
184
+ }
185
+ }));
package/src/pi/config.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Config loading: project `.pi/settings.json` replaces global, per-field `??`
3
- * falls back to DEFAULT. Config field `hashlineEdit` (drop the `pi-` prefix,
4
- * camelCase).
2
+ * Config loading: project `.pi/settings.json` replaces global, and each setting
3
+ * that is missing or invalid falls back to its schema default. Config field
4
+ * `hashlineEdit` (drop the `pi-` prefix, camelCase).
5
5
  *
6
6
  * @module pi-hashline-edit/pi
7
7
  */
@@ -9,37 +9,98 @@
9
9
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
10
10
  import * as fs from "node:fs";
11
11
  import * as path from "node:path";
12
+ import { Type, type Static, type TSchema } from "typebox";
13
+ import { Value } from "typebox/value";
12
14
  import { HASH_LEN_MAX, HASH_LEN_MIN } from "../core/hash.ts";
13
- import { isIntegerInRange } from "./schema.ts";
15
+ import { GREP_CONTEXT_RANGE, integerRange, POSITIVE_SAFE_INTEGER } from "./schema.ts";
14
16
 
15
- export interface HashlineEditConfig {
16
- /** Master switch: when false the extension registers no tools — pi's built-ins remain. */
17
- enabled: boolean;
18
- /** Expose optional commands after edit/replace/write. Enabled by default; false disables them. */
19
- actionFusion: boolean;
20
- /** Line hash length (default 4). */
21
- hashLen: number;
22
- /** First-pass ±line radius before full-file recovery (default 15; 0 disables recovery). */
23
- shiftRadius: number;
17
+ function integerSetting(
18
+ range: ReturnType<typeof integerRange>,
19
+ value: number,
20
+ description: string,
21
+ ) {
22
+ return Type.Number({ ...range, default: value, description });
24
23
  }
25
24
 
26
- const SHIFT_RADIUS_MAX = 100;
25
+ /** Settings schema: the single source of setting types, bounds, and defaults. */
26
+ export const configSchema = Type.Object({
27
+ enabled: Type.Boolean({
28
+ default: true,
29
+ description:
30
+ "Master switch: when false the extension registers no tools; Pi's built-ins remain.",
31
+ }),
32
+ actionFusion: Type.Boolean({
33
+ default: true,
34
+ description: "Expose optional then_run commands after edit/replace/write.",
35
+ }),
36
+ hashLen: integerSetting(
37
+ integerRange(HASH_LEN_MIN, HASH_LEN_MAX),
38
+ 4,
39
+ "Line hash length shared by every anchored tool.",
40
+ ),
41
+ shiftRadius: integerSetting(
42
+ integerRange(0, 100),
43
+ 15,
44
+ "First-pass ±line radius before full-file recovery; 0 disables recovery.",
45
+ ),
46
+ read: Type.Object({
47
+ defaultLimit: integerSetting(
48
+ POSITIVE_SAFE_INTEGER,
49
+ 500,
50
+ "Lines returned when limit is omitted.",
51
+ ),
52
+ maxKiB: integerSetting(integerRange(1, 4096), 256, "Anchored text returned per call, in KiB."),
53
+ }),
54
+ grep: Type.Object({
55
+ defaultLimit: integerSetting(
56
+ POSITIVE_SAFE_INTEGER,
57
+ 100,
58
+ "Matching lines returned when limit is omitted.",
59
+ ),
60
+ defaultContext: integerSetting(
61
+ GREP_CONTEXT_RANGE,
62
+ 0,
63
+ "Context lines shown when context is omitted.",
64
+ ),
65
+ }),
66
+ replace: Type.Object({
67
+ regexTimeoutMs: integerSetting(
68
+ integerRange(1_000, 300_000),
69
+ 5_000,
70
+ "Time limit for one regex batch, in milliseconds.",
71
+ ),
72
+ }),
73
+ });
27
74
 
28
- export const DEFAULT_CONFIG: HashlineEditConfig = {
29
- enabled: true,
30
- actionFusion: true,
31
- hashLen: 4,
32
- shiftRadius: 15,
33
- };
75
+ export type HashlineEditConfig = Static<typeof configSchema>;
76
+
77
+ function asRecord(value: unknown): Record<string, unknown> {
78
+ return value !== null && typeof value === "object" && !Array.isArray(value)
79
+ ? (value as Record<string, unknown>)
80
+ : {};
81
+ }
82
+
83
+ /** Keep each valid leaf; replace a missing or invalid leaf with its default. */
84
+ function resolveSetting<T extends TSchema>(schema: T, value: unknown): Static<T> {
85
+ if (Type.IsObject(schema)) {
86
+ const source = asRecord(value);
87
+ return Object.fromEntries(
88
+ Object.entries(schema.properties).map(([key, property]) => [
89
+ key,
90
+ resolveSetting(property, source[key]),
91
+ ]),
92
+ ) as Static<T>;
93
+ }
94
+ return (Value.Check(schema, value) ? value : Value.Create(schema)) as Static<T>;
95
+ }
96
+
97
+ export const DEFAULT_CONFIG: HashlineEditConfig = resolveSetting(configSchema, {});
34
98
 
35
99
  /** Parse JSON directly without stripping comments (standard JSON forbids comments; on error fall back to default). */
36
100
  function readSettings(filePath: string): Record<string, unknown> {
37
101
  try {
38
102
  if (!fs.existsSync(filePath)) return {};
39
- const value: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8"));
40
- return value !== null && typeof value === "object" && !Array.isArray(value)
41
- ? (value as Record<string, unknown>)
42
- : {};
103
+ return asRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
43
104
  } catch {
44
105
  return {};
45
106
  }
@@ -47,25 +108,10 @@ function readSettings(filePath: string): Record<string, unknown> {
47
108
 
48
109
  /**
49
110
  * Load config. The `hashlineEdit` in project `cwd/.pi/settings.json` replaces
50
- * the global one wholesale; missing fields fall back to DEFAULT_CONFIG.
111
+ * the global one wholesale; missing or invalid settings use their defaults.
51
112
  */
52
113
  export function loadConfig(cwd?: string): HashlineEditConfig {
53
114
  const globalSettings = readSettings(path.join(getAgentDir(), "settings.json"));
54
115
  const projectSettings = cwd ? readSettings(path.join(cwd, ".pi", "settings.json")) : {};
55
- const value = projectSettings.hashlineEdit ?? globalSettings.hashlineEdit;
56
- const raw =
57
- value !== null && typeof value === "object" && !Array.isArray(value)
58
- ? (value as Record<string, unknown>)
59
- : {};
60
- return {
61
- enabled: typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_CONFIG.enabled,
62
- actionFusion:
63
- typeof raw.actionFusion === "boolean" ? raw.actionFusion : DEFAULT_CONFIG.actionFusion,
64
- hashLen: isIntegerInRange(raw.hashLen, HASH_LEN_MIN, HASH_LEN_MAX)
65
- ? raw.hashLen
66
- : DEFAULT_CONFIG.hashLen,
67
- shiftRadius: isIntegerInRange(raw.shiftRadius, 0, SHIFT_RADIUS_MAX)
68
- ? raw.shiftRadius
69
- : DEFAULT_CONFIG.shiftRadius,
70
- };
116
+ return resolveSetting(configSchema, projectSettings.hashlineEdit ?? globalSettings.hashlineEdit);
71
117
  }
@@ -0,0 +1,58 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
4
+ import { MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
5
+ import { formatSearchWarnings } from "./grep-output.ts";
6
+ import { MAX_RG_STDERR_BYTES, runText } from "./rg-process.ts";
7
+
8
+ const diagnostic = (size: number) =>
9
+ `regex parse error:\n${"intermediate context 中🙂\n".repeat(size)}error: unclosed group\n`;
10
+
11
+ test("bounded diagnostics retain opening context and the final cause across streamed chunks", () => {
12
+ const source = diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES);
13
+ const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
14
+ const chunkChars = 113;
15
+ for (let offset = 0; offset < source.length; offset += chunkChars) {
16
+ buffer.append(source.slice(offset, offset + chunkChars));
17
+ }
18
+ const result = buffer.toString();
19
+ assert.match(result, /^regex parse error:/);
20
+ assert.match(result, /error: unclosed group\n$/);
21
+ assert.match(result, /omitted/i);
22
+ assert.ok(Buffer.byteLength(result) <= MAX_SEARCH_DIAGNOSTIC_BYTES);
23
+ });
24
+
25
+ test("diagnostics within the budget are unchanged", () => {
26
+ const buffer = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
27
+ const source = "path: 权限不足🙂\nretry with another path\n";
28
+ for (const point of source) buffer.append(point);
29
+ assert.equal(buffer.toString(), source);
30
+ });
31
+
32
+ test("search warning aggregation retains the final cause and labels truncation", () => {
33
+ const result = formatSearchWarnings([diagnostic(MAX_SEARCH_DIAGNOSTIC_BYTES)]);
34
+ assert.match(result, /Search incomplete/);
35
+ assert.match(result, /regex parse error:/);
36
+ assert.match(result, /error: unclosed group/);
37
+ assert.match(result, /omitted/i);
38
+ });
39
+
40
+ test("stderr collection preserves UTF-8 and reports overflow without losing the final cause", async () => {
41
+ for (const source of ["权限不足🙂\n", diagnostic(MAX_RG_STDERR_BYTES)]) {
42
+ const result = await runText(
43
+ process.execPath,
44
+ ["--input-type=module", "--eval", "process.stdin.pipe(process.stderr)"],
45
+ Buffer.from(source),
46
+ AbortSignal.timeout(10000),
47
+ );
48
+ if (Buffer.byteLength(source) <= MAX_RG_STDERR_BYTES) {
49
+ assert.equal(result.stderr, source);
50
+ } else {
51
+ assert.match(result.stderr, /^regex parse error:/);
52
+ assert.match(result.stderr, /error: unclosed group\n$/);
53
+ assert.match(result.stderr, /omitted/i);
54
+ assert.doesNotMatch(result.stderr, /�/);
55
+ assert.ok(Buffer.byteLength(result.stderr) <= MAX_RG_STDERR_BYTES);
56
+ }
57
+ }
58
+ });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Bounded diagnostic text shared by ripgrep stderr, batch aggregation, and
3
+ * model-facing search warnings. Retain the opening context and final cause;
4
+ * mark omitted text instead of silently dropping diagnostics.
5
+ */
6
+ import { truncateHead, truncateTail } from "@earendil-works/pi-coding-agent";
7
+ import { formatKiB } from "./budgets.ts";
8
+
9
+ export class DiagnosticBuffer {
10
+ private head = "";
11
+ private tail = "";
12
+ private truncated = false;
13
+ private readonly notice: string;
14
+ private readonly headBytes: number;
15
+ private readonly tailBytes: number;
16
+
17
+ private readonly maxBytes: number;
18
+
19
+ constructor(maxBytes: number) {
20
+ this.maxBytes = maxBytes;
21
+ this.notice = `\n[Diagnostics truncated (${formatKiB(maxBytes)} limit); middle omitted.]\n`;
22
+ const contentBytes = maxBytes - Buffer.byteLength(this.notice);
23
+ this.headBytes = Math.floor(contentBytes / 2);
24
+ this.tailBytes = contentBytes - this.headBytes;
25
+ }
26
+
27
+ append(text: string): void {
28
+ if (!this.truncated) {
29
+ const combined = this.head + text;
30
+ if (Buffer.byteLength(combined) <= this.maxBytes) {
31
+ this.head = combined;
32
+ return;
33
+ }
34
+ this.head = truncateHead(combined, {
35
+ maxBytes: this.headBytes,
36
+ maxLines: Number.MAX_SAFE_INTEGER,
37
+ }).content;
38
+ this.tail = this.truncateTail(combined);
39
+ this.truncated = true;
40
+ return;
41
+ }
42
+ this.tail = this.truncateTail(this.tail + text);
43
+ }
44
+
45
+ toString(): string {
46
+ return this.truncated ? this.head + this.notice + this.tail : this.head;
47
+ }
48
+
49
+ private truncateTail(text: string): string {
50
+ // Pi's truncated previews omit the final newline; streaming must retain it
51
+ // so the next chunk cannot merge two diagnostic lines.
52
+ const newline = text.endsWith("\n") ? "\n" : "";
53
+ const preview = truncateTail(text, {
54
+ maxBytes: this.tailBytes - newline.length,
55
+ maxLines: Number.MAX_SAFE_INTEGER,
56
+ });
57
+ return preview.content + (preview.truncated ? newline : "");
58
+ }
59
+ }
@@ -18,6 +18,7 @@ import { createActionFusionExecutor } from "./action-fusion.ts";
18
18
  import { computeLineHash } from "../core/hash.ts";
19
19
  import { splitLines } from "../core/lines.ts";
20
20
  import { callTool } from "./tool-call.testing.ts";
21
+ import { DEFAULT_CONFIG } from "./config.ts";
21
22
 
22
23
  async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
23
24
  const dir = await mkdtemp(join(tmpdir(), "hl-e2e-"));
@@ -31,7 +32,7 @@ async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
31
32
  const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
32
33
 
33
34
  function h(text: string, line: number) {
34
- return `${line}#${computeLineHash(line, splitLines(text)[line - 1])}`;
35
+ return `${line}#${computeLineHash(line, splitLines(text)[line - 1], 4)}`;
35
36
  }
36
37
 
37
38
  function anchorLine(block: string, line: number) {
@@ -62,13 +63,14 @@ test("E2E Dev D1: Search-and-edit single function without separate read call", a
62
63
  ].join("\n") + "\n";
63
64
  await writeFile(file, original);
64
65
 
65
- const grep = makeGrepOverride(dir);
66
- const edit = makeEditOverride(dir);
66
+ const grep = makeGrepOverride(dir, DEFAULT_CONFIG);
67
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
67
68
 
68
69
  // Turn 1: Search with context: 3
69
70
  const grepResult = await call(grep, {
70
71
  path: "calc.ts",
71
72
  pattern: "calculateDiscount",
73
+ literal: true,
72
74
  context: 3,
73
75
  });
74
76
  const grepText = grepResult.content[0].text;
@@ -105,7 +107,7 @@ test("E2E Dev D2: Chained multi-site edits using returned fresh anchors", async
105
107
  ].join("\n") + "\n";
106
108
  await writeFile(file, original);
107
109
 
108
- const edit = makeEditOverride(dir);
110
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
109
111
 
110
112
  // Step 1: Edit version
111
113
  const r1 = await call(edit, {
@@ -167,7 +169,7 @@ test("E2E Dev D3: Recovery from shifted anchor after external line insertion", a
167
169
  ].join("\n") + "\n";
168
170
  await writeFile(file, externallyModified);
169
171
 
170
- const edit = makeEditOverride(dir);
172
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
171
173
 
172
174
  // Agent attempts edit with stale anchor
173
175
  let candidateAnchor = "";
@@ -211,7 +213,7 @@ test("E2E Dev D4: Bulk replace with Action Fusion then_run validation", async ()
211
213
  return "All checks passed";
212
214
  });
213
215
 
214
- const replace = makeReplaceTool(dir, fusionExecutor);
216
+ const replace = makeReplaceTool(dir, DEFAULT_CONFIG, fusionExecutor);
215
217
  const res = await call(replace, {
216
218
  path: "api.ts",
217
219
  replacements: [{ find: "old_var", replace: "new_var" }],
@@ -234,7 +236,7 @@ test("E2E Dev D5: Line ending preservation and deletion successor anchor", async
234
236
  const crlfText = "line1\r\nline2\r\nline3\r\nline4\r\n";
235
237
  await writeFile(file, crlfText);
236
238
 
237
- const edit = makeEditOverride(dir);
239
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
238
240
 
239
241
  // Delete line 2: line 3 shifts to line 2 (deletion successor)
240
242
  const res = await call(edit, {
@@ -255,7 +257,7 @@ test("E2E Dev D6: structured edit batches use one original snapshot", async () =
255
257
  const file = join(dir, "batch.txt");
256
258
  const original = "alpha\nbeta\ngamma\n";
257
259
  await writeFile(file, original);
258
- await call(makeEditOverride(dir), {
260
+ await call(makeEditOverride(dir, DEFAULT_CONFIG), {
259
261
  path: "batch.txt",
260
262
  edits: [
261
263
  { op: "replace", anchor: h(original, 1), body: ["ALPHA"] },
@@ -278,7 +280,7 @@ test("E2E Holdout H1: Ambiguous candidates provide distinguishing neighborhoods"
278
280
  ) + "\n";
279
281
  await writeFile(file, text);
280
282
 
281
- const edit = makeEditOverride(dir);
283
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
282
284
  // The cited content moved away from line 3 and now occurs at lines 2 and 5.
283
285
  const staleAnchor = h("header\nheader\n return true;\n", 3);
284
286
  let candidateAnchor = "";
@@ -321,7 +323,7 @@ test("E2E Holdout H2: Action Fusion command failure preserves file changes and a
321
323
  throw new Error("Syntax error on line 42");
322
324
  });
323
325
 
324
- const edit = makeEditOverride(dir, fusionExecutor);
326
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG, fusionExecutor);
325
327
  const res = await call(edit, {
326
328
  path: "fusion_fail.ts",
327
329
  edits: [{ op: "replace", anchor: h("let x = 1;\n", 1), body: ["let x = 2;"] }],
@@ -343,7 +345,7 @@ test("E2E Holdout H3: UTF-8 BOM file retains BOM at byte 0 after first-line edit
343
345
  const bomContent = "\uFEFFline1\nline2\n";
344
346
  await writeFile(file, bomContent);
345
347
 
346
- const edit = makeEditOverride(dir);
348
+ const edit = makeEditOverride(dir, DEFAULT_CONFIG);
347
349
  const a1 = h(bomContent, 1);
348
350
 
349
351
  await call(edit, {