@floydous/pi-agent-kernel 0.3.2 → 0.3.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.
@@ -1,10 +1,10 @@
1
1
  ## Tool Selection
2
- - **Known identifier / error string / symbol:** Use `rg` (via bash) directly.
2
+ - **Known identifier / error string / symbol:** Use `rg` (via bash) directly with specific symbols or assertion phrases. Avoid broad single-word searches (e.g. `index`, `path`) that return noisy matches.
3
3
  - **Unlocated concept with no names:** Use `code_search` to find relevant files.
4
- - **Code inspection:** Use `read(path, offset, limit)` to read contiguous sections with scope and context (e.g. `limit: 300`). Use `symbol=` only for isolated functions in files >500 lines.
4
+ - **Code inspection:** When search identifies a file and line, read a targeted range centered on that location via `read(path, offset, limit)`. Plain text reads are default and most token-efficient; request `anchors` only for narrow ranges (<100 lines) when editing with anchors. Use multi-file `paths` when inspecting multiple short files or when their relevant regions are independently known. Use `symbol=` for isolated functions in large files (>500 lines).
5
5
 
6
6
  ## Execution Workflow
7
- 1. **Turn 1 Grounding:** Run the reproduction test or inspect git status on Turn 1. Extract the exact failure line and assertion before searching.
7
+ 1. **Turn 1 Grounding:** Check the workspace reproduction diff provided in context under "Workspace Pre-Flight" and run the failing test on Turn 1. Avoid redundant `git diff`, `git log`, or `git status` commands when the reproduction patch is already visible.
8
8
  2. **Root-Cause Layering:** Trace call chains to the callee/producer where the value originates. Fix the root cause, never the downstream caller.
9
- 3. **Surgical Edits:** Use single-block replacements with 2–3 lines of unique surrounding context for clear anchoring.
9
+ 3. **Surgical Edits:** Use single-block replacements with 2–3 lines of unique surrounding context for clear anchoring. When a fix spans multiple files, apply them together in one turn using `edit(files: [{path, search, replace}, ...])`.
10
10
  4. **Deterministic Exit:** Run the verification test immediately after editing. When tests pass (exit code 0), conclude immediately with a concise summary. Do not invoke further diffs or checks.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.3] - 2026-09-20
4
+
5
+ ### Added
6
+ - **Multi-File Atomic Edits**: Extended the `edit` tool with `files: { path, search, replace, line_hint, edits }[]` payload (with resilient per-item `path` normalization in `edits`). Implemented a 2-stage atomic commit with preflight validation, duplicate path detection, in-memory snapshot backups, and automatic rollback across all targets if any file fails patch application or syntax verification.
7
+ - **Batch Multi-File `read`**: Extended the `read` tool to accept `paths: string[]` (and resilient alias `path: string[]`), allowing the model to inspect multiple files in one turn while authorizing all targets in `EpistemicGuard`.
8
+ - **Automatic Turn 1 Reproduction Diff Grounding**: In `before_agent_start`, automatically detects unstaged/staged git diffs and injects a sanitized, clamped (max 25 lines, 2KB hard ceiling) reproduction status into initial context with session caching, eliminating redundant Turn 1 exploratory `git status` / `git diff` commands.
9
+
10
+ ### Changed
11
+ - **Read Tool Budgeting & Anchor Guardrails**: Bounded batch reading to 150 lines per file and a 24KB aggregate ceiling with explicit continuation markers (`[truncated: <file>, returned lines 1-150 of <N>. Continue with read(path, offset=151)]`). Added a 100-line cap on explicit `anchors: true` requests (`MAX_ANCHOR_LINES = 100`) to prevent models from generating expensive `#HASH│` line hashes on large files.
12
+ - **Targeted Reading Workflow Guidance**: Updated `AGENT_KERNEL_SYS_PROMPT.md` to emphasize targeted sequential reads (`read(path, offset, limit)`) centered on search coordinates as the primary inspection workflow, reserving batch `paths` for short files or known regions.
13
+ - **Search Specificity Guidance**: Directed agents toward exact identifiers, error symbols, and test phrases, preventing noisy broad single-word searches from polluting conversation context.
14
+
15
+ ### Validated
16
+ - Verified 38 test suites passing (`npm test`) with 0 regressions.
17
+ - Multi-harness benchmarks on `cx/gpt-5.6-luna:high` across all 8 standard tasks demonstrate:
18
+ - **100% Solve Rate (8 / 8 tasks solved)**.
19
+ - **Aggregate task time cut in half**: **600s (10.0m) vs 1,223s (20.4m)** (-50.9% time reduction, **2.04× faster**).
20
+ - **Uncached input tokens reduced by -18.4%**: **270k vs 331k** (-60.8k tokens saved across the suite).
21
+ - **Tool calls reduced**: **107 calls vs 112 calls**.
22
+ - Consistent speedup across all repositories: UFO (36s vs 119s), Fastify (47s vs 177s), p-limit (60s vs 176s), Ky (89s vs 253s), Zod (135s vs 212s), Hono (64s vs 96s), UUID (53s vs 64s), and Picomatch (116s vs 126s).
23
+
3
24
  ## [0.3.2] - 2026-09-16
4
25
 
5
26
  ### Added
package/README.md CHANGED
@@ -20,27 +20,23 @@ How tool overhead compares to an unconstrained agent harness across standard cod
20
20
 
21
21
  ---
22
22
 
23
- ## Cross-harness benchmark and reproducibility
23
+ ## Benchmarks
24
24
 
25
- `pi-agent-kernel` is evaluated against an 8-task repair suite drawn from merged bug fixes in open-source repositories (`hono`, `ky`, `zod`, `ufo`, `picomatch`, `fastify`, `uuid`, `p-limit`). Prompts describe the bug report and expected behavior without providing the implementation fix or file locations.
25
+ Evaluating 6 coding agent harnesses across 8 real-world bug fixes (`hono`, `ky`, `zod`, `ufo`, `picomatch`, `fastify`, `uuid`, `p-limit`) on `cx/gpt-5.6-luna:high`:
26
26
 
27
- ### Cross-harness 8-task benchmark on GPT 5.6 Luna High (`cx/gpt-5.6-luna:high`)
28
-
29
- Six harnesses were run on the same 8 tasks with identical prompts and repository states on `cx/gpt-5.6-luna:high` through OmniRoute:
30
-
31
- | Harness | Tasks Solved | Success Rate | Total Time | Input Tokens | Output Tokens | Total Turn Tokens | Tool Calls |
27
+ | Harness | Solved | Success | Time | Input Tokens | Output Tokens | Total Turn Tokens | Tool Calls |
32
28
  |---|:---:|:---:|---:|---:|---:|---:|:---:|
33
- | Pi + Agent-Kernel | 8 / 8 | 100% | 1,223s (20.4m) | 331,247 | 13,587 | 762,626 | 112 |
34
- | Pi (Vanilla) | 8 / 8 | 100% | 1,224s (20.4m) | 709,232 | 32,325 | 1,544,373 | 149 |
35
- | Codex CLI | 8 / 8 | 100% | 1,228s (20.5m) | 3,236,287 | 40,091 | 3,276,378 | 102 |
36
- | OpenCode | 8 / 8 | 100% | 1,557s (26.0m) | 1,419,628 | 22,987 | 3,612,533 | 229 |
37
- | OMP | 7 / 8 | 87.5% | 1,164s (19.4m) | 906,173 | 29,810 | 4,157,487 | 384 |
38
- | Claude Code | 6 / 8 | 75% | 2,160s (36.0m) | 4,390,998 | 85,836 | 4,476,834 | 183 |
39
-
40
- The suite tests retrieval, root-cause diagnosis, and verification from behavioral descriptions. Pi + Agent-Kernel solved all 8 tasks with the lowest token footprint: 762,626 total turn tokens compared to Pi Vanilla's 1,544,373 (-50.6% token reduction, saving 781,747 tokens) and external harnesses ranging from 3.28M (Codex CLI) to 4.48M (Claude Code). Note on cross-harness metrics: token accounting reflects each harness's reported telemetry and diff format (for example, OpenCode emits verbose full diffs). In Claude Code, 6 tasks completed within turn limits, and 1 additional task passed test verification after timing out. OMP failed verification on task-4-ufo.
29
+ | Pi + Agent-Kernel | 8 / 8 | 100% | 10m 00s | 270k | 13.5k | 861k | 107 |
30
+ | Pi (Vanilla) | 8 / 8 | 100% | 20m 24s | 709k | 32.3k | 1.54M | 149 |
31
+ | Codex CLI | 8 / 8 | 100% | 20m 28s | 3.24M | 40.1k | 3.28M | 102 |
32
+ | OpenCode | 8 / 8 | 100% | 25m 57s | 1.42M | 23.0k | 3.61M | 229 |
33
+ | OMP | 7 / 8 | 87.5% | 19m 24s | 906k | 29.8k | 4.16M | 384 |
34
+ | Claude Code | 6 / 8 | 75.0% | 36m 00s | 4.39M | 85.8k | 4.48M | 183 |
41
35
 
42
36
  ![Benchmark Comparison](static/benchmark-comparison.png)
43
37
 
38
+ *Prompts describe symptoms and expected behavior without providing the fix. Token totals reflect each tool's reported telemetry. In Claude Code, 1 additional task passed test verification after timing out.*
39
+
44
40
  ---
45
41
 
46
42
  ## Quick start
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floydous/pi-agent-kernel",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Focused code retrieval, editing, safety checks, and language-server support for Pi.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -10,6 +10,7 @@
10
10
  "scripts": {
11
11
  "test": "npx tsx tests/run-all.ts",
12
12
  "typecheck": "tsc --noEmit",
13
+ "preindex": "npx tsx agent-kernel-benchmark/preindex.ts",
13
14
  "bench": "npx tsx agent-kernel-benchmark/run.ts",
14
15
  "bench:clean": "npx tsx agent-kernel-benchmark/run.ts --clean",
15
16
  "bench:chart": "PATH=\"$HOME/.local/bin:$HOME/.venv/bin:$PATH\" python3 agent-kernel-benchmark/generate_chart.py"
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as path from "path";
2
2
  import * as fs from "node:fs";
3
+ import * as child_process from "node:child_process";
3
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
5
  import { computeRepoMap, evaluateCodebaseMetrics } from "./retrieval/repomap";
5
6
  import { HybridSearchIndex } from "./retrieval/search_index";
@@ -897,12 +898,91 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
897
898
  }
898
899
  });
899
900
 
900
- // 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching)
901
+ // 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching & Turn 1 Grounding)
901
902
  // Notice: Custom user instructions (AGENT.md / prompt templates) are respected as the primary authority.
902
903
  // Only runtime operational metadata (repo map) is dynamically attached and cached per session/cwd.
903
904
  let cachedRepoMap = "";
904
905
  let cachedRepoMapCwd = "";
905
906
  let lastRepoMapCheck = 0;
907
+ const sessionGroundingDone = new Set<string>();
908
+ const sessionGroundingText = new Map<string, string>();
909
+
910
+ function getPreFlightGrounding(cwd: string, sessionId: string): string {
911
+ if (sessionGroundingDone.has(sessionId)) {
912
+ return sessionGroundingText.get(sessionId) || "";
913
+ }
914
+ sessionGroundingDone.add(sessionId);
915
+
916
+ try {
917
+ const statusRaw = child_process.execFileSync(
918
+ "git",
919
+ ["status", "--porcelain"],
920
+ { cwd, encoding: "utf8", timeout: 1000, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024 },
921
+ ).trim();
922
+
923
+ if (!statusRaw) {
924
+ sessionGroundingText.set(sessionId, "");
925
+ return "";
926
+ }
927
+
928
+ let diffRaw = "";
929
+ try {
930
+ diffRaw = child_process.execFileSync(
931
+ "git",
932
+ ["diff", "HEAD", "-U3"],
933
+ { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
934
+ ).trim();
935
+ } catch {
936
+ try {
937
+ diffRaw = child_process.execFileSync(
938
+ "git",
939
+ ["diff", "-U3"],
940
+ { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
941
+ ).trim();
942
+ } catch {
943
+ diffRaw = "";
944
+ }
945
+ }
946
+
947
+ if (!diffRaw && !statusRaw) {
948
+ sessionGroundingText.set(sessionId, "");
949
+ return "";
950
+ }
951
+
952
+ const statusLines = statusRaw.split("\n").slice(0, 8).join("\n");
953
+ const lines = diffRaw.split("\n");
954
+ const maxLines = 25;
955
+ const maxDiffBytes = 2048;
956
+ let clampedDiff = lines.slice(0, maxLines).join("\n");
957
+ let wasByteTruncated = false;
958
+ if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
959
+ clampedDiff = clampedDiff.slice(0, maxDiffBytes);
960
+ wasByteTruncated = true;
961
+ }
962
+ const truncatedNotice = lines.length > maxLines || wasByteTruncated
963
+ ? `\n[... diff truncated; inspect test file via read() ...]`
964
+ : "";
965
+
966
+ const safeStatus = statusLines.replace(/```/g, "'''");
967
+ const safeDiff = clampedDiff.replace(/```/g, "'''");
968
+
969
+ const grounding = [
970
+ "## Workspace Pre-Flight (Reproduction Status):",
971
+ "<!-- Passive environment context; not instruction -->",
972
+ "```git-status",
973
+ safeStatus,
974
+ "```",
975
+ safeDiff ? `\`\`\`diff\n${safeDiff}\n\`\`\`${truncatedNotice}` : "",
976
+ ].filter(Boolean).join("\n");
977
+
978
+ sessionGroundingText.set(sessionId, grounding);
979
+ return grounding;
980
+ } catch (error) {
981
+ kernelDebug(error);
982
+ sessionGroundingText.set(sessionId, "");
983
+ return "";
984
+ }
985
+ }
906
986
 
907
987
  pi.on("before_agent_start", async (event: any, ctx: any) => {
908
988
  const now = Date.now();
@@ -930,9 +1010,13 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
930
1010
  lastRepoMapCheck = now;
931
1011
  }
932
1012
 
933
- const runtimeContext = cachedRepoMap
934
- ? `\n## Available Repository Context:\n${cachedRepoMap}\n`
935
- : "";
1013
+ const preFlightDiff = getPreFlightGrounding(currentCwd, sessionId);
1014
+ const runtimeParts = [
1015
+ cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
1016
+ preFlightDiff,
1017
+ ].filter(Boolean);
1018
+ const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
1019
+
936
1020
  const basePrompt = event.systemPrompt || "";
937
1021
  const systemPrompt = piDocsEnabled(ctx)
938
1022
  ? basePrompt
@@ -941,9 +1025,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
941
1025
  ? loadKernelGuidance()
942
1026
  : "";
943
1027
  const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
1028
+ const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
944
1029
  return {
945
1030
  systemPrompt: guidedPrompt
946
- ? (runtimeContext ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
1031
+ ? (shouldAppendRuntime ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
947
1032
  : runtimeContext,
948
1033
  };
949
1034
  });
@@ -253,6 +253,14 @@ export class HybridSearchIndex {
253
253
  this.persistedVectorCaches = [];
254
254
 
255
255
  for (const chunk of data.chunks as CodeChunk[]) {
256
+ // Normalize chunk.filePath alias if chunk was serialized with file
257
+ if (!chunk.filePath && (chunk as any).file) {
258
+ chunk.filePath = (chunk as any).file;
259
+ }
260
+ // Rebase absolutePath to the current workspace root if paths differ
261
+ if (chunk.filePath && this.cwd) {
262
+ chunk.absolutePath = path.resolve(this.cwd, chunk.filePath);
263
+ }
256
264
  this.chunks.set(chunk.id, chunk);
257
265
  this.bm25.addChunk(chunk);
258
266
  }
@@ -29,6 +29,288 @@ import {
29
29
  import { loadKernelConfig } from "../config";
30
30
  import type { SessionDeps } from "./context";
31
31
 
32
+ interface PreparedFileEdit {
33
+ resolvedPath: string;
34
+ relPath: string;
35
+ item: any;
36
+ isAnchorMode: boolean;
37
+ hasSingleAnchor: boolean;
38
+ hasSingleBlock: boolean;
39
+ hasMultiBlock: boolean;
40
+ searchBlocks: string[];
41
+ targetRanges: EvidenceRange[];
42
+ anchorBlocks: SmartAnchorEditBlock[];
43
+ anchorPreflight?: ReturnType<typeof preflightSmartAnchorEdits>;
44
+ }
45
+
46
+ function preflightFileEdit(
47
+ item: any,
48
+ ctx: any,
49
+ deps: SessionDeps,
50
+ benchmarkMethod: string | undefined,
51
+ ): { error?: string; prepared?: PreparedFileEdit } {
52
+ if (!item || typeof item !== "object" || !item.path) {
53
+ return { error: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.` };
54
+ }
55
+ const resolvedPath = resolveUserPath(item.path, ctx.cwd);
56
+ const relPath = path.relative(ctx.cwd, resolvedPath) || item.path;
57
+
58
+ if (!fs.existsSync(resolvedPath)) {
59
+ return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
60
+ }
61
+
62
+ let edits = item.edits;
63
+ if (Array.isArray(edits)) {
64
+ edits = edits.map((e: any) => {
65
+ if (!e || typeof e !== "object") return e;
66
+ const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
67
+ const replace = e.replace ?? e.newText ?? e.new_text ?? e.new;
68
+ return { ...e, search, replace };
69
+ });
70
+ }
71
+ const singleSearch = item.search ?? item.oldText ?? item.old_text ?? item.old;
72
+ const singleReplace = item.replace ?? item.newText ?? item.new_text ?? item.new;
73
+
74
+ const hasSingleAnchor =
75
+ (item.pos !== undefined || item.start_line !== undefined) &&
76
+ Array.isArray(item.lines);
77
+ const hasAnchorEdits =
78
+ Array.isArray(edits) &&
79
+ edits.length > 0 &&
80
+ edits.some(
81
+ (e: any) =>
82
+ e &&
83
+ (e.pos !== undefined ||
84
+ e.start_line !== undefined ||
85
+ (Array.isArray(e.lines) && typeof e.search !== "string")),
86
+ );
87
+ const isAnchorMode = hasSingleAnchor || hasAnchorEdits;
88
+ const hasSingleBlock = typeof singleSearch === "string" && typeof singleReplace === "string";
89
+ const hasMultiBlock = Array.isArray(edits) && edits.length > 0;
90
+
91
+ if (benchmarkMethod === "adaptive" && !isAnchorMode && !hasSingleBlock) {
92
+ return { error: `[EDIT ERROR] Adaptive mode requires search/replace or a numeric/hashed line range in '${relPath}'.` };
93
+ }
94
+
95
+ if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) {
96
+ return { error: `[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks for '${relPath}'.` };
97
+ }
98
+
99
+ const searchBlocks: string[] = [];
100
+ const targetRanges: EvidenceRange[] = [];
101
+ let anchorBlocks: SmartAnchorEditBlock[] = [];
102
+ let anchorPreflight: ReturnType<typeof preflightSmartAnchorEdits> | undefined;
103
+
104
+ if (isAnchorMode) {
105
+ if (hasSingleAnchor) {
106
+ anchorBlocks = [
107
+ {
108
+ pos: item.pos ?? item.start_line,
109
+ end: item.end ?? item.end_line,
110
+ lines: item.lines,
111
+ },
112
+ ];
113
+ } else {
114
+ anchorBlocks = edits;
115
+ }
116
+
117
+ let fileContent: string;
118
+ try {
119
+ fileContent = fs.readFileSync(resolvedPath, "utf8");
120
+ } catch (err: any) {
121
+ return { error: `[EDIT ERROR] Unable to read '${item.path}': ${err.message}` };
122
+ }
123
+
124
+ anchorPreflight = preflightSmartAnchorEdits(fileContent, anchorBlocks);
125
+ if (!anchorPreflight.success) {
126
+ return { error: anchorPreflight.error || `[EDIT FAILED] Invalid anchor edit in '${relPath}'.` };
127
+ }
128
+ if (anchorPreflight.targetRanges) {
129
+ targetRanges.push(...anchorPreflight.targetRanges);
130
+ }
131
+ } else if (hasSingleBlock) {
132
+ searchBlocks.push(singleSearch);
133
+ const singleOpt = {
134
+ startLine: item.start_line,
135
+ endLine: item.end_line,
136
+ lineHint: item.line_hint,
137
+ };
138
+ const preflight = preflightSurgicalPatchBlock(resolvedPath, singleSearch, singleOpt);
139
+ if (!preflight.success) {
140
+ if (preflight.isAmbiguous) {
141
+ return {
142
+ error: `[EDIT FAILED] Ambiguous Search Block in '${relPath}': ${preflight.error} Please provide more surrounding context lines to make the match unique.`,
143
+ };
144
+ }
145
+ return {
146
+ error: `[EDIT FAILED] Search Block Not Found in '${relPath}'. Check line context and try again.`,
147
+ };
148
+ }
149
+ if (preflight.targetRange) targetRanges.push(preflight.targetRange);
150
+ } else {
151
+ for (let i = 0; i < edits.length; i++) {
152
+ const block = edits[i];
153
+ if (!block || typeof block.search !== "string") continue;
154
+ searchBlocks.push(block.search);
155
+ const blockOpt = {
156
+ startLine: block.start_line,
157
+ endLine: block.end_line,
158
+ lineHint: block.line_hint,
159
+ };
160
+ const preflight = preflightSurgicalPatchBlock(resolvedPath, block.search, blockOpt);
161
+ if (!preflight.success) {
162
+ if (preflight.isAmbiguous) {
163
+ return {
164
+ error: `[EDIT FAILED] Block ${i + 1}/${edits.length} is ambiguous in '${relPath}': ${preflight.error} Please provide more surrounding context lines.`,
165
+ };
166
+ }
167
+ return {
168
+ error: `[EDIT FAILED] Block ${i + 1}/${edits.length} not found in '${relPath}'. Check line context and try again.`,
169
+ };
170
+ }
171
+ if (preflight.targetRange) targetRanges.push(preflight.targetRange);
172
+ }
173
+ }
174
+
175
+ const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
176
+ const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
177
+ resolvedPath,
178
+ "edit",
179
+ deps.getSessionId(ctx),
180
+ ctx.cwd,
181
+ config?.safety?.enable_epistemic_guard ?? true,
182
+ targetRanges,
183
+ searchBlocks,
184
+ );
185
+ if (!epistemicCheck.allowed) {
186
+ return { error: epistemicCheck.reason || `[ERROR] Epistemic read pre-condition failed for '${relPath}'.` };
187
+ }
188
+
189
+ return {
190
+ prepared: {
191
+ resolvedPath,
192
+ relPath,
193
+ item: { ...item, search: singleSearch, replace: singleReplace, edits },
194
+ isAnchorMode,
195
+ hasSingleAnchor,
196
+ hasSingleBlock,
197
+ hasMultiBlock,
198
+ searchBlocks,
199
+ targetRanges,
200
+ anchorBlocks,
201
+ anchorPreflight,
202
+ },
203
+ };
204
+ }
205
+
206
+ async function applyPreparedEdit(
207
+ prepared: PreparedFileEdit,
208
+ ctx: any,
209
+ deps: SessionDeps,
210
+ ): Promise<{ success: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
211
+ const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, anchorPreflight, targetRanges } = prepared;
212
+ let patchRes: ReturnType<typeof applySurgicalPatch>;
213
+ if (isAnchorMode) {
214
+ patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
215
+ } else if (hasMultiBlock) {
216
+ patchRes = applyMultiBlockPatch(resolvedPath, item.edits);
217
+ } else if (hasSingleBlock) {
218
+ const singleOpt = {
219
+ startLine: item.start_line,
220
+ endLine: item.end_line,
221
+ lineHint: item.line_hint,
222
+ };
223
+ patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, singleOpt);
224
+ } else {
225
+ return { success: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
226
+ }
227
+
228
+ if (!patchRes.success) {
229
+ return { success: false, error: renderEditFailure(patchRes.error || "patch failed") };
230
+ }
231
+
232
+ let diskContent: string;
233
+ try {
234
+ diskContent = fs.readFileSync(resolvedPath, "utf8");
235
+ } catch {
236
+ diskContent = "";
237
+ }
238
+
239
+ let deltaLines = 0;
240
+ if (isAnchorMode && anchorPreflight?.resolvedSpans) {
241
+ for (const span of anchorPreflight.resolvedSpans) {
242
+ const deletedCount = span.endLine - span.startLine + 1;
243
+ deltaLines += span.replacementLines.length - deletedCount;
244
+ }
245
+ } else if (hasSingleBlock) {
246
+ const searchLines = item.search.replace(/\r\n/g, "\n").split("\n").length;
247
+ const replaceLines = item.replace.replace(/\r\n/g, "\n").split("\n").length;
248
+ deltaLines = replaceLines - searchLines;
249
+ } else if (hasMultiBlock) {
250
+ for (const block of item.edits) {
251
+ if (block && typeof block.search === "string" && typeof block.replace === "string") {
252
+ const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
253
+ const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
254
+ deltaLines += (rLines - sLines);
255
+ }
256
+ }
257
+ }
258
+
259
+ globalEpistemicGuard.recordFileMutation(
260
+ resolvedPath,
261
+ deps.getSessionId(ctx),
262
+ ctx.cwd,
263
+ diskContent,
264
+ {
265
+ targetRanges: patchRes.targetRanges || targetRanges,
266
+ deltaLines,
267
+ },
268
+ );
269
+
270
+ deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
271
+
272
+ const readyLsp = LspManager.getInstance().getReadyClientForFile(resolvedPath, ctx.cwd);
273
+ if (readyLsp && readyLsp.getState() === "ready") {
274
+ try {
275
+ await readyLsp.changeDocument(resolvedPath, diskContent);
276
+ await readyLsp.saveDocument(resolvedPath, diskContent);
277
+ } catch (err) {
278
+ kernelDebug(err);
279
+ }
280
+ }
281
+
282
+ const verification = await verifyEditedFile(
283
+ resolvedPath,
284
+ readyLsp
285
+ ? async () => {
286
+ const result = await readyLsp.getDiagnosticsResult(resolvedPath);
287
+ return {
288
+ state: result.status,
289
+ findings: result.diagnostics.map((finding) => ({
290
+ line: finding.range.start.line + 1,
291
+ column: finding.range.start.character + 1,
292
+ message: finding.message,
293
+ severity:
294
+ finding.severity === 1
295
+ ? ("error" as const)
296
+ : finding.severity === 2
297
+ ? ("warning" as const)
298
+ : ("info" as const),
299
+ })),
300
+ };
301
+ }
302
+ : undefined,
303
+ );
304
+
305
+ const statusText = renderPostEditVerification(verification, undefined, relPath);
306
+ return {
307
+ success: verification.syntax.state !== "failed",
308
+ verification,
309
+ strategy: patchRes.strategy,
310
+ statusText,
311
+ };
312
+ }
313
+
32
314
  /** Extracted from index.ts — registers the `edit` tool. */
33
315
  export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
34
316
  // 7. Tool: `edit` (Unified Surgical Diff, Smart Anchor, & Multi-Block Editor - Replaces stock edit tool)
@@ -65,21 +347,36 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
65
347
  lines: Type.Optional(Type.Array(Type.String(), { description: "Replacement lines (empty to delete)" })),
66
348
  })
67
349
  : Type.Object({
68
- path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
69
- search: Type.Optional(Type.String({ description: "Exact text block to replace" })),
70
- replace: Type.Optional(Type.String({ description: "Replacement text block" })),
71
- line_hint: Type.Optional(Type.Number({ description: "Optional line number hint for disambiguation" })),
350
+ path: Type.Optional(Type.String({ description: "Path to file to edit" })),
351
+ search: Type.Optional(Type.String({ description: "Exact block to replace" })),
352
+ replace: Type.Optional(Type.String({ description: "Replacement text" })),
353
+ line_hint: Type.Optional(Type.Number({ description: "Line hint for disambiguation" })),
72
354
  edits: Type.Optional(
73
355
  Type.Array(
74
356
  Type.Object(
75
357
  {
76
- search: Type.Optional(Type.String({ description: "Exact text block to replace" })),
77
- replace: Type.Optional(Type.String({ description: "Replacement text block" })),
78
- line_hint: Type.Optional(Type.Number({ description: "Optional line hint" })),
358
+ search: Type.Optional(Type.String()),
359
+ replace: Type.Optional(Type.String()),
360
+ line_hint: Type.Optional(Type.Number()),
79
361
  },
80
362
  { additionalProperties: true },
81
363
  ),
82
- { description: "One or more targeted replacements" },
364
+ { description: "Targeted replacements" },
365
+ ),
366
+ ),
367
+ files: Type.Optional(
368
+ Type.Array(
369
+ Type.Object(
370
+ {
371
+ path: Type.String(),
372
+ search: Type.Optional(Type.String()),
373
+ replace: Type.Optional(Type.String()),
374
+ line_hint: Type.Optional(Type.Number()),
375
+ edits: Type.Optional(Type.Array(Type.Any())),
376
+ },
377
+ { additionalProperties: true },
378
+ ),
379
+ { description: "Multi-file edits" },
83
380
  ),
84
381
  ),
85
382
  }, { additionalProperties: true });
@@ -94,9 +391,9 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
94
391
  : benchmarkMethod === "search-replace"
95
392
  ? "Edit code with a unique exact search block and replacement block only."
96
393
  : benchmarkMethod === "adaptive"
97
- ? "Edit code with a unique search/replace block or numeric line range; use search first and line range if needed."
98
- : "Edit code using exact search/replace blocks (with optional line_hint for disambiguation), or multi-block edits via 'edits'. Includes syntax pre-validation and delimiter balancing.",
99
- promptSnippet: "Edit code using search/replace blocks (with optional line_hint) or multi-block 'edits'",
394
+ ? "Edit code with search/replace or line range; use search first."
395
+ : "Edit code with exact search/replace blocks (optional line_hint), multi-block 'edits', or multi-file 'files'. Auto-heals syntax.",
396
+ promptSnippet: "Edit code using search/replace (optional line_hint), multi-block 'edits', or multi-file 'files'",
100
397
  renderShell: "default",
101
398
  parameters: editToolParameters,
102
399
  async execute(
@@ -106,342 +403,176 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
106
403
  onUpdate: any,
107
404
  ctx: any,
108
405
  ): Promise<any> {
109
- if (!params || typeof params !== "object" || !params.path) {
110
- return {
111
- content: [
112
- {
113
- type: "text",
114
- text: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.`,
115
- },
116
- ],
117
- isError: true,
118
- };
406
+ // Check for multi-file payload
407
+ const fileEdits: any[] = [];
408
+ if (params && typeof params === "object") {
409
+ if (Array.isArray(params.files) && params.files.length > 0) {
410
+ for (const f of params.files) {
411
+ if (f && typeof f === "object" && typeof f.path === "string") {
412
+ fileEdits.push(f);
413
+ }
414
+ }
415
+ } else if (Array.isArray(params.edits) && params.edits.length > 0 && params.edits.some((e: any) => e && typeof e.path === "string")) {
416
+ for (const e of params.edits) {
417
+ if (e && typeof e === "object" && typeof e.path === "string") {
418
+ fileEdits.push(e);
419
+ }
420
+ }
421
+ }
119
422
  }
120
423
 
121
- const resolvedPath = resolveUserPath(params.path, ctx.cwd);
122
-
123
- // 1. Read-Before-Write Epistemic Guard Check
124
- const config = deps.getConfig?.(ctx.cwd) ?? loadKernelConfig(ctx.cwd);
125
- const searchBlocks: string[] = [];
126
- const targetRanges: EvidenceRange[] = [];
127
- let anchorBlocks: SmartAnchorEditBlock[] = [];
128
- let anchorPreflight: ReturnType<typeof preflightSmartAnchorEdits> | undefined;
129
-
130
- const hasSingleAnchor =
131
- (params.pos !== undefined || params.start_line !== undefined) &&
132
- Array.isArray(params.lines);
133
- const hasAnchorEdits =
134
- Array.isArray(params.edits) &&
135
- params.edits.length > 0 &&
136
- params.edits.some(
137
- (e: any) =>
138
- e &&
139
- (e.pos !== undefined ||
140
- e.start_line !== undefined ||
141
- (Array.isArray(e.lines) && typeof e.search !== "string")),
142
- );
143
- const isAnchorMode = hasSingleAnchor || hasAnchorEdits;
424
+ // Multi-file atomic execution
425
+ if (fileEdits.length > 0) {
426
+ // Check for duplicate canonical paths
427
+ const seenPaths = new Set<string>();
428
+ for (const item of fileEdits) {
429
+ if (!item || typeof item !== "object" || !item.path) {
430
+ return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true };
431
+ }
432
+ const canonical = resolveUserPath(item.path, ctx.cwd);
433
+ if (seenPaths.has(canonical)) {
434
+ return {
435
+ content: [{ type: "text", text: `[EDIT ERROR] Duplicate target path in multi-file edit: '${item.path}'.` }],
436
+ isError: true,
437
+ };
438
+ }
439
+ seenPaths.add(canonical);
440
+ }
144
441
 
145
- const hasSingleBlock =
146
- typeof params.search === "string" && typeof params.replace === "string";
147
- const hasMultiBlock = Array.isArray(params.edits) && params.edits.length > 0;
442
+ onUpdate?.({
443
+ content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }],
444
+ });
148
445
 
149
- if (benchmarkMethod === "adaptive" && !isAnchorMode && !hasSingleBlock) {
150
- return {
151
- content: [{ type: "text", text: "[EDIT ERROR] Adaptive mode requires search/replace or a numeric/hashed line range." }],
152
- isError: true,
153
- };
154
- }
446
+ // Step 1: Preflight ALL files atomically
447
+ const preparedList: PreparedFileEdit[] = [];
448
+ for (const item of fileEdits) {
449
+ const preflight = preflightFileEdit(item, ctx, deps, benchmarkMethod);
450
+ if (preflight.error || !preflight.prepared) {
451
+ return {
452
+ content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
453
+ isError: true,
454
+ };
455
+ }
456
+ preparedList.push(preflight.prepared);
457
+ }
155
458
 
156
- if (!isAnchorMode && !hasSingleBlock && !hasMultiBlock) {
157
- return {
158
- content: [
159
- {
160
- type: "text",
161
- text: "[EDIT ERROR] Must provide either smart anchors ('pos' and 'lines', or 'edits' with anchors) or 'search' and 'replace' blocks.",
162
- },
163
- ],
164
- isError: true,
165
- };
166
- }
459
+ // Step 2: Backup snapshots of all files for rollback
460
+ const originalSnapshots = new Map<string, string>();
461
+ for (const prep of preparedList) {
462
+ try {
463
+ originalSnapshots.set(prep.resolvedPath, fs.readFileSync(prep.resolvedPath, "utf8"));
464
+ } catch (err: any) {
465
+ return {
466
+ content: [{ type: "text", text: `[EDIT FAILED] Unable to snapshot '${prep.relPath}' for atomic write: ${err.message}` }],
467
+ isError: true,
468
+ };
469
+ }
470
+ }
167
471
 
168
- // Standardize edits payload (support old_text/new_text, oldText/newText, and old/new aliases)
169
- if (Array.isArray(params.edits)) {
170
- params.edits = params.edits.map((e: any) => {
171
- if (!e || typeof e !== "object") return e;
172
- const search = e.search ?? e.oldText ?? e.old_text ?? e.old;
173
- const replace = e.replace ?? e.newText ?? e.new_text ?? e.new;
174
- return {
175
- ...e,
176
- search,
177
- replace,
178
- };
472
+ // Step 3: Apply mutations with rollback guard
473
+ onUpdate?.({
474
+ content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }],
179
475
  });
180
- }
181
476
 
182
- if (isAnchorMode) {
183
- if (hasSingleAnchor) {
184
- anchorBlocks = [
185
- {
186
- pos: params.pos ?? params.start_line,
187
- end: params.end ?? params.end_line,
188
- lines: params.lines,
189
- },
190
- ];
191
- } else {
192
- anchorBlocks = params.edits;
193
- }
477
+ const outcomes: any[] = [];
478
+ const mutatedPaths: string[] = [];
479
+ let failureEncountered = false;
480
+ let failureReason = "";
194
481
 
195
- let fileContent: string;
196
- try {
197
- fileContent = fs.readFileSync(resolvedPath, "utf8");
198
- } catch (err: any) {
199
- return {
200
- content: [{ type: "text", text: `[EDIT ERROR] Unable to read '${params.path}': ${err.message}` }],
201
- isError: true,
202
- };
482
+ for (const prepared of preparedList) {
483
+ try {
484
+ const outcome = await applyPreparedEdit(prepared, ctx, deps);
485
+ outcomes.push(outcome);
486
+ mutatedPaths.push(prepared.resolvedPath);
487
+ if (!outcome.success) {
488
+ failureEncountered = true;
489
+ failureReason = outcome.error || outcome.statusText || "Verification failed";
490
+ break;
491
+ }
492
+ } catch (writeErr: any) {
493
+ failureEncountered = true;
494
+ failureReason = writeErr.message;
495
+ break;
496
+ }
203
497
  }
204
498
 
205
- anchorPreflight = preflightSmartAnchorEdits(fileContent, anchorBlocks);
206
- if (!anchorPreflight.success) {
207
- return {
208
- content: [{ type: "text", text: anchorPreflight.error || "[EDIT FAILED] Invalid anchor edit." }],
209
- isError: true,
210
- };
211
- }
212
- if (anchorPreflight.targetRanges) {
213
- targetRanges.push(...anchorPreflight.targetRanges);
214
- }
215
- } else if (hasSingleBlock) {
216
- searchBlocks.push(params.search);
217
- const singleOpt = {
218
- startLine: params.start_line,
219
- endLine: params.end_line,
220
- lineHint: params.line_hint,
221
- };
222
- const preflight = preflightSurgicalPatchBlock(resolvedPath, params.search, singleOpt);
223
- if (!preflight.success) {
224
- if (preflight.isAmbiguous) {
225
- return {
226
- content: [
227
- {
228
- type: "text",
229
- text: `[EDIT FAILED] Ambiguous Search Block: ${preflight.error} Please provide more surrounding context lines to make the match unique.`,
230
- },
231
- ],
232
- isError: true,
233
- };
499
+ // Rollback if any write or verification failed
500
+ if (failureEncountered) {
501
+ for (const mutated of mutatedPaths) {
502
+ const backup = originalSnapshots.get(mutated);
503
+ if (backup !== undefined) {
504
+ try {
505
+ fs.writeFileSync(mutated, backup, "utf8");
506
+ } catch (rbErr) {
507
+ kernelDebug(rbErr);
508
+ }
509
+ }
234
510
  }
235
511
  return {
236
- content: [
237
- {
238
- type: "text",
239
- text: `[EDIT FAILED] Search Block Not Found in '${params.path}'. Check line context and try again.`,
240
- },
241
- ],
512
+ content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and rolled back: ${failureReason}` }],
242
513
  isError: true,
243
514
  };
244
515
  }
245
- if (preflight.targetRange) targetRanges.push(preflight.targetRange);
246
- } else {
247
- // Multi-block patching reports ranges after applying blocks; preflight
248
- // uses the original file's coordinates for each search block.
249
- for (let i = 0; i < params.edits.length; i++) {
250
- const block = params.edits[i];
251
- if (!block || typeof block.search !== "string") continue;
252
- searchBlocks.push(block.search);
253
- const blockOpt = {
254
- startLine: block.start_line,
255
- endLine: block.end_line,
256
- lineHint: block.line_hint,
257
- };
258
- const preflight = preflightSurgicalPatchBlock(resolvedPath, block.search, blockOpt);
259
- if (!preflight.success) {
260
- if (preflight.isAmbiguous) {
261
- return {
262
- content: [
263
- {
264
- type: "text",
265
- text: `[EDIT FAILED] Block ${i + 1}/${params.edits.length} is ambiguous: ${preflight.error} Please provide more surrounding context lines.`,
266
- },
267
- ],
268
- isError: true,
269
- };
270
- }
271
- return {
272
- content: [
273
- {
274
- type: "text",
275
- text: `[EDIT FAILED] Block ${i + 1}/${params.edits.length} not found in '${params.path}'. Check line context and try again.`,
276
- },
277
- ],
278
- isError: true,
279
- };
280
- }
281
- if (preflight.targetRange) targetRanges.push(preflight.targetRange);
282
- }
283
- }
284
- const epistemicCheck = globalEpistemicGuard.checkReadPrecondition(
285
- resolvedPath,
286
- "edit",
287
- deps.getSessionId(ctx),
288
- ctx.cwd,
289
- config?.safety?.enable_epistemic_guard ?? true,
290
- targetRanges,
291
- searchBlocks,
292
- );
293
- if (!epistemicCheck.allowed) {
516
+
517
+ const affectedPaths = preparedList.map((p) => p.relPath);
294
518
  return {
295
- content: [
296
- {
297
- type: "text",
298
- text:
299
- epistemicCheck.reason || "[ERROR] Epistemic read pre-condition failed.",
300
- },
301
- ],
302
- isError: true,
519
+ content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
520
+ details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
303
521
  };
304
522
  }
305
523
 
306
- onUpdate?.({
307
- content: [{ type: "text", text: `Editing ${params.path}...` }],
308
- });
309
-
310
- let patchRes: ReturnType<typeof applySurgicalPatch>;
311
- if (isAnchorMode) {
312
- patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
313
- } else if (hasMultiBlock) {
314
- patchRes = applyMultiBlockPatch(resolvedPath, params.edits);
315
- } else if (hasSingleBlock) {
316
- const singleOpt = {
317
- startLine: params.start_line,
318
- endLine: params.end_line,
319
- lineHint: params.line_hint,
320
- };
321
- patchRes = applySurgicalPatch(resolvedPath, params.search, params.replace, singleOpt);
322
- } else {
524
+ // Single-file execution
525
+ const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
526
+ if (preflight.error || !preflight.prepared) {
323
527
  return {
324
- content: [{ type: "text", text: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` }],
528
+ content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
325
529
  isError: true,
326
530
  };
327
531
  }
328
532
 
329
- if (!patchRes.success) {
533
+ onUpdate?.({
534
+ content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }],
535
+ });
536
+
537
+ const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps);
538
+ if (!outcome.success && outcome.error) {
330
539
  return {
331
- content: [
332
- {
333
- type: "text",
334
- text: renderEditFailure(patchRes.error || "patch failed"),
335
- },
336
- ],
337
- details: { error: patchRes.error, success: false },
540
+ content: [{ type: "text", text: outcome.error }],
541
+ details: { success: false },
338
542
  isError: true,
339
543
  };
340
544
  }
341
545
 
342
- // Read back the exact content as written to disk
343
- let diskContent: string;
344
- try {
345
- diskContent = fs.readFileSync(resolvedPath, "utf8");
346
- } catch {
347
- diskContent = "";
348
- }
349
-
350
- // Calculate net line count difference from the edit blocks
351
- let deltaLines = 0;
352
- if (isAnchorMode && anchorPreflight?.resolvedSpans) {
353
- for (const span of anchorPreflight.resolvedSpans) {
354
- const deletedCount = span.endLine - span.startLine + 1;
355
- deltaLines += span.replacementLines.length - deletedCount;
356
- }
357
- } else if (hasSingleBlock) {
358
- const searchLines = params.search.replace(/\r\n/g, "\n").split("\n").length;
359
- const replaceLines = params.replace.replace(/\r\n/g, "\n").split("\n").length;
360
- deltaLines = replaceLines - searchLines;
361
- } else if (hasMultiBlock) {
362
- for (const block of params.edits) {
363
- if (block && typeof block.search === "string" && typeof block.replace === "string") {
364
- const sLines = block.search.replace(/\r\n/g, "\n").split("\n").length;
365
- const rLines = block.replace.replace(/\r\n/g, "\n").split("\n").length;
366
- deltaLines += (rLines - sLines);
367
- }
368
- }
369
- }
370
-
371
- // Update the Epistemic Guard ledger with the freshly written file snapshot.
372
- // This maintains authorization for subsequent edits in the same session without
373
- // forcing redundant reads, while preserving strict protection against external file drift.
374
- globalEpistemicGuard.recordFileMutation(
375
- resolvedPath,
376
- deps.getSessionId(ctx),
377
- ctx.cwd,
378
- diskContent,
379
- {
380
- targetRanges: patchRes.targetRanges || targetRanges,
381
- deltaLines,
382
- },
383
- );
384
-
385
- // The file was mutated even when post-edit diagnostics later report a
386
- // problem; never leave the search index serving its pre-edit content.
387
- deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
388
-
389
- // Verify locally first. Reuse an already-ready LSP client only; edit
390
- // verification must not spawn a server or trigger broad analysis.
391
- const readyLsp = LspManager.getInstance().getReadyClientForFile(
392
- resolvedPath,
393
- ctx.cwd,
394
- );
395
-
396
- // Synchronize LSP client in-memory buffer with the newly patched file
397
- if (readyLsp && readyLsp.getState() === "ready") {
398
- try {
399
- await readyLsp.changeDocument(resolvedPath, diskContent);
400
- await readyLsp.saveDocument(resolvedPath, diskContent);
401
- } catch (err) {
402
- kernelDebug(err);
403
- }
404
- }
405
- const verification = await verifyEditedFile(
406
- resolvedPath,
407
- readyLsp
408
- ? async () => {
409
- const result = await readyLsp.getDiagnosticsResult(resolvedPath);
410
- return {
411
- state: result.status,
412
- findings: result.diagnostics.map((finding) => ({
413
- line: finding.range.start.line + 1,
414
- column: finding.range.start.character + 1,
415
- message: finding.message,
416
- severity:
417
- finding.severity === 1
418
- ? ("error" as const)
419
- : finding.severity === 2
420
- ? ("warning" as const)
421
- : ("info" as const),
422
- })),
423
- };
424
- }
425
- : undefined,
426
- );
427
-
428
- const relPath = path.relative(ctx.cwd, resolvedPath) || resolvedPath;
429
- const statusText = renderPostEditVerification(verification, undefined, relPath);
430
546
  return {
431
- content: statusText ? [{ type: "text", text: statusText }] : [],
547
+ content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [],
432
548
  details: {
433
- strategy: patchRes.strategy,
434
- verification,
435
- success: verification.syntax.state === "clean",
549
+ strategy: outcome.strategy,
550
+ verification: outcome.verification,
551
+ success: outcome.verification?.syntax?.state === "clean",
436
552
  },
437
553
  isError:
438
- verification.syntax.state === "failed" ||
439
- verification.diagnostic.findings.some(
440
- (finding) => finding.severity === "error" || !finding.severity,
554
+ outcome.verification?.syntax?.state === "failed" ||
555
+ outcome.verification?.diagnostic?.findings?.some(
556
+ (finding: any) => finding.severity === "error" || !finding.severity,
441
557
  ),
442
558
  };
443
559
  },
444
560
  renderCall(args: any, theme: any, context: any) {
561
+ const fileEdits: string[] = [];
562
+ if (Array.isArray(args?.files)) {
563
+ for (const f of args.files) {
564
+ if (f?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path);
565
+ }
566
+ } else if (Array.isArray(args?.edits) && args.edits.some((e: any) => e?.path)) {
567
+ for (const e of args.edits) {
568
+ if (e?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path);
569
+ }
570
+ }
571
+ if (fileEdits.length > 0) {
572
+ return makeOutputText(
573
+ `${theme.fg("toolTitle", theme.bold("edit"))} [${theme.fg("accent", fileEdits.join(", "))}]`,
574
+ );
575
+ }
445
576
  const rawPath = args?.path || "";
446
577
  const relPath = rawPath
447
578
  ? path.relative(context.cwd, rawPath) || rawPath
@@ -97,17 +97,24 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
97
97
  : benchmarkMethod === "search-replace"
98
98
  ? "Read source text for exact search/replace edits."
99
99
  : benchmarkMethod === "adaptive"
100
- ? "Read bounded source with plain line numbers. Prefer unique search/replace; use numeric ranges when needed; request anchors only for uncertain targets."
101
- : "Read file contents (clean plain text by default) or extract a specific symbol via 'symbol'. Broad reads capped at 2,000 lines or 50KB. Use 'offset' and 'limit' to inspect specific line ranges.",
102
- promptSnippet: "Read file contents (clean plain text), inspect line ranges via offset/limit, or extract AST symbols via 'symbol'",
100
+ ? "Read source with line numbers. Prefer unique search/replace; use line ranges when needed."
101
+ : "Read file contents (plain text), extract a symbol via 'symbol', or read multiple files via 'paths'. Bounded at 2,000 lines or 50KB. Use 'offset'/'limit' for ranges.",
102
+ promptSnippet: "Read file contents, inspect line ranges, extract symbols, or read multiple files via 'paths'",
103
103
  renderShell: "default",
104
104
  parameters: Type.Object({
105
- path: Type.String({
106
- description: "File path (relative or absolute)",
107
- }),
105
+ path: Type.Optional(
106
+ Type.String({
107
+ description: "File path (relative or absolute). For multiple files, use 'paths'",
108
+ }),
109
+ ),
110
+ paths: Type.Optional(
111
+ Type.Array(Type.String(), {
112
+ description: "Read multiple files in one turn",
113
+ }),
114
+ ),
108
115
  symbol: Type.Optional(
109
116
  Type.String({
110
- description: "Top-level function, class, or type name to extract (omit for plain files or object keys)",
117
+ description: "Function, class, or type to extract",
111
118
  }),
112
119
  ),
113
120
  offset: Type.Optional(
@@ -122,17 +129,17 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
122
129
  ),
123
130
  surrounding_lines: Type.Optional(
124
131
  Type.Number({
125
- description: "Extra surrounding context lines for symbol (default: 0)",
132
+ description: "Extra surrounding context lines for symbol",
126
133
  }),
127
134
  ),
128
135
  anchors: Type.Optional(
129
136
  Type.Boolean({
130
- description: "Optional: format lines with LINE#HASH│ anchors (default: false, plain text)",
137
+ description: "Narrow ranges (<100 lines) with LINE#HASH│ anchors (default: false, plain text)",
131
138
  }),
132
139
  ),
133
140
  raw: Type.Optional(
134
141
  Type.Boolean({
135
- description: "Output clean raw text without line numbers or anchors",
142
+ description: "Clean raw text without line numbers or anchors",
136
143
  }),
137
144
  ),
138
145
  }),
@@ -143,15 +150,113 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
143
150
  onUpdate: any,
144
151
  ctx: any,
145
152
  ): Promise<any> {
146
- if (!params || typeof params !== "object" || !params.path) {
153
+ let targetPaths: string[] = [];
154
+ if (params && typeof params === "object") {
155
+ if (Array.isArray(params.paths)) {
156
+ targetPaths = params.paths.filter((p: any) => typeof p === "string" && p.trim().length > 0);
157
+ } else if (typeof params.paths === "string" && params.paths.trim().length > 0) {
158
+ targetPaths = [params.paths.trim()];
159
+ } else if (Array.isArray(params.path)) {
160
+ targetPaths = params.path.filter((p: any) => typeof p === "string" && p.trim().length > 0);
161
+ } else if (typeof params.path === "string" && params.path.trim().length > 0) {
162
+ targetPaths = [params.path.trim()];
163
+ }
164
+ }
165
+
166
+ if (targetPaths.length === 0) {
147
167
  return {
148
168
  content: [
149
- { type: "text", text: "[READ ERROR] Missing required 'path' parameter." },
169
+ { type: "text", text: "[READ ERROR] Missing required 'path' or 'paths' parameter." },
150
170
  ],
151
171
  isError: true,
152
172
  };
153
173
  }
154
174
 
175
+ // Batch mode: multiple files in one turn
176
+ if (targetPaths.length > 1) {
177
+ const MAX_BATCH_PATHS = 20;
178
+ const MAX_BATCH_BYTES = 24 * 1024; // 24KB aggregate ceiling across batch
179
+ const MAX_BATCH_FILE_LINES = 150; // max 150 lines per file in batch mode
180
+ const pathsToRead = targetPaths.slice(0, MAX_BATCH_PATHS);
181
+ const results: string[] = [];
182
+ const detailsList: any[] = [];
183
+ let hasAnySuccess = false;
184
+ let cumulativeBytes = 0;
185
+
186
+ for (let i = 0; i < pathsToRead.length; i++) {
187
+ const filePath = pathsToRead[i];
188
+ if (cumulativeBytes >= MAX_BATCH_BYTES) {
189
+ results.push(`[...] Remaining ${pathsToRead.length - i} file(s) skipped: batch byte limit reached (24KB) [...]`);
190
+ break;
191
+ }
192
+ const resolvedPath = resolveUserPath(filePath, ctx.cwd);
193
+ const relPath = path.relative(ctx.cwd, resolvedPath) || filePath;
194
+ if (!fs.existsSync(resolvedPath)) {
195
+ results.push(`=== file: ${relPath} ===\nFile not found: ${filePath}`);
196
+ continue;
197
+ }
198
+ try {
199
+ const content = fs.readFileSync(resolvedPath, "utf-8");
200
+ const lines = content.split("\n");
201
+ const totalLines = lines.length;
202
+ const fileOffset = params.offset && params.offset > 0 ? params.offset : 1;
203
+ const fileLimit = params.limit ? Math.min(params.limit, MAX_BATCH_FILE_LINES) : MAX_BATCH_FILE_LINES;
204
+ const startIdx = Math.max(0, fileOffset - 1);
205
+ const endIdx = Math.min(totalLines, startIdx + fileLimit);
206
+
207
+ const numberWidth = String(totalLines).length;
208
+ // Batch reads are always plain text to protect token budgets
209
+ const formatLine = (index: number) => formatReadLine(lines, index, false, numberWidth, benchmarkMethod);
210
+ const visibleIndexes = selectReadLineIndexes(lines, startIdx, endIdx, formatLine);
211
+ const outputLines = visibleIndexes.map(formatLine);
212
+ const isTruncated = (startIdx + visibleIndexes.length) < totalLines || startIdx > 0;
213
+ if (isTruncated) {
214
+ outputLines.push(`[truncated: ${relPath}, returned lines ${startIdx + 1}-${startIdx + visibleIndexes.length} of ${totalLines}. Continue with read(path, offset=${startIdx + visibleIndexes.length + 1})]`);
215
+ }
216
+
217
+ globalEpistemicGuard.recordFileRead(
218
+ resolvedPath,
219
+ deps.getSessionId(ctx),
220
+ ctx.cwd,
221
+ content,
222
+ {
223
+ coverage: {
224
+ complete: !isTruncated,
225
+ ranges: lineRanges(visibleIndexes),
226
+ totalLines,
227
+ },
228
+ provenance: "read",
229
+ },
230
+ );
231
+
232
+ const formattedOutput = `=== file: ${relPath} (${totalLines} lines) ===\n${outputLines.join("\n")}`;
233
+ cumulativeBytes += Buffer.byteLength(formattedOutput, "utf8");
234
+ results.push(formattedOutput);
235
+ detailsList.push({ path: filePath, totalLines, shownLines: visibleIndexes.length, truncated: isTruncated });
236
+ hasAnySuccess = true;
237
+
238
+ if (cumulativeBytes >= MAX_BATCH_BYTES && i < pathsToRead.length - 1) {
239
+ results.push(`[...] Remaining ${pathsToRead.length - 1 - i} file(s) skipped: batch byte limit reached (24KB) [...]`);
240
+ break;
241
+ }
242
+ } catch (err: any) {
243
+ results.push(`=== file: ${relPath} ===\nError reading file: ${err.message}`);
244
+ }
245
+ }
246
+
247
+ if (targetPaths.length > MAX_BATCH_PATHS) {
248
+ results.push(`[...] Note: Truncated to first ${MAX_BATCH_PATHS} files (${targetPaths.length - MAX_BATCH_PATHS} omitted).`);
249
+ }
250
+
251
+ return {
252
+ content: [{ type: "text", text: results.join("\n\n") }],
253
+ details: { batch: true, count: pathsToRead.length, files: detailsList },
254
+ isError: !hasAnySuccess,
255
+ };
256
+ }
257
+
258
+ // Single file read
259
+ params.path = targetPaths[0];
155
260
  const resolvedPath = resolveUserPath(params.path, ctx.cwd);
156
261
  if (!fs.existsSync(resolvedPath)) {
157
262
  return {
@@ -389,11 +494,21 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
389
494
  isError: true,
390
495
  };
391
496
  }
392
- const endIdx = Math.min(totalLines, startIdx + limit);
393
497
  const config = deps.getConfig?.(ctx.cwd);
394
498
  const defaultAnchors = config?.editing?.default_anchors ?? true;
395
499
  const configuredReadMode = readMode ?? config?.editing?.read_mode ?? "auto";
396
500
  const useAnchors = shouldUseAnchors(params, benchmarkMethod, configuredReadMode, defaultAnchors, false);
501
+
502
+ // Guardrail against excessive anchored line bloat
503
+ const MAX_ANCHOR_LINES = 100;
504
+ let effectiveLimit = limit;
505
+ let anchorNotice = "";
506
+ if (useAnchors && effectiveLimit > MAX_ANCHOR_LINES) {
507
+ effectiveLimit = MAX_ANCHOR_LINES;
508
+ anchorNotice = `\n[Notice: Anchored read capped to 100 lines to prevent token bloat. For broader inspection, use plain read without 'anchors'.]`;
509
+ }
510
+ const endIdx = Math.min(totalLines, startIdx + effectiveLimit);
511
+
397
512
  const numberWidth = String(totalLines).length;
398
513
  const formatLine = (index: number) => formatReadLine(lines, index, useAnchors, numberWidth, benchmarkMethod);
399
514
  const firstLineBytes = Buffer.byteLength(formatLine(startIdx), "utf8");
@@ -407,6 +522,9 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
407
522
  if (hiddenLines > 0 && !oversizedFirstLine) {
408
523
  outputLines.push(`[...] ${hiddenLines} lines omitted [...]. Use offset=${startIdx + visibleIndexes.length + 1} to continue.`);
409
524
  }
525
+ if (anchorNotice) {
526
+ outputLines.push(anchorNotice);
527
+ }
410
528
  const isTruncated = oversizedFirstLine || hasMore || startIdx > 0;
411
529
  if (isTruncated && hasMore && !oversizedFirstLine && hiddenLines === 0) {
412
530
  const lastShown = visibleIndexes[visibleIndexes.length - 1]! + 1;
@@ -443,7 +561,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
443
561
  }
444
562
  },
445
563
  renderCall(args: any, theme: any, context: any) {
446
- const rawPath = args?.path || "";
564
+ const targetPaths = Array.isArray(args?.paths) ? args.paths : (Array.isArray(args?.path) ? args.path : []);
565
+ if (targetPaths.length > 1) {
566
+ const pathsSummary = targetPaths.map((p: string) => path.relative(context.cwd, p) || p).join(", ");
567
+ return makeOutputText(
568
+ `${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`,
569
+ );
570
+ }
571
+ const rawPath = args?.path || (Array.isArray(args?.paths) ? args.paths[0] : "") || "";
447
572
  const relPath = rawPath
448
573
  ? path.relative(context.cwd, rawPath) || rawPath
449
574
  : "";