@criogaid/pi-hashline-edit 0.3.0 → 0.4.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.
- package/README.md +59 -50
- package/package.json +8 -3
- package/src/core/apply.test.ts +366 -310
- package/src/core/apply.ts +269 -202
- package/src/core/hash.test.ts +61 -23
- package/src/core/hash.ts +45 -16
- package/src/core/lines.test.ts +46 -27
- package/src/core/lines.ts +36 -28
- package/src/core/ranges.test.ts +73 -19
- package/src/core/ranges.ts +15 -15
- package/src/core/text.test.ts +3 -3
- package/src/core/text.ts +28 -9
- package/src/core/types.ts +54 -36
- package/src/index.ts +22 -16
- package/src/integration/grep-rg.test.ts +834 -219
- package/src/integration/large-text.test.ts +62 -0
- package/src/integration/replace-package.test.ts +37 -0
- package/src/pi/action-fusion.test.ts +535 -206
- package/src/pi/action-fusion.ts +469 -244
- package/src/pi/anchor-format.test.ts +30 -19
- package/src/pi/anchor-format.ts +27 -14
- package/src/pi/budgets.ts +20 -0
- package/src/pi/config.test.ts +60 -30
- package/src/pi/config.ts +45 -32
- package/src/pi/directory-sync.test.ts +55 -0
- package/src/pi/e2e-scenarios.test.ts +359 -0
- package/src/pi/edit-tool.ts +426 -262
- package/src/pi/error-text.ts +21 -0
- package/src/pi/execute.test.ts +1594 -694
- package/src/pi/failure-context.test.ts +105 -83
- package/src/pi/failure-context.ts +83 -71
- package/src/pi/failure-path.test.ts +171 -64
- package/src/pi/file-commit.test.ts +446 -233
- package/src/pi/file-commit.ts +347 -203
- package/src/pi/fusion-card.test.ts +118 -83
- package/src/pi/fusion-card.ts +120 -85
- package/src/pi/grep-output.ts +208 -0
- package/src/pi/grep-render.ts +58 -0
- package/src/pi/grep-scope.ts +152 -0
- package/src/pi/grep-search.ts +217 -0
- package/src/pi/grep-tool.ts +191 -766
- package/src/pi/grep.test.ts +562 -150
- package/src/pi/mutation-result.test.ts +37 -0
- package/src/pi/mutation-result.ts +107 -59
- package/src/pi/mutation-runner.ts +168 -0
- package/src/pi/path.ts +20 -12
- package/src/pi/pi.test.ts +95 -52
- package/src/pi/read-tool.ts +219 -130
- package/src/pi/registration.test.ts +274 -113
- package/src/pi/render.test.ts +218 -83
- package/src/pi/render.ts +152 -95
- package/src/pi/replace-apply.ts +109 -0
- package/src/pi/replace-tool.ts +280 -240
- package/src/pi/replace-worker.mjs +4 -0
- package/src/pi/replace-worker.ts +10 -0
- package/src/pi/replace.test.ts +773 -389
- package/src/pi/result-safety.test.ts +779 -342
- package/src/pi/rg-line-filter.test.ts +64 -36
- package/src/pi/rg-line-filter.ts +40 -124
- package/src/pi/rg-line-ranges.test.ts +57 -31
- package/src/pi/rg-line-ranges.ts +44 -82
- package/src/pi/rg-text-view.ts +106 -36
- package/src/pi/schema.ts +27 -0
- package/src/pi/state.ts +7 -7
- package/src/pi/text-stream.test.ts +118 -0
- package/src/pi/text-stream.ts +136 -0
- package/src/pi/tool-call.testing.ts +37 -0
- package/src/pi/write-tool.ts +115 -52
- package/src/pi/write.test.ts +248 -96
|
@@ -4,103 +4,138 @@ import { initTheme } from "@earendil-works/pi-coding-agent";
|
|
|
4
4
|
import { registerFusionCards } from "./fusion-card.ts";
|
|
5
5
|
import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
6
6
|
|
|
7
|
-
const theme = {
|
|
8
|
-
|
|
7
|
+
const theme = {
|
|
8
|
+
fg: (_color: string, text: string) => text,
|
|
9
|
+
bg: (_color: string, text: string) => text,
|
|
10
|
+
bold: (text: string) => text,
|
|
11
|
+
};
|
|
12
|
+
const themeKeys = [
|
|
13
|
+
Symbol.for("@earendil-works/pi-coding-agent:theme"),
|
|
14
|
+
Symbol.for("@mariozechner/pi-coding-agent:theme"),
|
|
15
|
+
];
|
|
9
16
|
const originalThemes = themeKeys.map((key) => Object.getOwnPropertyDescriptor(globalThis, key));
|
|
10
17
|
before(() => initTheme("dark"));
|
|
11
|
-
after(() =>
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
18
|
+
after(() =>
|
|
19
|
+
themeKeys.forEach((key, index) => {
|
|
20
|
+
const original = originalThemes[index];
|
|
21
|
+
if (original) Object.defineProperty(globalThis, key, original);
|
|
22
|
+
else Reflect.deleteProperty(globalThis, key);
|
|
23
|
+
}),
|
|
24
|
+
);
|
|
16
25
|
|
|
17
26
|
function harness(entries: any[] = []) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const renderers = new Map<string, any>();
|
|
28
|
+
const handlers = new Map<string, any>();
|
|
29
|
+
const backgrounds: string[] = [];
|
|
30
|
+
const report = registerFusionCards({
|
|
31
|
+
on(event: string, handler: any) {
|
|
32
|
+
handlers.set(event, handler);
|
|
33
|
+
},
|
|
34
|
+
registerEntryRenderer(type: string, renderer: any) {
|
|
35
|
+
renderers.set(type, renderer);
|
|
36
|
+
},
|
|
37
|
+
appendEntry(customType: string, data: unknown) {
|
|
38
|
+
entries.push({ type: "custom", customType, data: structuredClone(data) });
|
|
39
|
+
},
|
|
40
|
+
} as any);
|
|
41
|
+
const restore = (event = "session_start", branch = entries, extra = {}) =>
|
|
42
|
+
handlers.get(event)({}, { sessionManager: { getBranch: () => branch }, ...extra });
|
|
43
|
+
const card = (entry: any, expanded = false) =>
|
|
44
|
+
renderers.get(entry.customType)(
|
|
45
|
+
entry,
|
|
46
|
+
{ expanded },
|
|
47
|
+
{
|
|
48
|
+
...theme,
|
|
49
|
+
bg: (color: string, text: string) => {
|
|
50
|
+
backgrounds.push(color);
|
|
51
|
+
return text;
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
);
|
|
55
|
+
return { entries, report, restore, card, backgrounds };
|
|
31
56
|
}
|
|
32
57
|
|
|
33
58
|
const waiting: ActionFusionProgress = {
|
|
34
|
-
|
|
35
|
-
|
|
59
|
+
toolCallId: "call-1",
|
|
60
|
+
path: "file.ts",
|
|
61
|
+
commandText: "npm test",
|
|
62
|
+
command: "waiting",
|
|
63
|
+
publication: "NOT_PUBLISHED",
|
|
64
|
+
freshness: "unknown",
|
|
65
|
+
output: "",
|
|
66
|
+
mutationCompleted: false,
|
|
36
67
|
};
|
|
37
68
|
|
|
38
69
|
test("one independent card updates live and only persists its endpoints", () => {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
70
|
+
const h = harness();
|
|
71
|
+
h.report(waiting);
|
|
72
|
+
const card = h.card(h.entries[0]);
|
|
73
|
+
assert.match(card.render(100).join("\n"), /waiting/);
|
|
74
|
+
assert.equal(h.backgrounds.at(-1), "toolPendingBg");
|
|
75
|
+
h.report({
|
|
76
|
+
...waiting,
|
|
77
|
+
command: "running",
|
|
78
|
+
publication: "PUBLISHED",
|
|
79
|
+
output: "first test passed",
|
|
80
|
+
});
|
|
81
|
+
assert.match(card.render(100).join("\n"), /running[\s\S]*first test passed/);
|
|
82
|
+
assert.equal(h.entries.length, 1);
|
|
83
|
+
const output = Array.from({ length: 20 }, (_, i) => `output line ${i}`).join("\n");
|
|
84
|
+
h.report({
|
|
85
|
+
...waiting,
|
|
86
|
+
command: "succeeded",
|
|
87
|
+
publication: "PUBLISHED",
|
|
88
|
+
freshness: "changed",
|
|
89
|
+
output,
|
|
90
|
+
});
|
|
91
|
+
assert.equal(h.entries.length, 2);
|
|
92
|
+
assert.equal(h.entries[0].data.command, "waiting");
|
|
93
|
+
const collapsed = card.render(100).join("\n");
|
|
94
|
+
assert.match(collapsed, /succeeded/);
|
|
95
|
+
assert.doesNotMatch(collapsed, /publication=|freshness=|Anchors are stale|file\.ts/);
|
|
96
|
+
assert.equal(h.backgrounds.at(-1), "toolSuccessBg");
|
|
97
|
+
assert.match(collapsed, /output line 19/);
|
|
98
|
+
assert.doesNotMatch(collapsed, /output line 0\b/);
|
|
99
|
+
assert.match(h.card(h.entries[0], true).render(100).join("\n"), /output line 0\b/);
|
|
58
100
|
});
|
|
59
101
|
|
|
60
102
|
test("session restore uses final snapshots and marks unfinished calls unknown", () => {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
103
|
+
const h = harness();
|
|
104
|
+
h.report(waiting);
|
|
105
|
+
h.report({
|
|
106
|
+
...waiting,
|
|
107
|
+
command: "failed",
|
|
108
|
+
publication: "PUBLISHED",
|
|
109
|
+
output: "Command exited with code 7",
|
|
110
|
+
});
|
|
111
|
+
const resumed = harness(h.entries);
|
|
112
|
+
resumed.restore();
|
|
113
|
+
assert.match(
|
|
114
|
+
resumed.card(h.entries[0]).render(100).join("\n"),
|
|
115
|
+
/failed[\s\S]*Command exited with code 7/,
|
|
116
|
+
);
|
|
117
|
+
assert.equal(resumed.backgrounds.at(-1), "toolErrorBg");
|
|
118
|
+
resumed.restore("session_tree", [h.entries[0]]);
|
|
119
|
+
assert.match(
|
|
120
|
+
resumed.card(h.entries[0]).render(100).join("\n"),
|
|
121
|
+
/interrupted \(final status unknown\)/,
|
|
122
|
+
);
|
|
70
123
|
});
|
|
71
124
|
|
|
72
125
|
test("skips and cancellations stay neutral and restore their own reason", () => {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
test("legacy snapshots separate known command failures and suppress mutation diagnostics", () => {
|
|
91
|
-
for (const command of ["skipped", "failed", "cancelled"] as const) {
|
|
92
|
-
const output = command === "skipped"
|
|
93
|
-
? "mutation failed; the command was not run [then_run:skipped]\nNo file changes were published. Command skipped.\nAnchor mismatch: 1 shifted.\nInput-anchor checks"
|
|
94
|
-
: `mutation completed; then_run did not complete successfully [then_run:${command === "cancelled" ? "skipped" : "failed"}]\nFile changes are saved. Command ${command}.\nactual command diagnostic`;
|
|
95
|
-
const entries = [
|
|
96
|
-
{ type: "custom", customType: "hashline-then-run", data: waiting },
|
|
97
|
-
{ type: "custom", customType: "hashline-then-run-result", data: { ...waiting, command, publication: "PUBLISHED", output } },
|
|
98
|
-
];
|
|
99
|
-
const h = harness(entries);
|
|
100
|
-
h.restore();
|
|
101
|
-
const text = h.card(entries[0], true).render(160).join("\n");
|
|
102
|
-
assert.doesNotMatch(text, /Anchor mismatch|Input-anchor|publication=|freshness=|File changes are saved|mutation completed/);
|
|
103
|
-
assert.match(text, command === "skipped" ? /Command was not run/ : /actual command diagnostic/);
|
|
104
|
-
assert.equal(entries[1].data.output, output, "restoring must not rewrite persisted evidence");
|
|
105
|
-
}
|
|
126
|
+
for (const command of ["skipped", "cancelled"] as const) {
|
|
127
|
+
const h = harness();
|
|
128
|
+
h.report(waiting);
|
|
129
|
+
h.report({ ...waiting, command, reason: "Not run because the mutation did not complete." });
|
|
130
|
+
for (const restored of [false, true]) {
|
|
131
|
+
const view = restored ? harness(h.entries) : h;
|
|
132
|
+
if (restored) view.restore();
|
|
133
|
+
const output = view.card(h.entries[0], true).render(160).join("\n");
|
|
134
|
+
assert.match(output, /Not run because the mutation did not complete/);
|
|
135
|
+
assert.doesNotMatch(output, /publication=|freshness=|\(no output\)/);
|
|
136
|
+
assert.ok(!view.backgrounds.includes("toolErrorBg"));
|
|
137
|
+
assert.ok(!view.backgrounds.includes("toolSuccessBg"));
|
|
138
|
+
assert.equal(view.backgrounds.at(-1), "customMessageBg");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
106
141
|
});
|
package/src/pi/fusion-card.ts
CHANGED
|
@@ -6,97 +6,132 @@ import type { ActionFusionProgress } from "./action-fusion.ts";
|
|
|
6
6
|
const CARD_TYPE = "hashline-then-run";
|
|
7
7
|
const RESULT_TYPE = "hashline-then-run-result";
|
|
8
8
|
|
|
9
|
-
type CommandCardData = Pick<
|
|
9
|
+
type CommandCardData = Pick<
|
|
10
|
+
ActionFusionProgress,
|
|
11
|
+
"toolCallId" | "commandText" | "command" | "output" | "reason"
|
|
12
|
+
>;
|
|
10
13
|
|
|
11
|
-
function commandCardData({
|
|
12
|
-
|
|
14
|
+
function commandCardData({
|
|
15
|
+
toolCallId,
|
|
16
|
+
commandText,
|
|
17
|
+
command,
|
|
18
|
+
output,
|
|
19
|
+
reason,
|
|
20
|
+
}: ActionFusionProgress): CommandCardData {
|
|
21
|
+
return { toolCallId, commandText, command, output, ...(reason ? { reason } : {}) };
|
|
13
22
|
}
|
|
14
23
|
|
|
15
24
|
/** Render one durable transcript card per fused command without adding model context. */
|
|
16
25
|
export function registerFusionCards(pi: ExtensionAPI) {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
26
|
+
let currentCwd = process.cwd();
|
|
27
|
+
const bash = createBashToolDefinition(process.cwd());
|
|
28
|
+
const states = new Map<string, CommandCardData>();
|
|
29
|
+
const active = new Set<string>();
|
|
20
30
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
};
|
|
45
|
-
pi.on("session_start", (_event, ctx) => restore(ctx));
|
|
46
|
-
pi.on("session_tree", (_event, ctx) => restore(ctx));
|
|
31
|
+
const restore = (ctx: ExtensionContext) => {
|
|
32
|
+
if (ctx.cwd) currentCwd = ctx.cwd;
|
|
33
|
+
states.clear();
|
|
34
|
+
active.clear();
|
|
35
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
36
|
+
if (
|
|
37
|
+
entry.type !== "custom" ||
|
|
38
|
+
(entry.customType !== CARD_TYPE && entry.customType !== RESULT_TYPE)
|
|
39
|
+
)
|
|
40
|
+
continue;
|
|
41
|
+
const data = entry.data as ActionFusionProgress | undefined;
|
|
42
|
+
if (
|
|
43
|
+
data &&
|
|
44
|
+
typeof data.toolCallId === "string" &&
|
|
45
|
+
typeof data.commandText === "string" &&
|
|
46
|
+
typeof data.output === "string"
|
|
47
|
+
) {
|
|
48
|
+
states.set(data.toolCallId, commandCardData(data));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
pi.on("session_start", (_event, ctx) => restore(ctx));
|
|
53
|
+
pi.on("session_tree", (_event, ctx) => restore(ctx));
|
|
47
54
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
55
|
+
pi.registerEntryRenderer<CommandCardData>(CARD_TYPE, (entry, { expanded }, theme) => {
|
|
56
|
+
const initial = entry.data;
|
|
57
|
+
if (!initial) return undefined;
|
|
58
|
+
const statusText = new Text("", 0, 0);
|
|
59
|
+
const box = new Box(1, 1);
|
|
60
|
+
let call: Component | undefined;
|
|
61
|
+
let result: Component | undefined;
|
|
62
|
+
const rendererState = { startedAt: undefined, endedAt: undefined, interval: undefined };
|
|
63
|
+
return {
|
|
64
|
+
invalidate: () => box.invalidate(),
|
|
65
|
+
render(width) {
|
|
66
|
+
// Read live state during rendering; native tool updates schedule the repaint.
|
|
67
|
+
const current = states.get(initial.toolCallId) ?? initial;
|
|
68
|
+
const pending = current.command === "waiting" || current.command === "running";
|
|
69
|
+
const interrupted = pending && !active.has(current.toolCallId);
|
|
70
|
+
const status = interrupted ? "interrupted (final status unknown)" : current.command;
|
|
71
|
+
const failed = current.command === "failed" || current.command === "timeout";
|
|
72
|
+
const color =
|
|
73
|
+
pending || current.command === "cancelled"
|
|
74
|
+
? "warning"
|
|
75
|
+
: failed
|
|
76
|
+
? "error"
|
|
77
|
+
: current.command === "succeeded"
|
|
78
|
+
? "success"
|
|
79
|
+
: "dim";
|
|
80
|
+
const background =
|
|
81
|
+
pending && !interrupted
|
|
82
|
+
? "toolPendingBg"
|
|
83
|
+
: failed
|
|
84
|
+
? "toolErrorBg"
|
|
85
|
+
: current.command === "succeeded"
|
|
86
|
+
? "toolSuccessBg"
|
|
87
|
+
: "customMessageBg";
|
|
88
|
+
box.setBgFn((line) => theme.bg(background, line));
|
|
89
|
+
statusText.setText(
|
|
90
|
+
`${theme.fg("toolTitle", theme.bold("then_run"))} · ${theme.fg(color, status)}`,
|
|
91
|
+
);
|
|
92
|
+
const context = {
|
|
93
|
+
args: { command: current.commandText },
|
|
94
|
+
toolCallId: current.toolCallId,
|
|
95
|
+
cwd: currentCwd,
|
|
96
|
+
state: rendererState,
|
|
97
|
+
invalidate: () => box.invalidate(),
|
|
98
|
+
// Parent tool updates drive entry rendering; leave the native elapsed-time timer off.
|
|
99
|
+
executionStarted: false,
|
|
100
|
+
argsComplete: true,
|
|
101
|
+
isPartial: pending && !interrupted,
|
|
102
|
+
expanded,
|
|
103
|
+
showImages: false,
|
|
104
|
+
isError: failed,
|
|
105
|
+
};
|
|
106
|
+
call = bash.renderCall!(context.args, theme, { ...context, lastComponent: call });
|
|
107
|
+
box.clear();
|
|
108
|
+
box.addChild(statusText);
|
|
109
|
+
box.addChild(call);
|
|
110
|
+
if (current.reason) box.addChild(new Text(theme.fg("dim", current.reason), 0, 0));
|
|
111
|
+
if (current.output || current.command === "succeeded" || failed) {
|
|
112
|
+
result = bash.renderResult!(
|
|
113
|
+
{ content: [{ type: "text", text: current.output }], details: undefined },
|
|
114
|
+
{ expanded, isPartial: context.isPartial },
|
|
115
|
+
theme,
|
|
116
|
+
{ ...context, lastComponent: result },
|
|
117
|
+
);
|
|
118
|
+
box.addChild(result);
|
|
119
|
+
}
|
|
120
|
+
return box.render(width);
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
});
|
|
90
124
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
125
|
+
return (progress: ActionFusionProgress, ctx?: ExtensionContext) => {
|
|
126
|
+
if (ctx?.cwd) currentCwd = ctx.cwd;
|
|
127
|
+
const first = !states.has(progress.toolCallId);
|
|
128
|
+
const data = commandCardData(progress);
|
|
129
|
+
states.set(progress.toolCallId, data);
|
|
130
|
+
const pending = progress.command === "waiting" || progress.command === "running";
|
|
131
|
+
if (pending) active.add(progress.toolCallId);
|
|
132
|
+
else active.delete(progress.toolCallId);
|
|
133
|
+
// Only endpoints are persisted; streaming snapshots reuse Bash's bounded output.
|
|
134
|
+
if (first) pi.appendEntry(CARD_TYPE, data);
|
|
135
|
+
if (!pending) pi.appendEntry(RESULT_TYPE, data);
|
|
136
|
+
};
|
|
102
137
|
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { truncateHead, formatSize, DEFAULT_MAX_BYTES } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { UNSUPPORTED_TEXT_NUL } from "../core/text.ts";
|
|
5
|
+
import { createAnchorFormatter, displayCarriageReturns } from "./anchor-format.ts";
|
|
6
|
+
import { fileReadWarning, type RgMatch } from "./grep-search.ts";
|
|
7
|
+
import { scanTextLines } from "./text-stream.ts";
|
|
8
|
+
import { formatKiB, MAX_SEARCH_DIAGNOSTIC_BYTES } from "./budgets.ts";
|
|
9
|
+
|
|
10
|
+
/** Maximum UTF-16 units in a line preview, excluding its partial-line label. */
|
|
11
|
+
const GREP_MAX_LINE_LENGTH = 500;
|
|
12
|
+
const MAX_CONCURRENT_FILE_READS = 16;
|
|
13
|
+
|
|
14
|
+
export function formatSearchWarnings(warnings: readonly string[]): string {
|
|
15
|
+
if (!warnings.length) return "";
|
|
16
|
+
const summary = truncateHead([...new Set(warnings)].join("\n"), {
|
|
17
|
+
maxBytes: MAX_SEARCH_DIAGNOSTIC_BYTES,
|
|
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).` : ""}]`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function previewLine(text: string, column = 0): { text: string; wasTruncated: boolean } {
|
|
23
|
+
if (text.length <= GREP_MAX_LINE_LENGTH) return { text, wasTruncated: false };
|
|
24
|
+
let start = Math.max(0, Math.min(column - 100, text.length - GREP_MAX_LINE_LENGTH));
|
|
25
|
+
// Slice at UTF-16 boundaries without splitting an astral character.
|
|
26
|
+
if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start])) start++;
|
|
27
|
+
let end = Math.min(text.length, start + GREP_MAX_LINE_LENGTH);
|
|
28
|
+
if (end < text.length && /[\uDC00-\uDFFF]/.test(text[end])) end--;
|
|
29
|
+
return {
|
|
30
|
+
text: `[partial, columns ${start + 1}-${end}] ${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`,
|
|
31
|
+
wasTruncated: true,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface FormatMatchesOptions {
|
|
36
|
+
cwd: string;
|
|
37
|
+
raw: readonly RgMatch[];
|
|
38
|
+
outputMode: "content" | "files" | "count";
|
|
39
|
+
context: number;
|
|
40
|
+
anchors: ReturnType<typeof createAnchorFormatter>;
|
|
41
|
+
signal?: AbortSignal;
|
|
42
|
+
warnings: string[];
|
|
43
|
+
searchRevisions: ReadonlyMap<string, string>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function formatMatches(options: FormatMatchesOptions) {
|
|
47
|
+
const { cwd, raw, outputMode, context, anchors, signal, warnings, searchRevisions } = options;
|
|
48
|
+
const byFile = new Map<string, RgMatch[]>();
|
|
49
|
+
for (const match of raw) {
|
|
50
|
+
const lines = byFile.get(match.filePath) ?? [];
|
|
51
|
+
lines.push(match);
|
|
52
|
+
byFile.set(match.filePath, lines);
|
|
53
|
+
}
|
|
54
|
+
for (const lines of byFile.values()) lines.sort((a, b) => a.lineNumber - b.lineNumber);
|
|
55
|
+
const formatPath = (filePath: string): string => {
|
|
56
|
+
const absolute = resolve(cwd, filePath);
|
|
57
|
+
const rel = relative(cwd, absolute);
|
|
58
|
+
return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)
|
|
59
|
+
? rel.replace(/\\/g, "/")
|
|
60
|
+
: absolute;
|
|
61
|
+
};
|
|
62
|
+
const blocks: string[] = [];
|
|
63
|
+
let linesTruncated = false;
|
|
64
|
+
if (outputMode === "content") {
|
|
65
|
+
const fileEntries = [...byFile.entries()];
|
|
66
|
+
const fileResults = new Array<{ block?: string; warning?: string }>(fileEntries.length);
|
|
67
|
+
let nextIndex = 0;
|
|
68
|
+
const workerAbort = new AbortController();
|
|
69
|
+
const scanSignal = signal ? AbortSignal.any([signal, workerAbort.signal]) : workerAbort.signal;
|
|
70
|
+
let failed = false;
|
|
71
|
+
let failure: unknown;
|
|
72
|
+
const workers = Array.from(
|
|
73
|
+
{ length: Math.min(MAX_CONCURRENT_FILE_READS, fileEntries.length) },
|
|
74
|
+
async () => {
|
|
75
|
+
try {
|
|
76
|
+
while (!workerAbort.signal.aborted && nextIndex < fileEntries.length) {
|
|
77
|
+
const current = nextIndex++;
|
|
78
|
+
const [filePath, matchLines] = fileEntries[current];
|
|
79
|
+
const columns = new Map(matchLines.map((match) => [match.lineNumber, match.column]));
|
|
80
|
+
const matchedTexts = new Map(
|
|
81
|
+
matchLines.map((match) => [match.lineNumber, match.matchedText]),
|
|
82
|
+
);
|
|
83
|
+
const windowSet = new Set<number>();
|
|
84
|
+
for (const { lineNumber } of matchLines) {
|
|
85
|
+
for (let n = Math.max(1, lineNumber - context); n <= lineNumber + context; n++)
|
|
86
|
+
windowSet.add(n);
|
|
87
|
+
}
|
|
88
|
+
const rows: string[] = [];
|
|
89
|
+
const matchedRows = new Set<number>();
|
|
90
|
+
const hash = createHash("sha256");
|
|
91
|
+
try {
|
|
92
|
+
const stats = await scanTextLines(
|
|
93
|
+
filePath,
|
|
94
|
+
(number) => windowSet.has(number),
|
|
95
|
+
(line) => {
|
|
96
|
+
if (line.text === undefined) return;
|
|
97
|
+
const matchedText = matchedTexts.get(line.number);
|
|
98
|
+
if (matchedText !== undefined && matchedText !== line.text) {
|
|
99
|
+
throw new Error("File changed during search; rerun the query.");
|
|
100
|
+
}
|
|
101
|
+
if (matchedTexts.has(line.number)) matchedRows.add(line.number);
|
|
102
|
+
const { text: display, wasTruncated } = previewLine(
|
|
103
|
+
displayCarriageReturns(line.text),
|
|
104
|
+
columns.get(line.number),
|
|
105
|
+
);
|
|
106
|
+
if (wasTruncated) linesTruncated = true;
|
|
107
|
+
rows.push(anchors.row(line.number, line.text, display));
|
|
108
|
+
},
|
|
109
|
+
{ signal: scanSignal, onBytes: (bytes) => hash.update(bytes) },
|
|
110
|
+
);
|
|
111
|
+
if (stats.hasNul) throw new Error(UNSUPPORTED_TEXT_NUL);
|
|
112
|
+
if (matchLines.some(({ lineNumber }) => !matchedRows.has(lineNumber))) {
|
|
113
|
+
throw new Error("File changed during search; rerun the query.");
|
|
114
|
+
}
|
|
115
|
+
const searchRevision = searchRevisions.get(filePath);
|
|
116
|
+
if (searchRevision && searchRevision !== hash.digest("hex")) {
|
|
117
|
+
throw new Error("File changed during search; rerun the query.");
|
|
118
|
+
}
|
|
119
|
+
const header = `${formatPath(filePath)} · ${matchLines.length} match${matchLines.length !== 1 ? "es" : ""}\n`;
|
|
120
|
+
fileResults[current] = { block: header + rows.join("\n") };
|
|
121
|
+
} catch (error) {
|
|
122
|
+
const warning = fileReadWarning(filePath, error, scanSignal);
|
|
123
|
+
if (!warning) throw error;
|
|
124
|
+
fileResults[current] = { warning };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (!failed) {
|
|
129
|
+
failed = true;
|
|
130
|
+
failure = error;
|
|
131
|
+
workerAbort.abort();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
);
|
|
136
|
+
await Promise.all(workers);
|
|
137
|
+
if (failed) throw failure;
|
|
138
|
+
for (const result of fileResults) {
|
|
139
|
+
if (result.warning) warnings.push(result.warning);
|
|
140
|
+
else if (result.block) blocks.push(result.block);
|
|
141
|
+
}
|
|
142
|
+
} else if (outputMode === "files") {
|
|
143
|
+
for (const filePath of byFile.keys()) blocks.push(formatPath(filePath));
|
|
144
|
+
} else {
|
|
145
|
+
let total = 0;
|
|
146
|
+
for (const [filePath, matchLines] of byFile) {
|
|
147
|
+
blocks.push(`${formatPath(filePath)}: ${matchLines.length}`);
|
|
148
|
+
total += matchLines.length;
|
|
149
|
+
}
|
|
150
|
+
blocks.push(
|
|
151
|
+
`Total: ${total} match${total !== 1 ? "es" : ""} in ${byFile.size} file${byFile.size !== 1 ? "s" : ""}`,
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
return { blocks, linesTruncated };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface AssembleGrepOutputOptions {
|
|
158
|
+
blocks: readonly string[];
|
|
159
|
+
warnings: readonly string[];
|
|
160
|
+
outputMode: "content" | "files" | "count";
|
|
161
|
+
/** Notice for an invalid regex that was searched literally; undefined when no fallback happened. */
|
|
162
|
+
literalFallbackNotice: string | undefined;
|
|
163
|
+
matchLimitReached: boolean;
|
|
164
|
+
effectiveLimit: number;
|
|
165
|
+
linesTruncated: boolean;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function assembleGrepOutput(options: AssembleGrepOutputOptions): {
|
|
169
|
+
content: [{ type: "text"; text: string }];
|
|
170
|
+
details: { incomplete: true } | undefined;
|
|
171
|
+
} {
|
|
172
|
+
const {
|
|
173
|
+
blocks,
|
|
174
|
+
warnings,
|
|
175
|
+
outputMode,
|
|
176
|
+
literalFallbackNotice,
|
|
177
|
+
matchLimitReached,
|
|
178
|
+
effectiveLimit,
|
|
179
|
+
linesTruncated,
|
|
180
|
+
} = options;
|
|
181
|
+
|
|
182
|
+
if (!blocks.length && warnings.length) {
|
|
183
|
+
throw new Error(`No matches could be displayed.${formatSearchWarnings(warnings)}`);
|
|
184
|
+
}
|
|
185
|
+
let output = blocks.join(outputMode === "content" ? "\n\n" : "\n");
|
|
186
|
+
const truncation = truncateHead(output, { maxBytes: DEFAULT_MAX_BYTES });
|
|
187
|
+
output = truncation.content;
|
|
188
|
+
|
|
189
|
+
const notices: string[] = literalFallbackNotice ? [literalFallbackNotice] : [];
|
|
190
|
+
if (matchLimitReached) {
|
|
191
|
+
notices.push(
|
|
192
|
+
`${effectiveLimit} matches limit reached. Use limit=${effectiveLimit * 2} for more, or refine pattern`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
if (truncation.truncated) notices.push(`${formatSize(DEFAULT_MAX_BYTES)} limit reached`);
|
|
196
|
+
if (linesTruncated) {
|
|
197
|
+
notices.push(
|
|
198
|
+
`Line previews capped at ${GREP_MAX_LINE_LENGTH} chars (anchors hash full lines); use read for full content`,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
if (notices.length) output += `\n\n[${notices.join(". ")}]`;
|
|
202
|
+
output += formatSearchWarnings(warnings);
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
content: [{ type: "text" as const, text: output }],
|
|
206
|
+
details: warnings.length ? { incomplete: true } : undefined,
|
|
207
|
+
};
|
|
208
|
+
}
|