@floydous/pi-agent-kernel 0.3.31 → 0.4.1

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.
Files changed (40) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +6 -4
  2. package/CHANGELOG.md +35 -4
  3. package/README.md +39 -74
  4. package/config.example.toml +36 -0
  5. package/docs/configuration.md +11 -3
  6. package/docs/retrieval.md +17 -1
  7. package/docs/testing.md +5 -3
  8. package/package.json +9 -7
  9. package/src/config/agent_kernel_command.ts +91 -91
  10. package/src/config/kernel_config.ts +179 -43
  11. package/src/config/toml.ts +15 -4
  12. package/src/context/session_repair.ts +179 -80
  13. package/src/editing/patch.ts +28 -16
  14. package/src/editing/smart_anchor.ts +29 -36
  15. package/src/editing/syntax-verify.ts +52 -18
  16. package/src/index.ts +257 -219
  17. package/src/lsp/lsp_client.ts +138 -23
  18. package/src/lsp/lsp_formatter.ts +61 -24
  19. package/src/lsp/lsp_installer.ts +277 -561
  20. package/src/lsp/lsp_manager.ts +1 -1
  21. package/src/lsp/lsp_registry.ts +110 -73
  22. package/src/retrieval/ast_search.ts +136 -172
  23. package/src/retrieval/repomap.ts +8 -47
  24. package/src/retrieval/search_bm25.ts +5 -2
  25. package/src/retrieval/search_cache.ts +69 -0
  26. package/src/retrieval/search_chunker.ts +21 -43
  27. package/src/retrieval/search_config.ts +75 -18
  28. package/src/retrieval/search_embedder.ts +8 -16
  29. package/src/retrieval/search_index.ts +923 -123
  30. package/src/retrieval/workspace_walker.ts +262 -0
  31. package/src/safety/atomic_write.ts +59 -20
  32. package/src/safety/epistemic_guard.ts +163 -43
  33. package/src/safety/output_clamper.ts +316 -74
  34. package/src/tools/code_search_output.ts +59 -23
  35. package/src/tools/code_search_tool.ts +42 -46
  36. package/src/tools/context.ts +15 -1
  37. package/src/tools/edit_tool.ts +124 -43
  38. package/src/tools/lsp_tool.ts +17 -4
  39. package/src/tools/read_tool.ts +48 -7
  40. package/config.toml +0 -31
@@ -16,8 +16,12 @@ export type TomlValue =
16
16
  | TomlValue[]
17
17
  | { [key: string]: TomlValue };
18
18
 
19
+ function isDangerousKey(key: string): boolean {
20
+ return key === "__proto__" || key === "prototype" || key === "constructor";
21
+ }
22
+
19
23
  export function parseToml(tomlStr: string): Record<string, TomlValue> {
20
- const root: Record<string, TomlValue> = {};
24
+ const root: Record<string, TomlValue> = Object.create(null);
21
25
  let currentTable: Record<string, TomlValue> = root;
22
26
 
23
27
  const lines = tomlStr.split(/\r?\n/);
@@ -33,12 +37,15 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
33
37
  // Table header: [table] or [table.sub]
34
38
  if (line.startsWith("[") && line.endsWith("]") && !line.startsWith("[[")) {
35
39
  const tableName = line.slice(1, -1).trim();
36
- const parts = tableName.split(".").map((p) => p.trim());
40
+ const parts = tableName.split(".").map((p) => p.trim().replace(/^["']|["']$/g, ""));
41
+ if (parts.some(isDangerousKey)) {
42
+ continue;
43
+ }
37
44
  let cursor = root;
38
45
  for (const part of parts) {
39
- const existing = cursor[part];
46
+ const existing = Object.prototype.hasOwnProperty.call(cursor, part) ? cursor[part] : undefined;
40
47
  if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
41
- cursor[part] = {};
48
+ cursor[part] = Object.create(null);
42
49
  }
43
50
  cursor = cursor[part] as Record<string, TomlValue>;
44
51
  }
@@ -51,6 +58,10 @@ export function parseToml(tomlStr: string): Record<string, TomlValue> {
51
58
  if (eqIndex === -1) continue;
52
59
 
53
60
  const key = line.slice(0, eqIndex).trim();
61
+ const cleanKey = key.replace(/^["']|["']$/g, "").trim();
62
+ if (isDangerousKey(cleanKey) || cleanKey.split(".").some(isDangerousKey)) {
63
+ continue;
64
+ }
54
65
  let rawValue = line.slice(eqIndex + 1).trim();
55
66
 
56
67
  // Handle multi-line arrays if open bracket without close bracket
@@ -1,99 +1,198 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import * as os from "os";
1
+ import * as crypto from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
4
  import { getPiHomeDir } from "../config";
5
+ import { writeFileSyncAtomic } from "../safety/atomic_write";
6
+ import { kernelDebug } from "../safety/kernel_debug";
5
7
 
6
- /**
7
- * Sanitizes and repairs session JSONL files in ~/.pi/agent/sessions/
8
- * Ensures that any compaction, branch_summary, or message entry with a partial
9
- * usage object has a valid `cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }`
10
- * to prevent uncaught TypeErrors in Pi's TUI footer renderer (usage-totals.js:15).
11
- */
12
- export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number; repairedEntries: number } {
13
- let repairedFiles = 0;
14
- let repairedEntries = 0;
8
+ const MAX_SESSION_FILE_SIZE = 10 * 1024 * 1024;
9
+ const MAX_SESSIONS_SCANNED = 20;
15
10
 
11
+ export interface SessionRepairOptions {
12
+ agentDir?: string;
13
+ skipFile?: string;
14
+ apply?: boolean;
15
+ }
16
+
17
+ export interface SessionRepairStats {
18
+ scannedFiles: number;
19
+ candidateFiles: number;
20
+ repairedFiles: number;
21
+ repairedEntries: number;
22
+ skippedFiles: number;
23
+ failedFiles: number;
24
+ dryRun: boolean;
25
+ }
26
+
27
+ interface FileRepairResult {
28
+ candidate: boolean;
29
+ repaired: boolean;
30
+ entries: number;
31
+ skipped: boolean;
32
+ error?: string;
33
+ }
34
+
35
+ function sha256(content: string): string {
36
+ return crypto.createHash("sha256").update(content).digest("hex");
37
+ }
38
+
39
+ function samePath(left: string, right: string): boolean {
40
+ const a = path.resolve(left);
41
+ const b = path.resolve(right);
42
+ return process.platform === "win32"
43
+ ? a.toLowerCase() === b.toLowerCase()
44
+ : a === b;
45
+ }
46
+
47
+ function withRepairLock<T>(filePath: string, operation: () => T): T {
48
+ const lockPath = `${filePath}.agent-kernel-repair.lock`;
49
+ let descriptor: number | undefined;
16
50
  try {
17
- const baseAgentDir = agentDir || path.join(getPiHomeDir(), "agent");
18
- const sessionsDir = path.join(baseAgentDir, "sessions");
51
+ descriptor = fs.openSync(lockPath, "wx", 0o600);
52
+ } catch (error: any) {
53
+ if (error?.code === "EEXIST") throw new Error("another repair holds the file lock");
54
+ throw error;
55
+ }
56
+ try {
57
+ fs.writeFileSync(descriptor, `${process.pid}\n${new Date().toISOString()}\n`, "utf8");
58
+ return operation();
59
+ } finally {
60
+ if (descriptor !== undefined) fs.closeSync(descriptor);
61
+ try {
62
+ fs.unlinkSync(lockPath);
63
+ } catch (error) {
64
+ kernelDebug(error);
65
+ }
66
+ }
67
+ }
68
+
69
+ function repairSessionFile(filePath: string, apply: boolean): FileRepairResult {
70
+ const stat = fs.lstatSync(filePath);
71
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_SESSION_FILE_SIZE) {
72
+ return { candidate: false, repaired: false, entries: 0, skipped: true };
73
+ }
19
74
 
20
- if (!fs.existsSync(sessionsDir)) {
21
- return { repairedFiles: 0, repairedEntries: 0 };
75
+ const original = fs.readFileSync(filePath, "utf8");
76
+ let entriesRepaired = 0;
77
+ const repairedLines = original.split(/(\r?\n)/).map((line, index) => {
78
+ // Keep captured separators verbatim so repaired records retain each original EOL.
79
+ if (index % 2 === 1 || !line.trim()) return line;
80
+ try {
81
+ const entry = JSON.parse(line);
82
+ let modified = false;
83
+ if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
84
+ if (!entry.usage.cost || typeof entry.usage.cost.total !== "number") {
85
+ entry.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
86
+ modified = true;
87
+ }
88
+ }
89
+ if (entry.type === "message" && entry.message?.usage) {
90
+ if (!entry.message.usage.cost || typeof entry.message.usage.cost.total !== "number") {
91
+ entry.message.usage.cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
92
+ modified = true;
93
+ }
94
+ }
95
+ if (modified) {
96
+ entriesRepaired++;
97
+ return JSON.stringify(entry);
98
+ }
99
+ } catch {
100
+ // Leave malformed lines byte-for-byte unchanged.
22
101
  }
102
+ return line;
103
+ });
23
104
 
24
- const sessionFolders = fs.readdirSync(sessionsDir);
105
+ if (entriesRepaired === 0) {
106
+ return { candidate: false, repaired: false, entries: 0, skipped: false };
107
+ }
108
+ if (!apply) {
109
+ return { candidate: true, repaired: false, entries: entriesRepaired, skipped: false };
110
+ }
25
111
 
26
- for (const folder of sessionFolders) {
27
- const folderPath = path.join(sessionsDir, folder);
28
- if (!fs.statSync(folderPath).isDirectory()) continue;
112
+ const originalHash = sha256(original);
113
+ const repairedContent = repairedLines.join("");
114
+ return withRepairLock(filePath, () => {
115
+ const current = fs.readFileSync(filePath, "utf8");
116
+ if (sha256(current) !== originalHash) {
117
+ return { candidate: true, repaired: false, entries: 0, skipped: true, error: "file changed during repair" };
118
+ }
29
119
 
30
- const files = fs.readdirSync(folderPath);
31
- for (const file of files) {
32
- if (!file.endsWith(".jsonl")) continue;
120
+ const backupPath = `${filePath}.${Date.now()}.agent-kernel.bak`;
121
+ fs.copyFileSync(filePath, backupPath, fs.constants.COPYFILE_EXCL);
122
+ if (sha256(fs.readFileSync(filePath, "utf8")) !== originalHash) {
123
+ throw new Error("file changed before replacement");
124
+ }
125
+ writeFileSyncAtomic(filePath, repairedContent);
126
+ if (fs.readFileSync(filePath, "utf8") !== repairedContent) {
127
+ throw new Error("repaired content verification failed");
128
+ }
129
+ return { candidate: true, repaired: true, entries: entriesRepaired, skipped: false };
130
+ });
131
+ }
33
132
 
133
+ export function sanitizeSessionFiles(
134
+ optionsOrAgentDir: SessionRepairOptions | string = {},
135
+ ): SessionRepairStats {
136
+ const options = typeof optionsOrAgentDir === "string"
137
+ ? { agentDir: optionsOrAgentDir }
138
+ : optionsOrAgentDir;
139
+ const apply = options.apply === true;
140
+ const stats: SessionRepairStats = {
141
+ scannedFiles: 0,
142
+ candidateFiles: 0,
143
+ repairedFiles: 0,
144
+ repairedEntries: 0,
145
+ skippedFiles: 0,
146
+ failedFiles: 0,
147
+ dryRun: !apply,
148
+ };
149
+
150
+ try {
151
+ const baseAgentDir = options.agentDir || path.join(getPiHomeDir(), "agent");
152
+ const sessionsDir = path.join(baseAgentDir, "sessions");
153
+ if (!fs.existsSync(sessionsDir)) return stats;
154
+
155
+ const sessionFolders = fs.readdirSync(sessionsDir)
156
+ .map((folder) => {
157
+ const folderPath = path.join(sessionsDir, folder);
158
+ try {
159
+ const stat = fs.lstatSync(folderPath);
160
+ return { folderPath, isDir: stat.isDirectory() && !stat.isSymbolicLink(), mtime: stat.mtimeMs };
161
+ } catch {
162
+ return { folderPath, isDir: false, mtime: 0 };
163
+ }
164
+ })
165
+ .filter((folder) => folder.isDir)
166
+ .sort((a, b) => b.mtime - a.mtime)
167
+ .slice(0, MAX_SESSIONS_SCANNED);
168
+
169
+ for (const { folderPath } of sessionFolders) {
170
+ for (const file of fs.readdirSync(folderPath)) {
171
+ if (!file.endsWith(".jsonl")) continue;
34
172
  const filePath = path.join(folderPath, file);
173
+ if (options.skipFile && samePath(filePath, options.skipFile)) {
174
+ stats.skippedFiles++;
175
+ continue;
176
+ }
177
+ stats.scannedFiles++;
35
178
  try {
36
- const content = fs.readFileSync(filePath, "utf8");
37
- const lines = content.split("\n");
38
- let fileModified = false;
39
-
40
- const repairedLines = lines.map((line) => {
41
- if (!line.trim()) return line;
42
- try {
43
- const entry = JSON.parse(line);
44
- let entryModified = false;
45
-
46
- // Check compaction / branch_summary usage
47
- if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
48
- if (!entry.usage.cost || typeof entry.usage.cost.total !== "number") {
49
- entry.usage.cost = {
50
- input: 0,
51
- output: 0,
52
- cacheRead: 0,
53
- cacheWrite: 0,
54
- total: 0,
55
- };
56
- entryModified = true;
57
- }
58
- }
59
-
60
- // Check message usage
61
- if (entry.type === "message" && entry.message && entry.message.usage) {
62
- if (!entry.message.usage.cost || typeof entry.message.usage.cost.total !== "number") {
63
- entry.message.usage.cost = {
64
- input: 0,
65
- output: 0,
66
- cacheRead: 0,
67
- cacheWrite: 0,
68
- total: 0,
69
- };
70
- entryModified = true;
71
- }
72
- }
73
-
74
- if (entryModified) {
75
- fileModified = true;
76
- repairedEntries++;
77
- return JSON.stringify(entry);
78
- }
79
- } catch (e) {
80
- // Ignore unparseable lines
81
- }
82
- return line;
83
- });
84
-
85
- if (fileModified) {
86
- fs.writeFileSync(filePath, repairedLines.join("\n"), "utf8");
87
- repairedFiles++;
179
+ const result = repairSessionFile(filePath, apply);
180
+ if (result.candidate) stats.candidateFiles++;
181
+ if (result.repaired) {
182
+ stats.repairedFiles++;
183
+ stats.repairedEntries += result.entries;
88
184
  }
89
- } catch (err) {
90
- // Ignore individual file read errors
185
+ if (result.skipped) stats.skippedFiles++;
186
+ } catch (error) {
187
+ stats.failedFiles++;
188
+ kernelDebug(`Session repair failed for ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
91
189
  }
92
190
  }
93
191
  }
94
- } catch (err) {
95
- // Ignore top-level directory errors
192
+ } catch (error) {
193
+ stats.failedFiles++;
194
+ kernelDebug(error);
96
195
  }
97
196
 
98
- return { repairedFiles, repairedEntries };
197
+ return stats;
99
198
  }
@@ -442,6 +442,7 @@ export function applySurgicalPatch(
442
442
  end_line?: number;
443
443
  line_hint?: number;
444
444
  autoHeal?: boolean;
445
+ syntaxGate?: "warn" | "block";
445
446
  },
446
447
  ): PatchResult {
447
448
  const resolvedPath = resolvePatchPath(filePath);
@@ -466,7 +467,7 @@ export function applySurgicalPatch(
466
467
  // Delimiter & Bracket Auto-Healing:
467
468
  if (!syntax.valid) {
468
469
  const ext = path.extname(resolvedPath).toLowerCase();
469
- if (ext === ".json") {
470
+ if (ext === ".json" && options?.autoHeal !== false) {
470
471
  const healedJson = healJsonContent(candidateContent);
471
472
  if (healedJson) {
472
473
  candidateContent = healedJson;
@@ -493,12 +494,15 @@ export function applySurgicalPatch(
493
494
  }
494
495
 
495
496
  if (!syntax.valid) {
496
- return {
497
- success: false,
498
- filePath: resolvedPath,
499
- strategy: result.strategy,
500
- error: syntax.error || "Candidate syntax validation failed",
501
- };
497
+ const shouldBlock = options?.syntaxGate !== "warn";
498
+ if (shouldBlock) {
499
+ return {
500
+ success: false,
501
+ filePath: resolvedPath,
502
+ strategy: result.strategy,
503
+ error: syntax.error || "Candidate syntax validation failed",
504
+ };
505
+ }
502
506
  }
503
507
 
504
508
  const writeError = writePatchedContent(
@@ -513,7 +517,9 @@ export function applySurgicalPatch(
513
517
 
514
518
  const finalStrategy = autoHealed
515
519
  ? `${result.strategy} (auto-healed syntax)`
516
- : result.strategy;
520
+ : !syntax.valid
521
+ ? `${result.strategy} (applied with syntax warning)`
522
+ : result.strategy;
517
523
 
518
524
  return {
519
525
  success: true,
@@ -531,6 +537,7 @@ export function applySurgicalPatch(
531
537
  export function applyMultiBlockPatch(
532
538
  filePath: string,
533
539
  blocks: PatchBlock[],
540
+ options: { autoHeal?: boolean; syntaxGate?: "warn" | "block" } = {},
534
541
  ): PatchResult {
535
542
  const resolvedPath = resolvePatchPath(filePath);
536
543
  const target = readPatchTarget(resolvedPath);
@@ -632,7 +639,7 @@ export function applyMultiBlockPatch(
632
639
 
633
640
  if (!syntax.valid) {
634
641
  const ext = path.extname(resolvedPath).toLowerCase();
635
- if (ext === ".json") {
642
+ if (ext === ".json" && options.autoHeal !== false) {
636
643
  const healedJson = healJsonContent(candidateContent);
637
644
  if (healedJson) {
638
645
  candidateContent = healedJson;
@@ -643,12 +650,15 @@ export function applyMultiBlockPatch(
643
650
  }
644
651
 
645
652
  if (!syntax.valid) {
646
- return {
647
- success: false,
648
- filePath: resolvedPath,
649
- strategy: appliedStrategies.join(", "),
650
- error: syntax.error || "Candidate syntax validation failed",
651
- };
653
+ const shouldBlock = options.syntaxGate !== "warn";
654
+ if (shouldBlock) {
655
+ return {
656
+ success: false,
657
+ filePath: resolvedPath,
658
+ strategy: appliedStrategies.join(", "),
659
+ error: syntax.error || "Candidate syntax validation failed",
660
+ };
661
+ }
652
662
  }
653
663
 
654
664
  const writeError = writePatchedContent(
@@ -663,7 +673,9 @@ export function applyMultiBlockPatch(
663
673
 
664
674
  const finalStrategy = autoHealed
665
675
  ? `${appliedStrategies.join(", ")} (auto-healed syntax)`
666
- : appliedStrategies.join(", ");
676
+ : !syntax.valid
677
+ ? `${appliedStrategies.join(", ")} (applied with syntax warning)`
678
+ : appliedStrategies.join(", ");
667
679
 
668
680
  return {
669
681
  success: true,
@@ -248,42 +248,25 @@ export function preflightSmartAnchorEdits(
248
248
  };
249
249
  }
250
250
 
251
- let recoveredNeighbor = false;
252
-
253
- // Verify Start Anchor Hash
251
+ // A supplied hash authenticates the exact requested line. Attention
252
+ // spillover must never redirect a write to a neighboring line.
254
253
  if (startHash) {
255
254
  const actualHash = computeLineHash(fileLines, startLine - 1);
256
255
  if (actualHash !== startHash) {
257
- // Neighbor tolerance check: attention spillover across adjacent lines
258
- const prevHash = startLine > 1 ? computeLineHash(fileLines, startLine - 2) : undefined;
259
- const nextHash = startLine < totalLines ? computeLineHash(fileLines, startLine) : undefined;
260
-
261
- if (startHash === prevHash || startHash === nextHash) {
262
- recoveredNeighbor = true;
263
- } else {
264
- return {
265
- success: false,
266
- error: formatStaleAnchorError(fileLines, startLine, startHash, actualHash),
267
- };
268
- }
256
+ return {
257
+ success: false,
258
+ error: formatStaleAnchorError(fileLines, startLine, startHash, actualHash),
259
+ };
269
260
  }
270
261
  }
271
262
 
272
- // Verify End Anchor Hash
273
263
  if (endHash) {
274
264
  const actualEndHash = computeLineHash(fileLines, endLine - 1);
275
265
  if (actualEndHash !== endHash) {
276
- const prevHash = endLine > 1 ? computeLineHash(fileLines, endLine - 2) : undefined;
277
- const nextHash = endLine < totalLines ? computeLineHash(fileLines, endLine) : undefined;
278
-
279
- if (endHash === prevHash || endHash === nextHash) {
280
- recoveredNeighbor = true;
281
- } else {
282
- return {
283
- success: false,
284
- error: formatStaleAnchorError(fileLines, endLine, endHash, actualEndHash),
285
- };
286
- }
266
+ return {
267
+ success: false,
268
+ error: formatStaleAnchorError(fileLines, endLine, endHash, actualEndHash),
269
+ };
287
270
  }
288
271
  }
289
272
 
@@ -292,7 +275,7 @@ export function preflightSmartAnchorEdits(
292
275
  startLine,
293
276
  endLine,
294
277
  replacementLines,
295
- recoveredNeighbor,
278
+ recoveredNeighbor: false,
296
279
  });
297
280
  targetRanges.push({ startLine, endLine });
298
281
  }
@@ -323,6 +306,7 @@ export function preflightSmartAnchorEdits(
323
306
  export function applySmartAnchorEdits(
324
307
  filePath: string,
325
308
  edits: SmartAnchorEditBlock[],
309
+ options: { syntaxGate?: "warn" | "block" } = {},
326
310
  ): PatchResult {
327
311
  const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
328
312
  if (!fs.existsSync(resolvedPath)) {
@@ -346,7 +330,10 @@ export function applySmartAnchorEdits(
346
330
  };
347
331
  }
348
332
 
349
- const preflight = preflightSmartAnchorEdits(originalContent, edits);
333
+ const hadCrlf = originalContent.includes("\r\n");
334
+ const contentNorm = originalContent.replace(/\r\n/g, "\n");
335
+
336
+ const preflight = preflightSmartAnchorEdits(contentNorm, edits);
350
337
  if (!preflight.success || !preflight.resolvedSpans) {
351
338
  return {
352
339
  success: false,
@@ -356,7 +343,7 @@ export function applySmartAnchorEdits(
356
343
  };
357
344
  }
358
345
 
359
- const fileLines = originalContent.split("\n");
346
+ const fileLines = contentNorm.split("\n");
360
347
  const currentLines = [...fileLines];
361
348
 
362
349
  // Sort spans strictly bottom-to-top (descending line number) so edits do not shift earlier lines
@@ -364,14 +351,20 @@ export function applySmartAnchorEdits(
364
351
 
365
352
  for (const span of sortedSpans) {
366
353
  const deleteCount = span.endLine - span.startLine + 1;
367
- currentLines.splice(span.startLine - 1, deleteCount, ...span.replacementLines);
354
+ const cleanReplacementLines = span.replacementLines.flatMap((line) =>
355
+ line.replace(/\r\n/g, "\n").split("\n"),
356
+ );
357
+ currentLines.splice(span.startLine - 1, deleteCount, ...cleanReplacementLines);
368
358
  }
369
359
 
370
- const candidateContent = currentLines.join("\n");
360
+ const candidateContentNorm = currentLines.join("\n");
361
+ const candidateContent = hadCrlf
362
+ ? candidateContentNorm.replace(/\n/g, "\r\n")
363
+ : candidateContentNorm;
371
364
 
372
365
  // Syntax validation gate
373
366
  const syntax = checkSyntaxContent(resolvedPath, candidateContent);
374
- if (!syntax.valid) {
367
+ if (!syntax.valid && options.syntaxGate !== "warn") {
375
368
  return {
376
369
  success: false,
377
370
  filePath: resolvedPath,
@@ -404,10 +397,10 @@ export function applySmartAnchorEdits(
404
397
  // Unified diff output
405
398
  const diffOutput = diff.createPatch(
406
399
  resolvedPath,
407
- originalContent,
408
- candidateContent,
400
+ contentNorm,
401
+ candidateContentNorm,
409
402
  "original",
410
- "modified",
403
+ "updated",
411
404
  );
412
405
 
413
406
  return {
@@ -52,7 +52,7 @@ function regexCanStart(prevSig: string, lastWord: string): boolean {
52
52
  }
53
53
 
54
54
  function checkTsStructure(content: string): string | null {
55
- const stack: { ch: string; line: number }[] = [];
55
+ const stack: { ch: string; line: number; isTemplateInterp?: boolean }[] = [];
56
56
  let line = 1;
57
57
  let i = 0;
58
58
  // State machine over raw source: code | 'str' | "str" | `tpl` | //line | /*block */ | /regex/
@@ -83,7 +83,7 @@ function checkTsStructure(content: string): string | null {
83
83
  const next = content[i + 1];
84
84
  if (ch === "\n") {
85
85
  line++;
86
- if (state === "lineComment") state = "code";
86
+ if (state === "lineComment" || state === "regex") state = "code";
87
87
  i++;
88
88
  continue;
89
89
  }
@@ -99,18 +99,32 @@ function checkTsStructure(content: string): string | null {
99
99
  break;
100
100
  case "squote":
101
101
  if (ch === "\\") i++;
102
- else if (ch === "'") state = "code";
102
+ else if (ch === "'") {
103
+ state = "code";
104
+ prevSig = "'";
105
+ lastWord = "";
106
+ }
103
107
  break;
104
108
  case "dquote":
105
109
  if (ch === "\\") i++;
106
- else if (ch === '"') state = "code";
110
+ else if (ch === '"') {
111
+ state = "code";
112
+ prevSig = '"';
113
+ lastWord = "";
114
+ }
107
115
  break;
108
116
  case "template":
109
- if (ch === "\\") i++;
110
- else if (ch === "`") state = "code";
111
- // NOTE: ${...} interpolations are tracked as part of the template
112
- // body; braces inside them are balanced by JS itself, and any
113
- // imbalance surfaces as an unbalanced delimiter anyway.
117
+ if (ch === "\\") {
118
+ i++;
119
+ } else if (ch === "$" && next === "{") {
120
+ stack.push({ ch: "{", line, isTemplateInterp: true });
121
+ state = "code";
122
+ i++;
123
+ } else if (ch === "`") {
124
+ state = "code";
125
+ prevSig = "`";
126
+ lastWord = "";
127
+ }
114
128
  break;
115
129
  case "code":
116
130
  if (ch === "/" && next === "/") {
@@ -119,7 +133,7 @@ function checkTsStructure(content: string): string | null {
119
133
  } else if (ch === "/" && next === "*") {
120
134
  state = "blockComment";
121
135
  i++;
122
- } else if (ch === "/" && regexCanStart(prevSig, lastWord)) {
136
+ } else if (ch === "/" && prevSig !== "<" && next !== ">" && regexCanStart(prevSig, lastWord)) {
123
137
  // Regex literal (division makes no sense at this position).
124
138
  // Delimiters inside it are pattern syntax, not code structure.
125
139
  state = "regex";
@@ -144,6 +158,11 @@ function checkTsStructure(content: string): string | null {
144
158
  if (!top || top.ch !== closers[ch]) {
145
159
  return `Unbalanced '${ch}' on line ${line}${top ? ` (unclosed '${top.ch}' from line ${top.line})` : " (no matching opener)"}`;
146
160
  }
161
+ if (top.isTemplateInterp) {
162
+ state = "template";
163
+ prevSig = "}";
164
+ lastWord = "";
165
+ }
147
166
  }
148
167
  if (!/\s/.test(ch)) prevSig = ch;
149
168
  // Accumulate identifier/number tokens; whitespace preserves the
@@ -167,9 +186,12 @@ function checkTsStructure(content: string): string | null {
167
186
  i++;
168
187
  }
169
188
 
170
- if (state === "squote" || state === "dquote" || state === "template") {
189
+ if (state === "squote" || state === "dquote") {
171
190
  return `Unterminated string literal (reached end of file, last line ${line})`;
172
191
  }
192
+ if (state === "template") {
193
+ return `Unterminated template literal (reached end of file, last line ${line})`;
194
+ }
173
195
  if (state === "blockComment") {
174
196
  return `Unterminated block comment (last line ${line})`;
175
197
  }
@@ -180,6 +202,15 @@ function checkTsStructure(content: string): string | null {
180
202
  return null;
181
203
  }
182
204
 
205
+ export function resolveTypeScriptCompiler(): string {
206
+ try {
207
+ return path.join(path.dirname(require.resolve("typescript/package.json")), "bin", "tsc");
208
+ } catch {
209
+ // Compatibility fallback for unusual loaders that do not expose require.resolve.
210
+ return path.resolve(__dirname, "../../node_modules/typescript/bin/tsc");
211
+ }
212
+ }
213
+
183
214
  function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
184
215
  if (!fs.existsSync(resolvedPath)) {
185
216
  return { valid: true, status: "clean" };
@@ -228,14 +259,17 @@ function validateSyntaxAtPath(resolvedPath: string): VerificationResult {
228
259
  ext === ".mts" ||
229
260
  ext === ".cts"
230
261
  ) {
231
- const tsContent = fs.readFileSync(resolvedPath, "utf8");
232
- const structuralError = checkTsStructure(tsContent);
233
- if (structuralError) throw new Error(structuralError);
262
+ const isJsx = ext === ".tsx" || ext === ".jsx";
263
+ // JSX/TSX text contains arbitrary unescaped delimiters (e.g. <p>step (1)</p>)
264
+ // that a naive bracket counter misidentifies. For JSX, tsc with --jsx preserve
265
+ // performs complete and authoritative syntax validation.
266
+ if (!isJsx) {
267
+ const tsContent = fs.readFileSync(resolvedPath, "utf8");
268
+ const structuralError = checkTsStructure(tsContent);
269
+ if (structuralError) throw new Error(structuralError);
270
+ }
234
271
 
235
- const compiler = path.resolve(
236
- __dirname,
237
- "../../node_modules/typescript/bin/tsc",
238
- );
272
+ const compiler = resolveTypeScriptCompiler();
239
273
  const compilerArgs = [
240
274
  "--noEmit",
241
275
  "--noCheck",