@floydous/pi-agent-kernel 0.1.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/LICENSE +15 -0
- package/README.md +108 -0
- package/config.toml +24 -0
- package/docs/README.md +22 -0
- package/docs/architecture.md +40 -0
- package/docs/configuration.md +43 -0
- package/docs/editing-and-verification.md +41 -0
- package/docs/lsp.md +31 -0
- package/docs/retrieval.md +42 -0
- package/docs/testing.md +32 -0
- package/package.json +48 -0
- package/src/config/index.ts +2 -0
- package/src/config/kernel_config.ts +218 -0
- package/src/config/toml.ts +237 -0
- package/src/context/session_repair.ts +99 -0
- package/src/dedup/content_store.ts +365 -0
- package/src/dedup/recall_tool.ts +157 -0
- package/src/editing/patch.ts +482 -0
- package/src/editing/post_edit_verification.ts +200 -0
- package/src/editing/syntax-verify.ts +353 -0
- package/src/index.ts +852 -0
- package/src/lsp/adapters/base.ts +42 -0
- package/src/lsp/adapters/index.ts +21 -0
- package/src/lsp/adapters/python.ts +37 -0
- package/src/lsp/adapters/rust.ts +35 -0
- package/src/lsp/adapters/typescript.ts +40 -0
- package/src/lsp/index.ts +13 -0
- package/src/lsp/lsp_client.ts +650 -0
- package/src/lsp/lsp_detector.ts +52 -0
- package/src/lsp/lsp_formatter.ts +284 -0
- package/src/lsp/lsp_installer.ts +604 -0
- package/src/lsp/lsp_manager.ts +202 -0
- package/src/lsp/lsp_modal.ts +675 -0
- package/src/lsp/lsp_registry.ts +539 -0
- package/src/lsp/lsp_types.ts +143 -0
- package/src/retrieval/ast_search.ts +926 -0
- package/src/retrieval/repomap.ts +779 -0
- package/src/retrieval/search_bm25.ts +190 -0
- package/src/retrieval/search_chunker.ts +251 -0
- package/src/retrieval/search_config.ts +162 -0
- package/src/retrieval/search_embedder.ts +362 -0
- package/src/retrieval/search_index.ts +753 -0
- package/src/retrieval/search_modal.ts +358 -0
- package/src/retrieval/symbol_reader.ts +200 -0
- package/src/safety/atomic_write.ts +26 -0
- package/src/safety/epistemic_guard.ts +733 -0
- package/src/safety/kernel_debug.ts +15 -0
- package/src/safety/output_clamper.ts +213 -0
- package/src/tools/ast_search_tool.ts +131 -0
- package/src/tools/code_search_tool.ts +147 -0
- package/src/tools/context.ts +20 -0
- package/src/tools/edit_tool.ts +288 -0
- package/src/tools/lsp_tool.ts +813 -0
- package/src/tools/read_tool.ts +348 -0
- package/src/tools/repo_map_tool.ts +57 -0
- package/src/ui/footer.ts +287 -0
- package/src/ui/tui_utils.ts +278 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// Recall Tool
|
|
2
|
+
// Dereferences a [=rN,sizeB,tool,paramsKey] dedup notice back to the full
|
|
3
|
+
// original tool-result text. No preamble, no formatting — bare bytes only.
|
|
4
|
+
|
|
5
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { Type } from "typebox";
|
|
7
|
+
import { Text, makeOutputText } from "../ui/tui_utils";
|
|
8
|
+
import type { DedupStore } from "./content_store";
|
|
9
|
+
import type { SessionDeps } from "../tools/context";
|
|
10
|
+
|
|
11
|
+
export interface RecallDeps extends SessionDeps {
|
|
12
|
+
getDedupStore: () => DedupStore;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RecallEntry {
|
|
16
|
+
fullText: string;
|
|
17
|
+
sizeBytes: number;
|
|
18
|
+
toolName: string;
|
|
19
|
+
paramsKey: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Pure decision logic. Extracted from the tool so it can be unit-tested
|
|
24
|
+
* without the Pi extension harness.
|
|
25
|
+
*
|
|
26
|
+
* Returns one of:
|
|
27
|
+
* - { kind: "ok", fullText, sizeBytes, toolName, paramsKey }
|
|
28
|
+
* - { kind: "error", message } (validation failure or unknown ref)
|
|
29
|
+
*/
|
|
30
|
+
export function decideRecall(
|
|
31
|
+
ref: unknown,
|
|
32
|
+
store: {
|
|
33
|
+
get: (sessionId: string, ref: string) => RecallEntry | null;
|
|
34
|
+
},
|
|
35
|
+
sessionId: string,
|
|
36
|
+
):
|
|
37
|
+
| { kind: "ok"; fullText: string; sizeBytes: number; toolName: string; paramsKey: string }
|
|
38
|
+
| { kind: "error"; message: string } {
|
|
39
|
+
const refStr = typeof ref === "string" ? ref.trim() : "";
|
|
40
|
+
if (!refStr) {
|
|
41
|
+
return { kind: "error", message: "[recall] ref is required (e.g. 'r1')." };
|
|
42
|
+
}
|
|
43
|
+
if (!/^r\d+$/.test(refStr)) {
|
|
44
|
+
return {
|
|
45
|
+
kind: "error",
|
|
46
|
+
message: `[recall] invalid ref '${refStr}'; expected format 'rN' where N is a positive integer.`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const got = store.get(sessionId, refStr);
|
|
50
|
+
if (got === null) {
|
|
51
|
+
return {
|
|
52
|
+
kind: "error",
|
|
53
|
+
message: `[recall] no content stored at ref '${refStr}' in this session.`,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
kind: "ok",
|
|
58
|
+
fullText: got.fullText,
|
|
59
|
+
sizeBytes: got.sizeBytes,
|
|
60
|
+
toolName: got.toolName,
|
|
61
|
+
paramsKey: got.paramsKey,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Extracted pattern: registers the `recall` tool. */
|
|
66
|
+
export function registerRecallTool(pi: ExtensionAPI, deps: RecallDeps): void {
|
|
67
|
+
pi.registerTool({
|
|
68
|
+
name: "recall",
|
|
69
|
+
label: "Recall Dedup'd Result",
|
|
70
|
+
description:
|
|
71
|
+
"Retrieve the full text of a tool result that was replaced by a dedup reference like [=rN,sizeB,tool,paramsKey]. The `ref` is the rN identifier from a prior tool result. Returns the bare original text and the tool name and paramsKey so the caller can decide what to do next.",
|
|
72
|
+
promptSnippet:
|
|
73
|
+
"Recover the full text of a tool result that was dedup'd, by its rN reference",
|
|
74
|
+
renderShell: "default",
|
|
75
|
+
parameters: Type.Object({
|
|
76
|
+
ref: Type.String({
|
|
77
|
+
description:
|
|
78
|
+
"The reference identifier, e.g. 'r1', 'r2'. Comes from a [=rN,sizeB,tool,paramsKey] dedup notice in a prior tool result.",
|
|
79
|
+
}),
|
|
80
|
+
}),
|
|
81
|
+
async execute(
|
|
82
|
+
_toolCallId: string,
|
|
83
|
+
params: any,
|
|
84
|
+
_signal: any,
|
|
85
|
+
_onUpdate: any,
|
|
86
|
+
ctx: any,
|
|
87
|
+
): Promise<any> {
|
|
88
|
+
const ref = (params?.ref || "").trim();
|
|
89
|
+
if (!ref) {
|
|
90
|
+
return {
|
|
91
|
+
content: [
|
|
92
|
+
{ type: "text", text: "[recall] ref is required (e.g. 'r1')." },
|
|
93
|
+
],
|
|
94
|
+
isError: true,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (!/^r\d+$/.test(ref)) {
|
|
98
|
+
return {
|
|
99
|
+
content: [
|
|
100
|
+
{
|
|
101
|
+
type: "text",
|
|
102
|
+
text: `[recall] invalid ref '${ref}'; expected format 'rN' where N is a positive integer.`,
|
|
103
|
+
},
|
|
104
|
+
],
|
|
105
|
+
isError: true,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const sessionId = deps.getSessionId(ctx);
|
|
110
|
+
const store = deps.getDedupStore();
|
|
111
|
+
const got = store.get(sessionId, ref);
|
|
112
|
+
if (got === null) {
|
|
113
|
+
return {
|
|
114
|
+
content: [
|
|
115
|
+
{
|
|
116
|
+
type: "text",
|
|
117
|
+
text: `[recall] no content stored at ref '${ref}' in this session.`,
|
|
118
|
+
},
|
|
119
|
+
],
|
|
120
|
+
isError: true,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Bare text. No preamble, no formatting. The LLM knows what rN is.
|
|
125
|
+
// Include toolName and paramsKey in the `details` so the host
|
|
126
|
+
// TUI can show provenance but the LLM-context output stays bare.
|
|
127
|
+
return {
|
|
128
|
+
content: [{ type: "text", text: got.fullText }],
|
|
129
|
+
details: {
|
|
130
|
+
ref,
|
|
131
|
+
sizeBytes: got.sizeBytes,
|
|
132
|
+
toolName: got.toolName,
|
|
133
|
+
paramsKey: got.paramsKey,
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
},
|
|
137
|
+
renderCall(args: any, theme: any, _context: any) {
|
|
138
|
+
return makeOutputText(
|
|
139
|
+
`${theme.fg("toolTitle", theme.bold("recall"))} ${theme.fg("accent", args?.ref || "")}`,
|
|
140
|
+
);
|
|
141
|
+
},
|
|
142
|
+
renderResult(result: any, options: any, theme: any, context: any) {
|
|
143
|
+
if (context.isError) {
|
|
144
|
+
const errMsg =
|
|
145
|
+
result.content?.find((c: any) => c.type === "text")?.text ||
|
|
146
|
+
"Recall failed";
|
|
147
|
+
return makeOutputText(`\n${theme.fg("error", errMsg)}`);
|
|
148
|
+
}
|
|
149
|
+
if (!options.expanded) {
|
|
150
|
+
return new Text("", 0, 0);
|
|
151
|
+
}
|
|
152
|
+
const output =
|
|
153
|
+
result.content?.find((c: any) => c.type === "text")?.text || "";
|
|
154
|
+
return makeOutputText(`\n${theme.fg("toolOutput", output)}`);
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { resolveUserPath } from "../safety/epistemic_guard";
|
|
4
|
+
import * as diff from "diff";
|
|
5
|
+
import { checkSyntaxContent } from "./syntax-verify";
|
|
6
|
+
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Result of composing and validating a surgical patch.
|
|
10
|
+
*
|
|
11
|
+
* `success: true` means the requested block was located, the complete
|
|
12
|
+
* candidate content passed the local syntax gate, and the target was written.
|
|
13
|
+
* It does not imply type correctness, semantic correctness, or clean LSP
|
|
14
|
+
* diagnostics; those checks remain the caller's responsibility.
|
|
15
|
+
*/
|
|
16
|
+
export interface PatchResult {
|
|
17
|
+
success: boolean;
|
|
18
|
+
filePath: string;
|
|
19
|
+
strategy: string;
|
|
20
|
+
diffOutput?: string;
|
|
21
|
+
error?: string;
|
|
22
|
+
targetRanges?: PatchTargetRange[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface PatchBlock {
|
|
26
|
+
search: string;
|
|
27
|
+
replace: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Inclusive 1-based line span matched by an edit block before mutation. */
|
|
31
|
+
export interface PatchTargetRange {
|
|
32
|
+
startLine: number;
|
|
33
|
+
endLine: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function lineRangeFromOffsets(
|
|
37
|
+
content: string,
|
|
38
|
+
startOffset: number,
|
|
39
|
+
length: number,
|
|
40
|
+
): PatchTargetRange {
|
|
41
|
+
const startLine = content.slice(0, startOffset).split("\n").length;
|
|
42
|
+
// When a match ends with a trailing newline (e.g. "foo\n"), that newline is the
|
|
43
|
+
// delimiter terminating the line, not content on the next line.
|
|
44
|
+
let effectiveLength = Math.max(length, 1);
|
|
45
|
+
if (
|
|
46
|
+
effectiveLength > 1 &&
|
|
47
|
+
content.slice(startOffset, startOffset + effectiveLength).endsWith("\n")
|
|
48
|
+
) {
|
|
49
|
+
effectiveLength -= 1;
|
|
50
|
+
}
|
|
51
|
+
const matched = content.slice(startOffset, startOffset + effectiveLength);
|
|
52
|
+
return {
|
|
53
|
+
startLine,
|
|
54
|
+
endLine: startLine + Math.max(0, matched.split("\n").length - 1),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function computeSimilarity(a: string, b: string): number {
|
|
59
|
+
if (a === b) return 1;
|
|
60
|
+
const len = Math.max(a.length, b.length);
|
|
61
|
+
if (len === 0) return 1;
|
|
62
|
+
const changes = diff.diffChars(a, b);
|
|
63
|
+
let common = 0;
|
|
64
|
+
for (const part of changes) {
|
|
65
|
+
if (!part.added && !part.removed) common += part.value.length;
|
|
66
|
+
}
|
|
67
|
+
return common / len;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function restoreLineEndings(content: string, hadCrlf: boolean): string {
|
|
71
|
+
return hadCrlf ? content.replace(/\n/g, "\r\n") : content;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function replaceLineWindow(
|
|
75
|
+
contentLines: string[],
|
|
76
|
+
start: number,
|
|
77
|
+
length: number,
|
|
78
|
+
replacement: string,
|
|
79
|
+
hadCrlf: boolean,
|
|
80
|
+
): string {
|
|
81
|
+
return restoreLineEndings(
|
|
82
|
+
[
|
|
83
|
+
...contentLines.slice(0, start),
|
|
84
|
+
replacement,
|
|
85
|
+
...contentLines.slice(start + length),
|
|
86
|
+
].join("\n"),
|
|
87
|
+
hadCrlf,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function applySingleBlock(
|
|
92
|
+
content: string,
|
|
93
|
+
search: string,
|
|
94
|
+
replace: string,
|
|
95
|
+
): {
|
|
96
|
+
success: boolean;
|
|
97
|
+
newContent: string;
|
|
98
|
+
strategy: string;
|
|
99
|
+
error?: string;
|
|
100
|
+
targetRange?: PatchTargetRange;
|
|
101
|
+
} {
|
|
102
|
+
const hadCrlf = content.includes("\r\n");
|
|
103
|
+
const searchNorm = search.replace(/\r\n/g, "\n");
|
|
104
|
+
const replaceNorm = replace.replace(/\r\n/g, "\n");
|
|
105
|
+
const contentNorm = content.replace(/\r\n/g, "\n");
|
|
106
|
+
|
|
107
|
+
if (!searchNorm.trim()) {
|
|
108
|
+
return {
|
|
109
|
+
success: false,
|
|
110
|
+
newContent: content,
|
|
111
|
+
strategy: "none",
|
|
112
|
+
error: "SEARCH block cannot be empty or whitespace-only.",
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Exact matching is safest, but duplicate or overlapping occurrences are
|
|
117
|
+
// rejected rather than silently selecting one.
|
|
118
|
+
const exactMatches: number[] = [];
|
|
119
|
+
let exactOffset = contentNorm.indexOf(searchNorm);
|
|
120
|
+
while (exactOffset !== -1) {
|
|
121
|
+
exactMatches.push(exactOffset);
|
|
122
|
+
exactOffset = contentNorm.indexOf(searchNorm, exactOffset + 1);
|
|
123
|
+
}
|
|
124
|
+
if (exactMatches.length === 1) {
|
|
125
|
+
const start = exactMatches[0];
|
|
126
|
+
const newContent =
|
|
127
|
+
contentNorm.slice(0, start) +
|
|
128
|
+
replaceNorm +
|
|
129
|
+
contentNorm.slice(start + searchNorm.length);
|
|
130
|
+
return {
|
|
131
|
+
success: true,
|
|
132
|
+
newContent: restoreLineEndings(newContent, hadCrlf),
|
|
133
|
+
strategy: "exact",
|
|
134
|
+
targetRange: lineRangeFromOffsets(contentNorm, start, searchNorm.length),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
if (exactMatches.length > 1) {
|
|
138
|
+
return {
|
|
139
|
+
success: false,
|
|
140
|
+
newContent: content,
|
|
141
|
+
strategy: "none",
|
|
142
|
+
error: `SEARCH block is ambiguous: found ${exactMatches.length} exact matches.`,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Keep every line in the normalized window, including leading, trailing, and
|
|
147
|
+
// interior blank lines. Dropping any of them can make unrelated regions look
|
|
148
|
+
// identical or remove formatting adjacent to the replacement.
|
|
149
|
+
const contentLines = contentNorm.split("\n");
|
|
150
|
+
const searchLines = searchNorm.split("\n");
|
|
151
|
+
const normalizedSearch = searchLines.map((line) => line.trim());
|
|
152
|
+
const normalizedMatches: number[] = [];
|
|
153
|
+
|
|
154
|
+
for (let i = 0; i <= contentLines.length - searchLines.length; i++) {
|
|
155
|
+
let matches = true;
|
|
156
|
+
for (let j = 0; j < searchLines.length; j++) {
|
|
157
|
+
if (contentLines[i + j].trim() !== normalizedSearch[j]) {
|
|
158
|
+
matches = false;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (matches) normalizedMatches.push(i);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (normalizedMatches.length === 1) {
|
|
166
|
+
return {
|
|
167
|
+
success: true,
|
|
168
|
+
newContent: replaceLineWindow(
|
|
169
|
+
contentLines,
|
|
170
|
+
normalizedMatches[0],
|
|
171
|
+
searchLines.length,
|
|
172
|
+
replaceNorm,
|
|
173
|
+
hadCrlf,
|
|
174
|
+
),
|
|
175
|
+
strategy: "whitespace_normalized",
|
|
176
|
+
targetRange: {
|
|
177
|
+
startLine: normalizedMatches[0] + 1,
|
|
178
|
+
endLine: normalizedMatches[0] + searchLines.length,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
if (normalizedMatches.length > 1) {
|
|
183
|
+
return {
|
|
184
|
+
success: false,
|
|
185
|
+
newContent: content,
|
|
186
|
+
strategy: "none",
|
|
187
|
+
error: `SEARCH block is ambiguous: found ${normalizedMatches.length} whitespace-normalized matches.`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Fuzzy matching is accepted only with a high score and a clear margin over
|
|
192
|
+
// the next candidate. Ties and near-ties fail closed.
|
|
193
|
+
const candidates: Array<{ index: number; score: number }> = [];
|
|
194
|
+
for (let i = 0; i <= contentLines.length - searchLines.length; i++) {
|
|
195
|
+
let scoreSum = 0;
|
|
196
|
+
for (let j = 0; j < searchLines.length; j++) {
|
|
197
|
+
scoreSum += computeSimilarity(
|
|
198
|
+
contentLines[i + j].trim(),
|
|
199
|
+
searchLines[j].trim(),
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
candidates.push({ index: i, score: scoreSum / searchLines.length });
|
|
203
|
+
}
|
|
204
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
205
|
+
|
|
206
|
+
const best = candidates[0];
|
|
207
|
+
const second = candidates[1];
|
|
208
|
+
const minimumScore = 0.85;
|
|
209
|
+
const minimumMargin = 0.05;
|
|
210
|
+
if (best && best.score >= minimumScore) {
|
|
211
|
+
if (second && best.score - second.score < minimumMargin) {
|
|
212
|
+
return {
|
|
213
|
+
success: false,
|
|
214
|
+
newContent: content,
|
|
215
|
+
strategy: "none",
|
|
216
|
+
error: `SEARCH block is ambiguous: fuzzy candidates are too close (${(best.score * 100).toFixed(1)}% best).`,
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
success: true,
|
|
221
|
+
newContent: replaceLineWindow(
|
|
222
|
+
contentLines,
|
|
223
|
+
best.index,
|
|
224
|
+
searchLines.length,
|
|
225
|
+
replaceNorm,
|
|
226
|
+
hadCrlf,
|
|
227
|
+
),
|
|
228
|
+
strategy: `fuzzy (similarity: ${(best.score * 100).toFixed(1)}%)`,
|
|
229
|
+
targetRange: {
|
|
230
|
+
startLine: best.index + 1,
|
|
231
|
+
endLine: best.index + searchLines.length,
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
success: false,
|
|
238
|
+
newContent: content,
|
|
239
|
+
strategy: "none",
|
|
240
|
+
error: "Could not locate SEARCH block. Check line context and try again.",
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Locate a single-block edit without mutating the target. The edit tool uses
|
|
246
|
+
* this narrow preflight to compare the matched span with visible read evidence.
|
|
247
|
+
*/
|
|
248
|
+
export function findSurgicalPatchTargetRange(
|
|
249
|
+
filePath: string,
|
|
250
|
+
search: string,
|
|
251
|
+
): PatchTargetRange | null {
|
|
252
|
+
const resolvedPath = resolvePatchPath(filePath);
|
|
253
|
+
const target = readPatchTarget(resolvedPath);
|
|
254
|
+
if ("error" in target) return null;
|
|
255
|
+
const result = applySingleBlock(target.content, search, "");
|
|
256
|
+
return result.success ? result.targetRange ?? null : null;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function resolvePatchPath(filePath: string): string {
|
|
260
|
+
return resolveUserPath(filePath, process.cwd());
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function readPatchTarget(
|
|
264
|
+
resolvedPath: string,
|
|
265
|
+
): { content: string } | { error: PatchResult } {
|
|
266
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
267
|
+
return {
|
|
268
|
+
error: {
|
|
269
|
+
success: false,
|
|
270
|
+
filePath: resolvedPath,
|
|
271
|
+
strategy: "none",
|
|
272
|
+
error: `File not found: ${resolvedPath}`,
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
return { content: fs.readFileSync(resolvedPath, "utf8") };
|
|
278
|
+
} catch (error: any) {
|
|
279
|
+
return {
|
|
280
|
+
error: {
|
|
281
|
+
success: false,
|
|
282
|
+
filePath: resolvedPath,
|
|
283
|
+
strategy: "none",
|
|
284
|
+
error: `Unable to read file ${resolvedPath}: ${error.message}`,
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function writePatchedContent(
|
|
291
|
+
resolvedPath: string,
|
|
292
|
+
originalContent: string,
|
|
293
|
+
newContent: string,
|
|
294
|
+
): PatchResult | null {
|
|
295
|
+
// Avoid clobbering an external edit made after the patch was composed.
|
|
296
|
+
try {
|
|
297
|
+
if (fs.readFileSync(resolvedPath, "utf8") !== originalContent) {
|
|
298
|
+
return {
|
|
299
|
+
success: false,
|
|
300
|
+
filePath: resolvedPath,
|
|
301
|
+
strategy: "none",
|
|
302
|
+
error: `File changed while the patch was being prepared: ${resolvedPath}. Re-read and retry.`,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
writeFileSyncAtomic(resolvedPath, newContent);
|
|
306
|
+
return null;
|
|
307
|
+
} catch (error: any) {
|
|
308
|
+
return {
|
|
309
|
+
success: false,
|
|
310
|
+
filePath: resolvedPath,
|
|
311
|
+
strategy: "none",
|
|
312
|
+
error: `Unable to write ${resolvedPath}: ${error.message}`,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
export function applySurgicalPatch(
|
|
318
|
+
filePath: string,
|
|
319
|
+
search: string,
|
|
320
|
+
replace: string,
|
|
321
|
+
): PatchResult {
|
|
322
|
+
const resolvedPath = resolvePatchPath(filePath);
|
|
323
|
+
const target = readPatchTarget(resolvedPath);
|
|
324
|
+
if ("error" in target) return target.error;
|
|
325
|
+
|
|
326
|
+
const originalContent = target.content;
|
|
327
|
+
const result = applySingleBlock(originalContent, search, replace);
|
|
328
|
+
if (!result.success) {
|
|
329
|
+
return {
|
|
330
|
+
success: false,
|
|
331
|
+
filePath: resolvedPath,
|
|
332
|
+
strategy: "none",
|
|
333
|
+
error: `${result.error} in ${resolvedPath}`,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const syntax = checkSyntaxContent(resolvedPath, result.newContent);
|
|
338
|
+
if (!syntax.valid) {
|
|
339
|
+
return {
|
|
340
|
+
success: false,
|
|
341
|
+
filePath: resolvedPath,
|
|
342
|
+
strategy: result.strategy,
|
|
343
|
+
error: syntax.error || "Candidate syntax validation failed",
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const writeError = writePatchedContent(
|
|
348
|
+
resolvedPath,
|
|
349
|
+
originalContent,
|
|
350
|
+
result.newContent,
|
|
351
|
+
);
|
|
352
|
+
if (writeError) {
|
|
353
|
+
writeError.strategy = result.strategy;
|
|
354
|
+
return writeError;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
success: true,
|
|
359
|
+
filePath: resolvedPath,
|
|
360
|
+
strategy: result.strategy,
|
|
361
|
+
targetRanges: result.targetRange ? [result.targetRange] : [],
|
|
362
|
+
diffOutput: diff.createPatch(
|
|
363
|
+
path.basename(resolvedPath),
|
|
364
|
+
originalContent,
|
|
365
|
+
result.newContent,
|
|
366
|
+
),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function applyMultiBlockPatch(
|
|
371
|
+
filePath: string,
|
|
372
|
+
blocks: PatchBlock[],
|
|
373
|
+
): PatchResult {
|
|
374
|
+
const resolvedPath = resolvePatchPath(filePath);
|
|
375
|
+
const target = readPatchTarget(resolvedPath);
|
|
376
|
+
if ("error" in target) return target.error;
|
|
377
|
+
if (!Array.isArray(blocks) || blocks.length === 0) {
|
|
378
|
+
return {
|
|
379
|
+
success: false,
|
|
380
|
+
filePath: resolvedPath,
|
|
381
|
+
strategy: "none",
|
|
382
|
+
error: "At least one patch block is required.",
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
const originalContent = target.content;
|
|
387
|
+
const plannedRanges: PatchTargetRange[] = [];
|
|
388
|
+
|
|
389
|
+
// Preflight every search against the same original snapshot. Returned ranges
|
|
390
|
+
// deliberately use original-file coordinates so callers can compare them with
|
|
391
|
+
// the read evidence used to authorize this atomic edit; they do not move when
|
|
392
|
+
// an earlier replacement changes the line count.
|
|
393
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
394
|
+
const block = blocks[i];
|
|
395
|
+
if (
|
|
396
|
+
!block ||
|
|
397
|
+
typeof block.search !== "string" ||
|
|
398
|
+
typeof block.replace !== "string"
|
|
399
|
+
) {
|
|
400
|
+
return {
|
|
401
|
+
success: false,
|
|
402
|
+
filePath: resolvedPath,
|
|
403
|
+
strategy: "none",
|
|
404
|
+
error: `Block ${i + 1}/${blocks.length} is malformed.`,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const located = applySingleBlock(originalContent, block.search, "");
|
|
409
|
+
if (!located.success || !located.targetRange) {
|
|
410
|
+
return {
|
|
411
|
+
success: false,
|
|
412
|
+
filePath: resolvedPath,
|
|
413
|
+
strategy: "none",
|
|
414
|
+
error: `Block ${i + 1}/${blocks.length} failed: ${located.error} in ${resolvedPath}`,
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
const overlaps = plannedRanges.some(
|
|
419
|
+
(range) =>
|
|
420
|
+
range.startLine <= located.targetRange!.endLine &&
|
|
421
|
+
located.targetRange!.startLine <= range.endLine,
|
|
422
|
+
);
|
|
423
|
+
if (overlaps) {
|
|
424
|
+
return {
|
|
425
|
+
success: false,
|
|
426
|
+
filePath: resolvedPath,
|
|
427
|
+
strategy: "none",
|
|
428
|
+
error: `Block ${i + 1}/${blocks.length} overlaps another patch target in ${resolvedPath}.`,
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
plannedRanges.push({ ...located.targetRange });
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let currentContent = originalContent;
|
|
435
|
+
const appliedStrategies: string[] = [];
|
|
436
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
437
|
+
const block = blocks[i];
|
|
438
|
+
const result = applySingleBlock(currentContent, block.search, block.replace);
|
|
439
|
+
if (!result.success) {
|
|
440
|
+
return {
|
|
441
|
+
success: false,
|
|
442
|
+
filePath: resolvedPath,
|
|
443
|
+
strategy: "none",
|
|
444
|
+
error: `Block ${i + 1}/${blocks.length} failed: ${result.error} in ${resolvedPath}`,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
currentContent = result.newContent;
|
|
448
|
+
appliedStrategies.push(`Block ${i + 1}: ${result.strategy}`);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const syntax = checkSyntaxContent(resolvedPath, currentContent);
|
|
452
|
+
if (!syntax.valid) {
|
|
453
|
+
return {
|
|
454
|
+
success: false,
|
|
455
|
+
filePath: resolvedPath,
|
|
456
|
+
strategy: appliedStrategies.join(", "),
|
|
457
|
+
error: syntax.error || "Candidate syntax validation failed",
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const writeError = writePatchedContent(
|
|
462
|
+
resolvedPath,
|
|
463
|
+
originalContent,
|
|
464
|
+
currentContent,
|
|
465
|
+
);
|
|
466
|
+
if (writeError) {
|
|
467
|
+
writeError.strategy = appliedStrategies.join(", ");
|
|
468
|
+
return writeError;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return {
|
|
472
|
+
success: true,
|
|
473
|
+
filePath: resolvedPath,
|
|
474
|
+
strategy: appliedStrategies.join(", "),
|
|
475
|
+
targetRanges: plannedRanges,
|
|
476
|
+
diffOutput: diff.createPatch(
|
|
477
|
+
path.basename(resolvedPath),
|
|
478
|
+
originalContent,
|
|
479
|
+
currentContent,
|
|
480
|
+
),
|
|
481
|
+
};
|
|
482
|
+
}
|