@floydous/pi-agent-kernel 0.4.3 → 0.6.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/AGENT_KERNEL_SYS_PROMPT.md +15 -12
- package/CHANGELOG.md +87 -0
- package/README.md +6 -54
- package/config.example.toml +1 -8
- package/docs/README.md +1 -2
- package/docs/architecture.md +2 -3
- package/docs/configuration.md +11 -10
- package/docs/editing-and-verification.md +21 -8
- package/docs/podman-linux-checks.md +24 -0
- package/docs/release-discipline.md +10 -0
- package/docs/retrieval.md +21 -23
- package/docs/testing.md +3 -3
- package/grammars/tree-sitter-html.wasm +0 -0
- package/package.json +5 -3
- package/src/config/agent_kernel_command.ts +60 -625
- package/src/config/kernel_config.ts +53 -69
- package/src/config/toml.ts +6 -1
- package/src/editing/auto_heal.ts +1 -1
- package/src/editing/patch.ts +75 -37
- package/src/editing/post_edit_verification.ts +20 -14
- package/src/editing/smart_anchor.ts +9 -6
- package/src/editing/syntax-verify.ts +79 -222
- package/src/index.ts +36 -453
- package/src/retrieval/html_chunker.ts +526 -0
- package/src/retrieval/search_bm25.ts +39 -28
- package/src/retrieval/search_chunker.ts +69 -7
- package/src/retrieval/search_config.ts +21 -40
- package/src/retrieval/search_embedder.ts +14 -31
- package/src/retrieval/search_index.ts +338 -129
- package/src/retrieval/search_modal.ts +1208 -222
- package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
- package/src/retrieval/tree_sitter_engine.ts +171 -36
- package/src/retrieval/workspace_walker.ts +78 -2
- package/src/safety/atomic_write.ts +1 -1
- package/src/safety/epistemic_guard.ts +105 -31
- package/src/safety/host_environment.ts +180 -0
- package/src/safety/output_clamper.ts +97 -27
- package/src/tools/code_search_output.ts +11 -2
- package/src/tools/code_search_tool.ts +25 -13
- package/src/tools/context.ts +11 -10
- package/src/tools/edit_tool.ts +243 -154
- package/src/tools/read_tool.ts +285 -214
- package/src/tools/stream_reader.ts +206 -0
- package/src/ui/footer.ts +7 -7
- package/docs/lsp.md +0 -31
- package/src/lsp/adapters/base.ts +0 -42
- package/src/lsp/adapters/index.ts +0 -21
- package/src/lsp/adapters/python.ts +0 -37
- package/src/lsp/adapters/rust.ts +0 -35
- package/src/lsp/adapters/typescript.ts +0 -40
- package/src/lsp/index.ts +0 -13
- package/src/lsp/lsp_client.ts +0 -765
- package/src/lsp/lsp_detector.ts +0 -52
- package/src/lsp/lsp_formatter.ts +0 -323
- package/src/lsp/lsp_installer.ts +0 -320
- package/src/lsp/lsp_manager.ts +0 -202
- package/src/lsp/lsp_modal.ts +0 -675
- package/src/lsp/lsp_registry.ts +0 -600
- package/src/lsp/lsp_types.ts +0 -143
- package/src/retrieval/ast_search.ts +0 -999
- package/src/retrieval/symbol_reader.ts +0 -228
- package/src/tools/ast_search_formatter.ts +0 -161
- package/src/tools/ast_search_tool.ts +0 -146
- package/src/tools/lsp_tool.ts +0 -794
- package/src/tools/repo_map_tool.ts +0 -56
|
@@ -7,11 +7,8 @@ import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
|
7
7
|
|
|
8
8
|
export interface RetrievalConfig {
|
|
9
9
|
default_profile: "auto" | "lean" | "hybrid" | "full" | "off";
|
|
10
|
-
repo_map_budget: number;
|
|
11
|
-
repo_map_min_files: number;
|
|
12
|
-
repo_map_min_bytes: number;
|
|
13
10
|
max_search_results: number;
|
|
14
|
-
|
|
11
|
+
excluded_paths?: string[];
|
|
15
12
|
}
|
|
16
13
|
|
|
17
14
|
export interface SafetyConfig {
|
|
@@ -27,25 +24,17 @@ export interface EditingConfig {
|
|
|
27
24
|
default_anchors: boolean;
|
|
28
25
|
read_mode: "auto" | "plain" | "anchored";
|
|
29
26
|
syntax_gate?: "warn" | "block";
|
|
27
|
+
normalize_fullwidth_dots?: boolean;
|
|
30
28
|
}
|
|
31
29
|
|
|
32
30
|
export interface KernelConfigOverrides {
|
|
33
31
|
retrieval?: Partial<RetrievalConfig>;
|
|
34
32
|
safety?: Partial<SafetyConfig>;
|
|
35
33
|
editing?: Partial<EditingConfig>;
|
|
36
|
-
lsp?: Partial<LspConfig>;
|
|
37
34
|
ui?: Partial<UiConfig>;
|
|
38
35
|
instructions?: Partial<InstructionsConfig>;
|
|
39
36
|
}
|
|
40
37
|
|
|
41
|
-
export interface LspConfig {
|
|
42
|
-
idle_timeout_ms: number;
|
|
43
|
-
diagnostic_timeout_ms: number;
|
|
44
|
-
init_timeout_ms: number;
|
|
45
|
-
spinner_interval_ms: number;
|
|
46
|
-
disabled_servers: string[];
|
|
47
|
-
}
|
|
48
|
-
|
|
49
38
|
export interface UiConfig {
|
|
50
39
|
enable_pastel_footer: boolean;
|
|
51
40
|
}
|
|
@@ -53,13 +42,13 @@ export interface UiConfig {
|
|
|
53
42
|
export interface InstructionsConfig {
|
|
54
43
|
enabled: boolean;
|
|
55
44
|
pi_docs: boolean;
|
|
45
|
+
host_environment: boolean;
|
|
56
46
|
}
|
|
57
47
|
|
|
58
48
|
export interface KernelConfig {
|
|
59
49
|
retrieval: RetrievalConfig;
|
|
60
50
|
safety: SafetyConfig;
|
|
61
51
|
editing: EditingConfig;
|
|
62
|
-
lsp: LspConfig;
|
|
63
52
|
ui: UiConfig;
|
|
64
53
|
instructions: InstructionsConfig;
|
|
65
54
|
}
|
|
@@ -67,11 +56,8 @@ export interface KernelConfig {
|
|
|
67
56
|
const DEFAULT_CONFIG: KernelConfig = {
|
|
68
57
|
retrieval: {
|
|
69
58
|
default_profile: "lean",
|
|
70
|
-
repo_map_budget: 1024,
|
|
71
|
-
repo_map_min_files: 10,
|
|
72
|
-
repo_map_min_bytes: 50 * 1024,
|
|
73
59
|
max_search_results: 5,
|
|
74
|
-
|
|
60
|
+
excluded_paths: [],
|
|
75
61
|
},
|
|
76
62
|
safety: {
|
|
77
63
|
enable_epistemic_guard: true,
|
|
@@ -85,13 +71,7 @@ const DEFAULT_CONFIG: KernelConfig = {
|
|
|
85
71
|
default_anchors: false,
|
|
86
72
|
read_mode: "plain",
|
|
87
73
|
syntax_gate: "warn",
|
|
88
|
-
|
|
89
|
-
lsp: {
|
|
90
|
-
idle_timeout_ms: 5 * 60 * 1000, // 5 minutes
|
|
91
|
-
diagnostic_timeout_ms: 8000, // 8s for type-checking on large workspaces
|
|
92
|
-
init_timeout_ms: 25000, // 25s for heavy servers like rust-analyzer/vtsls/gopls
|
|
93
|
-
spinner_interval_ms: 80,
|
|
94
|
-
disabled_servers: [],
|
|
74
|
+
normalize_fullwidth_dots: true,
|
|
95
75
|
},
|
|
96
76
|
ui: {
|
|
97
77
|
enable_pastel_footer: true,
|
|
@@ -99,6 +79,7 @@ const DEFAULT_CONFIG: KernelConfig = {
|
|
|
99
79
|
instructions: {
|
|
100
80
|
enabled: true,
|
|
101
81
|
pi_docs: true,
|
|
82
|
+
host_environment: true,
|
|
102
83
|
},
|
|
103
84
|
};
|
|
104
85
|
|
|
@@ -107,11 +88,8 @@ export class KernelConfigError extends Error {}
|
|
|
107
88
|
const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
|
|
108
89
|
retrieval: new Set([
|
|
109
90
|
"default_profile",
|
|
110
|
-
"repo_map_budget",
|
|
111
|
-
"repo_map_min_files",
|
|
112
|
-
"repo_map_min_bytes",
|
|
113
91
|
"max_search_results",
|
|
114
|
-
"
|
|
92
|
+
"excluded_paths",
|
|
115
93
|
]),
|
|
116
94
|
safety: new Set([
|
|
117
95
|
"enable_epistemic_guard",
|
|
@@ -120,22 +98,28 @@ const ALLOWED_CONFIG_KEYS: Record<keyof KernelConfig, ReadonlySet<string>> = {
|
|
|
120
98
|
"max_total_bytes",
|
|
121
99
|
"exec_timeout_ms",
|
|
122
100
|
]),
|
|
123
|
-
editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate"]),
|
|
124
|
-
lsp: new Set([
|
|
125
|
-
"idle_timeout_ms",
|
|
126
|
-
"diagnostic_timeout_ms",
|
|
127
|
-
"init_timeout_ms",
|
|
128
|
-
"spinner_interval_ms",
|
|
129
|
-
"disabled_servers",
|
|
130
|
-
]),
|
|
101
|
+
editing: new Set(["mode", "default_anchors", "read_mode", "syntax_gate", "normalize_fullwidth_dots"]),
|
|
131
102
|
ui: new Set(["enable_pastel_footer"]),
|
|
132
|
-
instructions: new Set(["enabled", "pi_docs"]),
|
|
103
|
+
instructions: new Set(["enabled", "pi_docs", "host_environment"]),
|
|
133
104
|
};
|
|
134
105
|
|
|
106
|
+
const DEPRECATED_RETRIEVAL_KEYS = new Set([
|
|
107
|
+
"enable_tools",
|
|
108
|
+
"repo_map_budget",
|
|
109
|
+
"repo_map_min_files",
|
|
110
|
+
"repo_map_min_bytes",
|
|
111
|
+
]);
|
|
112
|
+
|
|
135
113
|
function configPath(parts: string[]): string {
|
|
136
114
|
return parts.join(".");
|
|
137
115
|
}
|
|
138
116
|
|
|
117
|
+
function requireStringArray(value: unknown, path: string): void {
|
|
118
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) {
|
|
119
|
+
throw new KernelConfigError(`${path} must be an array of strings`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
139
123
|
function requireBoolean(value: unknown, path: string): void {
|
|
140
124
|
if (typeof value !== "boolean") throw new KernelConfigError(`${path} must be a boolean`);
|
|
141
125
|
}
|
|
@@ -167,11 +151,10 @@ export function validateKernelConfig(config: KernelConfig): KernelConfig {
|
|
|
167
151
|
|
|
168
152
|
const retrieval = config.retrieval;
|
|
169
153
|
requireEnum(retrieval.default_profile, "retrieval.default_profile", ["auto", "lean", "hybrid", "full", "off"]);
|
|
170
|
-
requireSafeInt(retrieval.repo_map_budget, "retrieval.repo_map_budget", 64, 32_768);
|
|
171
|
-
requireSafeInt(retrieval.repo_map_min_files, "retrieval.repo_map_min_files", 0, 10_000);
|
|
172
|
-
requireSafeInt(retrieval.repo_map_min_bytes, "retrieval.repo_map_min_bytes", 0, 1024 * 1024 * 1024);
|
|
173
154
|
requireSafeInt(retrieval.max_search_results, "retrieval.max_search_results", 1, 15);
|
|
174
|
-
|
|
155
|
+
if (retrieval.excluded_paths !== undefined) {
|
|
156
|
+
requireStringArray(retrieval.excluded_paths, "retrieval.excluded_paths");
|
|
157
|
+
}
|
|
175
158
|
|
|
176
159
|
const safety = config.safety;
|
|
177
160
|
requireBoolean(safety.enable_epistemic_guard, "safety.enable_epistemic_guard");
|
|
@@ -186,24 +169,16 @@ export function validateKernelConfig(config: KernelConfig): KernelConfig {
|
|
|
186
169
|
if (config.editing.syntax_gate !== undefined) {
|
|
187
170
|
requireEnum(config.editing.syntax_gate, "editing.syntax_gate", ["warn", "block"]);
|
|
188
171
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
requireSafeInt(config.lsp.diagnostic_timeout_ms, "lsp.diagnostic_timeout_ms", 100, 120_000);
|
|
192
|
-
requireSafeInt(config.lsp.init_timeout_ms, "lsp.init_timeout_ms", 100, 5 * 60 * 1_000);
|
|
193
|
-
requireSafeInt(config.lsp.spinner_interval_ms, "lsp.spinner_interval_ms", 16, 1_000);
|
|
194
|
-
if (
|
|
195
|
-
!Array.isArray(config.lsp.disabled_servers) ||
|
|
196
|
-
config.lsp.disabled_servers.length > 64 ||
|
|
197
|
-
config.lsp.disabled_servers.some(
|
|
198
|
-
(server) => typeof server !== "string" || !/^[a-z0-9._-]{1,64}$/i.test(server),
|
|
199
|
-
)
|
|
200
|
-
) {
|
|
201
|
-
throw new KernelConfigError("lsp.disabled_servers must be an array of up to 64 safe server keys");
|
|
172
|
+
if (config.editing.normalize_fullwidth_dots !== undefined) {
|
|
173
|
+
requireBoolean(config.editing.normalize_fullwidth_dots, "editing.normalize_fullwidth_dots");
|
|
202
174
|
}
|
|
203
175
|
|
|
204
176
|
requireBoolean(config.ui.enable_pastel_footer, "ui.enable_pastel_footer");
|
|
205
177
|
requireBoolean(config.instructions.enabled, "instructions.enabled");
|
|
206
178
|
requireBoolean(config.instructions.pi_docs, "instructions.pi_docs");
|
|
179
|
+
if (config.instructions.host_environment !== undefined) {
|
|
180
|
+
requireBoolean(config.instructions.host_environment, "instructions.host_environment");
|
|
181
|
+
}
|
|
207
182
|
return config;
|
|
208
183
|
}
|
|
209
184
|
|
|
@@ -212,20 +187,26 @@ export function mergeKernelConfig(target: KernelConfig, source: unknown): Kernel
|
|
|
212
187
|
if (!source || typeof source !== "object" || Array.isArray(source)) {
|
|
213
188
|
throw new KernelConfigError("Configuration root must be a table");
|
|
214
189
|
}
|
|
190
|
+
const sanitizedSource: Record<string, unknown> = {};
|
|
215
191
|
for (const [section, value] of Object.entries(source as Record<string, unknown>)) {
|
|
192
|
+
if (section === "lsp") continue; // Deprecated legacy section: accepted and ignored
|
|
216
193
|
if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig]) {
|
|
217
194
|
throw new KernelConfigError(`Unknown configuration section: ${section}`);
|
|
218
195
|
}
|
|
219
196
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
220
197
|
throw new KernelConfigError(`${section} must be a table`);
|
|
221
198
|
}
|
|
222
|
-
|
|
199
|
+
const sectionObj: Record<string, unknown> = {};
|
|
200
|
+
for (const [key, val] of Object.entries(value as Record<string, unknown>)) {
|
|
201
|
+
if (section === "retrieval" && DEPRECATED_RETRIEVAL_KEYS.has(key)) continue; // Deprecated legacy setting: accepted and ignored
|
|
223
202
|
if (!ALLOWED_CONFIG_KEYS[section as keyof KernelConfig].has(key)) {
|
|
224
203
|
throw new KernelConfigError(`Unknown configuration key: ${configPath([section, key])}`);
|
|
225
204
|
}
|
|
205
|
+
sectionObj[key] = val;
|
|
226
206
|
}
|
|
207
|
+
sanitizedSource[section] = sectionObj;
|
|
227
208
|
}
|
|
228
|
-
mergeDeep(candidate,
|
|
209
|
+
mergeDeep(candidate, sanitizedSource);
|
|
229
210
|
validateKernelConfig(candidate);
|
|
230
211
|
for (const key of Object.keys(target) as Array<keyof KernelConfig>) {
|
|
231
212
|
delete (target as any)[key];
|
|
@@ -323,15 +304,10 @@ export function loadKernelConfig(
|
|
|
323
304
|
}
|
|
324
305
|
|
|
325
306
|
// 3. Environment Variable Overrides
|
|
326
|
-
if (process.env.PI_REPO_MAP_BUDGET) {
|
|
327
|
-
const b = parseInt(process.env.PI_REPO_MAP_BUDGET, 10);
|
|
328
|
-
if (!isNaN(b)) config.retrieval.repo_map_budget = b;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
307
|
if (process.env.PI_RETRIEVAL_PROFILE) {
|
|
332
308
|
const p = process.env.PI_RETRIEVAL_PROFILE.toLowerCase();
|
|
333
309
|
if (p === "lean" || p === "hybrid" || p === "full") {
|
|
334
|
-
config.retrieval.default_profile = p
|
|
310
|
+
config.retrieval.default_profile = p;
|
|
335
311
|
}
|
|
336
312
|
}
|
|
337
313
|
|
|
@@ -366,10 +342,11 @@ export function removeGlobalKernelConfigKey(section: string, key: string): void
|
|
|
366
342
|
if (!fs.existsSync(globalPath)) return;
|
|
367
343
|
|
|
368
344
|
try {
|
|
369
|
-
const existing
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
345
|
+
const existing = parseToml(fs.readFileSync(globalPath, "utf-8"));
|
|
346
|
+
const sec = existing[section];
|
|
347
|
+
if (sec && typeof sec === "object" && !Array.isArray(sec) && (sec as Record<string, TomlValue>)[key] !== undefined) {
|
|
348
|
+
delete (sec as Record<string, TomlValue>)[key];
|
|
349
|
+
if (Object.keys(sec).length === 0) {
|
|
373
350
|
delete existing[section];
|
|
374
351
|
}
|
|
375
352
|
validateConfigDocument(existing);
|
|
@@ -384,11 +361,18 @@ export function removeGlobalKernelConfigKey(section: string, key: string): void
|
|
|
384
361
|
/**
|
|
385
362
|
* Read raw global configuration TOML if it exists
|
|
386
363
|
*/
|
|
387
|
-
export function getGlobalRawConfig(): Record<string,
|
|
364
|
+
export function getGlobalRawConfig(): Record<string, Record<string, TomlValue>> {
|
|
388
365
|
const globalPath = getGlobalConfigPath();
|
|
389
366
|
if (fs.existsSync(globalPath)) {
|
|
390
367
|
try {
|
|
391
|
-
|
|
368
|
+
const parsed = parseToml(fs.readFileSync(globalPath, "utf-8"));
|
|
369
|
+
const result: Record<string, Record<string, TomlValue>> = {};
|
|
370
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
371
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
372
|
+
result[key] = value as Record<string, TomlValue>;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return result;
|
|
392
376
|
} catch (e) {
|
|
393
377
|
kernelDebug(e);
|
|
394
378
|
}
|
package/src/config/toml.ts
CHANGED
|
@@ -77,7 +77,12 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
|
|
|
77
77
|
// Strip inline comment if not inside quote
|
|
78
78
|
rawValue = stripInlineComment(rawValue);
|
|
79
79
|
|
|
80
|
-
currentTable
|
|
80
|
+
Object.defineProperty(currentTable, cleanKey, {
|
|
81
|
+
value: parseTomlValue(rawValue),
|
|
82
|
+
writable: true,
|
|
83
|
+
enumerable: true,
|
|
84
|
+
configurable: true,
|
|
85
|
+
});
|
|
81
86
|
}
|
|
82
87
|
|
|
83
88
|
return root;
|
package/src/editing/auto_heal.ts
CHANGED
|
@@ -78,7 +78,7 @@ export function getUnclosedDelimiters(text: string): string[] {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
const map: Record<string, string> = { "{": "}", "(": ")", "[": "]" };
|
|
81
|
-
return stack.reverse().map((ch) => map[ch]);
|
|
81
|
+
return [...stack].reverse().map((ch) => map[ch] ?? "");
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
/**
|
package/src/editing/patch.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import * as fs from "fs";
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { resolveUserPath } from "../safety/epistemic_guard";
|
|
4
4
|
import * as diff from "diff";
|
|
5
|
-
import { checkSyntaxContent } from "./syntax-verify";
|
|
5
|
+
import { checkSyntaxContent, type VerificationResult } from "./syntax-verify";
|
|
6
6
|
import { writeFileSyncAtomic } from "../safety/atomic_write";
|
|
7
7
|
import { getUnclosedDelimiters, healJsonContent } from "./auto_heal";
|
|
8
8
|
/**
|
|
@@ -10,7 +10,7 @@ import { getUnclosedDelimiters, healJsonContent } from "./auto_heal";
|
|
|
10
10
|
*
|
|
11
11
|
* `success: true` means the requested block was located, the complete
|
|
12
12
|
* candidate content passed the local syntax gate, and the target was written.
|
|
13
|
-
* It does not imply type correctness, semantic correctness, or
|
|
13
|
+
* It does not imply type correctness, semantic correctness, or project-wide
|
|
14
14
|
* diagnostics; those checks remain the caller's responsibility.
|
|
15
15
|
*/
|
|
16
16
|
export interface PatchResult {
|
|
@@ -20,6 +20,8 @@ export interface PatchResult {
|
|
|
20
20
|
diffOutput?: string;
|
|
21
21
|
error?: string;
|
|
22
22
|
targetRanges?: PatchTargetRange[];
|
|
23
|
+
/** Syntax verdict on the content that was written. */
|
|
24
|
+
syntax?: VerificationResult;
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export interface PatchBlock {
|
|
@@ -85,14 +87,11 @@ function replaceLineWindow(
|
|
|
85
87
|
replacement: string,
|
|
86
88
|
hadCrlf: boolean,
|
|
87
89
|
): string {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
...contentLines.slice(0, start),
|
|
91
|
-
replacement,
|
|
92
|
-
|
|
93
|
-
].join("\n"),
|
|
94
|
-
hadCrlf,
|
|
95
|
-
);
|
|
90
|
+
const updatedLines =
|
|
91
|
+
replacement === ""
|
|
92
|
+
? [...contentLines.slice(0, start), ...contentLines.slice(start + length)]
|
|
93
|
+
: [...contentLines.slice(0, start), replacement, ...contentLines.slice(start + length)];
|
|
94
|
+
return restoreLineEndings(updatedLines.join("\n"), hadCrlf);
|
|
96
95
|
}
|
|
97
96
|
|
|
98
97
|
function applySingleBlock(
|
|
@@ -141,10 +140,23 @@ function applySingleBlock(
|
|
|
141
140
|
}
|
|
142
141
|
if (exactMatches.length === 1) {
|
|
143
142
|
const start = exactMatches[0];
|
|
143
|
+
let cutStart = start;
|
|
144
|
+
let cutEnd = start + searchNorm.length;
|
|
145
|
+
if (replaceNorm === "") {
|
|
146
|
+
const isLineStart = cutStart === 0 || contentNorm.charAt(cutStart - 1) === "\n";
|
|
147
|
+
const isLineEnd = cutEnd === contentNorm.length || contentNorm.charAt(cutEnd) === "\n";
|
|
148
|
+
if (isLineStart && isLineEnd) {
|
|
149
|
+
if (cutEnd < contentNorm.length && contentNorm.charAt(cutEnd) === "\n") {
|
|
150
|
+
cutEnd++;
|
|
151
|
+
} else if (cutStart > 0 && contentNorm.charAt(cutStart - 1) === "\n") {
|
|
152
|
+
cutStart--;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
144
156
|
const newContent =
|
|
145
|
-
contentNorm.slice(0,
|
|
157
|
+
contentNorm.slice(0, cutStart) +
|
|
146
158
|
replaceNorm +
|
|
147
|
-
contentNorm.slice(
|
|
159
|
+
contentNorm.slice(cutEnd);
|
|
148
160
|
return {
|
|
149
161
|
success: true,
|
|
150
162
|
newContent: restoreLineEndings(newContent, hadCrlf),
|
|
@@ -166,10 +178,23 @@ function applySingleBlock(
|
|
|
166
178
|
}
|
|
167
179
|
}
|
|
168
180
|
const start = bestOffset;
|
|
181
|
+
let cutStart = start;
|
|
182
|
+
let cutEnd = start + searchNorm.length;
|
|
183
|
+
if (replaceNorm === "") {
|
|
184
|
+
const isLineStart = cutStart === 0 || contentNorm.charAt(cutStart - 1) === "\n";
|
|
185
|
+
const isLineEnd = cutEnd === contentNorm.length || contentNorm.charAt(cutEnd) === "\n";
|
|
186
|
+
if (isLineStart && isLineEnd) {
|
|
187
|
+
if (cutEnd < contentNorm.length && contentNorm.charAt(cutEnd) === "\n") {
|
|
188
|
+
cutEnd++;
|
|
189
|
+
} else if (cutStart > 0 && contentNorm.charAt(cutStart - 1) === "\n") {
|
|
190
|
+
cutStart--;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
169
194
|
const newContent =
|
|
170
|
-
contentNorm.slice(0,
|
|
195
|
+
contentNorm.slice(0, cutStart) +
|
|
171
196
|
replaceNorm +
|
|
172
|
-
contentNorm.slice(
|
|
197
|
+
contentNorm.slice(cutEnd);
|
|
173
198
|
return {
|
|
174
199
|
success: true,
|
|
175
200
|
newContent: restoreLineEndings(newContent, hadCrlf),
|
|
@@ -337,7 +362,7 @@ export function preflightSurgicalPatchBlock(
|
|
|
337
362
|
const resolvedPath = resolvePatchPath(filePath);
|
|
338
363
|
const target = readPatchTarget(resolvedPath);
|
|
339
364
|
if ("error" in target) {
|
|
340
|
-
const err =
|
|
365
|
+
const err = target.error.error || "Could not read target file";
|
|
341
366
|
return { success: false, error: err };
|
|
342
367
|
}
|
|
343
368
|
const result = applySingleBlock(target.content, search, "", options);
|
|
@@ -461,7 +486,7 @@ export function applySurgicalPatch(
|
|
|
461
486
|
}
|
|
462
487
|
|
|
463
488
|
let candidateContent = result.newContent;
|
|
464
|
-
let syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
489
|
+
let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
465
490
|
let autoHealed = false;
|
|
466
491
|
|
|
467
492
|
// Delimiter & Bracket Auto-Healing:
|
|
@@ -471,7 +496,7 @@ export function applySurgicalPatch(
|
|
|
471
496
|
const healedJson = healJsonContent(candidateContent);
|
|
472
497
|
if (healedJson) {
|
|
473
498
|
candidateContent = healedJson;
|
|
474
|
-
syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
499
|
+
syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
475
500
|
autoHealed = syntax.valid;
|
|
476
501
|
}
|
|
477
502
|
} else if (options?.autoHeal !== false) {
|
|
@@ -482,7 +507,7 @@ export function applySurgicalPatch(
|
|
|
482
507
|
const retryReplace = replace + appendDelims;
|
|
483
508
|
const reResult = applySingleBlock(originalContent, search, retryReplace, options);
|
|
484
509
|
if (reResult.success) {
|
|
485
|
-
const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent);
|
|
510
|
+
const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent, originalContent);
|
|
486
511
|
if (reSyntax.valid) {
|
|
487
512
|
candidateContent = reResult.newContent;
|
|
488
513
|
syntax = reSyntax;
|
|
@@ -515,17 +540,19 @@ export function applySurgicalPatch(
|
|
|
515
540
|
return writeError;
|
|
516
541
|
}
|
|
517
542
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
543
|
+
let finalStrategy = result.strategy;
|
|
544
|
+
if (autoHealed) {
|
|
545
|
+
finalStrategy = `${result.strategy} (auto-healed syntax)`;
|
|
546
|
+
} else if (!syntax.valid) {
|
|
547
|
+
finalStrategy = `${result.strategy} (applied with syntax warning)`;
|
|
548
|
+
}
|
|
523
549
|
|
|
524
550
|
return {
|
|
525
551
|
success: true,
|
|
526
552
|
filePath: resolvedPath,
|
|
527
553
|
strategy: finalStrategy,
|
|
528
554
|
targetRanges: result.targetRange ? [result.targetRange] : [],
|
|
555
|
+
syntax,
|
|
529
556
|
diffOutput: diff.createPatch(
|
|
530
557
|
path.basename(resolvedPath),
|
|
531
558
|
originalContent,
|
|
@@ -588,10 +615,19 @@ export function applyMultiBlockPatch(
|
|
|
588
615
|
};
|
|
589
616
|
}
|
|
590
617
|
|
|
618
|
+
const targetRange = located.targetRange;
|
|
619
|
+
if (!targetRange) {
|
|
620
|
+
return {
|
|
621
|
+
success: false,
|
|
622
|
+
filePath: resolvedPath,
|
|
623
|
+
strategy: "none",
|
|
624
|
+
error: `Block ${i + 1}/${blocks.length} missing target range in ${resolvedPath}`,
|
|
625
|
+
};
|
|
626
|
+
}
|
|
591
627
|
const overlaps = plannedRanges.some(
|
|
592
628
|
(range) =>
|
|
593
|
-
range.startLine <=
|
|
594
|
-
|
|
629
|
+
range.startLine <= targetRange.endLine &&
|
|
630
|
+
targetRange.startLine <= range.endLine,
|
|
595
631
|
);
|
|
596
632
|
if (overlaps) {
|
|
597
633
|
return {
|
|
@@ -601,7 +637,7 @@ export function applyMultiBlockPatch(
|
|
|
601
637
|
error: `Block ${i + 1}/${blocks.length} overlaps another patch target in ${resolvedPath}.`,
|
|
602
638
|
};
|
|
603
639
|
}
|
|
604
|
-
plannedRanges.push({ ...
|
|
640
|
+
plannedRanges.push({ ...targetRange });
|
|
605
641
|
}
|
|
606
642
|
|
|
607
643
|
let currentContent = originalContent;
|
|
@@ -626,15 +662,15 @@ export function applyMultiBlockPatch(
|
|
|
626
662
|
error: `Block ${i + 1}/${blocks.length} failed: ${result.error} in ${resolvedPath}`,
|
|
627
663
|
};
|
|
628
664
|
}
|
|
629
|
-
const
|
|
630
|
-
const replaceCount = block.replace.split("\n").length;
|
|
631
|
-
lineDelta += (replaceCount - searchCount);
|
|
665
|
+
const beforeLines = currentContent.split("\n").length;
|
|
632
666
|
currentContent = result.newContent;
|
|
667
|
+
const afterLines = currentContent.split("\n").length;
|
|
668
|
+
lineDelta += (afterLines - beforeLines);
|
|
633
669
|
appliedStrategies.push(`Block ${i + 1}: ${result.strategy}`);
|
|
634
670
|
}
|
|
635
671
|
|
|
636
672
|
let candidateContent = currentContent;
|
|
637
|
-
let syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
673
|
+
let syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
638
674
|
let autoHealed = false;
|
|
639
675
|
|
|
640
676
|
if (!syntax.valid) {
|
|
@@ -643,7 +679,7 @@ export function applyMultiBlockPatch(
|
|
|
643
679
|
const healedJson = healJsonContent(candidateContent);
|
|
644
680
|
if (healedJson) {
|
|
645
681
|
candidateContent = healedJson;
|
|
646
|
-
syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
682
|
+
syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
647
683
|
autoHealed = syntax.valid;
|
|
648
684
|
}
|
|
649
685
|
}
|
|
@@ -671,17 +707,19 @@ export function applyMultiBlockPatch(
|
|
|
671
707
|
return writeError;
|
|
672
708
|
}
|
|
673
709
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
710
|
+
let finalStrategy = appliedStrategies.join(", ");
|
|
711
|
+
if (autoHealed) {
|
|
712
|
+
finalStrategy = `${appliedStrategies.join(", ")} (auto-healed syntax)`;
|
|
713
|
+
} else if (!syntax.valid) {
|
|
714
|
+
finalStrategy = `${appliedStrategies.join(", ")} (applied with syntax warning)`;
|
|
715
|
+
}
|
|
679
716
|
|
|
680
717
|
return {
|
|
681
718
|
success: true,
|
|
682
719
|
filePath: resolvedPath,
|
|
683
720
|
strategy: finalStrategy,
|
|
684
721
|
targetRanges: plannedRanges,
|
|
722
|
+
syntax,
|
|
685
723
|
diffOutput: diff.createPatch(
|
|
686
724
|
path.basename(resolvedPath),
|
|
687
725
|
originalContent,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { checkSyntax } from "./syntax-verify";
|
|
1
|
+
import { checkSyntax, type VerificationResult } from "./syntax-verify";
|
|
2
2
|
|
|
3
3
|
export type VerificationState =
|
|
4
4
|
| "clean"
|
|
@@ -53,10 +53,12 @@ function diagnosticValue(result: DiagnosticVerification): string {
|
|
|
53
53
|
counts.set(severity, (counts.get(severity) || 0) + 1);
|
|
54
54
|
}
|
|
55
55
|
return Array.from(counts.entries())
|
|
56
|
-
.map(
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
.map(([severity, count]) => {
|
|
57
|
+
let label = "err";
|
|
58
|
+
if (severity === "warning") label = "warn";
|
|
59
|
+
else if (severity === "info") label = "info";
|
|
60
|
+
return `${count} ${label}`;
|
|
61
|
+
})
|
|
60
62
|
.join(",");
|
|
61
63
|
}
|
|
62
64
|
|
|
@@ -77,6 +79,7 @@ export function renderPostEditVerification(
|
|
|
77
79
|
result: PostEditVerification,
|
|
78
80
|
reason?: string,
|
|
79
81
|
targetFile?: string,
|
|
82
|
+
lineSpanSummary?: string,
|
|
80
83
|
): string {
|
|
81
84
|
const hasSyntaxFailure = result.syntax.state === "failed";
|
|
82
85
|
const hasSyntaxUncertainty = [
|
|
@@ -99,7 +102,8 @@ export function renderPostEditVerification(
|
|
|
99
102
|
!hasDiagnosticWarning &&
|
|
100
103
|
(!hasSyntaxUncertainty || result.syntax.state === "clean")
|
|
101
104
|
) {
|
|
102
|
-
|
|
105
|
+
const spanInfo = lineSpanSummary ? ` (${lineSpanSummary})` : "";
|
|
106
|
+
return targetFile ? `Successfully applied edit to ${targetFile}${spanInfo}.` : `Successfully applied edit${spanInfo}.`;
|
|
103
107
|
}
|
|
104
108
|
|
|
105
109
|
const lines: string[] = [];
|
|
@@ -117,7 +121,7 @@ export function renderPostEditVerification(
|
|
|
117
121
|
}
|
|
118
122
|
|
|
119
123
|
// Edit was applied
|
|
120
|
-
lines.push("Edit: Applied");
|
|
124
|
+
lines.push(lineSpanSummary ? `Edit: Applied (${lineSpanSummary})` : "Edit: Applied");
|
|
121
125
|
|
|
122
126
|
if (hasSyntaxFailure || (hasSyntaxUncertainty && result.syntax.state !== "clean")) {
|
|
123
127
|
lines.push("Syntax Error:");
|
|
@@ -128,12 +132,12 @@ export function renderPostEditVerification(
|
|
|
128
132
|
const header = hasDiagnosticError ? "Diagnostics (errors):" : "Diagnostics (warnings):";
|
|
129
133
|
lines.push(header);
|
|
130
134
|
for (const finding of result.diagnostic.findings.slice(0, 5)) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
let pos = "";
|
|
136
|
+
if (finding.line !== undefined) {
|
|
137
|
+
pos = finding.column !== undefined
|
|
138
|
+
? `[${finding.line}:${finding.column}] `
|
|
139
|
+
: `[${finding.line}] `;
|
|
140
|
+
}
|
|
137
141
|
lines.push(` - ${pos}${compactMessage(finding.message)}`);
|
|
138
142
|
}
|
|
139
143
|
if (result.diagnostic.findings.length > 5) {
|
|
@@ -159,8 +163,10 @@ export function renderEditFailure(reason: string): string {
|
|
|
159
163
|
export async function verifyEditedFile(
|
|
160
164
|
filePath: string,
|
|
161
165
|
diagnostics?: () => Promise<DiagnosticCheck>,
|
|
166
|
+
/** The verdict the patch already reached on the written content; skips checking it again. */
|
|
167
|
+
precomputedSyntax?: VerificationResult,
|
|
162
168
|
): Promise<PostEditVerification> {
|
|
163
|
-
const syntax = checkSyntax(filePath);
|
|
169
|
+
const syntax = precomputedSyntax ?? checkSyntax(filePath);
|
|
164
170
|
if (!syntax.valid) {
|
|
165
171
|
return {
|
|
166
172
|
edit: "applied",
|
|
@@ -44,9 +44,9 @@ function fnvHash(prev: string, curr: string, next: string): string {
|
|
|
44
44
|
*/
|
|
45
45
|
export function computeLineHash(fileLines: readonly string[], index: number): string {
|
|
46
46
|
if (index < 0 || index >= fileLines.length) return "";
|
|
47
|
-
const prev = index > 0 ? normalizeLine(fileLines[index - 1]
|
|
48
|
-
const curr = normalizeLine(fileLines[index]
|
|
49
|
-
const next = index < fileLines.length - 1 ? normalizeLine(fileLines[index + 1]
|
|
47
|
+
const prev = index > 0 ? normalizeLine(fileLines[index - 1] ?? "") : "";
|
|
48
|
+
const curr = normalizeLine(fileLines[index] ?? "");
|
|
49
|
+
const next = index < fileLines.length - 1 ? normalizeLine(fileLines[index + 1] ?? "") : "";
|
|
50
50
|
return fnvHash(prev, curr, next);
|
|
51
51
|
}
|
|
52
52
|
|
|
@@ -282,9 +282,11 @@ export function preflightSmartAnchorEdits(
|
|
|
282
282
|
|
|
283
283
|
// Check for conflicting / overlapping spans
|
|
284
284
|
for (let j = 0; j < resolvedSpans.length; j++) {
|
|
285
|
-
const left = resolvedSpans[j]
|
|
285
|
+
const left = resolvedSpans[j];
|
|
286
|
+
if (!left) continue;
|
|
286
287
|
for (let k = j + 1; k < resolvedSpans.length; k++) {
|
|
287
|
-
const right = resolvedSpans[k]
|
|
288
|
+
const right = resolvedSpans[k];
|
|
289
|
+
if (!right) continue;
|
|
288
290
|
if (left.startLine <= right.endLine && right.startLine <= left.endLine) {
|
|
289
291
|
return {
|
|
290
292
|
success: false,
|
|
@@ -363,7 +365,7 @@ export function applySmartAnchorEdits(
|
|
|
363
365
|
: candidateContentNorm;
|
|
364
366
|
|
|
365
367
|
// Syntax validation gate
|
|
366
|
-
const syntax = checkSyntaxContent(resolvedPath, candidateContent);
|
|
368
|
+
const syntax = checkSyntaxContent(resolvedPath, candidateContent, originalContent);
|
|
367
369
|
if (!syntax.valid && options.syntaxGate !== "warn") {
|
|
368
370
|
return {
|
|
369
371
|
success: false,
|
|
@@ -409,5 +411,6 @@ export function applySmartAnchorEdits(
|
|
|
409
411
|
strategy: "smart_anchor",
|
|
410
412
|
diffOutput,
|
|
411
413
|
targetRanges: preflight.targetRanges,
|
|
414
|
+
syntax,
|
|
412
415
|
};
|
|
413
416
|
}
|