@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
@@ -3,7 +3,7 @@ import { Type } from "typebox";
3
3
  import { Text, makeOutputText } from "../ui/tui_utils";
4
4
  import { globalEpistemicGuard } from "../safety/epistemic_guard";
5
5
  import { formatCodeSearchResults, CODE_SEARCH_MODES, type CodeSearchMode } from "./code_search_output";
6
- import type { SearchDeps } from "./context";
6
+ import { speculativeToolsEnabled, type SearchDeps } from "./context";
7
7
 
8
8
  /** Extracted from index.ts — registers the `code_search` tool. */
9
9
  export function registerCodeSearchTool(
@@ -48,25 +48,20 @@ export function registerCodeSearchTool(
48
48
  isError: true,
49
49
  };
50
50
  }
51
-
52
- const requestedMode = params.mode ?? "auto";
53
- if (!(CODE_SEARCH_MODES as readonly string[]).includes(requestedMode)) {
51
+ if (deps.getConfig?.(ctx.cwd).retrieval.default_profile === "off") {
54
52
  return {
55
- content: [{
56
- type: "text",
57
- text: `[ERROR] Invalid mode "${String(requestedMode)}". Use auto, full, preview, or summary.`,
58
- }],
53
+ content: [{ type: "text", text: "[ERROR] Code search is disabled for this workspace." }],
59
54
  details: { count: 0 },
60
55
  isError: true,
61
56
  };
62
57
  }
63
58
 
64
- const scope = params.scope ?? "code";
65
- if (!["code", "all", "prose"].includes(scope)) {
59
+ const requestedMode = params.mode ?? "auto";
60
+ if (!(CODE_SEARCH_MODES as readonly string[]).includes(requestedMode)) {
66
61
  return {
67
62
  content: [{
68
63
  type: "text",
69
- text: `[ERROR] Invalid scope "${String(scope)}". Use code, all, or prose.`,
64
+ text: `[ERROR] Invalid mode "${String(requestedMode)}". Use auto, full, preview, or summary.`,
70
65
  }],
71
66
  details: { count: 0 },
72
67
  isError: true,
@@ -87,41 +82,8 @@ export function registerCodeSearchTool(
87
82
  limit,
88
83
  filePattern: params.file_pattern,
89
84
  rrfK: params.rrf_k,
90
- scope,
91
85
  });
92
86
 
93
- const sessionId = deps.getSessionId(ctx);
94
- for (const hit of hits) {
95
- const chunkRange =
96
- Number.isFinite(hit.chunk.startLine) && Number.isFinite(hit.chunk.endLine)
97
- ? [{ startLine: hit.chunk.startLine, endLine: hit.chunk.endLine }]
98
- : [];
99
- if (chunkRange.length > 0) {
100
- globalEpistemicGuard.recordFileRead(
101
- hit.chunk.absolutePath,
102
- sessionId,
103
- ctx.cwd,
104
- undefined,
105
- {
106
- coverage: { complete: false, ranges: chunkRange },
107
- provenance: "code_search",
108
- query,
109
- },
110
- );
111
- } else {
112
- globalEpistemicGuard.recordFileSearched(
113
- hit.chunk.absolutePath,
114
- sessionId,
115
- ctx.cwd,
116
- {
117
- coverage: { complete: false, ranges: [] },
118
- provenance: "code_search",
119
- query,
120
- },
121
- );
122
- }
123
- }
124
-
125
87
  const indexStatus = typeof index.getStatus === "function" ? index.getStatus() : undefined;
126
88
  const wantsVectors =
127
89
  indexStatus?.effectiveProfile === "hybrid" ||
@@ -138,7 +100,10 @@ export function registerCodeSearchTool(
138
100
  content: [
139
101
  {
140
102
  type: "text",
141
- text: `${vectorNotice}No code chunks found matching "${query}". (Tips: Try 'ast_search' for exact symbol names or 'rg' for exact text literals).`,
103
+ text: `${vectorNotice}No code chunks found matching "${query}". (` +
104
+ (speculativeToolsEnabled(deps.getConfig, ctx.cwd)
105
+ ? `Tips: Try 'ast_search' for exact symbol names or 'rg' for exact text literals.`
106
+ : `Tips: Try broader or different terms, or 'rg' for exact text literals.`),
142
107
  },
143
108
  ],
144
109
  details: { count: 0 },
@@ -150,6 +115,37 @@ export function registerCodeSearchTool(
150
115
  query,
151
116
  requestedMode as CodeSearchMode,
152
117
  );
118
+ const sessionId = deps.getSessionId(ctx);
119
+ const hitById = new Map(hits.map((hit) => [hit.chunk.id, hit]));
120
+ const visibleIds = new Set<string>();
121
+ for (const range of formatted.visibleRanges) {
122
+ const hit = hitById.get(range.chunkId);
123
+ if (!hit) continue;
124
+ visibleIds.add(range.chunkId);
125
+ globalEpistemicGuard.recordFileRead(
126
+ hit.chunk.absolutePath,
127
+ sessionId,
128
+ ctx.cwd,
129
+ undefined,
130
+ {
131
+ coverage: {
132
+ complete: false,
133
+ ranges: [{ startLine: range.startLine, endLine: range.endLine }],
134
+ },
135
+ provenance: "code_search",
136
+ query,
137
+ },
138
+ );
139
+ }
140
+ for (const hit of hits) {
141
+ if (visibleIds.has(hit.chunk.id)) continue;
142
+ globalEpistemicGuard.recordFileSearched(
143
+ hit.chunk.absolutePath,
144
+ sessionId,
145
+ ctx.cwd,
146
+ { coverage: { complete: false, ranges: [] }, provenance: "code_search", query },
147
+ );
148
+ }
153
149
 
154
150
  return {
155
151
  content: [
@@ -162,8 +158,8 @@ export function registerCodeSearchTool(
162
158
  count: hits.length,
163
159
  mode: formatted.mode,
164
160
  requestedMode,
165
- scope,
166
161
  truncated: formatted.truncated,
162
+ visibleRanges: formatted.visibleRanges,
167
163
  hits: hits.map((h) => ({
168
164
  id: h.chunk.id,
169
165
  score: h.rrfScore,
@@ -9,7 +9,21 @@ export interface SessionDeps {
9
9
  /** Load runtime settings for the active workspace. */
10
10
  getConfig?: (cwd: string) => import("../config").KernelConfig;
11
11
  /** Mark a successfully mutated file stale in the workspace index. */
12
- invalidateSearchFile?: (cwd: string, filePath: string) => void;
12
+ invalidateSearchFile?: (cwd: string, filePath: string) => void | Promise<void>;
13
+ }
14
+
15
+ /**
16
+ * Whether the opt-in tools (`get_repo_map`, `ast_search`, `lsp`) are registered for this
17
+ * workspace. Single source of truth: `src/index.ts` gates registration on this, and user-facing
18
+ * tool hints consult it so they never recommend a tool the model cannot actually call.
19
+ */
20
+ export function speculativeToolsEnabled(
21
+ getConfig: ((cwd: string) => import("../config").KernelConfig) | undefined,
22
+ cwd: string,
23
+ ): boolean {
24
+ const flag = process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS;
25
+ if (flag === "1" || flag === "true") return true;
26
+ return getConfig?.(cwd)?.retrieval?.enable_tools === true;
13
27
  }
14
28
 
15
29
  export interface SearchDeps extends SessionDeps {
@@ -4,6 +4,7 @@ import { Text, makeOutputText } from "../ui/tui_utils";
4
4
  import * as path from "node:path";
5
5
  import * as fs from "node:fs";
6
6
  import { kernelDebug } from "../safety/kernel_debug";
7
+ import { writeFileSyncAtomic } from "../safety/atomic_write";
7
8
  import {
8
9
  applySurgicalPatch,
9
10
  applyMultiBlockPatch,
@@ -29,6 +30,24 @@ import {
29
30
  import { loadKernelConfig } from "../config";
30
31
  import type { SessionDeps } from "./context";
31
32
 
33
+ function mutationLockKey(filePath: string): string {
34
+ const resolved = path.resolve(filePath);
35
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
36
+ }
37
+
38
+ export async function withFileMutationLocks<T>(
39
+ filePaths: string[],
40
+ operation: () => Promise<T>,
41
+ ): Promise<T> {
42
+ const { withFileMutationQueue } = await import("@earendil-works/pi-coding-agent");
43
+ const keys = [...new Set(filePaths.map(mutationLockKey))].sort();
44
+ const run = (index: number): Promise<T> =>
45
+ index >= keys.length
46
+ ? operation()
47
+ : withFileMutationQueue(keys[index]!, () => run(index + 1));
48
+ return run(0);
49
+ }
50
+
32
51
  interface PreparedFileEdit {
33
52
  resolvedPath: string;
34
53
  relPath: string;
@@ -53,7 +72,7 @@ function preflightFileEdit(
53
72
  return { error: `[EDIT ERROR] Missing required 'path' parameter or malformed argument payload.` };
54
73
  }
55
74
  const resolvedPath = resolveUserPath(item.path, ctx.cwd);
56
- const relPath = path.relative(ctx.cwd, resolvedPath) || item.path;
75
+ const relPath = (path.relative(ctx.cwd, resolvedPath) || item.path).replace(/\\/g, "/");
57
76
 
58
77
  if (!fs.existsSync(resolvedPath)) {
59
78
  return { error: `[EDIT FAILED] File not found: '${item.path}'.` };
@@ -207,26 +226,35 @@ async function applyPreparedEdit(
207
226
  prepared: PreparedFileEdit,
208
227
  ctx: any,
209
228
  deps: SessionDeps,
210
- ): Promise<{ success: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
229
+ options: { syntaxGate?: "warn" | "block" } = {},
230
+ ): Promise<{ success: boolean; mutated: boolean; error?: string; verification?: any; strategy?: string; statusText?: string }> {
211
231
  const { resolvedPath, relPath, item, isAnchorMode, hasSingleBlock, hasMultiBlock, anchorBlocks, anchorPreflight, targetRanges } = prepared;
232
+ const config = deps.getConfig?.(ctx.cwd);
233
+ const editingMode = config?.editing?.mode ?? "smart_anchor";
234
+ const autoHeal = editingMode !== "standard";
235
+ const syntaxGate = options.syntaxGate ?? config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
212
236
  let patchRes: ReturnType<typeof applySurgicalPatch>;
213
237
  if (isAnchorMode) {
214
- patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks);
238
+ patchRes = applySmartAnchorEdits(resolvedPath, anchorBlocks, { syntaxGate });
215
239
  } else if (hasMultiBlock) {
216
- patchRes = applyMultiBlockPatch(resolvedPath, item.edits);
240
+ patchRes = applyMultiBlockPatch(resolvedPath, item.edits, { autoHeal, syntaxGate });
217
241
  } else if (hasSingleBlock) {
218
242
  const singleOpt = {
219
243
  startLine: item.start_line,
220
244
  endLine: item.end_line,
221
245
  lineHint: item.line_hint,
222
246
  };
223
- patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, singleOpt);
247
+ patchRes = applySurgicalPatch(resolvedPath, item.search, item.replace, {
248
+ ...singleOpt,
249
+ autoHeal,
250
+ syntaxGate,
251
+ });
224
252
  } else {
225
- return { success: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
253
+ return { success: false, mutated: false, error: `[EDIT ERROR] Must provide either smart anchors or 'search' and 'replace' strings.` };
226
254
  }
227
255
 
228
256
  if (!patchRes.success) {
229
- return { success: false, error: renderEditFailure(patchRes.error || "patch failed") };
257
+ return { success: false, mutated: false, error: renderEditFailure(patchRes.error || "patch failed") };
230
258
  }
231
259
 
232
260
  let diskContent: string;
@@ -267,7 +295,7 @@ async function applyPreparedEdit(
267
295
  },
268
296
  );
269
297
 
270
- deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
298
+ await deps.invalidateSearchFile?.(ctx.cwd, resolvedPath);
271
299
 
272
300
  const readyLsp = LspManager.getInstance().getReadyClientForFile(resolvedPath, ctx.cwd);
273
301
  if (readyLsp && readyLsp.getState() === "ready") {
@@ -304,7 +332,8 @@ async function applyPreparedEdit(
304
332
 
305
333
  const statusText = renderPostEditVerification(verification, undefined, relPath);
306
334
  return {
307
- success: verification.syntax.state !== "failed",
335
+ success: true,
336
+ mutated: true,
308
337
  verification,
309
338
  strategy: patchRes.strategy,
310
339
  statusText,
@@ -423,22 +452,28 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
423
452
 
424
453
  // Multi-file atomic execution
425
454
  if (fileEdits.length > 0) {
455
+ const effectiveCwd = ctx?.cwd || process.cwd();
456
+ const effectiveCtx = ctx || { cwd: effectiveCwd };
426
457
  // Check for duplicate canonical paths
427
458
  const seenPaths = new Set<string>();
459
+ const lockPaths: string[] = [];
428
460
  for (const item of fileEdits) {
429
461
  if (!item || typeof item !== "object" || !item.path) {
430
462
  return { content: [{ type: "text", text: "[EDIT ERROR] Malformed file edit entry." }], isError: true };
431
463
  }
432
- const canonical = resolveUserPath(item.path, ctx.cwd);
433
- if (seenPaths.has(canonical)) {
464
+ const canonical = resolveUserPath(item.path, effectiveCwd);
465
+ const lookupKey = process.platform === "win32" ? canonical.toLowerCase() : canonical;
466
+ if (seenPaths.has(lookupKey)) {
434
467
  return {
435
468
  content: [{ type: "text", text: `[EDIT ERROR] Duplicate target path in multi-file edit: '${item.path}'.` }],
436
469
  isError: true,
437
470
  };
438
471
  }
439
- seenPaths.add(canonical);
472
+ seenPaths.add(lookupKey);
473
+ lockPaths.push(canonical);
440
474
  }
441
475
 
476
+ return withFileMutationLocks(lockPaths, async () => {
442
477
  onUpdate?.({
443
478
  content: [{ type: "text", text: `Preflighting ${fileEdits.length} file edits...` }],
444
479
  });
@@ -446,7 +481,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
446
481
  // Step 1: Preflight ALL files atomically
447
482
  const preparedList: PreparedFileEdit[] = [];
448
483
  for (const item of fileEdits) {
449
- const preflight = preflightFileEdit(item, ctx, deps, benchmarkMethod);
484
+ const preflight = preflightFileEdit(item, effectiveCtx, deps, benchmarkMethod);
450
485
  if (preflight.error || !preflight.prepared) {
451
486
  return {
452
487
  content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
@@ -469,8 +504,14 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
469
504
  }
470
505
  }
471
506
 
472
- // Step 3: Apply mutations with rollback guard
473
- onUpdate?.({
507
+ const sessionId = deps.getSessionId(ctx);
508
+ const originalEvidence = new Map(preparedList.map((prep) => [
509
+ prep.resolvedPath,
510
+ globalEpistemicGuard.getEvidence(prep.resolvedPath, sessionId, ctx.cwd),
511
+ ]));
512
+
513
+ // Step 3: Apply mutations with rollback guard
514
+ onUpdate?.({
474
515
  content: [{ type: "text", text: `Applying edits to ${preparedList.length} files...` }],
475
516
  });
476
517
 
@@ -481,9 +522,9 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
481
522
 
482
523
  for (const prepared of preparedList) {
483
524
  try {
484
- const outcome = await applyPreparedEdit(prepared, ctx, deps);
525
+ const outcome = await applyPreparedEdit(prepared, ctx, deps, { syntaxGate: "block" });
485
526
  outcomes.push(outcome);
486
- mutatedPaths.push(prepared.resolvedPath);
527
+ if (outcome.mutated) mutatedPaths.push(prepared.resolvedPath);
487
528
  if (!outcome.success) {
488
529
  failureEncountered = true;
489
530
  failureReason = outcome.error || outcome.statusText || "Verification failed";
@@ -497,32 +538,71 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
497
538
  }
498
539
 
499
540
  // Rollback if any write or verification failed
500
- if (failureEncountered) {
501
- for (const mutated of mutatedPaths) {
502
- const backup = originalSnapshots.get(mutated);
503
- if (backup !== undefined) {
504
- try {
505
- fs.writeFileSync(mutated, backup, "utf8");
506
- } catch (rbErr) {
507
- kernelDebug(rbErr);
508
- }
541
+ if (failureEncountered) {
542
+ const rollbackFailures: string[] = [];
543
+ for (const mutated of mutatedPaths) {
544
+ const backup = originalSnapshots.get(mutated);
545
+ if (backup === undefined) continue;
546
+ try {
547
+ writeFileSyncAtomic(mutated, backup);
548
+ if (fs.readFileSync(mutated, "utf8") !== backup) {
549
+ throw new Error("restored content verification failed");
509
550
  }
551
+ } catch (rbErr) {
552
+ rollbackFailures.push(`${path.basename(mutated)}: ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`);
553
+ continue;
510
554
  }
555
+
556
+ globalEpistemicGuard.restoreEvidence(
557
+ mutated,
558
+ sessionId,
559
+ originalEvidence.get(mutated) || null,
560
+ ctx.cwd,
561
+ );
562
+ try {
563
+ await deps.invalidateSearchFile?.(ctx.cwd, mutated);
564
+ } catch (indexErr) {
565
+ rollbackFailures.push(`${path.basename(mutated)} index: ${indexErr instanceof Error ? indexErr.message : String(indexErr)}`);
566
+ }
567
+ try {
568
+ const client = LspManager.getInstance().getReadyClientForFile(mutated, ctx.cwd);
569
+ if (client?.getState() === "ready") {
570
+ await client.changeDocument(mutated, backup);
571
+ await client.saveDocument(mutated, backup);
572
+ }
573
+ } catch (lspErr) {
574
+ rollbackFailures.push(`${path.basename(mutated)} LSP: ${lspErr instanceof Error ? lspErr.message : String(lspErr)}`);
575
+ }
576
+ }
577
+ if (rollbackFailures.length > 0) {
511
578
  return {
512
- content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and rolled back: ${failureReason}` }],
579
+ content: [{ type: "text", text: `[EDIT FAILED - PARTIAL ROLLBACK] Multi-file edit aborted; recovery errors: ${rollbackFailures.join("; ")}` }],
580
+ details: { rolledBack: false, recoveryErrors: rollbackFailures },
513
581
  isError: true,
514
582
  };
515
583
  }
516
-
517
- const affectedPaths = preparedList.map((p) => p.relPath);
518
584
  return {
519
- content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
520
- details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
585
+ content: [{ type: "text", text: `[EDIT FAILED - ROLLED BACK] Multi-file edit aborted and all file/index/LSP/guard state restored: ${failureReason}` }],
586
+ details: { rolledBack: true },
587
+ isError: true,
521
588
  };
522
589
  }
523
590
 
524
- // Single-file execution
525
- const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
591
+ const affectedPaths = preparedList.map((p) => p.relPath);
592
+ return {
593
+ content: [{ type: "text", text: `Successfully applied edits to ${affectedPaths.length} files: ${affectedPaths.join(", ")}.` }],
594
+ details: { multiFile: true, count: affectedPaths.length, files: affectedPaths },
595
+ };
596
+ });
597
+ }
598
+
599
+ // Single-file execution. Queue the complete preflight through
600
+ // post-verification sequence against host write/edit operations.
601
+ const singleLockPath = typeof params?.path === "string"
602
+ ? mutationLockKey(resolveUserPath(params.path, ctx.cwd))
603
+ : mutationLockKey(path.resolve(ctx.cwd, "__invalid_edit_target__"));
604
+ return withFileMutationLocks([singleLockPath], async () => {
605
+ const preflight = preflightFileEdit(params, ctx, deps, benchmarkMethod);
526
606
  if (preflight.error || !preflight.prepared) {
527
607
  return {
528
608
  content: [{ type: "text", text: preflight.error || "[EDIT FAILED] Preflight check failed." }],
@@ -534,7 +614,10 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
534
614
  content: [{ type: "text", text: `Editing ${preflight.prepared.relPath}...` }],
535
615
  });
536
616
 
537
- const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps);
617
+ const config = deps.getConfig?.(ctx.cwd);
618
+ const editingMode = config?.editing?.mode ?? "smart_anchor";
619
+ const syntaxGate = config?.editing?.syntax_gate ?? (editingMode === "standard" ? "block" : "warn");
620
+ const outcome = await applyPreparedEdit(preflight.prepared, ctx, deps, { syntaxGate });
538
621
  if (!outcome.success && outcome.error) {
539
622
  return {
540
623
  content: [{ type: "text", text: outcome.error }],
@@ -542,7 +625,8 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
542
625
  isError: true,
543
626
  };
544
627
  }
545
-
628
+ const hasSyntaxFailure = outcome.verification?.syntax?.state === "failed";
629
+ const shouldFlagError = !outcome.mutated || (editingMode === "standard" && hasSyntaxFailure);
546
630
  return {
547
631
  content: outcome.statusText ? [{ type: "text", text: outcome.statusText }] : [],
548
632
  details: {
@@ -550,22 +634,19 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
550
634
  verification: outcome.verification,
551
635
  success: outcome.verification?.syntax?.state === "clean",
552
636
  },
553
- isError:
554
- outcome.verification?.syntax?.state === "failed" ||
555
- outcome.verification?.diagnostic?.findings?.some(
556
- (finding: any) => finding.severity === "error" || !finding.severity,
557
- ),
637
+ isError: shouldFlagError,
558
638
  };
639
+ });
559
640
  },
560
641
  renderCall(args: any, theme: any, context: any) {
561
642
  const fileEdits: string[] = [];
562
643
  if (Array.isArray(args?.files)) {
563
644
  for (const f of args.files) {
564
- if (f?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path);
645
+ if (f?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(f.path, context.cwd)) || f.path).replace(/\\/g, "/"));
565
646
  }
566
647
  } else if (Array.isArray(args?.edits) && args.edits.some((e: any) => e?.path)) {
567
648
  for (const e of args.edits) {
568
- if (e?.path) fileEdits.push(path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path);
649
+ if (e?.path) fileEdits.push((path.relative(context.cwd, resolveUserPath(e.path, context.cwd)) || e.path).replace(/\\/g, "/"));
569
650
  }
570
651
  }
571
652
  if (fileEdits.length > 0) {
@@ -575,7 +656,7 @@ export function registerEditTool(pi: ExtensionAPI, deps: SessionDeps): void {
575
656
  }
576
657
  const rawPath = args?.path || "";
577
658
  const relPath = rawPath
578
- ? path.relative(context.cwd, rawPath) || rawPath
659
+ ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/")
579
660
  : "";
580
661
  return makeOutputText(
581
662
  `${theme.fg("toolTitle", theme.bold("edit"))} ${theme.fg("accent", relPath)}`,
@@ -21,7 +21,7 @@ import {
21
21
  } from "../retrieval/ast_search";
22
22
  import { checkSyntax } from "../editing/syntax-verify";
23
23
  import { kernelDebug } from "../safety/kernel_debug";
24
- import type { SessionDeps } from "./context";
24
+ import { speculativeToolsEnabled, type SessionDeps } from "./context";
25
25
 
26
26
  /** Extracted from index.ts — registers the `lsp` tool. */
27
27
  export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
@@ -447,7 +447,10 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
447
447
  }
448
448
 
449
449
  return result(
450
- `[LSP Notice] No installed LSP server found for ${path.basename(absPath)}. Use 'ast_search' or run '/lsp install' to configure an LSP server.`,
450
+ `[LSP Notice] No installed LSP server found for ${path.basename(absPath)}. ` +
451
+ (speculativeToolsEnabled(deps.getConfig, ctx.cwd)
452
+ ? `Use 'ast_search' or run '/lsp install' to configure an LSP server.`
453
+ : `Run '/lsp install' to configure an LSP server.`),
451
454
  "tree-sitter",
452
455
  { status: "unavailable" },
453
456
  );
@@ -519,7 +522,12 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
519
522
  if (params.exclude_declaration) {
520
523
  res = res.filter((loc) => {
521
524
  const locPath = uriToPath(loc.uri);
522
- const sameFile = locPath === absPath || path.resolve(locPath) === path.resolve(absPath);
525
+ const isWindows = process.platform === "win32";
526
+ const normLoc = path.resolve(locPath);
527
+ const normAbs = path.resolve(absPath);
528
+ const sameFile = isWindows
529
+ ? normLoc.toLowerCase() === normAbs.toLowerCase()
530
+ : normLoc === normAbs;
523
531
  const sameLine = loc.range?.start?.line === line0;
524
532
  return !(sameFile && sameLine);
525
533
  });
@@ -567,7 +575,12 @@ export function registerLspTool(pi: ExtensionAPI, deps?: SessionDeps): void {
567
575
  let astRefs = findSymbolReferences(ctx.cwd, targetSym);
568
576
  if (params.exclude_declaration) {
569
577
  astRefs = astRefs.filter((r) => {
570
- const sameFile = path.resolve(ctx.cwd, r.filePath) === path.resolve(absPath);
578
+ const isWindows = process.platform === "win32";
579
+ const normRef = path.resolve(ctx.cwd, r.filePath);
580
+ const normAbs = path.resolve(absPath);
581
+ const sameFile = isWindows
582
+ ? normRef.toLowerCase() === normAbs.toLowerCase()
583
+ : normRef === normAbs;
571
584
  return !(sameFile && r.line === (line0 + 1));
572
585
  });
573
586
  }
@@ -10,7 +10,7 @@ import {
10
10
  globalEpistemicGuard,
11
11
  resolveUserPath,
12
12
  } from "../safety/epistemic_guard";
13
- import type { SessionDeps } from "./context";
13
+ import { speculativeToolsEnabled, type SessionDeps } from "./context";
14
14
 
15
15
  function countFileLines(filePath: string): number {
16
16
  return fs.readFileSync(filePath, "utf8").split("\n").length;
@@ -18,6 +18,21 @@ function countFileLines(filePath: string): number {
18
18
 
19
19
  const MAX_READ_LINES = 2_000;
20
20
  const MAX_READ_BYTES = 50 * 1024;
21
+ const MAX_READ_FILE_BYTES = 5 * 1024 * 1024;
22
+ const DEFAULT_UNCONSTRAINED_LINES = 250;
23
+
24
+ function validateReadableFile(filePath: string): string | null {
25
+ try {
26
+ const stat = fs.statSync(filePath);
27
+ if (!stat.isFile()) return "Path is not a regular file";
28
+ if (stat.size > MAX_READ_FILE_BYTES) {
29
+ return `File is ${stat.size} bytes; maximum in-memory source size is ${MAX_READ_FILE_BYTES} bytes`;
30
+ }
31
+ return null;
32
+ } catch (error: any) {
33
+ return error?.code === "ENOENT" ? "File not found" : error?.message || String(error);
34
+ }
35
+ }
21
36
 
22
37
  function shouldUseAnchors(
23
38
  params: any,
@@ -190,12 +205,17 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
190
205
  break;
191
206
  }
192
207
  const resolvedPath = resolveUserPath(filePath, ctx.cwd);
193
- const relPath = path.relative(ctx.cwd, resolvedPath) || filePath;
208
+ const relPath = (path.relative(ctx.cwd, resolvedPath) || filePath).replace(/\\/g, "/");
194
209
  if (!fs.existsSync(resolvedPath)) {
195
210
  results.push(`=== file: ${relPath} ===\nFile not found: ${filePath}`);
196
211
  continue;
197
212
  }
198
213
  try {
214
+ const readLimitError = validateReadableFile(resolvedPath);
215
+ if (readLimitError) {
216
+ results.push(`=== file: ${relPath} ===\nRead rejected: ${readLimitError}`);
217
+ continue;
218
+ }
199
219
  const content = fs.readFileSync(resolvedPath, "utf-8");
200
220
  const lines = content.split("\n");
201
221
  const totalLines = lines.length;
@@ -265,6 +285,15 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
265
285
  };
266
286
  }
267
287
 
288
+ const readLimitError = validateReadableFile(resolvedPath);
289
+ if (readLimitError) {
290
+ return {
291
+ content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
292
+ details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
293
+ isError: true,
294
+ };
295
+ }
296
+
268
297
  // Mode 1: Targeted AST symbol extraction
269
298
  if (params.symbol && params.symbol.trim()) {
270
299
  const sym = params.symbol.trim();
@@ -312,7 +341,10 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
312
341
  .join("\n");
313
342
  errorText = `Symbol '${sym}' not found in ${params.path}.\nDid you mean:\n${formattedSuggestions}`;
314
343
  } else {
315
- errorText = `Symbol '${sym}' not found in ${params.path}. Use 'ast_search' to locate symbols or 'rg' in bash to search text.`;
344
+ errorText = `Symbol '${sym}' not found in ${params.path}. ` +
345
+ (speculativeToolsEnabled(deps.getConfig, ctx.cwd)
346
+ ? `Use 'ast_search' to locate symbols or 'rg' in bash to search text.`
347
+ : `Use 'code_search' to locate code or 'rg' in bash to search text.`);
316
348
  }
317
349
  return {
318
350
  content: [{ type: "text", text: errorText }],
@@ -359,7 +391,7 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
359
391
  const allFileLines = symbolSnapshot.split("\n");
360
392
  const formatted = res.symbols
361
393
  .map((s) => {
362
- const header = `// ${path.relative(ctx.cwd, s.filePath) || s.filePath}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}`;
394
+ const header = `// ${(path.relative(ctx.cwd, s.filePath) || s.filePath).replace(/\\/g, "/")}:${s.startLine}-${s.endLine} [${s.kind}] ${s.name}`;
363
395
  const body = useAnchors
364
396
  ? formatSmartAnchorLines(allFileLines, s.startLine, s.endLine)
365
397
  : benchmarkMethod === "line-range"
@@ -384,6 +416,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
384
416
 
385
417
  // Mode 2: Standard file reading
386
418
  try {
419
+ const readLimitError = validateReadableFile(resolvedPath);
420
+ if (readLimitError) {
421
+ return {
422
+ content: [{ type: "text", text: `[READ ERROR] ${readLimitError}: ${params.path}` }],
423
+ details: { error: "read_limit", maxBytes: MAX_READ_FILE_BYTES },
424
+ isError: true,
425
+ };
426
+ }
387
427
  const ext = path.extname(resolvedPath).toLowerCase();
388
428
  const isImage = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"].includes(
389
429
  ext,
@@ -477,7 +517,8 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
477
517
  }
478
518
 
479
519
  const offset = params.offset ?? 1;
480
- const limit = params.limit ?? totalLines;
520
+ const hasExplicitLimit = typeof params.limit === "number";
521
+ const limit = hasExplicitLimit ? params.limit : Math.min(totalLines, DEFAULT_UNCONSTRAINED_LINES);
481
522
  const startIdx = offset - 1;
482
523
 
483
524
  // Offset past the end of file: return a clean error instead of an
@@ -563,14 +604,14 @@ export function registerReadTool(pi: ExtensionAPI, deps: SessionDeps): void {
563
604
  renderCall(args: any, theme: any, context: any) {
564
605
  const targetPaths = Array.isArray(args?.paths) ? args.paths : (Array.isArray(args?.path) ? args.path : []);
565
606
  if (targetPaths.length > 1) {
566
- const pathsSummary = targetPaths.map((p: string) => path.relative(context.cwd, p) || p).join(", ");
607
+ const pathsSummary = targetPaths.map((p: string) => (path.relative(context.cwd, p) || p).replace(/\\/g, "/")).join(", ");
567
608
  return makeOutputText(
568
609
  `${theme.fg("toolTitle", theme.bold("read"))} [${theme.fg("accent", pathsSummary)}]`,
569
610
  );
570
611
  }
571
612
  const rawPath = args?.path || (Array.isArray(args?.paths) ? args.paths[0] : "") || "";
572
613
  const relPath = rawPath
573
- ? path.relative(context.cwd, rawPath) || rawPath
614
+ ? (path.relative(context.cwd, rawPath) || rawPath).replace(/\\/g, "/")
574
615
  : "";
575
616
  if (args?.symbol) {
576
617
  return makeOutputText(