@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,291 +0,0 @@
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 { Type } from "typebox";
8
- import registerHashline from "../index.ts";
9
- import { computeLineHash } from "../core/hash.ts";
10
- import { callTool } from "../pi/tool-call.testing.ts";
11
- import { type HashlineEditConfig } from "../pi/config.ts";
12
- import { DEFAULT_CONFIG } from "../pi/tool-factories.testing.ts";
13
- import { reportOf } from "../pi/report.ts";
14
- import { formatByteSize } from "../pi/budgets.ts";
15
- import { expectToolFailure } from "../pi/report-failure.testing.ts";
16
- import { openTestSession } from "../testing/session.testing.ts";
17
-
18
- test("relative Node preload → registration uses the workspace", async (t) => {
19
- const cwd = await mkdtemp(join(tmpdir(), "hashline-workspace-"));
20
- t.after(() => rm(cwd, { recursive: true, force: true }));
21
- const previous = process.env.NODE_OPTIONS;
22
- process.env.NODE_OPTIONS = "--require=./package.json";
23
- try {
24
- const { session } = await openTestSession(t, {
25
- cwd,
26
- tools: ["read"],
27
- configure: registerHashline,
28
- });
29
- assert.ok(session.getToolDefinition("read")?.prepareArguments);
30
- } finally {
31
- if (previous === undefined) delete process.env.NODE_OPTIONS;
32
- else process.env.NODE_OPTIONS = previous;
33
- }
34
- });
35
-
36
- test("SDK cwd differs from process cwd → project settings and relative tools use the workspace", async (t) => {
37
- const cwd = await mkdtemp(join(tmpdir(), "hashline-workspace-"));
38
- t.after(() => rm(cwd, { recursive: true, force: true }));
39
- const settings = join(cwd, ".pi", "settings.json");
40
- await mkdir(join(cwd, ".pi"));
41
- await writeFile(settings, JSON.stringify({ hashlineEdit: { hashLen: 8, actionFusion: false } }));
42
- await writeFile(join(cwd, "workspace.txt"), "from the SDK workspace\n");
43
- const hostCwd = process.cwd();
44
- assert.notEqual(cwd, hostCwd);
45
- const { session } = await openTestSession(t, {
46
- cwd,
47
- tools: ["read", "write", "edit"],
48
- configure: registerHashline,
49
- });
50
- const read = session.getToolDefinition("read");
51
- assert.ok(read);
52
- const result = await callTool(read, { path: "workspace.txt" }, { ctx: { cwd } });
53
- const anchor = `1#${computeLineHash(1, "from the SDK workspace", 8)}`;
54
- assert.ok(
55
- result.content.some((block) => block.type === "text" && block.text.includes(anchor)),
56
- JSON.stringify(result.content),
57
- );
58
- const write = session.getToolDefinition("write");
59
- assert.ok(write && Type.IsObject(write.parameters));
60
- assert.ok(!("then_run" in write.parameters.properties));
61
- const written = await callTool(
62
- write,
63
- { path: "workspace.txt", content: "written\n", mode: "overwrite" },
64
- { ctx: { cwd } },
65
- );
66
- assert.equal(reportOf(written, "write")?.publication, "PUBLISHED");
67
- assert.equal(await readFile(join(cwd, "workspace.txt"), "utf8"), "written\n");
68
-
69
- await session.reload({
70
- beforeSessionStart: () => {
71
- assert.ok(session.getToolDefinition("edit")?.prepareArguments);
72
- assert.ok(session.extensionRunner.getEntryRenderer("hashline-then-run"));
73
- },
74
- });
75
-
76
- await writeFile(settings, JSON.stringify({ hashlineEdit: { enabled: false } }));
77
- await session.reload({
78
- beforeSessionStart: () => {
79
- assert.equal(session.getToolDefinition("replace"), undefined);
80
- assert.equal(session.extensionRunner.getEntryRenderer("hashline-then-run"), undefined);
81
- },
82
- });
83
- const builtin = session.getToolDefinition("edit");
84
- assert.ok(builtin && Type.IsObject(builtin.parameters));
85
- assert.ok("edits" in builtin.parameters.properties);
86
- assert.equal(process.cwd(), hostCwd);
87
- });
88
-
89
- test("registered tools retain their configuration when another tool set is registered", async (t) => {
90
- const directory = await mkdtemp(join(tmpdir(), "hashline-config-registration-"));
91
- try {
92
- await mkdir(join(directory, ".pi"));
93
- const register = async (config: HashlineEditConfig) => {
94
- await writeFile(
95
- join(directory, ".pi", "settings.json"),
96
- JSON.stringify({ hashlineEdit: config }),
97
- );
98
- const tools = new Map<string, ToolDefinition>();
99
- await registerHashline({
100
- async exec() {
101
- return { stdout: directory, stderr: "", code: 0, killed: false, truncated: false };
102
- },
103
- on() {},
104
- registerEntryRenderer() {},
105
- registerTool(tool: ToolDefinition) {
106
- tools.set(tool.name, tool);
107
- },
108
- } as unknown as ExtensionAPI);
109
- return { tools, config };
110
- };
111
- const registrations = [
112
- {
113
- ...(await register({
114
- ...DEFAULT_CONFIG,
115
- actionFusion: false,
116
- hashLen: 6,
117
- shiftRadius: 1,
118
- read: { defaultLimit: 1, maxKiB: 1 },
119
- grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 1, defaultContext: 1 },
120
- replace: { regexTimeoutMs: 3_000 },
121
- })),
122
- expectedGrepLines: [1, 2, 3],
123
- },
124
- {
125
- ...(await register({
126
- ...DEFAULT_CONFIG,
127
- actionFusion: false,
128
- hashLen: 8,
129
- shiftRadius: 0,
130
- read: { defaultLimit: 2, maxKiB: 2 },
131
- grep: { ...DEFAULT_CONFIG.grep, defaultLimit: 2, defaultContext: 0 },
132
- replace: { regexTimeoutMs: 3_500 },
133
- })),
134
- expectedGrepLines: [2, 6],
135
- },
136
- ];
137
-
138
- for (const { tools, config, expectedGrepLines } of registrations) {
139
- const { hashLen, shiftRadius, read, grep, replace } = config;
140
- for (const name of ["read", "grep", "edit"] as const) {
141
- await t.test(`${name} retains the registered hash length ${hashLen}`, async () => {
142
- const tool = tools.get(name);
143
- assert.ok(tool);
144
- const path = `${hashLen}-${name}.txt`;
145
- await writeFile(join(directory, path), "before\n");
146
- const params = {
147
- read: { path },
148
- grep: { path, pattern: "before", literal: true },
149
- edit: {
150
- path,
151
- steps: [
152
- {
153
- action: "replace",
154
- anchor: `1#${computeLineHash(1, "before", hashLen)}`,
155
- lines: ["after"],
156
- },
157
- ],
158
- },
159
- }[name];
160
- const result = await callTool(tool, params);
161
- assert.equal(result.content[0].type, "text");
162
- const expected = name === "edit" ? "after" : "before";
163
- if (name === "edit") {
164
- assert.equal(result.isError, undefined);
165
- } else {
166
- const anchor = `1#${computeLineHash(1, expected, hashLen)}`;
167
- assert.match(result.content[0].text, new RegExp(`^${anchor}(?:│|$)`, "m"));
168
- }
169
- assert.equal(await readFile(join(directory, path), "utf8"), `${expected}\n`);
170
- });
171
- }
172
-
173
- await t.test(`edit retains the registered recovery radius ${shiftRadius}`, async () => {
174
- const tool = tools.get("edit");
175
- assert.ok(tool);
176
- const path = `${hashLen}-recovery.txt`;
177
- const text = "changed\ntarget\n";
178
- await writeFile(join(directory, path), text);
179
- await expectToolFailure(
180
- callTool(tool, {
181
- path,
182
- steps: [{ action: "delete", anchor: `1#${computeLineHash(1, "target", hashLen)}` }],
183
- }),
184
- "ANCHOR_MISMATCH",
185
- (report) => {
186
- assert.equal(report.failures?.[0].result, shiftRadius === 0 ? "unresolved" : "shifted");
187
- if (shiftRadius !== 0) assert.match(report.failures?.[0].candidate ?? "", /^2#/);
188
- },
189
- );
190
- assert.equal(await readFile(join(directory, path), "utf8"), text);
191
- });
192
-
193
- await t.test(
194
- `read retains registered limit ${read.defaultLimit} and budget ${read.maxKiB} KiB`,
195
- async () => {
196
- const tool = tools.get("read");
197
- assert.ok(tool);
198
- const path = `${hashLen}-read-settings.txt`;
199
- const lines = ["first", "second", "third"];
200
- await writeFile(join(directory, path), `${lines.join("\n")}\n`);
201
- const result = await callTool(tool, { path });
202
- assert.equal(result.content[0].type, "text");
203
- assert.deepEqual(
204
- result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
205
- lines
206
- .slice(0, read.defaultLimit)
207
- .map(
208
- (content, index) =>
209
- `${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`,
210
- ),
211
- );
212
- assert.equal(reportOf(result, "read")?.nextOffset, read.defaultLimit + 1);
213
-
214
- const wide = "界".repeat(500);
215
- await writeFile(join(directory, path), `${wide}\n`);
216
- const bounded = await callTool(tool, { path });
217
- assert.equal(bounded.content[0].type, "text");
218
- if (read.maxKiB === 1) {
219
- const maxBytes = read.maxKiB * 1024;
220
- assert.equal(reportOf(bounded, "read")?.lineTooLong, formatByteSize(maxBytes));
221
- assert.doesNotMatch(bounded.content[0].text, /^\d+#/m);
222
- } else {
223
- assert.ok(
224
- bounded.content[0].text.includes(`1#${computeLineHash(1, wide, hashLen)}│${wide}`),
225
- );
226
- assert.equal(reportOf(bounded, "read")?.outputLimit, undefined);
227
- assert.equal(reportOf(bounded, "read")?.nextOffset, undefined);
228
- }
229
- },
230
- );
231
-
232
- await t.test(
233
- `grep retains registered limit ${grep.defaultLimit} and context ${grep.defaultContext}`,
234
- async () => {
235
- const tool = tools.get("grep");
236
- assert.ok(tool);
237
- const path = `${hashLen}-grep-settings.txt`;
238
- const lines = [
239
- "before one",
240
- "needle one",
241
- "after one",
242
- "gap",
243
- "before two",
244
- "needle two",
245
- "after two",
246
- "gap",
247
- "before three",
248
- "needle three",
249
- "after three",
250
- ];
251
- await writeFile(join(directory, path), `${lines.join("\n")}\n`);
252
- const result = await callTool(tool, { path, pattern: "needle", literal: true });
253
- assert.equal(result.content[0].type, "text");
254
- assert.deepEqual(
255
- result.content[0].text.split("\n").filter((line: string) => /^\d+#/.test(line)),
256
- expectedGrepLines.map(
257
- (line) =>
258
- `${line}#${computeLineHash(line, lines[line - 1], hashLen)}│${lines[line - 1]}`,
259
- ),
260
- );
261
- assert.equal(reportOf(result, "grep")?.matchLimit, grep.defaultLimit);
262
- },
263
- );
264
-
265
- await t.test(
266
- `replace retains registered regex timeout ${replace.regexTimeoutMs}ms`,
267
- async () => {
268
- const tool = tools.get("replace");
269
- assert.ok(tool);
270
- const path = `${hashLen}-replace-settings.txt`;
271
- const original = `${"a".repeat(35)}!`;
272
- await writeFile(join(directory, path), original);
273
- await expectToolFailure(
274
- callTool(tool, {
275
- path,
276
- replacements: [{ find: "^(a+)+$", replace: "changed", literal: false }],
277
- }),
278
- "REGEX_TIMEOUT",
279
- (report) => {
280
- assert.equal(report.timeoutMs, replace.regexTimeoutMs);
281
- assert.equal(report.publication, "NOT_PUBLISHED");
282
- },
283
- );
284
- assert.equal(await readFile(join(directory, path), "utf8"), original);
285
- },
286
- );
287
- }
288
- } finally {
289
- await rm(directory, { recursive: true, force: true });
290
- }
291
- });
@@ -1,320 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { readFile, writeFile } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { test, type TestContext } from "node:test";
5
- import { Type } from "typebox";
6
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
7
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
- import { openTestSession, responseStream } from "../testing/session.testing.ts";
9
- import type { ActionFusionProgress } from "../pi/report-schema.ts";
10
- import { createActionFusionExecutor, type ThenRunInput } from "../pi/action-fusion.ts";
11
- import { makeWriteOverride } from "../pi/tool-factories.testing.ts";
12
- import { commandText } from "../pi/mutation-result.ts";
13
- import { reportOf } from "../pi/report.ts";
14
- import type { CommandStatus } from "../pi/report-schema.ts";
15
-
16
- /** Exercise the default runner through a real parent tool call, with no provider traffic. */
17
- async function openSession(
18
- t: TestContext,
19
- configure?: (pi: ExtensionAPI) => void,
20
- onProgress?: (event: ActionFusionProgress) => void,
21
- ) {
22
- const calls: { name: string; parent?: string }[] = [];
23
- const progress: ActionFusionProgress[] = [];
24
- const { cwd, session, model } = await openTestSession(t, {
25
- tools: ["write", "bash"],
26
- configure(pi, cwd) {
27
- pi.on("tool_call", (event) => {
28
- calls.push({ name: event.toolName, parent: event.parentToolCallId });
29
- });
30
- configure?.(pi);
31
- pi.registerTool(
32
- makeWriteOverride(
33
- cwd,
34
- createActionFusionExecutor((event) => {
35
- progress.push(event);
36
- onProgress?.(event);
37
- }),
38
- ),
39
- );
40
- },
41
- });
42
- return {
43
- cwd,
44
- calls,
45
- progress,
46
- abort: () => session.abort(),
47
- async run(thenRun: ThenRunInput, expectedFile: string | null = "saved\n") {
48
- let responses = 0;
49
- session.agent.streamFunction = () => {
50
- const first = responses++ === 0;
51
- assert.ok(responses <= 2, "Unexpected model request");
52
- return responseStream(model, {
53
- content: first
54
- ? [
55
- {
56
- type: "toolCall",
57
- id: "fused",
58
- name: "write",
59
- arguments: {
60
- path: "saved.txt",
61
- mode: "create",
62
- content: "saved\n",
63
- then_run: thenRun,
64
- },
65
- },
66
- ]
67
- : [{ type: "text", text: "Done." }],
68
- stopReason: first ? "toolUse" : "stop",
69
- });
70
- };
71
- await session.prompt("Run the requested local command after the mutation.");
72
- assert.equal(session.agent.state.errorMessage, undefined);
73
- const result = session.agent.state.messages.find(
74
- (message) => message.role === "toolResult" && message.toolCallId === "fused",
75
- );
76
- assert.ok(result?.role === "toolResult");
77
- assert.equal(result.isError, false, "A command failure must not fail the completed mutation");
78
- const saved = readFile(join(cwd, "saved.txt"), "utf8");
79
- if (expectedFile === null) await assert.rejects(saved, { code: "ENOENT" });
80
- else assert.equal(await saved, expectedFile);
81
- return {
82
- modelRequests: responses,
83
- report: reportOf(result, "write"),
84
- text: result.content
85
- .filter((block) => block.type === "text")
86
- .map((block) => block.text)
87
- .join("\n"),
88
- };
89
- },
90
- };
91
- }
92
-
93
- const commandCases: {
94
- name: string;
95
- source: string;
96
- timeout?: number;
97
- command: CommandStatus;
98
- diagnostic: RegExp;
99
- }[] = [
100
- {
101
- name: "successful exit",
102
- source: "console.log('checked');",
103
- command: "succeeded",
104
- diagnostic: /checked/,
105
- },
106
- {
107
- name: "nonzero exit with timeout in its output",
108
- source: "console.error('timeout regression failed'); process.exit(1);",
109
- command: "failed",
110
- diagnostic: /Command exited with code 1/,
111
- },
112
- {
113
- name: "nonzero exit with a timeout-shaped log line",
114
- source: "console.error('Command timed out after 60 seconds'); process.exit(7);",
115
- timeout: 60,
116
- command: "failed",
117
- diagnostic: /Command exited with code 7/,
118
- },
119
- {
120
- name: "actual timeout",
121
- source: "setTimeout(() => {}, 10_000);",
122
- timeout: 0.2,
123
- command: "timeout",
124
- diagnostic: /Command timed out after 0\.2 seconds/,
125
- },
126
- ];
127
- for (const { name, source, timeout, command, diagnostic } of commandCases) {
128
- test(`real session ${name} → preserves the command outcome and published file`, {
129
- timeout: 15_000,
130
- }, async (t) => {
131
- const f = await openSession(t);
132
- await writeFile(join(f.cwd, "command.mjs"), source);
133
- const result = await f.run({
134
- command: "node command.mjs",
135
- ...(timeout === undefined ? {} : { timeout }),
136
- });
137
- assert.equal(result.report?.publication, "PUBLISHED");
138
- assert.equal(result.report?.then_run?.status, command);
139
- assert.equal(result.report?.freshness, undefined);
140
- assert.match(result.text, diagnostic);
141
- assert.equal(f.progress.at(-1)?.command, command);
142
- });
143
- }
144
-
145
- for (const [freshness, source, expectedFile, status] of [
146
- ["changed", "fs.writeFileSync('saved.txt', 'after'); process.exitCode = 7;", "after", "failed"],
147
- ["missing", "fs.unlinkSync('saved.txt');", null, "succeeded"],
148
- ] as const) {
149
- test(`real session command leaves target ${freshness} → reports publication, command status and final freshness`, async (t) => {
150
- const f = await openSession(t);
151
- await writeFile(join(f.cwd, "command.mjs"), `import fs from 'node:fs';\n${source}`);
152
- const result = await f.run({ command: "node command.mjs" }, expectedFile);
153
- assert.equal(result.report?.publication, "PUBLISHED");
154
- assert.equal(result.report.then_run?.status, status);
155
- assert.equal(result.report.freshness, freshness);
156
- const wire = reportOf({ content: [{ type: "text", text: result.text }] }, "write");
157
- assert.equal(wire?.freshness, freshness);
158
- if (freshness === "changed") assert.match(wire.next ?? "", /Read the file/);
159
- else assert.equal(wire.next, undefined);
160
- });
161
- }
162
-
163
- test("cancelling a real session Bash command → reports cancellation and keeps the published mutation", {
164
- timeout: 15_000,
165
- }, async (t) => {
166
- const started = Promise.withResolvers<void>();
167
- const f = await openSession(t, undefined, (event) => {
168
- if (
169
- event.command === "running" &&
170
- event.result &&
171
- commandText(event.result.content).includes("READY")
172
- )
173
- started.resolve();
174
- });
175
- await writeFile(
176
- join(f.cwd, "command.mjs"),
177
- "console.log('READY'); setInterval(() => {}, 1000);\n",
178
- );
179
- const pending = f.run({ command: "node command.mjs" });
180
- await started.promise;
181
- await f.abort();
182
- const result = await pending;
183
- assert.equal(result.report?.publication, "PUBLISHED");
184
- assert.equal(result.report?.then_run?.status, "cancelled");
185
- assert.match(result.text, /Command aborted/);
186
- assert.equal(f.progress.at(-1)?.command, "cancelled");
187
- });
188
-
189
- test("session Bash permission checks wait → countdown starts with command execution progress", {
190
- timeout: 15_000,
191
- }, async (t) => {
192
- const checking = Promise.withResolvers<void>();
193
- const allowed = Promise.withResolvers<void>();
194
- const f = await openSession(t, (pi) => {
195
- pi.on("tool_call", async (event) => {
196
- if (event.toolName === "bash") {
197
- checking.resolve();
198
- await allowed.promise;
199
- }
200
- });
201
- });
202
- await writeFile(join(f.cwd, "command.mjs"), "console.log('checked');\n");
203
- const pending = f.run({ command: "node command.mjs", timeout: 10 });
204
- try {
205
- await checking.promise;
206
- assert.ok(f.progress.every((event) => event.timing === undefined));
207
- } finally {
208
- allowed.resolve();
209
- await pending;
210
- }
211
- assert.deepEqual(f.progress.find((event) => event.timing)?.timing, {
212
- timeoutSeconds: 10,
213
- remainingSeconds: 10,
214
- });
215
- assert.equal(f.progress.at(-1)?.command, "succeeded");
216
- });
217
-
218
- test("session Bash tool_call blocks then_run → no command side effect, mutation stays published", {
219
- timeout: 15_000,
220
- }, async (t) => {
221
- const f = await openSession(t, (pi) => {
222
- pi.on("tool_call", (event) =>
223
- event.toolName === "bash"
224
- ? { block: true, reason: "BLOCKED_BY_POLICY", terminate: true }
225
- : undefined,
226
- );
227
- });
228
- await writeFile(
229
- join(f.cwd, "command.mjs"),
230
- "import { writeFileSync } from 'node:fs'; writeFileSync('command-ran', 'yes');\n",
231
- );
232
- const result = await f.run({ command: "node command.mjs" });
233
- assert.equal(result.report?.publication, "PUBLISHED");
234
- assert.equal(result.report?.then_run?.status, "failed");
235
- assert.match(result.text, /BLOCKED_BY_POLICY/);
236
- assert.equal(result.modelRequests, 1, "Preserve the policy hook's request to stop the batch");
237
- await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
238
- assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
239
- });
240
-
241
- test("session Bash override and tool_result hook → then_run uses their final result", {
242
- timeout: 15_000,
243
- }, async (t) => {
244
- let executions = 0;
245
- const partial: AgentToolResult<unknown> = {
246
- content: [{ type: "text", text: "OVERRIDE_PROGRESS" }],
247
- details: { fullOutputPath: "/tmp/partial-command.log" },
248
- };
249
- const final: AgentToolResult<unknown> = {
250
- content: [
251
- { type: "text", text: "HOOK_REJECTED_OVERRIDE" },
252
- { type: "image", data: "iVBORw0KGgo=", mimeType: "image/png" },
253
- ],
254
- details: { fullOutputPath: "/tmp/final-command.log" },
255
- };
256
- const f = await openSession(t, (pi) => {
257
- pi.registerTool({
258
- name: "bash",
259
- label: "bash",
260
- description: "Session Bash override",
261
- parameters: Type.Object({ command: Type.String() }),
262
- async execute(_id, _args, _signal, onUpdate) {
263
- executions++;
264
- onUpdate?.(partial);
265
- return { content: [{ type: "text", text: "OVERRIDE_RESULT" }], details: {} };
266
- },
267
- });
268
- pi.on("tool_result", (event) =>
269
- event.toolName === "bash"
270
- ? {
271
- ...final,
272
- isError: true,
273
- }
274
- : undefined,
275
- );
276
- });
277
- await writeFile(
278
- join(f.cwd, "command.mjs"),
279
- "import { writeFileSync } from 'node:fs'; writeFileSync('command-ran', 'yes');\n",
280
- );
281
- const result = await f.run({ command: "node command.mjs" });
282
- assert.equal(executions, 1);
283
- assert.equal(result.report?.then_run?.status, "failed");
284
- assert.match(result.text, /HOOK_REJECTED_OVERRIDE/);
285
- assert.doesNotMatch(result.text, /OVERRIDE_RESULT/);
286
- assert.deepEqual(
287
- f.progress.find(
288
- (event) => event.result && commandText(event.result.content) === "OVERRIDE_PROGRESS",
289
- )?.result,
290
- partial,
291
- );
292
- assert.deepEqual(f.progress.at(-1)?.result, final);
293
- await assert.rejects(readFile(join(f.cwd, "command-ran")), { code: "ENOENT" });
294
- assert.ok(f.calls.some((call) => call.name === "bash" && call.parent === "fused"));
295
- });
296
-
297
- test("session Bash override writes the target through a nested call → fails without waiting on its own queue", {
298
- timeout: 3_000,
299
- }, async (t) => {
300
- const f = await openSession(t, (pi) => {
301
- pi.registerTool({
302
- name: "bash",
303
- label: "bash",
304
- description: "Session Bash override",
305
- parameters: Type.Object({ command: Type.String() }),
306
- async execute(_id, _args, _signal, _onUpdate, ctx) {
307
- const nested = await ctx.executeTool("write", {
308
- path: "./saved.txt",
309
- mode: "overwrite",
310
- content: "nested write\n",
311
- });
312
- return { ...nested.result, isError: nested.isError };
313
- },
314
- });
315
- });
316
- const result = await f.run({ command: "check" });
317
- assert.equal(result.report?.publication, "PUBLISHED");
318
- assert.equal(result.report?.then_run?.status, "failed");
319
- assert.ok(f.calls.some((call) => call.name === "write" && call.parent === "fused/1"));
320
- });
@@ -1,81 +0,0 @@
1
- import { listCandidates } from "../pi/grep-candidates.ts";
2
- import assert from "node:assert/strict";
3
- import { chmod, mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/promises";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { test } from "node:test";
7
- const { DEFAULT_CONFIG, makeGrepOverride } = await import("../pi/tool-factories.testing.ts");
8
-
9
- import { callTool } from "../pi/tool-call.testing.ts";
10
- import { expectToolFailure } from "../pi/report-failure.testing.ts";
11
-
12
- for (const condition of ["permission denied", "symlink loop"] as const) {
13
- test(`existing search path has ${condition} → grep retains the real filesystem error`, {
14
- skip:
15
- process.platform === "win32" ||
16
- (condition === "permission denied" && process.getuid?.() === 0)
17
- ? "Requires POSIX traversal permissions and symlinks; permission case requires a non-root user"
18
- : false,
19
- }, async (t) => {
20
- const directory = await mkdtemp(join(tmpdir(), "hashline-grep-scope-"));
21
- const denied = join(directory, "denied");
22
- t.after(async () => {
23
- if (condition === "permission denied") await chmod(denied, 0o700);
24
- await rm(directory, { recursive: true, force: true });
25
- });
26
- let path: string;
27
- let code: string;
28
- if (condition === "permission denied") {
29
- await mkdir(denied);
30
- path = join(denied, "source.txt");
31
- await writeFile(path, "needle中文\n");
32
- await chmod(denied, 0);
33
- code = "EACCES";
34
- } else {
35
- path = join(directory, "loop");
36
- await symlink("loop", path);
37
- code = "ELOOP";
38
- }
39
- await assert.rejects(stat(path), { code });
40
- const tool = makeGrepOverride(directory, DEFAULT_CONFIG);
41
- await expectToolFailure(
42
- callTool(tool, { path, pattern: "needle", literal: true, ignoreCase: false }),
43
- "FILESYSTEM_ERROR",
44
- (report) => {
45
- assert.doesNotMatch(report.message ?? "", /Path not found/);
46
- assert.ok(report.message?.includes(code));
47
- assert.equal(report.cause, undefined);
48
- },
49
- );
50
- });
51
- }
52
-
53
- test("prefilter hits an unreadable path without matches → preserves the diagnostic and offers no unfiltered candidates", {
54
- skip: process.getuid?.() === 0 ? "POSIX permission fixture requires a non-root user" : false,
55
- }, async (t) => {
56
- const directory = await mkdtemp(join(tmpdir(), "hashline-grep-prefilter-error-"));
57
- t.after(() => rm(directory, { recursive: true, force: true }));
58
- await writeFile(join(directory, "nonmatch.txt"), "other text\n");
59
- const inaccessible = join(directory, "inaccessible");
60
- if (process.platform === "win32") {
61
- await symlink(join(directory, "missing"), inaccessible, "junction");
62
- } else {
63
- await writeFile(inaccessible, "needle\n");
64
- await chmod(inaccessible, 0);
65
- }
66
-
67
- const offered: string[] = [];
68
- const { listing } = await listCandidates({
69
- scope: { searchPaths: [directory], globs: [] },
70
- query: { patterns: ["needle"], literal: true, ignoreCase: false, multiline: true },
71
- signal: new AbortController().signal,
72
- stopped: () => false,
73
- onCandidate: async ({ filePath }) => {
74
- offered.push(filePath);
75
- return true;
76
- },
77
- });
78
- assert.deepEqual(offered, []);
79
- assert.equal(listing?.code, 2);
80
- assert.match(listing.stderr, /inaccessible/);
81
- });