@criogaid/pi-hashline-edit 0.1.1 → 0.1.3
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.
- package/README.md +168 -197
- package/package.json +1 -1
- package/src/core/apply.test.ts +40 -1
- package/src/core/apply.ts +13 -3
- package/src/core/hash.test.ts +7 -3
- package/src/core/hash.ts +6 -10
- package/src/core/index.ts +1 -0
- package/src/core/text.test.ts +15 -0
- package/src/core/text.ts +18 -0
- package/src/core/types.ts +1 -2
- package/src/index.ts +4 -3
- package/src/integration/grep-rg.test.ts +20 -0
- package/src/pi/action-fusion.test.ts +8 -6
- package/src/pi/action-fusion.ts +39 -18
- package/src/pi/config.test.ts +28 -8
- package/src/pi/config.ts +9 -7
- package/src/pi/edit-tool.ts +44 -70
- package/src/pi/execute.test.ts +50 -1
- package/src/pi/failure-path.test.ts +10 -7
- package/src/pi/file-commit.test.ts +29 -1
- package/src/pi/file-commit.ts +39 -7
- package/src/pi/fusion-card.test.ts +1 -1
- package/src/pi/grep-tool.ts +20 -34
- package/src/pi/grep.test.ts +24 -6
- package/src/pi/mutation-result.ts +46 -0
- package/src/pi/read-tool.ts +4 -4
- package/src/pi/registration.test.ts +69 -9
- package/src/pi/render.ts +51 -1
- package/src/pi/replace-tool.ts +34 -44
- package/src/pi/result-safety.test.ts +169 -0
- package/src/pi/state.ts +2 -3
- package/src/pi/write-tool.ts +12 -2
- package/src/pi/write.test.ts +7 -1
package/src/pi/grep.test.ts
CHANGED
|
@@ -414,7 +414,7 @@ test("bounds rg predicate fanout for matchMode all", async () => {
|
|
|
414
414
|
});
|
|
415
415
|
});
|
|
416
416
|
|
|
417
|
-
test("rejects empty
|
|
417
|
+
test("rejects empty patterns while allowing wildcard, literal, and empty-line searches", async () => {
|
|
418
418
|
await withDir(async (dir) => {
|
|
419
419
|
const fake = fakeBackend();
|
|
420
420
|
const tool = makeGrepOverrideWithBackend(dir, fake.backend);
|
|
@@ -422,15 +422,15 @@ test("rejects empty and wildcard-only regexes without blocking literal or empty-
|
|
|
422
422
|
for (const pattern of ["", " ", []]) {
|
|
423
423
|
await assert.rejects(call(tool, { pattern }), /pattern (?:is required|must not be empty)/);
|
|
424
424
|
}
|
|
425
|
-
for (const pattern of [".*", "^.+$", ".?", "*"]) {
|
|
426
|
-
await assert.rejects(call(tool, { pattern }), /is wildcard-only/);
|
|
427
|
-
}
|
|
428
425
|
assert.equal(fake.calls.length, 0);
|
|
426
|
+
for (const pattern of [".*", "^.+$", ".?"]) {
|
|
427
|
+
assert.equal(text(await call(tool, { pattern })), "No matches found");
|
|
428
|
+
}
|
|
429
429
|
|
|
430
430
|
assert.equal(text(await call(tool, { pattern: ".*", literal: true })), "No matches found");
|
|
431
431
|
assert.equal(text(await call(tool, { pattern: "^$" })), "No matches found");
|
|
432
|
-
assert.equal(fake.calls.filter(({ args }) => !args.includes("--quiet")).length,
|
|
433
|
-
assert.equal(fake.calls.filter(({ args }) => args.includes("--quiet")).length,
|
|
432
|
+
assert.equal(fake.calls.filter(({ args }) => !args.includes("--quiet")).length, 5);
|
|
433
|
+
assert.equal(fake.calls.filter(({ args }) => args.includes("--quiet")).length, 4);
|
|
434
434
|
});
|
|
435
435
|
});
|
|
436
436
|
|
|
@@ -540,3 +540,21 @@ test("large candidate lines flush before the batch line-count limit", async () =
|
|
|
540
540
|
assert.deepEqual(sizes, [2, 1]);
|
|
541
541
|
});
|
|
542
542
|
});
|
|
543
|
+
|
|
544
|
+
test("grep rejects malformed UTF-8 and NUL bytes instead of hashing binary text", async () => {
|
|
545
|
+
await withDir(async (dir) =>
|
|
546
|
+
withEnabled(true, async () => {
|
|
547
|
+
const cases = [
|
|
548
|
+
{ name: "invalid.txt", bytes: Buffer.from([0x61, 0x0a, 0xc3, 0x28, 0x0a]), error: /UNSUPPORTED_ENCODING/ },
|
|
549
|
+
{ name: "nul.txt", bytes: Buffer.from([0x61, 0x00, 0x62]), error: /UNSUPPORTED_TEXT/ },
|
|
550
|
+
];
|
|
551
|
+
for (const fixture of cases) {
|
|
552
|
+
const file = join(dir, fixture.name);
|
|
553
|
+
await writeFile(file, fixture.bytes);
|
|
554
|
+
const fake = fakeBackend({ lines: [rgMatch(file, 1, "a\n")], paths: [file] });
|
|
555
|
+
await assert.rejects(call(makeGrepOverrideWithBackend(dir, fake.backend), { pattern: "a", path: file }), fixture.error);
|
|
556
|
+
assert.deepEqual(await readFile(file), fixture.bytes);
|
|
557
|
+
}
|
|
558
|
+
}),
|
|
559
|
+
);
|
|
560
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
|
|
3
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
4
|
+
|
|
5
|
+
export function observedFreshness(result: AgentToolResult<unknown>): "unchanged" | "changed" | "unknown" {
|
|
6
|
+
const versions = result.details as Partial<MutationVersions> | undefined;
|
|
7
|
+
if (!versions?.publishedRevision || !versions.observedRevision) return "unknown";
|
|
8
|
+
return versions.publishedRevision === versions.observedRevision ? "unchanged" : "changed";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Finalize from the observed commit revision unless a later freshness check supplies the decision. */
|
|
12
|
+
export function finalizeMutationResult<T>(
|
|
13
|
+
result: AgentToolResult<T>,
|
|
14
|
+
finalize: (result: AgentToolResult<T>, publishAnchors: boolean) => AgentToolResult<T>,
|
|
15
|
+
publishAnchors = observedFreshness(result) === "unchanged",
|
|
16
|
+
): AgentToolResult<T> {
|
|
17
|
+
try {
|
|
18
|
+
const finalized = finalize(result, publishAnchors);
|
|
19
|
+
return publishAnchors ? finalized : {
|
|
20
|
+
...finalized,
|
|
21
|
+
content: [...finalized.content, { type: "text", text: "Anchors omitted: target revision was not confirmed unchanged. Re-read before further edits." }],
|
|
22
|
+
};
|
|
23
|
+
} catch (error) {
|
|
24
|
+
const publication = (result.details as { publication?: PublicationStatus } | undefined)?.publication ?? "UNKNOWN";
|
|
25
|
+
throw new FileMutationError("post_process", publication, `Result generation failed; publication=${publication}. Re-read before retrying: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Bound complete anchor rows before hashing or constructing their output strings. */
|
|
30
|
+
export function formatMutationAnchors(lines: readonly string[], indices: Iterable<number>, hashLen: number, heading: string): string {
|
|
31
|
+
const notice = "\n… (additional anchors omitted: 40-row/16 KiB limit; use read for full content)";
|
|
32
|
+
const rows: string[] = [];
|
|
33
|
+
let bytes = Buffer.byteLength(`\n${heading}\n`) + Buffer.byteLength(notice);
|
|
34
|
+
let omitted = false;
|
|
35
|
+
for (const index of indices) {
|
|
36
|
+
const content = lines[index];
|
|
37
|
+
const rowBytes = Buffer.byteLength(`${index + 1}#${"X".repeat(hashLen)}│`) + Buffer.byteLength(content) + 1;
|
|
38
|
+
if (rows.length >= 40 || bytes + rowBytes > 16 * 1024) {
|
|
39
|
+
omitted = true;
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
rows.push(`${index + 1}#${computeLineHash(index + 1, content, hashLen)}│${content}`);
|
|
43
|
+
bytes += rowBytes;
|
|
44
|
+
}
|
|
45
|
+
return rows.length || omitted ? `\n${heading}\n${rows.join("\n")}${omitted ? notice : ""}` : "";
|
|
46
|
+
}
|
package/src/pi/read-tool.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { Text } from "@earendil-works/pi-tui";
|
|
|
14
14
|
import { readFile } from "node:fs/promises";
|
|
15
15
|
import { join, resolve } from "node:path";
|
|
16
16
|
import { homedir } from "node:os";
|
|
17
|
-
import {
|
|
17
|
+
import { decodeUtf8, computeLineHash } from "../core/index.ts";
|
|
18
18
|
import { hasFinalNewline, splitLines } from "../core/lines.ts";
|
|
19
19
|
import { getState } from "./state.ts";
|
|
20
20
|
import { parseHashline } from "./render.ts";
|
|
@@ -144,10 +144,10 @@ export function makeReadOverride(cwd: string) {
|
|
|
144
144
|
// binary/image detection (null byte) → delegate to the built-in (it uses file-type for images)
|
|
145
145
|
if (buf.includes(0)) return builtin.execute(toolCallId, params, signal, onUpdate, ctx);
|
|
146
146
|
|
|
147
|
-
const text = buf
|
|
147
|
+
const text = decodeUtf8(buf);
|
|
148
148
|
const allLines = splitLines(text);
|
|
149
149
|
const totalLines = allLines.length;
|
|
150
|
-
const
|
|
150
|
+
const hashLen = getState().config.hashLen;
|
|
151
151
|
|
|
152
152
|
// offset/limit
|
|
153
153
|
const offset = (params.offset as number | undefined) ?? 1;
|
|
@@ -155,7 +155,7 @@ export function makeReadOverride(cwd: string) {
|
|
|
155
155
|
const startIdx = Math.max(0, offset - 1);
|
|
156
156
|
const endIdx = Math.min(totalLines, startIdx + limit);
|
|
157
157
|
|
|
158
|
-
const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${
|
|
158
|
+
const rows = allLines.slice(startIdx, endIdx).map((line, index) => `${startIdx + index + 1}#${computeLineHash(startIdx + index + 1, line, hashLen)}│${line}`);
|
|
159
159
|
const truncation = truncateHead(rows.join("\n"), { maxBytes: MAX_BYTES, maxLines: rows.length });
|
|
160
160
|
|
|
161
161
|
const shownFrom = offset > 1 ? ` (from line ${offset})` : "";
|
|
@@ -5,21 +5,25 @@ import assert from "node:assert/strict";
|
|
|
5
5
|
import { test } from "node:test";
|
|
6
6
|
import registerHashline from "../index.ts";
|
|
7
7
|
import { getState } from "./state.ts";
|
|
8
|
+
import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import { ToolExecutionComponent } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tool-execution.js";
|
|
10
|
+
import { theme } from "../../node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js";
|
|
8
11
|
|
|
9
|
-
test("
|
|
12
|
+
test("mutation cards use Fusion by default and explicit false removes command support", async () => {
|
|
10
13
|
const dir = await mkdtemp(join(tmpdir(), "hashline-registration-"));
|
|
11
14
|
const previousCwd = process.cwd();
|
|
12
15
|
const state = getState();
|
|
13
16
|
const previousConfig = state.config;
|
|
14
17
|
try {
|
|
15
18
|
await mkdir(join(dir, ".pi"));
|
|
16
|
-
await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true
|
|
19
|
+
await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { enabled: true } }));
|
|
17
20
|
process.chdir(dir);
|
|
18
21
|
const tools: any[] = [];
|
|
19
22
|
const entries: any[] = [];
|
|
23
|
+
const renderers = new Map<string, any>();
|
|
20
24
|
registerHashline({
|
|
21
25
|
on() {},
|
|
22
|
-
registerEntryRenderer() {},
|
|
26
|
+
registerEntryRenderer(type: string, renderer: any) { renderers.set(type, renderer); },
|
|
23
27
|
appendEntry(customType: string, data: unknown) { entries.push({ customType, data }); },
|
|
24
28
|
registerTool(tool: any) { tools.push(tool); },
|
|
25
29
|
} as any);
|
|
@@ -27,12 +31,68 @@ test("enabled registration installs the Hashline write and shared Fusion schemas
|
|
|
27
31
|
for (const tool of tools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
|
|
28
32
|
assert.ok(tool.parameters.properties.then_run, `${tool.name} should expose then_run when actionFusion is enabled`);
|
|
29
33
|
}
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
34
|
+
initTheme("dark");
|
|
35
|
+
const cases = [
|
|
36
|
+
{ name: "write", args: { content: "published\n" } },
|
|
37
|
+
{ name: "edit", args: { edits: [{ op: "append", body: ["appended"] }] } },
|
|
38
|
+
{ name: "replace", args: { find: "published", replace: "published" } },
|
|
39
|
+
];
|
|
40
|
+
for (const { name, args } of cases) {
|
|
41
|
+
const tool = tools.find((tool) => tool.name === name);
|
|
42
|
+
const params = { path: "published.txt", ...args, then_run: { command: "exit 7" } };
|
|
43
|
+
const card = new ToolExecutionComponent(name, name, params, {}, tool, { requestRender() {} } as any, dir);
|
|
44
|
+
card.setArgsComplete();
|
|
45
|
+
card.markExecutionStarted();
|
|
46
|
+
const frames: { command: string; publication: string; mutationCompleted: boolean; output: string; commandOutput: string }[] = [];
|
|
47
|
+
const result = await tool.execute(name, params, undefined, (update: any) => {
|
|
48
|
+
card.updateResult({ ...update, isError: false }, true);
|
|
49
|
+
const entry = entries.find((entry) => entry.customType === "hashline-then-run" && entry.data.toolCallId === name);
|
|
50
|
+
const commandCard = renderers.get(entry.customType)(entry, { expanded: false }, theme);
|
|
51
|
+
frames.push({ ...update.details.actionFusion, output: card.render(100).join("\n"), commandOutput: commandCard.render(100).join("\n") });
|
|
52
|
+
}, { cwd: dir });
|
|
53
|
+
assert.equal(result.details.actionFusion.command, "failed");
|
|
54
|
+
assert.match(result.content[1].text, /File changes are saved|No file changes were published/);
|
|
55
|
+
assert.ok(frames[0].output.includes(theme.getBgAnsi("toolPendingBg")));
|
|
56
|
+
const running = frames.find((frame) => frame.command === "running")!;
|
|
57
|
+
assert.ok(running, `${name} should emit running progress`);
|
|
58
|
+
assert.ok(running.output.includes(theme.getBgAnsi("toolSuccessBg")), `${name} should turn green before then_run ends`);
|
|
59
|
+
assert.ok(!running.output.includes(theme.getBgAnsi("toolPendingBg")));
|
|
60
|
+
assert.ok(running.commandOutput.includes(theme.getBgAnsi("toolPendingBg")));
|
|
61
|
+
assert.ok(frames.at(-1)!.commandOutput.includes(theme.getBgAnsi("toolErrorBg")));
|
|
62
|
+
const completed = frames.find((frame) => frame.command === "waiting" && frame.mutationCompleted)!;
|
|
63
|
+
assert.ok(completed?.output.includes(theme.getBgAnsi("toolSuccessBg")), "mutation completion must repaint before command checks");
|
|
64
|
+
if (name === "replace") assert.equal(running.publication, "NOT_PUBLISHED");
|
|
65
|
+
card.updateResult({ ...result, isError: false });
|
|
66
|
+
assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
|
|
67
|
+
card.setExpanded(true);
|
|
68
|
+
assert.ok(card.render(100).join("\n").includes(theme.getBgAnsi("toolSuccessBg")));
|
|
69
|
+
|
|
70
|
+
const invalid = { ...params, path: "missing.txt", ...(name === "write" ? { mode: "overwrite" } : {}) };
|
|
71
|
+
const failedCard = new ToolExecutionComponent(name, `${name}-bad`, invalid, {}, tool, { requestRender() {} } as any, dir);
|
|
72
|
+
await assert.rejects(tool.execute(`${name}-bad`, invalid, undefined, (update: any) => {
|
|
73
|
+
failedCard.updateResult({ ...update, isError: false }, true);
|
|
74
|
+
}, { cwd: dir }), (error: Error) => {
|
|
75
|
+
failedCard.updateResult({ content: [{ type: "text", text: error.message }], isError: true });
|
|
76
|
+
const output = failedCard.render(100).join("\n");
|
|
77
|
+
assert.ok(output.includes(theme.getBgAnsi("toolErrorBg")), `${name} mutation failure should turn red`);
|
|
78
|
+
assert.ok(!output.includes(theme.getBgAnsi("toolPendingBg")));
|
|
79
|
+
return true;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
assert.deepEqual(entries.map((entry) => entry.data.command), cases.flatMap(() => ["waiting", "failed", "waiting", "skipped"]));
|
|
83
|
+
await writeFile(join(dir, ".pi", "settings.json"), JSON.stringify({ hashlineEdit: { actionFusion: false } }));
|
|
84
|
+
const disabledTools: any[] = [];
|
|
85
|
+
registerHashline({
|
|
86
|
+
on() {},
|
|
87
|
+
registerEntryRenderer() {},
|
|
88
|
+
registerTool(tool: any) { disabledTools.push(tool); },
|
|
89
|
+
} as any);
|
|
90
|
+
assert.equal(disabledTools.length, 5);
|
|
91
|
+
for (const tool of disabledTools.filter((tool) => ["edit", "replace", "write"].includes(tool.name))) {
|
|
92
|
+
assert.equal(tool.parameters.properties.then_run, undefined);
|
|
93
|
+
assert.equal(tool.renderShell, "default");
|
|
94
|
+
await assert.rejects(tool.execute("disabled", { path: "published.txt", then_run: { command: "exit 0" } }, undefined, undefined, { cwd: dir }), /then_run is unavailable/);
|
|
95
|
+
}
|
|
36
96
|
} finally {
|
|
37
97
|
process.chdir(previousCwd);
|
|
38
98
|
state.config = previousConfig;
|
package/src/pi/render.ts
CHANGED
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
* @module pi-hashline-edit/pi
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { renderDiff } from "@earendil-works/pi-coding-agent";
|
|
12
|
+
import { renderDiff, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import { Box, Container, Text } from "@earendil-works/pi-tui";
|
|
13
14
|
|
|
14
15
|
const HASHLINE_RE = /^(\d+)#[A-Za-z0-9]+│(.*)$/;
|
|
15
16
|
|
|
@@ -101,3 +102,52 @@ export function publishDiffCounts(
|
|
|
101
102
|
context.state.diffCounts = counts;
|
|
102
103
|
if (!prev || prev.added !== counts.added || prev.removed !== counts.removed) refreshHeader(counts);
|
|
103
104
|
}
|
|
105
|
+
|
|
106
|
+
/** Render mutation status or a diff, refreshing the call header's counts in place. */
|
|
107
|
+
export function renderMutationResult(
|
|
108
|
+
result: any, { isPartial, expanded }: any, theme: any, context: any,
|
|
109
|
+
pending: string, fallback: string, header: (args: any, theme: any, counts?: DiffCounts) => string,
|
|
110
|
+
): Text {
|
|
111
|
+
if (isPartial && result.details?.actionFusion?.publication !== "PUBLISHED") return new Text(theme.fg("warning", pending), 0, 0);
|
|
112
|
+
const content = result.content?.[0];
|
|
113
|
+
if (context.isError) {
|
|
114
|
+
const text = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
115
|
+
return new Text(theme.fg("error", text), 0, 0);
|
|
116
|
+
}
|
|
117
|
+
const diff: string | undefined = result.details?.diff;
|
|
118
|
+
// Refresh in place: invalidation inside a renderer re-enters updateDisplay.
|
|
119
|
+
publishDiffCounts(diff, context, (counts) => {
|
|
120
|
+
context.state?.callText?.setText(header(context.args, theme, counts));
|
|
121
|
+
});
|
|
122
|
+
if (!diff) {
|
|
123
|
+
// Only the summary is displayed; subsequent anchor rows are for the model.
|
|
124
|
+
const summary = content?.type === "text" ? content.text.split("\n")[0] : fallback;
|
|
125
|
+
return new Text(theme.fg("success", summary), 0, 0);
|
|
126
|
+
}
|
|
127
|
+
return new Text(renderDiffPreview(diff, expanded, theme), 0, 0);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Keep the mutation card's background independent of the fused command's lifetime. */
|
|
131
|
+
export function withMutationStatus(tool: ToolDefinition<any, any, any>): ToolDefinition<any, any, any> {
|
|
132
|
+
return {
|
|
133
|
+
...tool,
|
|
134
|
+
renderShell: "self",
|
|
135
|
+
renderCall(args, theme, context) {
|
|
136
|
+
const shell = context.state.mutationShell ??= { box: new Box(1, 1) };
|
|
137
|
+
shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
|
|
138
|
+
shell.box.clear();
|
|
139
|
+
shell.box.addChild(shell.call);
|
|
140
|
+
shell.box.setBgFn((line: string) => theme.bg(context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
|
|
141
|
+
return shell.box;
|
|
142
|
+
},
|
|
143
|
+
renderResult(result, options, theme, context) {
|
|
144
|
+
const shell = context.state.mutationShell;
|
|
145
|
+
const isPartial = options.isPartial && result.details?.actionFusion?.mutationCompleted !== true;
|
|
146
|
+
shell.result = tool.renderResult!(result, { ...options, isPartial }, theme, { ...context, isPartial, lastComponent: shell.result });
|
|
147
|
+
// Pi runs renderCall first; update its box in place without invalidating the tool row.
|
|
148
|
+
shell.box.addChild(shell.result);
|
|
149
|
+
shell.box.setBgFn((line: string) => theme.bg(isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg", line));
|
|
150
|
+
return new Container();
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
package/src/pi/replace-tool.ts
CHANGED
|
@@ -32,15 +32,14 @@ import {
|
|
|
32
32
|
import { Type, type Static } from "typebox";
|
|
33
33
|
import { Text } from "@earendil-works/pi-tui";
|
|
34
34
|
import { readFile } from "node:fs/promises";
|
|
35
|
-
import {
|
|
35
|
+
import { decodeEditableText, splitLines } from "../core/index.ts";
|
|
36
36
|
import { ACTION_FUSION_GUIDELINES, createActionFusionExecutor, createThenRunSchema, type ThenRunInput } from "./action-fusion.ts";
|
|
37
|
-
import { commitFile, FileMutationError, type PublicationStatus } from "./file-commit.ts";
|
|
37
|
+
import { byteRevision, commitFile, FileMutationError, type MutationVersions, type PublicationStatus } from "./file-commit.ts";
|
|
38
38
|
import { getState } from "./state.ts";
|
|
39
39
|
import { canonicalPath } from "./read-tool.ts";
|
|
40
|
-
import { formatDiffCounts,
|
|
40
|
+
import { formatDiffCounts, renderMutationResult, type DiffCounts } from "./render.ts";
|
|
41
|
+
import { finalizeMutationResult, formatMutationAnchors } from "./mutation-result.ts";
|
|
41
42
|
|
|
42
|
-
/** Cap on updated-anchor lines returned inline (bounds token cost for large spans). */
|
|
43
|
-
const MAX_ANCHOR_LINES = 40;
|
|
44
43
|
/** Default safety cap on match count (errors before writing if exceeded). */
|
|
45
44
|
const DEFAULT_MAX_MATCHES = 2000;
|
|
46
45
|
/** Valid JavaScript regular-expression flag characters (ES2023+, incl. hasIndices `d`). */
|
|
@@ -118,12 +117,10 @@ function changedSpan(oldLines: readonly string[], newLines: readonly string[]):
|
|
|
118
117
|
|
|
119
118
|
/** Format fresh `LINE#HASH│content` anchors for a contiguous span of the new file, capped. */
|
|
120
119
|
function formatSpanAnchors(newLines: readonly string[], span: { start: number; end: number }, hashLen: number): string {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const more = rows.length > MAX_ANCHOR_LINES ? `\n… (${rows.length - MAX_ANCHOR_LINES} more; re-read for full anchors)` : "";
|
|
126
|
-
return `\nUpdated anchors (changed region):\n${shown.join("\n")}${more}`;
|
|
120
|
+
function* indices() {
|
|
121
|
+
for (let i = span.start; i <= span.end; i++) yield i;
|
|
122
|
+
}
|
|
123
|
+
return formatMutationAnchors(newLines, indices(), hashLen, "Updated anchors (changed region):");
|
|
127
124
|
}
|
|
128
125
|
|
|
129
126
|
/** Truncate a string for one-line display, folding newlines into a marker. */
|
|
@@ -168,29 +165,8 @@ export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createAc
|
|
|
168
165
|
return text;
|
|
169
166
|
},
|
|
170
167
|
|
|
171
|
-
renderResult(result: any,
|
|
172
|
-
|
|
173
|
-
const content = result.content?.[0];
|
|
174
|
-
if (context.isError) {
|
|
175
|
-
const t = content?.type === "text" ? content.text.split("\n")[0] : "Error";
|
|
176
|
-
return new Text(theme.fg("error", t), 0, 0);
|
|
177
|
-
}
|
|
178
|
-
const diff: string | undefined = result.details?.diff;
|
|
179
|
-
// refresh the call header's +N -N in place — never invalidate from
|
|
180
|
-
// inside a renderer (re-enters updateDisplay, diff renders twice)
|
|
181
|
-
publishDiffCounts(diff, context, (counts) => {
|
|
182
|
-
context.state?.callText?.setText(replaceHeader(context.args, theme, counts));
|
|
183
|
-
});
|
|
184
|
-
if (!diff) {
|
|
185
|
-
// No net diff: show only the summary line — content.text also carries
|
|
186
|
-
// `Updated anchors` (hashline) for the model.
|
|
187
|
-
const summary = content?.type === "text" ? content.text.split("\n")[0] : "Replaced";
|
|
188
|
-
return new Text(theme.fg("success", summary), 0, 0);
|
|
189
|
-
}
|
|
190
|
-
// details.diff is pi-format (+N/-N/<space>N content); renderDiff handles
|
|
191
|
-
// semantic colors plus intra-line change highlighting
|
|
192
|
-
const rendered = renderDiffPreview(diff, expanded, theme);
|
|
193
|
-
return new Text(rendered, 0, 0);
|
|
168
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
169
|
+
return renderMutationResult(result, options, theme, context, "Replacing…", "Replaced", replaceHeader);
|
|
194
170
|
},
|
|
195
171
|
|
|
196
172
|
async execute(toolCallId: string, params: ReplaceParams & { then_run?: ThenRunInput }, signal: AbortSignal | undefined, onUpdate: any, ctx: any) {
|
|
@@ -199,9 +175,15 @@ export function makeReplaceTool(cwd: string, fusion?: ReturnType<typeof createAc
|
|
|
199
175
|
const state = getState();
|
|
200
176
|
const path = mutationParams.path;
|
|
201
177
|
const absolutePath = canonicalPath(cwd, path);
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
178
|
+
let mutationAnchors = "";
|
|
179
|
+
const mutate = () => withFileMutationQueue(absolutePath, () => runReplace(absolutePath, path, mutationParams, state.config.hashLen, signal, (anchors) => { mutationAnchors = anchors; }));
|
|
180
|
+
const finalizeMutation = (result: any, publishAnchors: boolean) => ({
|
|
181
|
+
...result,
|
|
182
|
+
content: result.content.map((block: any, index: number) => index === 0 && block.type === "text"
|
|
183
|
+
? { ...block, text: `${block.text}${publishAnchors ? mutationAnchors : ""}` } : block),
|
|
184
|
+
});
|
|
185
|
+
if (!fusion) return finalizeMutationResult(await mutate(), finalizeMutation);
|
|
186
|
+
return fusion({ toolCallId, absolutePath, thenRun: then_run, mutate, finalizeMutation, signal, ctx, onUpdate });
|
|
205
187
|
},
|
|
206
188
|
};
|
|
207
189
|
}
|
|
@@ -212,6 +194,7 @@ async function runReplace(
|
|
|
212
194
|
params: ReplaceParams,
|
|
213
195
|
hashLen: number,
|
|
214
196
|
signal: AbortSignal | undefined,
|
|
197
|
+
onAnchors: (anchors: string) => void,
|
|
215
198
|
) {
|
|
216
199
|
const { find, replace } = params;
|
|
217
200
|
const isRegex = params.regex === true;
|
|
@@ -220,8 +203,11 @@ async function runReplace(
|
|
|
220
203
|
if (find === "") throw new Error(`Replace ${displayPath}: \`find\` is empty.`);
|
|
221
204
|
|
|
222
205
|
let currentText: string;
|
|
206
|
+
let baseRevision: string;
|
|
223
207
|
try {
|
|
224
|
-
|
|
208
|
+
const currentBytes = await readFile(absPath);
|
|
209
|
+
baseRevision = byteRevision(currentBytes);
|
|
210
|
+
currentText = decodeEditableText(currentBytes);
|
|
225
211
|
} catch (e) {
|
|
226
212
|
const msg = e instanceof Error ? e.message : String(e);
|
|
227
213
|
throw new Error(`Error reading ${displayPath}: ${msg}`);
|
|
@@ -253,8 +239,6 @@ async function runReplace(
|
|
|
253
239
|
throw new Error(`Replace ${displayPath}: no matches for ${shown}.`);
|
|
254
240
|
}
|
|
255
241
|
|
|
256
|
-
// Literal mode uses a function replacement so `$` in `replace` stays literal;
|
|
257
|
-
// regex mode passes the string so $1/$& etc. expand.
|
|
258
242
|
// Literal mode uses a function replacement so `$` in `replace` stays literal;
|
|
259
243
|
// regex mode passes the string so $1/$& etc. expand.
|
|
260
244
|
const newText = isRegex ? currentText.replace(regex, replace) : currentText.replace(regex, () => replace);
|
|
@@ -264,20 +248,23 @@ async function runReplace(
|
|
|
264
248
|
if (signal?.aborted) throw new Error(`Replace ${displayPath} aborted before write.`);
|
|
265
249
|
|
|
266
250
|
let publication: PublicationStatus = "NOT_PUBLISHED";
|
|
251
|
+
let versions: MutationVersions = { baseRevision, publishedRevision: baseRevision, observedRevision: baseRevision };
|
|
267
252
|
if (changed) {
|
|
268
253
|
try {
|
|
269
|
-
|
|
254
|
+
const commit = await commitFile(absPath, newText, { mode: "overwrite", expectedRevision: baseRevision, signal });
|
|
255
|
+
publication = commit.publication;
|
|
256
|
+
versions = commit;
|
|
270
257
|
} catch (e) {
|
|
271
258
|
if (e instanceof FileMutationError) throw e;
|
|
272
259
|
throw new FileMutationError("commit", "UNKNOWN", `Error writing ${displayPath}: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
|
|
273
260
|
}
|
|
274
261
|
}
|
|
275
262
|
|
|
276
|
-
let details: EditToolDetails & { publication: PublicationStatus };
|
|
263
|
+
let details: EditToolDetails & MutationVersions & { publication: PublicationStatus; revision: string };
|
|
277
264
|
let anchors: string;
|
|
278
265
|
let note: string;
|
|
279
266
|
try {
|
|
280
|
-
//
|
|
267
|
+
// Diff, anchors, and summary generation happens after publication; preserve its state on failure.
|
|
281
268
|
const oldLf = currentText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
282
269
|
const newLf = newText.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
283
270
|
const { diff, firstChangedLine } = generateDiffString(oldLf, newLf);
|
|
@@ -286,6 +273,8 @@ async function runReplace(
|
|
|
286
273
|
patch: generateUnifiedPatch(displayPath, oldLf, newLf),
|
|
287
274
|
firstChangedLine,
|
|
288
275
|
publication,
|
|
276
|
+
...versions,
|
|
277
|
+
revision: versions.publishedRevision,
|
|
289
278
|
};
|
|
290
279
|
const oldLines = splitLines(currentText);
|
|
291
280
|
const newLines = splitLines(newText);
|
|
@@ -293,11 +282,12 @@ async function runReplace(
|
|
|
293
282
|
anchors = span ? formatSpanAnchors(newLines, span, hashLen) : "";
|
|
294
283
|
const matchWord = `match${count !== 1 ? "es" : ""}`;
|
|
295
284
|
note = changed ? `${count} ${matchWord}` : `${count} ${matchWord}, no net change`;
|
|
285
|
+
onAnchors(anchors);
|
|
296
286
|
} catch (error) {
|
|
297
287
|
throw new FileMutationError("post_process", publication, `file was published but replace result generation failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
298
288
|
}
|
|
299
289
|
return {
|
|
300
|
-
content: [{ type: "text" as const, text: `Replaced ${displayPath} (${note})
|
|
290
|
+
content: [{ type: "text" as const, text: `Replaced ${displayPath} (${note}).` }],
|
|
301
291
|
details,
|
|
302
292
|
};
|
|
303
293
|
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { computeLineHash } from "../core/hash.ts";
|
|
2
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { test } from "node:test";
|
|
8
|
+
import { createActionFusionExecutor } from "./action-fusion.ts";
|
|
9
|
+
import { makeReplaceTool } from "./replace-tool.ts";
|
|
10
|
+
import { makeWriteOverride } from "./write-tool.ts";
|
|
11
|
+
import { makeEditOverride } from "./edit-tool.ts";
|
|
12
|
+
import { FileMutationError } from "./file-commit.ts";
|
|
13
|
+
import { finalizeMutationResult } from "./mutation-result.ts";
|
|
14
|
+
|
|
15
|
+
const text = (result: any) => result.content.map((block: any) => block.text ?? "").join("\n");
|
|
16
|
+
|
|
17
|
+
test("replace withholds anchors in progress and after commands change or remove the file", async () => {
|
|
18
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-result-"));
|
|
19
|
+
try {
|
|
20
|
+
for (const state of ["changed", "missing", "unknown"] as const) {
|
|
21
|
+
for (const fails of [false, true]) {
|
|
22
|
+
const path = join(dir, `${state}-${fails}.txt`);
|
|
23
|
+
await writeFile(path, "before\n");
|
|
24
|
+
const updates: any[] = [];
|
|
25
|
+
const fusion = createActionFusionExecutor(async (_id, _input, _signal, _ctx, onUpdate) => {
|
|
26
|
+
if (state === "changed") await writeFile(path, "command output\n");
|
|
27
|
+
else {
|
|
28
|
+
await rm(path);
|
|
29
|
+
if (state === "unknown") await mkdir(path);
|
|
30
|
+
}
|
|
31
|
+
onUpdate?.({ content: [{ type: "text", text: "progress" }], details: undefined });
|
|
32
|
+
if (fails) throw new Error("command failed");
|
|
33
|
+
return "done";
|
|
34
|
+
});
|
|
35
|
+
const result = await makeReplaceTool(dir, fusion).execute("replace", {
|
|
36
|
+
path, find: "before", replace: "after", then_run: { command: "check" },
|
|
37
|
+
}, undefined, (update: any) => updates.push(update), { cwd: dir });
|
|
38
|
+
assert.equal(result.details.actionFusion.freshness, state);
|
|
39
|
+
assert.equal(result.details.publication, "PUBLISHED");
|
|
40
|
+
assert.doesNotMatch(text(result), /Updated anchors|\d+#[0-9A-Z]+│/);
|
|
41
|
+
assert.match(text(result), /Re-read/);
|
|
42
|
+
for (const update of updates) assert.doesNotMatch(text(update), /Updated anchors|\d+#[0-9A-Z]+│/);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
} finally {
|
|
46
|
+
await rm(dir, { recursive: true, force: true });
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("progress callback failures preserve publication and do not prevent the command", async () => {
|
|
51
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-progress-"));
|
|
52
|
+
try {
|
|
53
|
+
for (const callback of ["reporter", "update"]) {
|
|
54
|
+
let commands = 0;
|
|
55
|
+
const fail = () => { throw new Error("display unavailable"); };
|
|
56
|
+
const fusion = createActionFusionExecutor(async () => { commands++; return "done"; }, callback === "reporter" ? fail : undefined);
|
|
57
|
+
const path = join(dir, callback);
|
|
58
|
+
const result = await makeWriteOverride(dir, fusion).execute("write", {
|
|
59
|
+
path, content: "saved\n", then_run: { command: "check" },
|
|
60
|
+
}, undefined, callback === "update" ? fail : undefined, { cwd: dir });
|
|
61
|
+
assert.equal(commands, 1);
|
|
62
|
+
assert.equal(await readFile(path, "utf8"), "saved\n");
|
|
63
|
+
assert.equal(result.details.actionFusion.publication, "PUBLISHED");
|
|
64
|
+
assert.equal(result.details.actionFusion.command, "succeeded");
|
|
65
|
+
assert.match(text(result), /display unavailable/);
|
|
66
|
+
}
|
|
67
|
+
const fusion = createActionFusionExecutor(undefined, () => { throw new Error("display unavailable"); });
|
|
68
|
+
await assert.rejects(fusion({
|
|
69
|
+
toolCallId: "failed", absolutePath: join(dir, "failed"), thenRun: { command: "check" },
|
|
70
|
+
mutate: async () => { throw new FileMutationError("post_process", "PUBLISHED", "original failure"); },
|
|
71
|
+
signal: undefined, ctx: { cwd: dir } as any,
|
|
72
|
+
}), (error: any) => error.publication === "PUBLISHED" && /original failure/.test(error.message));
|
|
73
|
+
} finally {
|
|
74
|
+
await rm(dir, { recursive: true, force: true });
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("standalone and Fusion finalizers suppress anchors unless commit observations agree", async () => {
|
|
79
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-finalizer-"));
|
|
80
|
+
try {
|
|
81
|
+
for (const observedRevision of ["published", "external", undefined]) {
|
|
82
|
+
const mutation = { content: [{ type: "text" as const, text: "saved" }], details: { publication: "PUBLISHED" as const, publishedRevision: "published", observedRevision } };
|
|
83
|
+
const finalize = (result: AgentToolResult<typeof mutation.details>, expose: boolean) => ({ ...result, content: [{ type: "text" as const, text: `saved${expose ? " ANCHOR" : ""}` }] });
|
|
84
|
+
const standalone = finalizeMutationResult(mutation, finalize);
|
|
85
|
+
const fused = await createActionFusionExecutor()({ toolCallId: "no-command", absolutePath: join(dir, "file"), thenRun: undefined, mutate: async () => mutation, finalizeMutation: finalize, signal: undefined, ctx: { cwd: dir } as any });
|
|
86
|
+
for (const result of [standalone, fused]) {
|
|
87
|
+
assert.equal(text(result).includes("ANCHOR"), observedRevision === "published");
|
|
88
|
+
assert.equal(result.details.publication, "PUBLISHED");
|
|
89
|
+
if (observedRevision !== "published") assert.match(text(result), /Re-read/);
|
|
90
|
+
}
|
|
91
|
+
assert.throws(() => finalizeMutationResult(mutation, () => { throw new Error("formatting failed"); }),
|
|
92
|
+
(error: any) => error instanceof FileMutationError && error.publication === "PUBLISHED" && /publication=PUBLISHED/.test(error.message));
|
|
93
|
+
}
|
|
94
|
+
} finally {
|
|
95
|
+
await rm(dir, { recursive: true, force: true });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("mutation anchor output and aggregate anchor diagnostics have byte budgets", async () => {
|
|
100
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-budget-"));
|
|
101
|
+
try {
|
|
102
|
+
const path = join(dir, "long.txt");
|
|
103
|
+
const long = "界".repeat(100000);
|
|
104
|
+
for (const name of ["edit", "replace"]) {
|
|
105
|
+
await writeFile(path, "before\n");
|
|
106
|
+
const tool = name === "edit" ? makeEditOverride(dir) : makeReplaceTool(dir);
|
|
107
|
+
const args = name === "edit" ? { edits: [{ op: "append", body: [long] }] } : { find: "before", replace: long };
|
|
108
|
+
const result = await tool.execute(name, { path, ...args }, undefined, undefined, { cwd: dir });
|
|
109
|
+
const output = text(result);
|
|
110
|
+
assert.ok(Buffer.byteLength(output) < 17 * 1024);
|
|
111
|
+
assert.match(output, /omitted|truncated/i);
|
|
112
|
+
assert.doesNotMatch(output, /\d+#[0-9A-Z]+│界/);
|
|
113
|
+
assert.ok((await readFile(path, "utf8")).includes(long));
|
|
114
|
+
}
|
|
115
|
+
await writeFile(path, "current\n");
|
|
116
|
+
await assert.rejects(makeEditOverride(dir).execute("errors", {
|
|
117
|
+
path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: "1#XXXX" })),
|
|
118
|
+
}, undefined, undefined, { cwd: dir }), (error: Error) => {
|
|
119
|
+
assert.ok(Buffer.byteLength(error.message) <= 16 * 1024);
|
|
120
|
+
assert.match(error.message, /omitted|truncated/i);
|
|
121
|
+
return true;
|
|
122
|
+
});
|
|
123
|
+
} finally {
|
|
124
|
+
await rm(dir, { recursive: true, force: true });
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("every mutation entry rejects unpaired surrogates without running then_run", async () => {
|
|
129
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-unicode-"));
|
|
130
|
+
try {
|
|
131
|
+
let commands = 0;
|
|
132
|
+
const fusion = createActionFusionExecutor(async () => { commands++; return "done"; });
|
|
133
|
+
const path = join(dir, "file.txt");
|
|
134
|
+
await writeFile(path, "original\n");
|
|
135
|
+
for (const [tool, args] of [
|
|
136
|
+
[makeEditOverride(dir, fusion), { edits: [{ op: "append", body: ["\ud800"] }] }],
|
|
137
|
+
[makeReplaceTool(dir, fusion), { find: "original", replace: "\udfff" }],
|
|
138
|
+
[makeWriteOverride(dir, fusion), { content: "\ud800" }],
|
|
139
|
+
] as const) {
|
|
140
|
+
await assert.rejects(tool.execute("unicode", { path, ...args, then_run: { command: "check" } }, undefined, undefined, { cwd: dir }),
|
|
141
|
+
(error: any) => error.publication === "NOT_PUBLISHED" && /INVALID_UNICODE/.test(error.message));
|
|
142
|
+
assert.equal(await readFile(path, "utf8"), "original\n");
|
|
143
|
+
}
|
|
144
|
+
assert.equal(commands, 0);
|
|
145
|
+
} finally {
|
|
146
|
+
await rm(dir, { recursive: true, force: true });
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test("ambiguous recovery bounds candidate lists and never claims content identity", async () => {
|
|
151
|
+
const dir = await mkdtemp(join(tmpdir(), "hashline-candidates-"));
|
|
152
|
+
try {
|
|
153
|
+
const path = join(dir, "file.txt");
|
|
154
|
+
const lines = Array.from({ length: 100 }, () => "same");
|
|
155
|
+
lines[49] = "different";
|
|
156
|
+
await writeFile(path, lines.join("\n"));
|
|
157
|
+
await assert.rejects(makeEditOverride(dir).execute("ambiguous", {
|
|
158
|
+
path, edits: Array.from({ length: 1000 }, () => ({ op: "delete", anchor: `50#${computeLineHash(50, "same")}` })),
|
|
159
|
+
}, undefined, undefined, { cwd: dir }), (error: Error) => {
|
|
160
|
+
assert.ok(Buffer.byteLength(error.message) <= 16 * 1024);
|
|
161
|
+
assert.match(error.message, /ambiguous checksum matches/);
|
|
162
|
+
assert.match(error.message, /candidates omitted/);
|
|
163
|
+
assert.doesNotMatch(error.message, /same content/);
|
|
164
|
+
return true;
|
|
165
|
+
});
|
|
166
|
+
} finally {
|
|
167
|
+
await rm(dir, { recursive: true, force: true });
|
|
168
|
+
}
|
|
169
|
+
});
|