@criogaid/pi-hashline-edit 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -30
- package/package.json +3 -3
- package/src/core/apply.test.ts +194 -104
- package/src/core/apply.ts +6 -37
- package/src/core/errors.ts +9 -0
- package/src/core/hash.test.ts +8 -8
- package/src/core/hash.ts +5 -5
- package/src/{pi/replace-apply.ts → core/replace.ts} +4 -4
- package/src/core/text.test.ts +30 -1
- package/src/core/text.ts +9 -6
- package/src/core/types.ts +4 -7
- package/src/index.ts +9 -11
- package/src/integration/config-registration.test.ts +206 -0
- package/src/integration/grep-rg.test.ts +285 -153
- package/src/integration/large-text.test.ts +11 -12
- package/src/integration/replace-package.test.ts +11 -7
- package/src/pi/action-fusion.test.ts +251 -39
- package/src/pi/action-fusion.ts +113 -117
- package/src/pi/anchor-format.test.ts +91 -24
- package/src/pi/anchor-format.ts +43 -9
- package/src/pi/budgets.ts +7 -2
- package/src/pi/config.test.ts +153 -40
- package/src/pi/config.ts +87 -41
- package/src/pi/diagnostic-buffer.test.ts +58 -0
- package/src/pi/diagnostic-buffer.ts +59 -0
- package/src/pi/e2e-scenarios.test.ts +13 -11
- package/src/pi/edit-tool.ts +21 -157
- package/src/pi/error-text.ts +10 -5
- package/src/pi/execute.test.ts +299 -175
- package/src/pi/failure-context.test.ts +7 -2
- package/src/pi/failure-context.ts +155 -8
- package/src/pi/failure-path.test.ts +33 -26
- package/src/pi/file-commit.ts +2 -1
- package/src/pi/fusion-card.test.ts +26 -0
- package/src/pi/fusion-card.ts +102 -6
- package/src/pi/grep-output.ts +50 -35
- package/src/pi/grep-render.ts +13 -15
- package/src/pi/grep-scope.ts +8 -46
- package/src/pi/grep-search.ts +90 -63
- package/src/pi/grep-tool.ts +109 -121
- package/src/pi/grep.test.ts +597 -377
- package/src/pi/mutation-outcome.testing.ts +22 -0
- package/src/pi/mutation-result.test.ts +51 -2
- package/src/pi/mutation-result.ts +62 -55
- package/src/pi/mutation-runner.ts +16 -33
- package/src/pi/pi.test.ts +11 -6
- package/src/pi/read-tool.ts +62 -34
- package/src/pi/registration.test.ts +7 -7
- package/src/pi/render.test.ts +143 -9
- package/src/pi/render.ts +32 -96
- package/src/pi/replace-regex.ts +54 -0
- package/src/pi/replace-tool.ts +25 -59
- package/src/pi/replace-worker.ts +2 -2
- package/src/pi/replace.test.ts +62 -58
- package/src/pi/result-safety.test.ts +124 -84
- package/src/pi/rg-line-ranges.ts +3 -2
- package/src/pi/{rg-line-filter.test.ts → rg-process.test.ts} +1 -1
- package/src/pi/{rg-line-filter.ts → rg-process.ts} +43 -9
- package/src/pi/rg-text-view.ts +25 -38
- package/src/pi/schema.ts +2 -10
- package/src/pi/text-stream.test.ts +153 -0
- package/src/pi/text-stream.ts +33 -13
- package/src/pi/write-tool.ts +3 -2
- package/src/pi/write.test.ts +10 -9
- package/src/core/index.ts +0 -14
- package/src/pi/state.ts +0 -26
|
@@ -89,7 +89,7 @@ test("ambiguous context preserves complete rows at the byte budget", () => {
|
|
|
89
89
|
const exact = "x".repeat(16 * 1024 - Buffer.byteLength("1#XXXX│\n"));
|
|
90
90
|
const lines = [exact, "target", "last"];
|
|
91
91
|
const byteLimited = format(lines.join("\n"), [ambiguous(lines, [2, 3])]).text;
|
|
92
|
-
assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact)}│${exact}\n`));
|
|
92
|
+
assert.ok(byteLimited.includes(`1#${computeLineHash(1, exact, 4)}│${exact}\n`));
|
|
93
93
|
assert.match(byteLimited, /Candidate-neighborhood rows: 1\/3; 2 omitted/);
|
|
94
94
|
assert.match(byteLimited, /truncated: byte limit/);
|
|
95
95
|
assert.doesNotMatch(byteLimited, /^2#[0-9A-Z]+│/m);
|
|
@@ -131,7 +131,12 @@ test("unique candidates inside ambiguous neighborhoods retain the candidate row
|
|
|
131
131
|
const lines = ["prefix", "x".repeat(4096), "match", "match"];
|
|
132
132
|
const output = format(lines.join("\n"), [
|
|
133
133
|
ambiguous(lines, [3, 4]),
|
|
134
|
-
failure({
|
|
134
|
+
failure({
|
|
135
|
+
kind: "found",
|
|
136
|
+
scope: "local",
|
|
137
|
+
newLine: 2,
|
|
138
|
+
newHash: computeLineHash(2, lines[1], 4),
|
|
139
|
+
}),
|
|
135
140
|
]).text;
|
|
136
141
|
assert.match(output, /truncated: candidate row limit/);
|
|
137
142
|
assert.doesNotMatch(output, /^2#[0-9A-Z]+│/m);
|
|
@@ -1,11 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded anchor-failure diagnostics for edit: failure details with recovery
|
|
3
|
+
* candidates, input-anchor checks, and ambiguous-candidate neighborhoods.
|
|
4
|
+
*
|
|
5
|
+
* @module pi-hashline-edit/pi
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { truncateHead } from "@earendil-works/pi-coding-agent";
|
|
1
9
|
import type { AnchorFormatter } from "./anchor-format.ts";
|
|
2
10
|
import { splitLines } from "../core/lines.ts";
|
|
3
|
-
import type { AnchorFailure } from "../core/types.ts";
|
|
11
|
+
import type { Anchor, AnchorFailure, ApplyFailure } from "../core/types.ts";
|
|
4
12
|
import { mergeRanges } from "../core/ranges.ts";
|
|
5
|
-
import { MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
|
|
13
|
+
import { formatKiB, MAX_BLOCK_BYTES, MAX_RECOVERY_CANDIDATE_BYTES } from "./budgets.ts";
|
|
6
14
|
|
|
7
15
|
const CONTEXT_RADIUS = 3;
|
|
8
|
-
|
|
16
|
+
const MAX_AMBIGUOUS_CANDIDATES = 8;
|
|
17
|
+
|
|
18
|
+
/** Select the shared candidate prefix for detail lists and observation neighborhoods. */
|
|
19
|
+
export function selectAmbiguousCandidates(candidates: readonly Anchor[]): readonly Anchor[] {
|
|
20
|
+
return candidates.slice(0, MAX_AMBIGUOUS_CANDIDATES);
|
|
21
|
+
}
|
|
9
22
|
|
|
10
23
|
type Interval = { lo: number; hi: number };
|
|
11
24
|
type ContextRow = { line: number; text: string };
|
|
@@ -82,9 +95,7 @@ export function formatAmbiguousCandidateNeighborhoods(
|
|
|
82
95
|
): { text: string; shownLines: ReadonlySet<number> } {
|
|
83
96
|
const centers = failures.flatMap((failure) =>
|
|
84
97
|
failure.recovery.kind === "ambiguous"
|
|
85
|
-
? failure.recovery.candidates
|
|
86
|
-
.slice(0, MAX_AMBIGUOUS_CANDIDATES)
|
|
87
|
-
.map((candidate) => candidate.line)
|
|
98
|
+
? selectAmbiguousCandidates(failure.recovery.candidates).map((candidate) => candidate.line)
|
|
88
99
|
: [],
|
|
89
100
|
);
|
|
90
101
|
if (centers.length === 0) return { text: "", shownLines: new Set() };
|
|
@@ -95,7 +106,7 @@ export function formatAmbiguousCandidateNeighborhoods(
|
|
|
95
106
|
if (failure.recovery.kind === "found") candidateLines.add(failure.recovery.newLine);
|
|
96
107
|
}
|
|
97
108
|
const { rows, total, truncatedBy } = collectContextRows(lines, centers, anchors, candidateLines);
|
|
98
|
-
const body = [
|
|
109
|
+
const body = [`Ambiguous-candidate neighborhoods (+/-${CONTEXT_RADIUS}; observation only):`];
|
|
99
110
|
if (rows.length === 0) {
|
|
100
111
|
body.push("No complete neighborhood row fits the limits.");
|
|
101
112
|
} else {
|
|
@@ -106,8 +117,144 @@ export function formatAmbiguousCandidateNeighborhoods(
|
|
|
106
117
|
`Candidate-neighborhood rows: ${rows.length}/${total}; ${total - rows.length} omitted.`,
|
|
107
118
|
);
|
|
108
119
|
body.push(
|
|
109
|
-
`Candidate neighborhoods truncated: ${truncatedBy} (
|
|
120
|
+
`Candidate neighborhoods truncated: ${truncatedBy} (${formatKiB(MAX_BLOCK_BYTES)}; candidate row ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}; lowest lines first).`,
|
|
110
121
|
);
|
|
111
122
|
}
|
|
112
123
|
return { text: `\n${body.join("\n")}`, shownLines: new Set(rows.map((row) => row.line)) };
|
|
113
124
|
}
|
|
125
|
+
|
|
126
|
+
/** Keep independent byte budgets for failure details and input-anchor checks. */
|
|
127
|
+
function boundDiagnostic(message: string, notice: string): string {
|
|
128
|
+
const bounded = truncateHead(message, { maxBytes: MAX_BLOCK_BYTES - Buffer.byteLength(notice) });
|
|
129
|
+
return bounded.content + (bounded.truncated ? notice : "");
|
|
130
|
+
}
|
|
131
|
+
/** Format failure mappings and complete unique-candidate rows within the detail budget. */
|
|
132
|
+
function formatFailureDetails(
|
|
133
|
+
failure: ApplyFailure,
|
|
134
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
135
|
+
candidateLines: ReadonlySet<number>,
|
|
136
|
+
): string {
|
|
137
|
+
if (failure.kind !== "anchor") return failure.message;
|
|
138
|
+
|
|
139
|
+
const lines: string[] = [];
|
|
140
|
+
const currentLines = splitLines(snapshot.currentText);
|
|
141
|
+
const shownCandidates = new Set(candidateLines);
|
|
142
|
+
let found = 0;
|
|
143
|
+
let ambiguous = 0;
|
|
144
|
+
let none = 0;
|
|
145
|
+
for (const f of failure.failures) {
|
|
146
|
+
if (f.recovery.kind === "found") found++;
|
|
147
|
+
else if (f.recovery.kind === "ambiguous") ambiguous++;
|
|
148
|
+
else none++;
|
|
149
|
+
const where = `op #${f.opIndex} ${f.op} ${f.which} (line ${f.cited.line})`;
|
|
150
|
+
const search =
|
|
151
|
+
f.recovery.kind === "none"
|
|
152
|
+
? ""
|
|
153
|
+
: f.recovery.scope === "local"
|
|
154
|
+
? "Search: local; matches outside the window were not checked."
|
|
155
|
+
: "Search: full file.";
|
|
156
|
+
switch (f.recovery.kind) {
|
|
157
|
+
case "found": {
|
|
158
|
+
const content = currentLines[f.recovery.newLine - 1];
|
|
159
|
+
const candidate = snapshot.anchors.reference(f.recovery.newLine, f.recovery.newHash);
|
|
160
|
+
const row =
|
|
161
|
+
content === undefined ? candidate : snapshot.anchors.row(f.recovery.newLine, content);
|
|
162
|
+
let detail = `• ${where}: checksum-matching candidate ${candidate}. ${search}`;
|
|
163
|
+
if (!shownCandidates.has(f.recovery.newLine)) {
|
|
164
|
+
if (
|
|
165
|
+
content !== undefined &&
|
|
166
|
+
Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES
|
|
167
|
+
) {
|
|
168
|
+
detail += `\n${row}`;
|
|
169
|
+
shownCandidates.add(f.recovery.newLine);
|
|
170
|
+
} else {
|
|
171
|
+
detail += ` Candidate content exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
lines.push(detail);
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
case "ambiguous": {
|
|
178
|
+
const candidates = selectAmbiguousCandidates(f.recovery.candidates);
|
|
179
|
+
const list = candidates
|
|
180
|
+
.map((candidate) => `"${snapshot.anchors.reference(candidate.line, candidate.hash)}"`)
|
|
181
|
+
.join(" / ");
|
|
182
|
+
const omitted = f.recovery.candidates.length - candidates.length;
|
|
183
|
+
const more = omitted ? ` (${omitted} more candidates omitted)` : "";
|
|
184
|
+
lines.push(`• ${where}: ambiguous checksum matches: ${list}${more}. ${search}`);
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case "none": {
|
|
188
|
+
const row =
|
|
189
|
+
f.current === null ? null : snapshot.anchors.row(f.cited.line, f.current.content);
|
|
190
|
+
if (row !== null && Buffer.byteLength(row, "utf8") <= MAX_RECOVERY_CANDIDATE_BYTES) {
|
|
191
|
+
lines.push(
|
|
192
|
+
`• ${where}: no checksum-matching candidate found. Current cited line (validation snapshot; observation only):\n${row}\nConfirm this is the intended target before reusing its anchor directly; retries revalidate.`,
|
|
193
|
+
);
|
|
194
|
+
} else {
|
|
195
|
+
lines.push(
|
|
196
|
+
`• ${where}: no checksum-matching candidate found. Use read or grep to inspect the current file before retrying.` +
|
|
197
|
+
(f.current === null
|
|
198
|
+
? " Cited line is out of range."
|
|
199
|
+
: ` Current row exceeds ${formatKiB(MAX_RECOVERY_CANDIDATE_BYTES)}.`),
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const parts: string[] = [];
|
|
207
|
+
if (found) parts.push(`${found} shifted`);
|
|
208
|
+
if (ambiguous) parts.push(`${ambiguous} ambiguous`);
|
|
209
|
+
if (none) parts.push(`${none} unresolved`);
|
|
210
|
+
const message = [
|
|
211
|
+
`Anchor mismatch: ${parts.join(", ")}.`,
|
|
212
|
+
"No changes written by this edit batch.",
|
|
213
|
+
...lines,
|
|
214
|
+
].join("\n");
|
|
215
|
+
return boundDiagnostic(
|
|
216
|
+
message,
|
|
217
|
+
`\nDiagnostic output truncated at ${formatKiB(MAX_BLOCK_BYTES)}.`,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function formatAnchorChecks(failure: ApplyFailure, anchors: AnchorFormatter): string {
|
|
222
|
+
const rows = failure.checks.map(
|
|
223
|
+
(check) =>
|
|
224
|
+
`op ${check.opIndex} / ${check.which} / ${anchors.reference(check.cited.line, check.cited.hash)} / ${check.status}`,
|
|
225
|
+
);
|
|
226
|
+
const message = [
|
|
227
|
+
"Input-anchor checks (this snapshot):",
|
|
228
|
+
...rows,
|
|
229
|
+
"Anchor checks only; retries revalidate.",
|
|
230
|
+
].join("\n");
|
|
231
|
+
return boundDiagnostic(
|
|
232
|
+
message,
|
|
233
|
+
`\nAnchor-check output truncated at ${formatKiB(MAX_BLOCK_BYTES)}; omitted entries are not implied matched.`,
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Keep validation status and observation context visible even when failure details are truncated. */
|
|
238
|
+
export function formatFailure(
|
|
239
|
+
failure: ApplyFailure,
|
|
240
|
+
snapshot: Readonly<{ currentText: string; anchors: AnchorFormatter }>,
|
|
241
|
+
isBatch: boolean,
|
|
242
|
+
): string {
|
|
243
|
+
const candidateNeighborhoods =
|
|
244
|
+
failure.kind === "anchor"
|
|
245
|
+
? formatAmbiguousCandidateNeighborhoods(
|
|
246
|
+
snapshot.currentText,
|
|
247
|
+
failure.failures,
|
|
248
|
+
snapshot.anchors,
|
|
249
|
+
)
|
|
250
|
+
: { text: "", shownLines: new Set<number>() };
|
|
251
|
+
const guidance =
|
|
252
|
+
failure.kind === "anchor"
|
|
253
|
+
? "\nCheck the intended target before retrying; use read or grep for omitted or additional context."
|
|
254
|
+
: "";
|
|
255
|
+
const anchorChecks =
|
|
256
|
+
isBatch && failure.checks.length > 0
|
|
257
|
+
? `\n${formatAnchorChecks(failure, snapshot.anchors)}`
|
|
258
|
+
: "";
|
|
259
|
+
return `${formatFailureDetails(failure, snapshot, candidateNeighborhoods.shownLines)}${anchorChecks}${candidateNeighborhoods.text}${guidance}`;
|
|
260
|
+
}
|
|
@@ -3,8 +3,15 @@ import { tmpdir } from "node:os";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import assert from "node:assert/strict";
|
|
5
5
|
import { test } from "node:test";
|
|
6
|
-
import {
|
|
7
|
-
|
|
6
|
+
import {
|
|
7
|
+
createActionFusionExecutor,
|
|
8
|
+
ActionFusionError,
|
|
9
|
+
THEN_RUN_STALE,
|
|
10
|
+
THEN_RUN_SUCCEEDED,
|
|
11
|
+
} from "./action-fusion.ts";
|
|
12
|
+
import { FileMutationError } from "./file-commit.ts";
|
|
13
|
+
import { staleTargetNotice } from "./mutation-result.ts";
|
|
14
|
+
import { publishedMutation } from "./mutation-outcome.testing.ts";
|
|
8
15
|
|
|
9
16
|
async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
10
17
|
const dir = await mkdtemp(join(tmpdir(), "hashline-failure-"));
|
|
@@ -16,10 +23,11 @@ async function withTemp<T>(run: (dir: string) => Promise<T>): Promise<T> {
|
|
|
16
23
|
}
|
|
17
24
|
|
|
18
25
|
const context = (cwd: string) => ({ cwd }) as any;
|
|
19
|
-
const result = (content: string) =>
|
|
20
|
-
content
|
|
21
|
-
|
|
22
|
-
|
|
26
|
+
const result = (content: string) =>
|
|
27
|
+
publishedMutation(content, {
|
|
28
|
+
content: [{ type: "text", text: "mutation" }],
|
|
29
|
+
details: undefined,
|
|
30
|
+
});
|
|
23
31
|
|
|
24
32
|
test("published post-processing failure skips command and preserves publication state", async () =>
|
|
25
33
|
withTemp(async (dir) => {
|
|
@@ -82,8 +90,9 @@ test("command failure still reports final changed freshness", async () =>
|
|
|
82
90
|
command: "failed",
|
|
83
91
|
freshness: "changed",
|
|
84
92
|
});
|
|
85
|
-
assert.
|
|
86
|
-
assert.
|
|
93
|
+
assert.deepEqual(outcome.content[1], { type: "text", text: staleTargetNotice(THEN_RUN_STALE) });
|
|
94
|
+
assert.equal(outcome.content.length, 3);
|
|
95
|
+
assert.match(outcome.content[2].text, /command failed/);
|
|
87
96
|
}));
|
|
88
97
|
|
|
89
98
|
test("timeout and cancellation do not rerun mutation and still inspect freshness", async () =>
|
|
@@ -154,7 +163,7 @@ test("queue is released after a failed command", async () =>
|
|
|
154
163
|
);
|
|
155
164
|
}));
|
|
156
165
|
|
|
157
|
-
test("
|
|
166
|
+
test("successful command finalizes anchors and retains completed progress", async () =>
|
|
158
167
|
withTemp(async (dir) => {
|
|
159
168
|
const target = join(dir, "finalize.txt");
|
|
160
169
|
const progress: any[] = [];
|
|
@@ -162,23 +171,21 @@ test("result generation failure cannot overwrite an already successful command",
|
|
|
162
171
|
async () => "command finished",
|
|
163
172
|
(event) => progress.push(event),
|
|
164
173
|
);
|
|
165
|
-
await
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
/mutation result failure/,
|
|
181
|
-
);
|
|
174
|
+
const completed = await fusion({
|
|
175
|
+
toolCallId: "finalize",
|
|
176
|
+
absolutePath: target,
|
|
177
|
+
thenRun: { command: "check" },
|
|
178
|
+
signal: undefined,
|
|
179
|
+
ctx: context(dir),
|
|
180
|
+
mutate: async () => {
|
|
181
|
+
await writeFile(target, "saved\n");
|
|
182
|
+
return { ...result("saved\n"), anchors: " ANCHOR" };
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
assert.deepEqual(completed.content, [
|
|
186
|
+
{ type: "text", text: "mutation ANCHOR" },
|
|
187
|
+
{ type: "text", text: `${THEN_RUN_SUCCEEDED}\ncommand finished` },
|
|
188
|
+
]);
|
|
182
189
|
assert.equal(progress.filter((event) => event.command === "succeeded").length, 1);
|
|
183
190
|
assert.equal(progress.at(-1).publication, "PUBLISHED");
|
|
184
191
|
assert.equal(progress.at(-1).freshness, "unchanged");
|
package/src/pi/file-commit.ts
CHANGED
|
@@ -14,7 +14,8 @@ import {
|
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
15
15
|
import { createHash } from "node:crypto";
|
|
16
16
|
import { decodeEditableText, unwritableTextReason } from "../core/text.ts";
|
|
17
|
-
import { errorMessage
|
|
17
|
+
import { errorMessage } from "../core/errors.ts";
|
|
18
|
+
import { OPERATION_ABORTED, throwIfCancelled } from "./error-text.ts";
|
|
18
19
|
|
|
19
20
|
export type PublicationStatus = "NOT_PUBLISHED" | "PUBLISHED" | "UNKNOWN";
|
|
20
21
|
export type CommitMode = "create" | "overwrite";
|
|
@@ -139,3 +139,29 @@ test("skips and cancellations stay neutral and restore their own reason", () =>
|
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
141
|
});
|
|
142
|
+
|
|
143
|
+
test("timed command cards show remaining seconds only while actively running", () => {
|
|
144
|
+
const h = harness();
|
|
145
|
+
h.report(waiting);
|
|
146
|
+
const card = h.card(h.entries[0]);
|
|
147
|
+
assert.doesNotMatch(card.render(160).join("\n"), /remaining/);
|
|
148
|
+
const running: ActionFusionProgress = {
|
|
149
|
+
...waiting,
|
|
150
|
+
command: "running",
|
|
151
|
+
publication: "PUBLISHED",
|
|
152
|
+
mutationCompleted: true,
|
|
153
|
+
timing: { timeoutSeconds: 10, remainingSeconds: 10 },
|
|
154
|
+
};
|
|
155
|
+
h.report(running);
|
|
156
|
+
assert.match(card.render(160).join("\n"), /10s remaining/);
|
|
157
|
+
h.report({ ...running, timing: { timeoutSeconds: 10, remainingSeconds: 7 } });
|
|
158
|
+
assert.match(card.render(160).join("\n"), /7s remaining/);
|
|
159
|
+
assert.equal(h.entries.length, 1);
|
|
160
|
+
h.report({ ...running, timing: { timeoutSeconds: 10, remainingSeconds: 0 } });
|
|
161
|
+
assert.match(card.render(160).join("\n"), /0s remaining/);
|
|
162
|
+
h.report({ ...running, command: "timeout", output: "Command timed out after 10 seconds" });
|
|
163
|
+
assert.doesNotMatch(card.render(160).join("\n"), /remaining/);
|
|
164
|
+
const restored = harness(h.entries);
|
|
165
|
+
restored.restore();
|
|
166
|
+
assert.doesNotMatch(restored.card(h.entries[0]).render(160).join("\n"), /remaining/);
|
|
167
|
+
});
|
package/src/pi/fusion-card.ts
CHANGED
|
@@ -1,14 +1,28 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Action Fusion presentation: the mutation card shell that keeps the file
|
|
3
|
+
* result's status independent of the fused command, and the separate
|
|
4
|
+
* transcript card for each then_run command.
|
|
5
|
+
*
|
|
6
|
+
* @module pi-hashline-edit/pi
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {
|
|
10
|
+
ExtensionAPI,
|
|
11
|
+
ExtensionContext,
|
|
12
|
+
ToolDefinition,
|
|
13
|
+
} from "@earendil-works/pi-coding-agent";
|
|
2
14
|
import { createBashToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { Box, Text, type Component } from "@earendil-works/pi-tui";
|
|
15
|
+
import { Box, Container, Text, type Component } from "@earendil-works/pi-tui";
|
|
16
|
+
import type { TSchema } from "typebox";
|
|
4
17
|
import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
18
|
+
import { renderToolError, type MutationRenderState } from "./render.ts";
|
|
5
19
|
|
|
6
20
|
const CARD_TYPE = "hashline-then-run";
|
|
7
21
|
const RESULT_TYPE = "hashline-then-run-result";
|
|
8
22
|
|
|
9
23
|
type CommandCardData = Pick<
|
|
10
24
|
ActionFusionProgress,
|
|
11
|
-
"toolCallId" | "commandText" | "command" | "output" | "reason"
|
|
25
|
+
"toolCallId" | "commandText" | "command" | "output" | "reason" | "timing"
|
|
12
26
|
>;
|
|
13
27
|
|
|
14
28
|
function commandCardData({
|
|
@@ -17,8 +31,16 @@ function commandCardData({
|
|
|
17
31
|
command,
|
|
18
32
|
output,
|
|
19
33
|
reason,
|
|
34
|
+
timing,
|
|
20
35
|
}: ActionFusionProgress): CommandCardData {
|
|
21
|
-
return {
|
|
36
|
+
return {
|
|
37
|
+
toolCallId,
|
|
38
|
+
commandText,
|
|
39
|
+
command,
|
|
40
|
+
output,
|
|
41
|
+
...(reason ? { reason } : {}),
|
|
42
|
+
...(timing ? { timing } : {}),
|
|
43
|
+
};
|
|
22
44
|
}
|
|
23
45
|
|
|
24
46
|
/** Render one durable transcript card per fused command without adding model context. */
|
|
@@ -68,6 +90,10 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
68
90
|
const pending = current.command === "waiting" || current.command === "running";
|
|
69
91
|
const interrupted = pending && !active.has(current.toolCallId);
|
|
70
92
|
const status = interrupted ? "interrupted (final status unknown)" : current.command;
|
|
93
|
+
const countdown =
|
|
94
|
+
current.command === "running" && !interrupted && current.timing
|
|
95
|
+
? ` · ${current.timing.remainingSeconds}s remaining`
|
|
96
|
+
: "";
|
|
71
97
|
const failed = current.command === "failed" || current.command === "timeout";
|
|
72
98
|
const color =
|
|
73
99
|
pending || current.command === "cancelled"
|
|
@@ -87,10 +113,13 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
87
113
|
: "customMessageBg";
|
|
88
114
|
box.setBgFn((line) => theme.bg(background, line));
|
|
89
115
|
statusText.setText(
|
|
90
|
-
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`,
|
|
116
|
+
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status + countdown)}`,
|
|
91
117
|
);
|
|
92
118
|
const context = {
|
|
93
|
-
args: {
|
|
119
|
+
args: {
|
|
120
|
+
command: current.commandText,
|
|
121
|
+
...(current.timing ? { timeout: current.timing.timeoutSeconds } : {}),
|
|
122
|
+
},
|
|
94
123
|
toolCallId: current.toolCallId,
|
|
95
124
|
cwd: currentCwd,
|
|
96
125
|
state: rendererState,
|
|
@@ -135,3 +164,70 @@ export function registerFusionCards(pi: ExtensionAPI) {
|
|
|
135
164
|
if (!pending) pi.appendEntry(RESULT_TYPE, data);
|
|
136
165
|
};
|
|
137
166
|
}
|
|
167
|
+
|
|
168
|
+
/** Mutation render state plus the shell that keeps the card status independent of then_run. */
|
|
169
|
+
interface FusedMutationRenderState extends MutationRenderState {
|
|
170
|
+
mutationShell?: {
|
|
171
|
+
box: Box;
|
|
172
|
+
call?: Component;
|
|
173
|
+
result?: Component;
|
|
174
|
+
fileState?: { freshness?: string };
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Keep the mutation card's background independent of the fused command's lifetime. */
|
|
179
|
+
export function withMutationStatus<TParams extends TSchema, TDetails>(
|
|
180
|
+
tool: ToolDefinition<TParams, TDetails, FusedMutationRenderState>,
|
|
181
|
+
): ToolDefinition<TParams, TDetails, FusedMutationRenderState> {
|
|
182
|
+
return {
|
|
183
|
+
...tool,
|
|
184
|
+
renderShell: "self",
|
|
185
|
+
renderCall(args, theme, context) {
|
|
186
|
+
const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
|
|
187
|
+
shell.call = tool.renderCall!(args, theme, { ...context, lastComponent: shell.call });
|
|
188
|
+
shell.box.clear();
|
|
189
|
+
shell.box.addChild(shell.call);
|
|
190
|
+
shell.box.setBgFn((line: string) =>
|
|
191
|
+
theme.bg(
|
|
192
|
+
context.isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
|
|
193
|
+
line,
|
|
194
|
+
),
|
|
195
|
+
);
|
|
196
|
+
return shell.box;
|
|
197
|
+
},
|
|
198
|
+
renderResult(result, options, theme, context) {
|
|
199
|
+
const shell = (context.state.mutationShell ??= { box: new Box(1, 1) });
|
|
200
|
+
const details = result.details as
|
|
201
|
+
| { actionFusion?: { mutationCompleted?: boolean; freshness?: string } }
|
|
202
|
+
| undefined;
|
|
203
|
+
const isPartial = options.isPartial && details?.actionFusion?.mutationCompleted !== true;
|
|
204
|
+
// Pi serializes fused failures into one diagnostic; retain it when the card expands.
|
|
205
|
+
const fusedError = context.isError && (context.args as { then_run?: unknown })?.then_run;
|
|
206
|
+
shell.result = fusedError
|
|
207
|
+
? renderToolError(result, theme, options.expanded)
|
|
208
|
+
: tool.renderResult!(result, { ...options, isPartial }, theme, {
|
|
209
|
+
...context,
|
|
210
|
+
isPartial,
|
|
211
|
+
lastComponent: shell.result,
|
|
212
|
+
});
|
|
213
|
+
// Pi runs renderCall first; update its box in place without invalidating the tool row.
|
|
214
|
+
shell.box.addChild(shell.result);
|
|
215
|
+
const file = details?.actionFusion ?? shell.fileState;
|
|
216
|
+
if (file) {
|
|
217
|
+
shell.fileState = { freshness: file.freshness };
|
|
218
|
+
if (file.freshness === "changed" || file.freshness === "missing") {
|
|
219
|
+
shell.box.addChild(
|
|
220
|
+
new Text(theme.fg("warning", `Anchors are stale: target ${file.freshness}.`), 0, 0),
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
shell.box.setBgFn((line: string) =>
|
|
225
|
+
theme.bg(
|
|
226
|
+
isPartial ? "toolPendingBg" : context.isError ? "toolErrorBg" : "toolSuccessBg",
|
|
227
|
+
line,
|
|
228
|
+
),
|
|
229
|
+
);
|
|
230
|
+
return new Container();
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
package/src/pi/grep-output.ts
CHANGED
|
@@ -1,27 +1,45 @@
|
|
|
1
1
|
import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { DiagnosticBuffer } from "./diagnostic-buffer.ts";
|
|
2
3
|
import { createHash } from "node:crypto";
|
|
3
4
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { fileReadWarning, type RgMatch } from "./grep-search.ts";
|
|
5
|
+
import { createAnchorFormatter, displayCarriageReturns, plainRow } from "./anchor-format.ts";
|
|
6
|
+
import { fileReadWarning, type RgMatch, type SearchFileSnapshot } from "./grep-search.ts";
|
|
7
7
|
import { scanTextLines } from "./text-stream.ts";
|
|
8
|
-
import {
|
|
8
|
+
import { GREP_MAX_LINE_LENGTH, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
|
|
9
|
+
import { searchChangedError } from "./error-text.ts";
|
|
9
10
|
|
|
10
|
-
/**
|
|
11
|
-
const
|
|
11
|
+
/** UTF-16 units kept before the match column when a preview window is cut. */
|
|
12
|
+
const GREP_PREVIEW_LEAD = 100;
|
|
12
13
|
const MAX_CONCURRENT_FILE_READS = 16;
|
|
14
|
+
const INVALID_UTF8_PREVIEW_NOTICE =
|
|
15
|
+
"Invalid UTF-8: replacement characters shown; plain line numbers cannot be used as edit anchors";
|
|
16
|
+
|
|
17
|
+
/** Content-mode file header: `<path> · <N> match(es)`. parseFileHeader is its TUI parser. */
|
|
18
|
+
function formatFileHeader(path: string, matches: number): string {
|
|
19
|
+
return `${path} · ${matches} match${matches !== 1 ? "es" : ""}`;
|
|
20
|
+
}
|
|
21
|
+
const FILE_HEADER = /^(.+?) · (\d+ match(?:es)?)$/;
|
|
22
|
+
|
|
23
|
+
export function parseFileHeader(line: string): { path: string; summary: string } | undefined {
|
|
24
|
+
const match = FILE_HEADER.exec(line);
|
|
25
|
+
return match ? { path: match[1], summary: match[2] } : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Notices and search diagnostics open with `[` (see assembleGrepOutput and formatSearchWarnings). */
|
|
29
|
+
export function isNoticeLine(line: string): boolean {
|
|
30
|
+
return line.startsWith("[");
|
|
31
|
+
}
|
|
13
32
|
|
|
14
33
|
export function formatSearchWarnings(warnings: readonly string[]): string {
|
|
15
34
|
if (!warnings.length) return "";
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
}
|
|
19
|
-
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${summary.content}${summary.truncated ? `\nAdditional search diagnostics omitted (${formatKiB(MAX_SEARCH_DIAGNOSTIC_BYTES)} limit).` : ""}]`;
|
|
35
|
+
const diagnostics = new DiagnosticBuffer(MAX_SEARCH_DIAGNOSTIC_BYTES);
|
|
36
|
+
for (const warning of new Set(warnings)) diagnostics.append(`${warning}\n`);
|
|
37
|
+
return `\n\n[Search incomplete; results and counts cover only confirmed matches.\n${diagnostics.toString().trimEnd()}]`;
|
|
20
38
|
}
|
|
21
39
|
|
|
22
40
|
function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
|
|
23
41
|
if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
|
|
24
|
-
let start = Math.max(0, Math.min(column -
|
|
42
|
+
let start = Math.max(0, Math.min(column - GREP_PREVIEW_LEAD, text.length - GREP_MAX_LINE_LENGTH));
|
|
25
43
|
// Slice at UTF-16 boundaries without splitting an astral character.
|
|
26
44
|
if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
|
|
27
45
|
let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
|
|
@@ -40,11 +58,11 @@ interface FormatMatchesOptions {
|
|
|
40
58
|
anchors: ReturnType<typeof createAnchorFormatter>;
|
|
41
59
|
signal?: AbortSignal;
|
|
42
60
|
warnings: string[];
|
|
43
|
-
|
|
61
|
+
searchSnapshots: ReadonlyMap<string, SearchFileSnapshot>;
|
|
44
62
|
}
|
|
45
63
|
|
|
46
64
|
export async function formatMatches(options: FormatMatchesOptions) {
|
|
47
|
-
const { cwd, raw, outputMode, context, anchors, signal, warnings,
|
|
65
|
+
const { cwd, raw, outputMode, context, anchors, signal, warnings, searchSnapshots } = options;
|
|
48
66
|
const byFile = new Map<string, RgMatch[]>();
|
|
49
67
|
for (const match of raw) {
|
|
50
68
|
const lines = byFile.get(match.filePath) ?? [];
|
|
@@ -89,6 +107,8 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
89
107
|
const matchedRows = new Set<number>();
|
|
90
108
|
const hash = createHash("sha256");
|
|
91
109
|
try {
|
|
110
|
+
// Content-mode search snapshots every file before recording its matches.
|
|
111
|
+
const snapshot = searchSnapshots.get(filePath)!;
|
|
92
112
|
const stats = await scanTextLines(
|
|
93
113
|
filePath,
|
|
94
114
|
(number) => windowSet.has(number),
|
|
@@ -96,7 +116,7 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
96
116
|
if (line.text === undefined) return;
|
|
97
117
|
const matchedText = matchedTexts.get(line.number);
|
|
98
118
|
if (matchedText !== undefined && matchedText !== line.text) {
|
|
99
|
-
throw
|
|
119
|
+
throw searchChangedError();
|
|
100
120
|
}
|
|
101
121
|
if (matchedTexts.has(line.number)) matchedRows.add(line.number);
|
|
102
122
|
const { text: display, wasTruncated } = previewLine(
|
|
@@ -104,20 +124,24 @@ export async function formatMatches(options: FormatMatchesOptions) {
|
|
|
104
124
|
columns.get(line.number),
|
|
105
125
|
);
|
|
106
126
|
if (wasTruncated) linesTruncated = true;
|
|
107
|
-
rows.push(
|
|
127
|
+
rows.push(
|
|
128
|
+
snapshot.validUtf8
|
|
129
|
+
? anchors.row(line.number, line.text, display)
|
|
130
|
+
: plainRow(line.number, display),
|
|
131
|
+
);
|
|
108
132
|
},
|
|
109
|
-
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
|
|
133
|
+
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes), decoding: "lossy" },
|
|
110
134
|
);
|
|
111
|
-
if (stats.hasNul) throw
|
|
135
|
+
if (stats.hasNul) throw searchChangedError();
|
|
112
136
|
if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
|
|
113
|
-
throw
|
|
137
|
+
throw searchChangedError();
|
|
114
138
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
throw new Error("File changed during search; rerun the query.");
|
|
139
|
+
if (snapshot.revision !== hash.digest("hex")) {
|
|
140
|
+
throw searchChangedError();
|
|
118
141
|
}
|
|
119
|
-
const header = `${formatPath(filePath)
|
|
120
|
-
|
|
142
|
+
const header = `${formatFileHeader(formatPath(filePath), matchLines.length)}\n`;
|
|
143
|
+
const notice = snapshot.validUtf8 ? "" : `\n[${INVALID_UTF8_PREVIEW_NOTICE}]`;
|
|
144
|
+
fileResults[current] = { block: header + rows.join("\n") + notice };
|
|
121
145
|
} catch (error) {
|
|
122
146
|
const warning = fileReadWarning(filePath, error, scanSignal);
|
|
123
147
|
if (!warning) throw error;
|
|
@@ -158,8 +182,6 @@ interface AssembleGrepOutputOptions {
|
|
|
158
182
|
blocks: readonly string[];
|
|
159
183
|
warnings: readonly string[];
|
|
160
184
|
outputMode: "content" | "files" | "count";
|
|
161
|
-
/** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
|
|
162
|
-
literalFallbackNotice: string | undefined;
|
|
163
185
|
matchLimitReached: boolean;
|
|
164
186
|
effectiveLimit: number;
|
|
165
187
|
linesTruncated: boolean;
|
|
@@ -169,15 +191,8 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
169
191
|
content: [{ type: "text"; text: string }];
|
|
170
192
|
details: { incomplete: true } | undefined;
|
|
171
193
|
} {
|
|
172
|
-
const {
|
|
173
|
-
|
|
174
|
-
warnings,
|
|
175
|
-
outputMode,
|
|
176
|
-
literalFallbackNotice,
|
|
177
|
-
matchLimitReached,
|
|
178
|
-
effectiveLimit,
|
|
179
|
-
linesTruncated,
|
|
180
|
-
} = options;
|
|
194
|
+
const { blocks, warnings, outputMode, matchLimitReached, effectiveLimit, linesTruncated } =
|
|
195
|
+
options;
|
|
181
196
|
|
|
182
197
|
if (!blocks.length && warnings.length) {
|
|
183
198
|
throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
|
|
@@ -186,7 +201,7 @@ export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
|
186
201
|
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
187
202
|
output = truncation.content;
|
|
188
203
|
|
|
189
|
-
const notices: string[] =
|
|
204
|
+
const notices: string[] = [];
|
|
190
205
|
if (matchLimitReached) {
|
|
191
206
|
notices.push(
|
|
192
207
|
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|