@criogaid/pi-hashline-edit 0.13.0 → 0.15.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 (152) hide show
  1. package/README.md +18 -12
  2. package/README.zh-CN.md +18 -12
  3. package/package.json +8 -1
  4. package/src/core/AGENTS.md +3 -1
  5. package/src/core/apply.ts +110 -117
  6. package/src/core/character-set.ts +2 -3
  7. package/src/core/copy-span.ts +15 -0
  8. package/src/core/errors.ts +24 -9
  9. package/src/core/lines.ts +71 -17
  10. package/src/core/ranges.ts +5 -4
  11. package/src/core/replace-schema.ts +3 -1
  12. package/src/core/replace.ts +50 -29
  13. package/src/core/search-analysis.ts +21 -22
  14. package/src/core/search.ts +15 -32
  15. package/src/core/types.ts +3 -0
  16. package/src/index.ts +47 -39
  17. package/src/pi/AGENTS.md +30 -19
  18. package/src/pi/action-fusion.ts +284 -211
  19. package/src/pi/argument-diagnostics.ts +50 -37
  20. package/src/pi/argument-error.ts +2 -2
  21. package/src/pi/argument-validation.ts +163 -66
  22. package/src/pi/budgets.ts +12 -0
  23. package/src/pi/diagnostic-buffer.ts +12 -11
  24. package/src/pi/edit-tool.ts +138 -115
  25. package/src/pi/error-text.ts +10 -2
  26. package/src/pi/failure-context.ts +24 -37
  27. package/src/pi/file-commit.ts +131 -164
  28. package/src/pi/file-read.ts +122 -31
  29. package/src/pi/fusion-arguments.ts +214 -0
  30. package/src/pi/fusion-card.ts +102 -60
  31. package/src/pi/grep-candidates.ts +35 -22
  32. package/src/pi/grep-output.ts +197 -190
  33. package/src/pi/grep-render.ts +22 -13
  34. package/src/pi/grep-reread.ts +7 -6
  35. package/src/pi/grep-scope.ts +31 -16
  36. package/src/pi/grep-search.ts +56 -47
  37. package/src/pi/grep-tool.ts +35 -33
  38. package/src/pi/grep-worker.ts +3 -4
  39. package/src/pi/mutation-diff.ts +238 -0
  40. package/src/pi/mutation-result.ts +102 -79
  41. package/src/pi/mutation-runner.ts +107 -84
  42. package/src/pi/native-bash.ts +41 -0
  43. package/src/pi/path.ts +59 -6
  44. package/src/pi/read-tool.ts +173 -138
  45. package/src/pi/regex-worker.ts +14 -8
  46. package/src/pi/render.ts +101 -54
  47. package/src/pi/replace-regex.ts +1 -1
  48. package/src/pi/replace-tool.ts +14 -7
  49. package/src/pi/report-cause.ts +34 -17
  50. package/src/pi/report-schema.ts +184 -85
  51. package/src/pi/report.ts +133 -64
  52. package/src/pi/rg-process.ts +68 -48
  53. package/src/pi/schema.ts +4 -0
  54. package/src/pi/text-stream.ts +81 -87
  55. package/src/pi/workspace-cwd.js +2 -0
  56. package/src/pi/workspace.ts +46 -0
  57. package/src/pi/write-tool.ts +19 -13
  58. package/src/core/apply.test.ts +0 -644
  59. package/src/core/case-fold.test.ts +0 -35
  60. package/src/core/character-set.test.ts +0 -97
  61. package/src/core/errors.test.ts +0 -39
  62. package/src/core/hash.test.ts +0 -64
  63. package/src/core/lines.test.ts +0 -63
  64. package/src/core/ranges.test.ts +0 -123
  65. package/src/core/replace.test.ts +0 -187
  66. package/src/core/search-analysis.test.ts +0 -210
  67. package/src/core/search-matrix.test.ts +0 -64
  68. package/src/core/search-matrix.testing.ts +0 -171
  69. package/src/core/search.test.ts +0 -132
  70. package/src/core/text.test.ts +0 -52
  71. package/src/integration/config-registration.test.ts +0 -291
  72. package/src/integration/fusion-dispatch.test.ts +0 -320
  73. package/src/integration/grep-errors.test.ts +0 -81
  74. package/src/integration/grep-flags.test.ts +0 -76
  75. package/src/integration/grep-js-completeness.test.ts +0 -278
  76. package/src/integration/grep-line-candidates.test.ts +0 -201
  77. package/src/integration/grep-matrix.test.ts +0 -118
  78. package/src/integration/grep-order.test.ts +0 -78
  79. package/src/integration/grep-path-matrix.test.ts +0 -128
  80. package/src/integration/grep-prefilter-coverage.test.ts +0 -204
  81. package/src/integration/grep-process-limits.test.ts +0 -122
  82. package/src/integration/grep-regex.test.ts +0 -412
  83. package/src/integration/grep-rg.test.ts +0 -1659
  84. package/src/integration/grep-scan-budget.test.ts +0 -111
  85. package/src/integration/grep-translation.test.ts +0 -199
  86. package/src/integration/large-text.test.ts +0 -70
  87. package/src/integration/model-budget-lifecycle.test.ts +0 -186
  88. package/src/integration/mutation-file-types.test.ts +0 -30
  89. package/src/integration/mutation-file-types.testing.ts +0 -33
  90. package/src/integration/npm-package.test.ts +0 -19
  91. package/src/integration/npm-package.testing.ts +0 -243
  92. package/src/integration/publication-read-changes.test.ts +0 -454
  93. package/src/integration/read-changes.test.ts +0 -98
  94. package/src/integration/replace-package.test.ts +0 -22
  95. package/src/integration/replace-package.testing.ts +0 -36
  96. package/src/integration/replace-worker-boundary.test.ts +0 -127
  97. package/src/integration/report-replay.test.ts +0 -91
  98. package/src/integration/utf8-errors.test.ts +0 -46
  99. package/src/pi/action-fusion.test.ts +0 -659
  100. package/src/pi/action-fusion.testing.ts +0 -38
  101. package/src/pi/anchor-format.test.ts +0 -124
  102. package/src/pi/argument-error.testing.ts +0 -46
  103. package/src/pi/argument-format.test.ts +0 -196
  104. package/src/pi/argument-validation.test.ts +0 -1007
  105. package/src/pi/codemode.test.ts +0 -101
  106. package/src/pi/config.test.ts +0 -204
  107. package/src/pi/diagnostic-buffer.test.ts +0 -115
  108. package/src/pi/directory-sync.test.ts +0 -57
  109. package/src/pi/execute.test.ts +0 -1257
  110. package/src/pi/extension-loading.test.ts +0 -14
  111. package/src/pi/extension-loading.testing.ts +0 -3
  112. package/src/pi/failure-context.test.ts +0 -370
  113. package/src/pi/failure-path.test.ts +0 -289
  114. package/src/pi/file-commit.test.ts +0 -628
  115. package/src/pi/file-read.test.ts +0 -29
  116. package/src/pi/file-snapshot.test.ts +0 -22
  117. package/src/pi/fusion-card-interaction.test.ts +0 -143
  118. package/src/pi/fusion-card.test.ts +0 -353
  119. package/src/pi/grep-candidates.test.ts +0 -26
  120. package/src/pi/grep-matrix.test.ts +0 -68
  121. package/src/pi/grep-order.test.ts +0 -447
  122. package/src/pi/grep-output.testing.ts +0 -24
  123. package/src/pi/grep-rg.testing.ts +0 -73
  124. package/src/pi/grep.test.ts +0 -1670
  125. package/src/pi/model-budgets.test.ts +0 -96
  126. package/src/pi/mutation-outcome.testing.ts +0 -20
  127. package/src/pi/mutation-result.test.ts +0 -96
  128. package/src/pi/output-budgets.test.ts +0 -221
  129. package/src/pi/pi.test.ts +0 -158
  130. package/src/pi/read-delegation.test.ts +0 -119
  131. package/src/pi/read.test.ts +0 -735
  132. package/src/pi/regex-worker.test.ts +0 -42
  133. package/src/pi/registration.test.ts +0 -549
  134. package/src/pi/render.test.ts +0 -841
  135. package/src/pi/replace.test.ts +0 -634
  136. package/src/pi/report-failure.testing.ts +0 -27
  137. package/src/pi/report.test.ts +0 -533
  138. package/src/pi/result-safety.test.ts +0 -597
  139. package/src/pi/rg-process.test.ts +0 -133
  140. package/src/pi/rg-regex.test.ts +0 -40
  141. package/src/pi/text-stream.test.ts +0 -281
  142. package/src/pi/tool-call.testing.ts +0 -61
  143. package/src/pi/tool-factories.testing.ts +0 -59
  144. package/src/pi/write.test.ts +0 -256
  145. package/src/testing/extension-loader.testing.ts +0 -24
  146. package/src/testing/installation.testing.ts +0 -77
  147. package/src/testing/process.testing.ts +0 -33
  148. package/src/testing/regex-host.testing.ts +0 -20
  149. package/src/testing/regex-translation-corpus.ts +0 -267
  150. package/src/testing/rg-line-listing.fixture.mjs +0 -7
  151. package/src/testing/run-tests.ts +0 -47
  152. package/src/testing/session.testing.ts +0 -127
@@ -1,42 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawnSync } from "node:child_process";
3
- import { test } from "node:test";
4
- import { pathToFileURL } from "node:url";
5
- import { resolve } from "node:path";
6
-
7
- const workerModule = pathToFileURL(resolve("src/pi/regex-worker.ts")).href;
8
- const grepEntry = pathToFileURL(resolve("src/pi/grep-worker.mjs")).href;
9
- const replaceEntry = pathToFileURL(resolve("src/pi/replace-worker.mjs")).href;
10
-
11
- test("input-type inherited from eval → both file workers run with other flags preserved", () => {
12
- const script = `
13
- (async () => {
14
- const { default: assert } = await import('node:assert/strict');
15
- const { withRegexWorker } = await import(${JSON.stringify(workerModule)});
16
- const run = (entry, input) => withRegexWorker(new URL(entry), value => value, 10000, undefined, send => send(input));
17
- const probe = new URL('data:text/javascript,' + encodeURIComponent("import { parentPort } from 'node:worker_threads'; parentPort.on('message', () => parentPort.postMessage({ result: process.execArgv }));"));
18
- const flags = await run(probe.href, {});
19
- assert.ok(flags.includes('--no-warnings'));
20
- assert.deepEqual(flags, process.execArgv);
21
- const search = await run(${JSON.stringify(grepEntry)}, { source: 'safe', query: { patterns: ['safe'], literal: false, ignoreCase: false, multiline: false }, limit: 10 });
22
- assert.equal(search.lines.length, 1);
23
- const replacement = await run(${JSON.stringify(replaceEntry)}, { source: 'safe', rules: [{ find: 'safe', replace: 'changed', literal: false }] });
24
- assert.equal(replacement.text, 'changed');
25
- })().catch(error => { console.error(error); process.exitCode = 1; });
26
- `;
27
- for (const flags of [
28
- ["--input-type=module"],
29
- ["--input-type", "module"],
30
- ["--input-type=commonjs"],
31
- ["--input-type", "commonjs"],
32
- ["--use-largepages=off"],
33
- ["--use-largepages=off", "--input-type=module"],
34
- ["--use-largepages=off", "--input-type=commonjs"],
35
- ]) {
36
- const result = spawnSync(process.execPath, [...flags, "--no-warnings", "--eval", script], {
37
- encoding: "utf8",
38
- timeout: 30000,
39
- });
40
- assert.equal(result.status, 0, `${flags.join(" ")}: ${result.stderr}`);
41
- }
42
- });
@@ -1,549 +0,0 @@
1
- import { rejectsArgument } from "./argument-error.testing.ts";
2
- import { createEditTool } from "@earendil-works/pi-coding-agent";
3
- import { validateToolArguments, type Tool } from "@earendil-works/pi-ai";
4
- import { makeStrictJsonSchema } from "@earendil-works/pi-ai/api/constrained-sampling";
5
- import { makeEditOverride } from "./tool-factories.testing.ts";
6
- import { makeReadOverride } from "./tool-factories.testing.ts";
7
- import { loadConfig } from "./config.ts";
8
- import { DEFAULT_CONFIG } from "./tool-factories.testing.ts";
9
- import { mkdir, mkdtemp, rm, writeFile, readFile } from "node:fs/promises";
10
- import { tmpdir } from "node:os";
11
- import { join } from "node:path";
12
- import assert from "node:assert/strict";
13
- import { test } from "node:test";
14
- import registerHashline from "../index.ts";
15
- import { initTheme } from "@earendil-works/pi-coding-agent";
16
- import type {
17
- ExtensionAPI,
18
- ExtensionContext,
19
- ToolDefinition,
20
- } from "@earendil-works/pi-coding-agent";
21
- import { ProcessTerminal, TuiMainScreen } from "@earendil-works/pi-tui";
22
- import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
23
- import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
24
- import { computeLineHash } from "../core/hash.ts";
25
- import { callTool } from "./tool-call.testing.ts";
26
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
27
- import type { ActionFusionProgress } from "./report-schema.ts";
28
- import { reportOf } from "./report.ts";
29
- import { formatByteSize } from "./budgets.ts";
30
- import { expectToolFailure } from "./report-failure.testing.ts";
31
- import { STRICT_SAMPLING } from "./schema.ts";
32
- import { NEXT_GUIDELINE } from "./report-schema.ts";
33
- import { ACTION_FUSION_GUIDELINES } from "./action-fusion.ts";
34
-
35
- test("registered tools with or without Fusion → expose prompt rules and convertible strict schemas", async (t) => {
36
- const guidelines = {
37
- edit: [
38
- "Batch all steps for one file into a single edit call, and send changes to different files in the same response; they do not interfere.",
39
- "Before citing a line after write, edit, or replace, get its anchor from a new read or grep. Only after edit, lines above the earliest changed line keep their anchors.",
40
- ],
41
- grep: [
42
- "When you need several independent searches, send them as separate grep calls in one response; they run in parallel.",
43
- ],
44
- };
45
- await withDir(async (dir) => {
46
- await mkdir(join(dir, ".pi"));
47
- for (const actionFusion of [false, true]) {
48
- await writeFile(
49
- join(dir, ".pi", "settings.json"),
50
- JSON.stringify({ hashlineEdit: { enabled: true, actionFusion } }),
51
- );
52
- const tools: (Tool & Pick<ToolDefinition, "promptGuidelines">)[] = [];
53
- const api: Pick<ExtensionAPI, "exec" | "on" | "registerEntryRenderer" | "registerTool"> = {
54
- async exec() {
55
- return { stdout: dir, stderr: "", code: 0, killed: false, truncated: false };
56
- },
57
- on() {
58
- return () => {};
59
- },
60
- registerEntryRenderer() {},
61
- registerTool(tool) {
62
- tools.push(tool);
63
- },
64
- };
65
- // The fixture implements the API methods used during registration.
66
- await registerHashline(api as ExtensionAPI);
67
- assert.equal(tools.length, 5);
68
- for (const tool of tools) {
69
- const { name } = tool;
70
- if (name === "read" || name === "edit" || name === "grep") {
71
- await t.test(`${name}/Fusion ${actionFusion} → registers the tool's prompt rules`, () => {
72
- if (name === "read") {
73
- const [codemodeRule = "", ...sharedRules] = tool.promptGuidelines ?? [];
74
- assert.match(
75
- codemodeRule,
76
- /Files containing NUL go to native read without a Hashline header/,
77
- );
78
- assert.deepEqual(sharedRules, [NEXT_GUIDELINE]);
79
- } else {
80
- assert.deepEqual(tool.promptGuidelines, [
81
- ...guidelines[name],
82
- ...(name === "edit" && actionFusion ? ACTION_FUSION_GUIDELINES : []),
83
- NEXT_GUIDELINE,
84
- ]);
85
- }
86
- });
87
- }
88
- await t.test(`${tool.name}/Fusion ${actionFusion} → supports strict sampling`, () => {
89
- assert.deepEqual(tool.constrainedSampling, STRICT_SAMPLING);
90
- const strict = makeStrictJsonSchema(tool.parameters);
91
- if (tool.name === "read") {
92
- assert.partialDeepStrictEqual(tool.parameters, {
93
- required: ["path"],
94
- properties: {
95
- anchors: {
96
- type: "boolean",
97
- description:
98
- "false omits LINE#HASH│ prefixes for files you will not edit, saving about a third of the tokens. The header stays and standalone CR displays as ␍ (default true).",
99
- },
100
- },
101
- });
102
- assert.partialDeepStrictEqual(strict, {
103
- properties: { anchors: { anyOf: [{ type: "boolean" }, { type: "null" }] } },
104
- });
105
- }
106
- if (tool.name === "edit") {
107
- assert.partialDeepStrictEqual(strict, {
108
- type: "object",
109
- additionalProperties: false,
110
- required: actionFusion ? ["path", "steps", "then_run"] : ["path", "steps"],
111
- properties: {
112
- steps: {
113
- type: "array",
114
- items: {
115
- type: "object",
116
- additionalProperties: false,
117
- required: ["action", "anchor", "end", "lines"],
118
- properties: {
119
- anchor: { anyOf: [{ type: "string" }, { type: "null" }] },
120
- end: { anyOf: [{ type: "string" }, { type: "null" }] },
121
- lines: { anyOf: [{ type: "array" }, { type: "null" }] },
122
- },
123
- },
124
- },
125
- ...(actionFusion
126
- ? { then_run: { anyOf: [{ type: "object" }, { type: "null" }] } }
127
- : {}),
128
- },
129
- });
130
- const properties = strict.properties as Record<
131
- string,
132
- { items?: { properties?: Record<string, unknown> } }
133
- >;
134
- assert.deepEqual(
135
- Object.keys(properties),
136
- actionFusion ? ["path", "steps", "then_run"] : ["path", "steps"],
137
- );
138
- const stepProperties = properties.steps.items?.properties;
139
- assert.ok(stepProperties);
140
- assert.deepEqual(Object.keys(stepProperties), ["action", "anchor", "end", "lines"]);
141
- }
142
- });
143
- }
144
- }
145
- });
146
- });
147
-
148
- test("mutation cards use Fusion by default and explicit false removes command support", async () => {
149
- const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
150
- try {
151
- await mkdir(join(dir, ".pi"));
152
- await writeFile(
153
- join(dir, ".pi", "settings.json"),
154
- JSON.stringify({ hashlineEdit: { enabled: true } }),
155
- );
156
- const tools: any[] = [];
157
- const entries: any[] = [];
158
- const renderers = new Map<string, any>();
159
- let start: ((event: unknown, ctx: unknown) => void) | undefined;
160
- await registerHashline({
161
- async exec() {
162
- return { stdout: dir, stderr: "", code: 0, killed: false, truncated: false };
163
- },
164
- on(event: string, handler: (event: unknown, ctx: unknown) => void) {
165
- if (event === "session_start") start = handler;
166
- },
167
- getSettings() {
168
- return {};
169
- },
170
- registerEntryRenderer(type: string, renderer: any) {
171
- renderers.set(type, renderer);
172
- },
173
- appendEntry(customType: string, data: unknown) {
174
- entries.push({ customType, data });
175
- },
176
- registerTool(tool: any) {
177
- tools.push(tool);
178
- },
179
- } as any);
180
- assert.deepEqual(
181
- tools.map((tool) => tool.name),
182
- ["write", "edit", "replace", "read", "grep"],
183
- );
184
- const grep = tools.find((tool) => tool.name === "grep");
185
- assert.deepEqual(Object.keys(grep.parameters.properties).sort(), [
186
- "context",
187
- "glob",
188
- "ignoreCase",
189
- "limit",
190
- "literal",
191
- "multiline",
192
- "outputMode",
193
- "path",
194
- "pattern",
195
- ]);
196
- assert.equal(grep.parameters.additionalProperties, false);
197
- assert.match(
198
- grep.parameters.properties.ignoreCase.description,
199
- /no pattern contains an uppercase letter/,
200
- );
201
- assert.doesNotMatch(grep.parameters.properties.ignoreCase.description, /flag/);
202
- await assert.rejects(
203
- callTool(grep, { pattern: "needle", literal: true, unexpected: true }),
204
- rejectsArgument("unexpected", /not allowed/),
205
- );
206
- for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
207
- assert.ok(
208
- tool.parameters.properties.then_run,
209
- `${tool.name} should expose then_run when actionFusion is enabled`,
210
- );
211
- assert.doesNotMatch(tool.description, /then_run/);
212
- }
213
- initTheme("dark");
214
- const tui = new TuiMainScreen(new ProcessTerminal());
215
- tui.requestRender = () => {};
216
- assert.ok(start);
217
- start(
218
- {},
219
- {
220
- cwd: dir,
221
- mode: "tui",
222
- sessionManager: { getBranch: () => entries },
223
- ui: {
224
- setWidget(_key: string, content: Parameters<ExtensionContext["ui"]["setWidget"]>[1]) {
225
- if (typeof content === "function") content(tui, theme);
226
- },
227
- },
228
- },
229
- );
230
- const cases = [
231
- { name: "write", args: { content: "published\n", mode: "create" } },
232
- { name: "edit", args: { steps: [{ action: "append", lines: ["appended"] }] } },
233
- {
234
- name: "replace",
235
- args: { replacements: [{ literal: true, find: "published", replace: "published" }] },
236
- },
237
- ] as const;
238
- for (const { name, args } of cases) {
239
- const tool = tools.find((tool) => tool.name === name);
240
- const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
241
- const card = new ToolExecutionComponent(name, name, params, {}, tool, tui, dir);
242
- card.setArgsComplete();
243
- card.markExecutionStarted();
244
- const frames: {
245
- command: string;
246
- mutationCompleted: boolean;
247
- output: string;
248
- commandOutput: string;
249
- expandedOutput: string;
250
- }[] = [];
251
- const result = await callTool(tool, params, {
252
- toolCallId: name,
253
- onUpdate: (update: AgentToolResult<{ actionFusion: ActionFusionProgress }>) => {
254
- card.updateResult({ ...update, isError: false }, true);
255
- const entry = entries.find(
256
- (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name,
257
- );
258
- const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
259
- card.setExpanded(true);
260
- const expandedOutput = card.render(100).join("\n");
261
- card.setExpanded(false);
262
- frames.push({
263
- ...update.details.actionFusion,
264
- output: card.render(100).join("\n"),
265
- commandOutput: commandCard.render(100).join("\n"),
266
- expandedOutput,
267
- });
268
- },
269
- ctx: { cwd: dir },
270
- });
271
- assert.equal(
272
- reportOf(result, name)?.publication,
273
- name === "replace" ? "NOT_PUBLISHED" : "PUBLISHED",
274
- );
275
- assert.equal(reportOf(result, name)?.then_run?.status, "failed");
276
- assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
277
- const running = frames.find((frame) => frame.command === "running")!;
278
- assert.ok(running, `${name} should emit running progress`);
279
- assert.ok(
280
- running.output.includes(theme.getBgAnsi("toolSuccessBg")),
281
- `${name} should finish its mutation card while then_run is running`,
282
- );
283
- assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
284
- assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
285
- assert.ok(frames.at(-1)!.commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
286
- const completed = frames.find(
287
- (frame) => frame.command === "waiting" && frame.mutationCompleted,
288
- )!;
289
- assert.ok(
290
- completed?.output.includes(theme.getBgAnsi("toolSuccessBg")),
291
- "mutation completion must finish its card before command checks",
292
- );
293
- for (const frame of frames) {
294
- const expectedBackground = theme.getBgAnsi(
295
- frame.mutationCompleted ? "toolSuccessBg" : "toolPendingBg",
296
- );
297
- assert.ok(frame.output.includes(expectedBackground));
298
- assert.ok(frame.expandedOutput.includes(expectedBackground));
299
- }
300
- if (name === "replace") {
301
- assert.match(running.output, /No diff available/);
302
- }
303
- card.updateResult({ ...result, isError: false });
304
- assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
305
- if (name === "replace") assert.match(card.render(100).join("\n"), /No net change/);
306
- card.setExpanded(true);
307
- assert.doesNotMatch(card.render(100).join("\n"), /Command exited/);
308
- assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
309
-
310
- const invalid = {
311
- ...params,
312
- path: "missing.txt",
313
- ...(name === "write" ? { mode: "overwrite" } : {}),
314
- };
315
- const failedCard = new ToolExecutionComponent(
316
- name,
317
- `${name}-bad`,
318
- invalid,
319
- {},
320
- tool,
321
- tui,
322
- dir,
323
- );
324
- const failed = await callTool(tool, invalid, {
325
- toolCallId: `${name}-bad`,
326
- onUpdate: (update: AgentToolResult<unknown>) =>
327
- failedCard.updateResult({ ...update, isError: false }, true),
328
- ctx: { cwd: dir },
329
- });
330
- assert.equal(failed.isError, true);
331
- const report = reportOf(failed, name);
332
- assert.equal(report?.error, "PATH_NOT_FOUND");
333
- failedCard.updateResult(failed);
334
- const output = failedCard.render(100).join("\n");
335
- assert.ok(
336
- output.includes(theme.getBgAnsi("toolErrorBg")),
337
- `${name} mutation failure should turn red`,
338
- );
339
- assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
340
- failedCard.setExpanded(true);
341
- const expandedError = failedCard.render(400).join("\n");
342
- assert.ok(expandedError.includes(report?.message ?? ""));
343
- if (report?.cause?.message) assert.ok(expandedError.includes(report.cause.message));
344
- assert.match(output, /PATH_NOT_FOUND/);
345
- const entry = entries.find(
346
- (entry) =>
347
- entry.customType === "hashline-then-run" && entry.data.toolCallId === `${name}-bad`,
348
- );
349
- const commandOutput = renderers
350
- .get(entry.customType)(entry, { expanded: true }, theme)
351
- .render(160)
352
- .join("\n");
353
- assert.match(commandOutput, /skipped[\s\S]*Not run.*mutation did not complete/);
354
- assert.doesNotMatch(commandOutput, /Error reading|does not exist/);
355
- assert.ok(!commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
356
- }
357
- assert.deepEqual(
358
- entries.map((entry) => entry.data.command),
359
- cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]),
360
- );
361
- assert.ok(
362
- entries.every(
363
- (entry) =>
364
- !("publication" in entry.data) &&
365
- !("path" in entry.data) &&
366
- ["unchanged", "changed", "missing", "unknown"].includes(entry.data.freshness),
367
- ),
368
- );
369
- await writeFile(join(dir, "stale.txt"), "header\ntarget\n");
370
- const edit = tools.find((tool) => tool.name === "edit");
371
- const stale = {
372
- path: "stale.txt",
373
- steps: [
374
- { action: "replace", anchor: `1#${computeLineHash(1, "target", 4)}`, lines: ["changed"] },
375
- ],
376
- then_run: { command: "exit 99" },
377
- };
378
- const staleCard = new ToolExecutionComponent("edit", "stale", stale, {}, edit, tui, dir);
379
- const failed = await callTool(edit, stale, {
380
- toolCallId: "stale",
381
- onUpdate: (update: AgentToolResult<unknown>) =>
382
- staleCard.updateResult({ ...update, isError: false }, true),
383
- ctx: { cwd: dir },
384
- });
385
- assert.equal(failed.isError, true);
386
- assert.equal(reportOf(failed, "edit")?.failures?.[0].result, "shifted");
387
- staleCard.updateResult(failed);
388
- assert.match(staleCard.render(160).join("\n"), /ANCHOR_MISMATCH/);
389
- const entry = entries.find(
390
- (entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === "stale",
391
- );
392
- const commandOutput = renderers
393
- .get(entry.customType)(entry, { expanded: true }, theme)
394
- .render(160)
395
- .join("\n");
396
- assert.match(commandOutput, /skipped/);
397
- assert.doesNotMatch(commandOutput, /ANCHOR_MISMATCH|candidate/);
398
- assert.equal(await readFile(join(dir, "stale.txt"), "utf8"), "header\ntarget\n");
399
- await writeFile(
400
- join(dir, ".pi", "settings.json"),
401
- JSON.stringify({ hashlineEdit: { actionFusion: false } }),
402
- );
403
- const disabledTools: any[] = [];
404
- await registerHashline({
405
- async exec() {
406
- return { stdout: dir, stderr: "", code: 0, killed: false, truncated: false };
407
- },
408
- on() {},
409
- registerEntryRenderer() {},
410
- registerTool(tool: any) {
411
- disabledTools.push(tool);
412
- },
413
- } as any);
414
- assert.deepEqual(
415
- disabledTools.map((tool) => tool.name),
416
- tools.map((tool) => tool.name),
417
- );
418
- for (const tool of disabledTools.filter((tool) =>
419
- ["edit", "replace", "write"].includes(tool.name),
420
- )) {
421
- assert.equal(tool.parameters.properties.then_run, undefined);
422
- assert.equal(tool.renderShell, "default");
423
- assert.doesNotMatch(tool.description, /then_run/);
424
- assert.equal(
425
- tool.description,
426
- tools.find((enabled) => enabled.name === tool.name)?.description,
427
- );
428
- // Without Action Fusion the schema has no then_run, so Pi rejects it before execute.
429
- await assert.rejects(
430
- callTool(
431
- tool,
432
- { path: "published.txt", then_run: { command: "exit 0" } },
433
- { ctx: { cwd: dir } },
434
- ),
435
- rejectsArgument("then_run", /not allowed/),
436
- );
437
- }
438
- } finally {
439
- await rm(dir, { recursive: true, force: true });
440
- }
441
- });
442
-
443
- async function withDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
444
- const dir = await mkdtemp(join(tmpdir(), "hl-"));
445
- try {
446
- return await fn(dir);
447
- } finally {
448
- await rm(dir, { recursive: true, force: true });
449
- }
450
- }
451
-
452
- /** Call a tool through Pi's argument preparation and schema validation, as production does. */
453
- const call = (tool: any, params: any) => callTool(tool, params, { toolCallId: "0" });
454
-
455
- /** Extract a `LINE#HASH` anchor from a read/edit result text block. */
456
- function anchorLine(block: string, line: number) {
457
- const m = new RegExp(`^${line}#([0-9A-Z]+)(?:│|$)`, "m").exec(block);
458
- if (!m) throw new Error(`line ${line} anchor not found in block`);
459
- return `${line}#${m[1]}`;
460
- }
461
-
462
- test("disabled config registers no tools — built-ins remain", async () => {
463
- await withDir(async (dir) => {
464
- await mkdir(join(dir, ".pi"));
465
- await writeFile(
466
- join(dir, ".pi", "settings.json"),
467
- JSON.stringify({ hashlineEdit: { enabled: false } }),
468
- );
469
- await writeFile(join(dir, "f.txt"), "old value\n");
470
- const registered: string[] = [];
471
- await registerHashline({
472
- async exec() {
473
- return { stdout: dir, stderr: "", code: 0, killed: false, truncated: false };
474
- },
475
- on() {
476
- assert.fail("Disabled extension must not subscribe to events");
477
- },
478
- registerEntryRenderer() {
479
- assert.fail("Disabled extension must not register a replay renderer");
480
- },
481
- registerTool(tool: { name: string }) {
482
- registered.push(tool.name);
483
- },
484
- } as any);
485
- assert.deepEqual(registered, []);
486
- const builtin = createEditTool(dir);
487
- const params = validateToolArguments(builtin, {
488
- name: "edit",
489
- arguments: { path: "f.txt", edits: [{ oldText: "old value", newText: "new value" }] },
490
- } as any);
491
- await call(builtin, params);
492
- assert.equal(await readFile(join(dir, "f.txt"), "utf-8"), "new value\n");
493
- });
494
- });
495
-
496
- test("loaded configuration controls hash length and recovery radius", async () =>
497
- withDir(async (dir) => {
498
- const text = "changed\ntarget\npadding\ntarget\n";
499
- await mkdir(join(dir, ".pi"));
500
- await writeFile(join(dir, "configured.txt"), text);
501
- for (const [hashLen, shiftRadius, expected] of [
502
- [6, 0, "unresolved"],
503
- [6, 1, "shifted"],
504
- [8, 3, "ambiguous"],
505
- ] as const) {
506
- await writeFile(
507
- join(dir, ".pi", "settings.json"),
508
- JSON.stringify({ hashlineEdit: { hashLen, shiftRadius } }),
509
- );
510
- const config = loadConfig(dir);
511
- const read = await call(makeReadOverride(dir, config), { path: "configured.txt" });
512
- assert.equal(anchorLine(read.content[0].text, 1).split("#")[1].length, hashLen);
513
- await expectToolFailure(
514
- call(makeEditOverride(dir, config), {
515
- path: "configured.txt",
516
- steps: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
517
- }),
518
- "ANCHOR_MISMATCH",
519
- (report) => {
520
- assert.equal(report.failures?.[0].result, expected);
521
- if (expected === "shifted") assert.match(report.failures?.[0].candidate ?? "", /^2#/);
522
- },
523
- );
524
- assert.equal(await readFile(join(dir, "configured.txt"), "utf8"), text);
525
- }
526
- }));
527
-
528
- test("configured read defaults bound omitted limits and returned bytes", async () =>
529
- withDir(async (dir) => {
530
- const read = makeReadOverride(dir, {
531
- ...DEFAULT_CONFIG,
532
- read: { defaultLimit: 2, maxKiB: 1 },
533
- });
534
- const description: unknown = Reflect.get(read.parameters.properties.limit, "description");
535
- assert.ok(typeof description === "string");
536
- assert.match(description, /default 2\)/);
537
- await writeFile(join(dir, "short.txt"), "a\nb\nc\n");
538
- const paged = await call(read, { path: "short.txt" });
539
- assert.equal(reportOf(paged, "read")?.nextOffset, 3);
540
- assert.match(reportOf(paged, "read")?.next ?? "", /offset.*nextOffset/);
541
- assert.match(paged.content[0].text, /^2#[0-9A-Z]+│b$/m);
542
- assert.doesNotMatch(paged.content[0].text, /^3#/m);
543
- const explicit = await call(read, { path: "short.txt", limit: 3 });
544
- assert.match(explicit.content[0].text, /^3#[0-9A-Z]+│c$/m);
545
- await writeFile(join(dir, "wide.txt"), `${"x".repeat(2048)}\n`);
546
- const wide = await call(read, { path: "wide.txt" });
547
- assert.equal(reportOf(wide, "read")?.lineTooLong, formatByteSize(1024));
548
- assert.doesNotMatch(wide.content[0].text, /^\d+#/m);
549
- }));