@floydous/pi-agent-kernel 0.3.1 → 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.
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Delimiter auto-healer for code and JSON.
3
+ *
4
+ * Catches the common agent failure mode where an edit truncates or forgets
5
+ * closing delimiters () [] {} in replacement blocks.
6
+ */
7
+
8
+ import { TreeSitterEngine } from "../retrieval/tree_sitter_engine";
9
+
10
+ export interface HealingResult {
11
+ healed: boolean;
12
+ code: string;
13
+ appliedFixes: string[];
14
+ reason?: string;
15
+ }
16
+
17
+ /**
18
+ * Calculates unclosed opening delimiters in a snippet of code,
19
+ * properly respecting string literals ('', "", ``), escapes, and comments (// and /* *\/).
20
+ */
21
+ export function getUnclosedDelimiters(text: string): string[] {
22
+ const stack: string[] = [];
23
+ let inStr: string | null = null;
24
+ let esc = false;
25
+ let inLineComment = false;
26
+ let inBlockComment = false;
27
+
28
+ for (let i = 0; i < text.length; i++) {
29
+ const c = text[i];
30
+ if (inLineComment) {
31
+ if (c === "\n") inLineComment = false;
32
+ continue;
33
+ }
34
+ if (inBlockComment) {
35
+ if (c === "*" && i + 1 < text.length && text[i + 1] === "/") {
36
+ inBlockComment = false;
37
+ i++;
38
+ }
39
+ continue;
40
+ }
41
+ if (inStr) {
42
+ if (esc) {
43
+ esc = false;
44
+ } else if (c === "\\") {
45
+ esc = true;
46
+ } else if (c === inStr) {
47
+ inStr = null;
48
+ }
49
+ continue;
50
+ }
51
+ if (c === "'" || c === '"' || c === "`") {
52
+ inStr = c;
53
+ continue;
54
+ }
55
+ if (c === "/" && i + 1 < text.length) {
56
+ if (text[i + 1] === "/") {
57
+ inLineComment = true;
58
+ i++;
59
+ continue;
60
+ } else if (text[i + 1] === "*") {
61
+ inBlockComment = true;
62
+ i++;
63
+ continue;
64
+ }
65
+ }
66
+ if (c === "{" || c === "(" || c === "[") {
67
+ stack.push(c);
68
+ } else if (c === "}" || c === ")" || c === "]") {
69
+ const match = stack[stack.length - 1];
70
+ if (
71
+ (match === "{" && c === "}") ||
72
+ (match === "(" && c === ")") ||
73
+ (match === "[" && c === "]")
74
+ ) {
75
+ stack.pop();
76
+ }
77
+ }
78
+ }
79
+
80
+ const map: Record<string, string> = { "{": "}", "(": ")", "[": "]" };
81
+ return stack.reverse().map((ch) => map[ch]);
82
+ }
83
+
84
+ /**
85
+ * Heals truncated JSON by stripping trailing commas and closing open braces/brackets.
86
+ */
87
+ export function healJsonContent(jsonStr: string): string | null {
88
+ try {
89
+ JSON.parse(jsonStr);
90
+ return jsonStr;
91
+ } catch {
92
+ // continue to repair
93
+ }
94
+
95
+ const stack: string[] = [];
96
+ let inStr = false;
97
+ let esc = false;
98
+ for (let i = 0; i < jsonStr.length; i++) {
99
+ const c = jsonStr[i];
100
+ if (inStr) {
101
+ if (esc) esc = false;
102
+ else if (c === "\\") esc = true;
103
+ else if (c === '"') inStr = false;
104
+ continue;
105
+ }
106
+ if (c === '"') inStr = true;
107
+ else if (c === "{" || c === "[") stack.push(c);
108
+ else if (c === "}" || c === "]") {
109
+ const top = stack[stack.length - 1];
110
+ if ((top === "{" && c === "}") || (top === "[" && c === "]")) stack.pop();
111
+ }
112
+ }
113
+
114
+ if (stack.length === 0) return null;
115
+ const closers: Record<string, string> = { "{": "}", "[": "]" };
116
+ let candidate = jsonStr.trimEnd();
117
+ if (candidate.endsWith(",")) candidate = candidate.slice(0, -1);
118
+ for (let i = stack.length - 1; i >= 0; i--) {
119
+ candidate += "\n" + closers[stack[i]];
120
+ }
121
+ try {
122
+ JSON.parse(candidate);
123
+ return candidate;
124
+ } catch {
125
+ return null;
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Attempts to heal missing closing delimiters in a patched file using Tree-sitter.
131
+ */
132
+ export async function healMissingDelimitersWithAst(
133
+ filePath: string,
134
+ code: string,
135
+ ): Promise<HealingResult> {
136
+ const ext = "." + filePath.split(".").pop();
137
+ const engine = TreeSitterEngine.getInstance();
138
+ await engine.init();
139
+ await engine.loadLanguages([ext]);
140
+ const parser = engine.getParser(ext);
141
+
142
+ if (!parser) {
143
+ return {
144
+ healed: false,
145
+ code,
146
+ appliedFixes: [],
147
+ reason: "No parser available for language",
148
+ };
149
+ }
150
+
151
+ const initialTree = parser.parse(code);
152
+ if (!initialTree.rootNode.hasError) {
153
+ return { healed: true, code, appliedFixes: [], reason: "Code already valid" };
154
+ }
155
+
156
+ const missingNodes: any[] = [];
157
+ const errorNodes: any[] = [];
158
+
159
+ function walk(node: any) {
160
+ if (node.isMissing) {
161
+ missingNodes.push({
162
+ type: node.type,
163
+ startIndex: node.startIndex,
164
+ endIndex: node.endIndex,
165
+ startPosition: node.startPosition,
166
+ endPosition: node.endPosition,
167
+ });
168
+ }
169
+ if (node.isError) {
170
+ errorNodes.push(node);
171
+ }
172
+ for (let i = 0; i < node.childCount; i++) {
173
+ walk(node.child(i));
174
+ }
175
+ }
176
+ walk(initialTree.rootNode);
177
+
178
+ // If there are genuine syntax error nodes (not just missing tokens), do NOT blindly heal
179
+ if (errorNodes.length > 0 || missingNodes.length === 0) {
180
+ return {
181
+ healed: false,
182
+ code,
183
+ appliedFixes: [],
184
+ reason: `Unrecoverable syntax errors (${errorNodes.length} error nodes, ${missingNodes.length} missing nodes)`,
185
+ };
186
+ }
187
+
188
+ const allowedDelimiters = new Set(["}", ")", "]", ";"]);
189
+ const invalidMissing = missingNodes.filter((n) => !allowedDelimiters.has(n.type));
190
+ if (invalidMissing.length > 0) {
191
+ return {
192
+ healed: false,
193
+ code,
194
+ appliedFixes: [],
195
+ reason: `Non-delimiter tokens missing: ${invalidMissing.map((n) => n.type).join(", ")}`,
196
+ };
197
+ }
198
+
199
+ // Sort missing nodes descending by start index to preserve positions during insertion
200
+ const sorted = [...missingNodes].sort((a, b) => b.startIndex - a.startIndex);
201
+ let repairedCode = code;
202
+ const fixes: string[] = [];
203
+
204
+ for (const node of sorted) {
205
+ const insertPos = Math.min(node.startIndex, repairedCode.length);
206
+ const token = node.type;
207
+ const toInsert =
208
+ token === "}" && !repairedCode.slice(0, insertPos).endsWith("\n")
209
+ ? "\n" + token
210
+ : token;
211
+
212
+ repairedCode =
213
+ repairedCode.slice(0, insertPos) + toInsert + repairedCode.slice(insertPos);
214
+ fixes.push(`Inserted '${token}' at line ${node.startPosition.row + 1}`);
215
+ }
216
+
217
+ const verifyTree = parser.parse(repairedCode);
218
+ if (!verifyTree.rootNode.hasError) {
219
+ return {
220
+ healed: true,
221
+ code: repairedCode,
222
+ appliedFixes: fixes,
223
+ };
224
+ }
225
+
226
+ return {
227
+ healed: false,
228
+ code,
229
+ appliedFixes: [],
230
+ reason: "Syntax still invalid after delimiter insertion",
231
+ };
232
+ }
@@ -4,7 +4,7 @@ import { resolveUserPath } from "../safety/epistemic_guard";
4
4
  import * as diff from "diff";
5
5
  import { checkSyntaxContent } from "./syntax-verify";
6
6
  import { writeFileSyncAtomic } from "../safety/atomic_write";
7
-
7
+ import { getUnclosedDelimiters, healJsonContent } from "./auto_heal";
8
8
  /**
9
9
  * Result of composing and validating a surgical patch.
10
10
  *
@@ -25,6 +25,13 @@ export interface PatchResult {
25
25
  export interface PatchBlock {
26
26
  search: string;
27
27
  replace: string;
28
+ startLine?: number;
29
+ endLine?: number;
30
+ lineHint?: number;
31
+ start_line?: number;
32
+ end_line?: number;
33
+ line_hint?: number;
34
+ autoHeal?: boolean;
28
35
  }
29
36
 
30
37
  /** Inclusive 1-based line span matched by an edit block before mutation. */
@@ -92,12 +99,21 @@ function applySingleBlock(
92
99
  content: string,
93
100
  search: string,
94
101
  replace: string,
102
+ options?: {
103
+ startLine?: number;
104
+ endLine?: number;
105
+ lineHint?: number;
106
+ start_line?: number;
107
+ end_line?: number;
108
+ line_hint?: number;
109
+ },
95
110
  ): {
96
111
  success: boolean;
97
112
  newContent: string;
98
113
  strategy: string;
99
114
  error?: string;
100
115
  targetRange?: PatchTargetRange;
116
+ autoHealed?: boolean;
101
117
  } {
102
118
  const hadCrlf = content.includes("\r\n");
103
119
  const searchNorm = search.replace(/\r\n/g, "\n");
@@ -113,6 +129,8 @@ function applySingleBlock(
113
129
  };
114
130
  }
115
131
 
132
+ const hint = options?.lineHint ?? options?.line_hint ?? options?.startLine ?? options?.start_line;
133
+
116
134
  // Exact matching is safest, but duplicate or overlapping occurrences are
117
135
  // rejected rather than silently selecting one.
118
136
  const exactMatches: number[] = [];
@@ -135,6 +153,30 @@ function applySingleBlock(
135
153
  };
136
154
  }
137
155
  if (exactMatches.length > 1) {
156
+ if (hint !== undefined) {
157
+ const targetLine = hint;
158
+ let bestOffset = exactMatches[0];
159
+ let bestDistance = Infinity;
160
+ for (const offset of exactMatches) {
161
+ const line = contentNorm.slice(0, offset).split("\n").length;
162
+ const dist = Math.abs(line - targetLine);
163
+ if (dist < bestDistance) {
164
+ bestDistance = dist;
165
+ bestOffset = offset;
166
+ }
167
+ }
168
+ const start = bestOffset;
169
+ const newContent =
170
+ contentNorm.slice(0, start) +
171
+ replaceNorm +
172
+ contentNorm.slice(start + searchNorm.length);
173
+ return {
174
+ success: true,
175
+ newContent: restoreLineEndings(newContent, hadCrlf),
176
+ strategy: `exact (line-hinted near line ${contentNorm.slice(0, start).split("\n").length})`,
177
+ targetRange: lineRangeFromOffsets(contentNorm, start, searchNorm.length),
178
+ };
179
+ }
138
180
  return {
139
181
  success: false,
140
182
  newContent: content,
@@ -180,6 +222,34 @@ function applySingleBlock(
180
222
  };
181
223
  }
182
224
  if (normalizedMatches.length > 1) {
225
+ if (hint !== undefined) {
226
+ const targetLine = hint;
227
+ let bestIdx = normalizedMatches[0];
228
+ let bestDistance = Infinity;
229
+ for (const idx of normalizedMatches) {
230
+ const line = idx + 1;
231
+ const dist = Math.abs(line - targetLine);
232
+ if (dist < bestDistance) {
233
+ bestDistance = dist;
234
+ bestIdx = idx;
235
+ }
236
+ }
237
+ return {
238
+ success: true,
239
+ newContent: replaceLineWindow(
240
+ contentLines,
241
+ bestIdx,
242
+ searchLines.length,
243
+ replaceNorm,
244
+ hadCrlf,
245
+ ),
246
+ strategy: `whitespace_normalized (line-hinted near line ${bestIdx + 1})`,
247
+ targetRange: {
248
+ startLine: bestIdx + 1,
249
+ endLine: bestIdx + searchLines.length,
250
+ },
251
+ };
252
+ }
183
253
  return {
184
254
  success: false,
185
255
  newContent: content,
@@ -241,6 +311,47 @@ function applySingleBlock(
241
311
  };
242
312
  }
243
313
 
314
+ export interface PatchPreflightResult {
315
+ success: boolean;
316
+ targetRange?: PatchTargetRange;
317
+ error?: string;
318
+ isAmbiguous?: boolean;
319
+ }
320
+
321
+ /**
322
+ * Preflight a single-block edit without mutating the target. Returns detailed
323
+ * diagnostics including ambiguity detection and line coordinates.
324
+ */
325
+ export function preflightSurgicalPatchBlock(
326
+ filePath: string,
327
+ search: string,
328
+ options?: {
329
+ startLine?: number;
330
+ endLine?: number;
331
+ lineHint?: number;
332
+ start_line?: number;
333
+ end_line?: number;
334
+ line_hint?: number;
335
+ },
336
+ ): PatchPreflightResult {
337
+ const resolvedPath = resolvePatchPath(filePath);
338
+ const target = readPatchTarget(resolvedPath);
339
+ if ("error" in target) {
340
+ const err = (target.error as any).error || "Could not read target file";
341
+ return { success: false, error: err };
342
+ }
343
+ const result = applySingleBlock(target.content, search, "", options);
344
+ if (!result.success || !result.targetRange) {
345
+ const isAmbiguous = (result.error?.toLowerCase() || "").includes("ambiguous");
346
+ return {
347
+ success: false,
348
+ error: result.error || "Could not locate SEARCH block.",
349
+ isAmbiguous,
350
+ };
351
+ }
352
+ return { success: true, targetRange: result.targetRange };
353
+ }
354
+
244
355
  /**
245
356
  * Locate a single-block edit without mutating the target. The edit tool uses
246
357
  * this narrow preflight to compare the matched span with visible read evidence.
@@ -248,12 +359,17 @@ function applySingleBlock(
248
359
  export function findSurgicalPatchTargetRange(
249
360
  filePath: string,
250
361
  search: string,
362
+ options?: {
363
+ startLine?: number;
364
+ endLine?: number;
365
+ lineHint?: number;
366
+ start_line?: number;
367
+ end_line?: number;
368
+ line_hint?: number;
369
+ },
251
370
  ): 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;
371
+ const res = preflightSurgicalPatchBlock(filePath, search, options);
372
+ return res.success ? res.targetRange ?? null : null;
257
373
  }
258
374
 
259
375
  function resolvePatchPath(filePath: string): string {
@@ -318,13 +434,22 @@ export function applySurgicalPatch(
318
434
  filePath: string,
319
435
  search: string,
320
436
  replace: string,
437
+ options?: {
438
+ startLine?: number;
439
+ endLine?: number;
440
+ lineHint?: number;
441
+ start_line?: number;
442
+ end_line?: number;
443
+ line_hint?: number;
444
+ autoHeal?: boolean;
445
+ },
321
446
  ): PatchResult {
322
447
  const resolvedPath = resolvePatchPath(filePath);
323
448
  const target = readPatchTarget(resolvedPath);
324
449
  if ("error" in target) return target.error;
325
450
 
326
451
  const originalContent = target.content;
327
- const result = applySingleBlock(originalContent, search, replace);
452
+ const result = applySingleBlock(originalContent, search, replace, options);
328
453
  if (!result.success) {
329
454
  return {
330
455
  success: false,
@@ -334,7 +459,39 @@ export function applySurgicalPatch(
334
459
  };
335
460
  }
336
461
 
337
- const syntax = checkSyntaxContent(resolvedPath, result.newContent);
462
+ let candidateContent = result.newContent;
463
+ let syntax = checkSyntaxContent(resolvedPath, candidateContent);
464
+ let autoHealed = false;
465
+
466
+ // Delimiter & Bracket Auto-Healing:
467
+ if (!syntax.valid) {
468
+ const ext = path.extname(resolvedPath).toLowerCase();
469
+ if (ext === ".json") {
470
+ const healedJson = healJsonContent(candidateContent);
471
+ if (healedJson) {
472
+ candidateContent = healedJson;
473
+ syntax = checkSyntaxContent(resolvedPath, candidateContent);
474
+ autoHealed = syntax.valid;
475
+ }
476
+ } else if (options?.autoHeal !== false) {
477
+ // Check if the replacement block truncated closing delimiters
478
+ const unclosed = getUnclosedDelimiters(replace);
479
+ if (unclosed.length > 0) {
480
+ const appendDelims = "\n" + unclosed.join("");
481
+ const retryReplace = replace + appendDelims;
482
+ const reResult = applySingleBlock(originalContent, search, retryReplace, options);
483
+ if (reResult.success) {
484
+ const reSyntax = checkSyntaxContent(resolvedPath, reResult.newContent);
485
+ if (reSyntax.valid) {
486
+ candidateContent = reResult.newContent;
487
+ syntax = reSyntax;
488
+ autoHealed = true;
489
+ }
490
+ }
491
+ }
492
+ }
493
+ }
494
+
338
495
  if (!syntax.valid) {
339
496
  return {
340
497
  success: false,
@@ -347,22 +504,26 @@ export function applySurgicalPatch(
347
504
  const writeError = writePatchedContent(
348
505
  resolvedPath,
349
506
  originalContent,
350
- result.newContent,
507
+ candidateContent,
351
508
  );
352
509
  if (writeError) {
353
510
  writeError.strategy = result.strategy;
354
511
  return writeError;
355
512
  }
356
513
 
514
+ const finalStrategy = autoHealed
515
+ ? `${result.strategy} (auto-healed syntax)`
516
+ : result.strategy;
517
+
357
518
  return {
358
519
  success: true,
359
520
  filePath: resolvedPath,
360
- strategy: result.strategy,
521
+ strategy: finalStrategy,
361
522
  targetRanges: result.targetRange ? [result.targetRange] : [],
362
523
  diffOutput: diff.createPatch(
363
524
  path.basename(resolvedPath),
364
525
  originalContent,
365
- result.newContent,
526
+ candidateContent,
366
527
  ),
367
528
  };
368
529
  }
@@ -405,7 +566,12 @@ export function applyMultiBlockPatch(
405
566
  };
406
567
  }
407
568
 
408
- const located = applySingleBlock(originalContent, block.search, "");
569
+ const opt = {
570
+ startLine: block.startLine ?? block.start_line,
571
+ endLine: block.endLine ?? block.end_line,
572
+ lineHint: block.lineHint ?? block.line_hint,
573
+ };
574
+ const located = applySingleBlock(originalContent, block.search, "", opt);
409
575
  if (!located.success || !located.targetRange) {
410
576
  return {
411
577
  success: false,
@@ -433,9 +599,18 @@ export function applyMultiBlockPatch(
433
599
 
434
600
  let currentContent = originalContent;
435
601
  const appliedStrategies: string[] = [];
602
+ let lineDelta = 0;
436
603
  for (let i = 0; i < blocks.length; i++) {
437
604
  const block = blocks[i];
438
- const result = applySingleBlock(currentContent, block.search, block.replace);
605
+ const baseStart = block.startLine ?? block.start_line;
606
+ const baseEnd = block.endLine ?? block.end_line;
607
+ const baseHint = block.lineHint ?? block.line_hint;
608
+ const opt = {
609
+ startLine: baseStart !== undefined ? baseStart + lineDelta : undefined,
610
+ endLine: baseEnd !== undefined ? baseEnd + lineDelta : undefined,
611
+ lineHint: baseHint !== undefined ? baseHint + lineDelta : undefined,
612
+ };
613
+ const result = applySingleBlock(currentContent, block.search, block.replace, opt);
439
614
  if (!result.success) {
440
615
  return {
441
616
  success: false,
@@ -444,11 +619,29 @@ export function applyMultiBlockPatch(
444
619
  error: `Block ${i + 1}/${blocks.length} failed: ${result.error} in ${resolvedPath}`,
445
620
  };
446
621
  }
622
+ const searchCount = block.search.split("\n").length;
623
+ const replaceCount = block.replace.split("\n").length;
624
+ lineDelta += (replaceCount - searchCount);
447
625
  currentContent = result.newContent;
448
626
  appliedStrategies.push(`Block ${i + 1}: ${result.strategy}`);
449
627
  }
450
628
 
451
- const syntax = checkSyntaxContent(resolvedPath, currentContent);
629
+ let candidateContent = currentContent;
630
+ let syntax = checkSyntaxContent(resolvedPath, candidateContent);
631
+ let autoHealed = false;
632
+
633
+ if (!syntax.valid) {
634
+ const ext = path.extname(resolvedPath).toLowerCase();
635
+ if (ext === ".json") {
636
+ const healedJson = healJsonContent(candidateContent);
637
+ if (healedJson) {
638
+ candidateContent = healedJson;
639
+ syntax = checkSyntaxContent(resolvedPath, candidateContent);
640
+ autoHealed = syntax.valid;
641
+ }
642
+ }
643
+ }
644
+
452
645
  if (!syntax.valid) {
453
646
  return {
454
647
  success: false,
@@ -461,22 +654,26 @@ export function applyMultiBlockPatch(
461
654
  const writeError = writePatchedContent(
462
655
  resolvedPath,
463
656
  originalContent,
464
- currentContent,
657
+ candidateContent,
465
658
  );
466
659
  if (writeError) {
467
660
  writeError.strategy = appliedStrategies.join(", ");
468
661
  return writeError;
469
662
  }
470
663
 
664
+ const finalStrategy = autoHealed
665
+ ? `${appliedStrategies.join(", ")} (auto-healed syntax)`
666
+ : appliedStrategies.join(", ");
667
+
471
668
  return {
472
669
  success: true,
473
670
  filePath: resolvedPath,
474
- strategy: appliedStrategies.join(", "),
671
+ strategy: finalStrategy,
475
672
  targetRanges: plannedRanges,
476
673
  diffOutput: diff.createPatch(
477
674
  path.basename(resolvedPath),
478
675
  originalContent,
479
- currentContent,
676
+ candidateContent,
480
677
  ),
481
678
  };
482
679
  }
@@ -76,6 +76,7 @@ function verificationEntries(
76
76
  export function renderPostEditVerification(
77
77
  result: PostEditVerification,
78
78
  reason?: string,
79
+ targetFile?: string,
79
80
  ): string {
80
81
  const hasSyntaxFailure = result.syntax.state === "failed";
81
82
  const hasSyntaxUncertainty = [
@@ -90,7 +91,7 @@ export function renderPostEditVerification(
90
91
  (finding) => finding.severity === "warning" || finding.severity === "info",
91
92
  );
92
93
 
93
- // Token density: return empty string on completely clean verification
94
+ // Return explicit concise confirmation on clean verification
94
95
  if (
95
96
  result.edit === "applied" &&
96
97
  !hasSyntaxFailure &&
@@ -98,7 +99,7 @@ export function renderPostEditVerification(
98
99
  !hasDiagnosticWarning &&
99
100
  (!hasSyntaxUncertainty || result.syntax.state === "clean")
100
101
  ) {
101
- return "";
102
+ return targetFile ? `Successfully applied edit to ${targetFile}.` : "Successfully applied edit.";
102
103
  }
103
104
 
104
105
  const lines: string[] = [];