Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(code): renew coding agent, surgical file_edit + P1/P2 audit fixes

purple2b05de86b10b
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index 9770b3f2..21cc1614 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -186,6 +186,53 @@ pub fn fs_read(path: String, chatId: Option<String>, workingDirectory: Option<St
}
}
+/// Match new content to the EXISTING file's line-ending + BOM convention so an
+/// edit produces a minimal diff instead of flipping every line. Local coding
+/// models emit `\n`; on a Windows repo whose files are CRLF, writing that raw
+/// turned every edit into a whole-file whitespace diff. For a NEW file we honor
+/// exactly what the caller sent — there is no convention to match.
+fn normalize_to_existing_style(existing: Option<&[u8]>, new: &str) -> Vec<u8> {
+ const BOM: [u8; 3] = [0xEF, 0xBB, 0xBF];
+ let existing = match existing {
+ Some(e) => e,
+ None => return new.as_bytes().to_vec(),
+ };
+ let had_bom = existing.starts_with(&BOM);
+ // The file is treated as CRLF if it contains any CRLF pair.
+ let existing_crlf = existing.windows(2).any(|w| w == b"\r\n");
+ // Normalize incoming to LF first (idempotent), then to the target style.
+ let lf = new.replace("\r\n", "\n");
+ let bodied = if existing_crlf { lf.replace('\n', "\r\n") } else { lf };
+ let mut out = Vec::with_capacity(bodied.len() + 3);
+ if had_bom && !bodied.as_bytes().starts_with(&BOM) {
+ out.extend_from_slice(&BOM);
+ }
+ out.extend_from_slice(bodied.as_bytes());
+ out
+}
+
+/// Write bytes to `target` atomically: a temp file in the SAME directory, then
+/// rename over the target. A crash or interrupt can never leave a half-written
+/// (truncated) file where the original was — std::fs::rename replaces the
+/// destination on both Unix and Windows.
+fn write_atomic(target: &Path, bytes: &[u8]) -> Result<(), String> {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static SEQ: AtomicU64 = AtomicU64::new(0);
+ let parent = target.parent().ok_or_else(|| "No parent directory".to_string())?;
+ let base = target
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_else(|| "file".to_string());
+ let seq = SEQ.fetch_add(1, Ordering::Relaxed);
+ let tmp = parent.join(format!(".{}.tmp{}-{}", base, std::process::id(), seq));
+ fs::write(&tmp, bytes).map_err(|e| format!("Write error: {}", e))?;
+ if let Err(e) = fs::rename(&tmp, target) {
+ let _ = fs::remove_file(&tmp);
+ return Err(format!("Write error (rename): {}", e));
+ }
+ Ok(())
+}
+
#[tauri::command]
#[allow(non_snake_case)]
pub fn fs_write(path: String, content: String, chatId: Option<String>, workingDirectory: Option<String>) -> Result<serde_json::Value, String> {
@@ -193,8 +240,29 @@ pub fn fs_write(path: String, content: String, chatId: Option<String>, workingDi
if let Some(parent) = full.parent() {
fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;
}
- fs::write(&full, &content).map_err(|e| format!("Write error: {}", e))?;
- Ok(serde_json::json!({ "status": "saved", "path": full.to_string_lossy() }))
+ // Read the current bytes (if any) to preserve the file's EOL/BOM convention
+ // and to detect a no-op write.
+ let existing = fs::read(&full).ok();
+ let out_bytes = normalize_to_existing_style(existing.as_deref(), &content);
+
+ if let Some(ref old) = existing {
+ if old.as_slice() == out_bytes.as_slice() {
+ // Nothing changed — skip the write so there is no spurious mtime
+ // bump and no misleading "saved" for an identical file.
+ return Ok(serde_json::json!({
+ "status": "unchanged",
+ "path": full.to_string_lossy(),
+ "bytes": out_bytes.len(),
+ }));
+ }
+ }
+
+ write_atomic(&full, &out_bytes)?;
+ Ok(serde_json::json!({
+ "status": "saved",
+ "path": full.to_string_lossy(),
+ "bytes": out_bytes.len(),
+ }))
}
#[tauri::command]
@@ -434,7 +502,60 @@ pub async fn save_binary_file_dialog(
#[cfg(test)]
mod tests {
- use super::{is_workspace_root_path, resolve_path};
+ use super::{is_workspace_root_path, normalize_to_existing_style, resolve_path};
+
+ // ── #11: fs_write preserves the existing file's EOL + BOM convention ──
+ #[test]
+ fn new_file_keeps_content_verbatim() {
+ // No existing file → honor exactly what the caller sent (LF).
+ assert_eq!(normalize_to_existing_style(None, "a\nb\n"), b"a\nb\n");
+ // Even CRLF the caller explicitly sent is preserved for a new file.
+ assert_eq!(normalize_to_existing_style(None, "a\r\nb"), b"a\r\nb");
+ }
+
+ #[test]
+ fn crlf_file_gets_lf_content_converted() {
+ let existing = b"old\r\nlines\r\n";
+ assert_eq!(
+ normalize_to_existing_style(Some(existing), "new\nlines\n"),
+ b"new\r\nlines\r\n"
+ );
+ }
+
+ #[test]
+ fn lf_file_stays_lf() {
+ let existing = b"old\nlines\n";
+ assert_eq!(
+ normalize_to_existing_style(Some(existing), "new\nlines\n"),
+ b"new\nlines\n"
+ );
+ }
+
+ #[test]
+ fn crlf_conversion_is_idempotent() {
+ let existing = b"x\r\ny\r\n";
+ // Caller already sent CRLF — must not become \r\r\n.
+ assert_eq!(
+ normalize_to_existing_style(Some(existing), "a\r\nb\r\n"),
+ b"a\r\nb\r\n"
+ );
+ }
+
+ #[test]
+ fn existing_bom_is_preserved() {
+ let existing = b"\xEF\xBB\xBFhello\n";
+ let out = normalize_to_existing_style(Some(existing), "world\n");
+ assert_eq!(out, b"\xEF\xBB\xBFworld\n");
+ // Not doubled when the new content already carries the BOM.
+ let out2 = normalize_to_existing_style(Some(existing), "\u{feff}world\n");
+ assert_eq!(out2, b"\xEF\xBB\xBFworld\n");
+ }
+
+ #[test]
+ fn no_bom_stays_no_bom() {
+ let existing = b"plain\n";
+ assert_eq!(normalize_to_existing_style(Some(existing), "x\n"), b"x\n");
+ }
#[test]
fn workspace_root_paths_match() {
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index dc2922eb..3af3bfc4 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -1564,7 +1564,7 @@ button{-webkit-appearance:none;appearance:none}
{name:'maxLength',type:'number',description:'Max chars to return (default: 24000)',required:false}]},
{name:'file_read', description:'Read the complete contents of a file. PREFER absolute paths; relative paths resolve against the agent workspace (~/agent-workspace). The entire file is returned — there is no pagination or range parameter. DO NOT re-read a file you just wrote with file_write; the write response already confirmed the save. For directory listings use file_list; for content search across many files use file_search.',
parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true}]},
- {name:'file_write', description:'Write a file. Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. To preserve existing content and append, use file_read FIRST then file_write with the combined content. PREFER absolute paths. Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',
+ {name:'file_write', description:'Write a WHOLE file. Use for CREATING a new file or fully replacing one. To change part of an EXISTING file, PREFER file_edit — it is far cheaper than resending the whole file and never truncates a large one. Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. PREFER absolute paths. Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',
parameters:[{name:'path',type:'string',description:'Path to the file (absolute preferred)',required:true},
{name:'content',type:'string',description:'The complete new content of the file',required:true}]},
{name:'file_list', description:'List directory contents. Returns entries with name, isDir, size, full path. Supports recursive=true for full tree and glob pattern ("*.ts", "**/*.py"). PREFER a specific pattern over recursive listing of large trees — recursing home / C:\\ is slow. For content search (grep), use file_search instead.',
@@ -2839,7 +2839,7 @@ button{-webkit-appearance:none;appearance:none}
var PERMISSION_META = [
{key:'filesystem', label:'Filesystem', desc:'Agent can read/write files + run code on the desktop.'},
{key:'downloads', label:'Downloads', desc:'Agent can trigger model pulls / installs (Ollama + ComfyUI).'},
- {key:'process_control', label:'Process Control', desc:'Remote clients can access ComfyUI (generate images / video).'}
+ {key:'process_control', label:'Process Control', desc:'Reach ComfyUI and Ollama on the desktop, and start or stop them.'}
];
function fetchRemotePerms(){
diff --git a/src/api/__tests__/context-compaction.test.ts b/src/api/__tests__/context-compaction.test.ts
index b8bab763..6d5f3c77 100644
--- a/src/api/__tests__/context-compaction.test.ts
+++ b/src/api/__tests__/context-compaction.test.ts
@@ -132,7 +132,44 @@ describe('compactMessages', () => {
{ role: 'assistant', content: 'new answer' },
]
const result = compactMessages(messages, 50)
- // Should have compacted the tool call pair into a summary
+ // Oldest messages (incl. the tool call pair) are dropped, not summarized.
expect(result.length).toBeLessThanOrEqual(messages.length)
})
+
+ it('keeps a recent tool result verbatim — never a char-truncated slice', () => {
+ // A file the agent read must survive compaction intact, or the model edits
+ // against content it can no longer see.
+ const bigResult = 'export const config = {\n' + ' key: "value",\n'.repeat(60) + '}'
+ const messages: OllamaChatMessage[] = [
+ { role: 'system', content: 'sys' },
+ { role: 'user', content: 'old '.repeat(400) },
+ { role: 'assistant', content: 'old '.repeat(400) },
+ { role: 'user', content: 'read the config' },
+ { role: 'assistant', content: '', tool_calls: [{ function: { name: 'file_read', arguments: { path: 'config.ts' } } }] },
+ { role: 'tool', content: bigResult },
+ { role: 'assistant', content: 'done' },
+ ]
+ const result = compactMessages(messages, 150)
+ const toolMsg = result.find((m) => m.role === 'tool')
+ // Full content, not a 80-char summary line.
+ expect(toolMsg?.content).toBe(bigResult)
+ })
+
+ it('drops oldest messages behind a notice, not a lossy summary', () => {
+ const messages: OllamaChatMessage[] = [
+ { role: 'system', content: 'sys' },
+ ...Array.from({ length: 10 }, (_, i) => ({
+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'user' | 'assistant',
+ content: `msg ${i} ${'x'.repeat(200)}`,
+ })),
+ { role: 'user', content: 'latest' },
+ ]
+ const result = compactMessages(messages, 120)
+ // Real system prompt stays first.
+ expect(result[0].content).toBe('sys')
+ // A trim notice is present (not a "[Previous conversation summary]").
+ expect(result.some((m) => m.role === 'system' && m.content.includes('trimmed to fit'))).toBe(true)
+ // Newest message preserved verbatim.
+ expect(result[result.length - 1].content).toBe('latest')
+ })
})
diff --git a/src/api/__tests__/tool-description-parity.test.ts b/src/api/__tests__/tool-description-parity.test.ts
index 74d5dbf3..08aa80a5 100644
--- a/src/api/__tests__/tool-description-parity.test.ts
+++ b/src/api/__tests__/tool-description-parity.test.ts
@@ -159,6 +159,10 @@ describe('tool-description-parity — extraction sanity', () => {
// a "desktop only" observation; video_generate isn't listed there yet).
const MOBILE_SKIP: ReadonlySet<string> = new Set<string>([
'run_workflow', 'delegate_task',
+ // file_edit (2.5.9 surgical edit) is desktop-only: its executor lives in
+ // src/api/mcp/builtin-tools.ts and the mobile remote surface has no Rust
+ // dispatcher for it (same situation as the other TS-only coding tools below).
+ 'file_edit',
'run_tests',
'git_status', 'git_commit', 'git_push', 'git_log', 'git_diff',
'gh_pr_create',
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.ts
index e0906228..e02c924f 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -25,14 +25,15 @@ const offeredDefNames = AGENT_TOOL_DEFS
// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────
describe('AGENT_TOOL_DEFS', () => {
- it('contains exactly 29 tool definitions', () => {
+ it('contains exactly 30 tool definitions', () => {
// Phase 13 v2.4.0: delegate_task added as a builtin (→ 15 tools).
// v2.5.0 sprint A/B/C from uselu: +13 codex tools — shell_task_*,
// shell_execute_background, git_*, gh_pr_create, pr_resume,
// project_init, run_tests (→ 28 tools).
// v2.5.0 Feature EE: video_generate (text-to-video via the VRAM hand-off
// orchestrator) added alongside image_generate (→ 29 tools).
- expect(AGENT_TOOL_DEFS).toHaveLength(29)
+ // v2.5.9 M1: file_edit (surgical SEARCH/REPLACE edit) (→ 30 tools).
+ expect(AGENT_TOOL_DEFS).toHaveLength(30)
})
const expectedTools = [
@@ -40,6 +41,7 @@ describe('AGENT_TOOL_DEFS', () => {
'web_fetch',
'file_read',
'file_write',
+ 'file_edit',
'file_list',
'file_search',
'code_execute',
@@ -97,7 +99,7 @@ describe('AGENT_TOOL_DEFS', () => {
// shell, git, gh, project_init, run_tests — all touch the user's machine).
// v2.5.0 Feature EE: video_generate (image category → confirm default).
expect(confirmNames).toEqual([
- 'code_execute', 'delegate_task', 'file_list', 'file_read', 'file_search',
+ 'code_execute', 'delegate_task', 'file_edit', 'file_list', 'file_read', 'file_search',
'file_write', 'gh_pr_create', 'git_commit', 'git_diff', 'git_log',
'git_push', 'git_status', 'image_generate', 'pr_resume', 'project_init',
'run_tests', 'run_workflow', 'screenshot', 'shell_execute',
diff --git a/src/api/agents/__tests__/embedding-router.test.ts b/src/api/agents/__tests__/embedding-router.test.ts
index 67d9aff6..fe435a47 100644
--- a/src/api/agents/__tests__/embedding-router.test.ts
+++ b/src/api/agents/__tests__/embedding-router.test.ts
@@ -150,9 +150,30 @@ describe('embedding-router — cosine edge cases', () => {
it('opposite vector → -1', () => {
expect(__internal.cosine([1, 2, 3], [-1, -2, -3])).toBeCloseTo(-1, 5)
})
- it('different-length vectors use the shorter length', () => {
- const v = __internal.cosine([1, 2, 3], [1, 2])
- expect(Number.isFinite(v)).toBe(true)
+ it('different-length vectors return 0 (incompatible embedding spaces)', () => {
+ // A mid-session embed-backend switch changes vector dimension; comparing
+ // only the overlap yields a garbage similarity, so cosine refuses.
+ expect(__internal.cosine([1, 2, 3], [1, 2])).toBe(0)
+ expect(__internal.cosine([1, 2], [1, 2, 3])).toBe(0)
+ })
+})
+
+describe('embedding-router — backend switch self-heals the cache (#14)', () => {
+ it('drops stale-dimension vectors and re-embeds in the new space', async () => {
+ clearEmbeddingCache()
+ const tools = [{ name: 'a', description: 'apple' }]
+ // First backend: 26-dim character-frequency vectors.
+ await precomputeToolEmbeddings(tools, fakeEmbed)
+ expect(__internal.CACHE.size).toBe(1)
+ // Second backend: 4-dim vectors (a different embedding model). Ranking must
+ // NOT compare across spaces — it drops the stale entry instead.
+ const smallEmbed = async (texts: string[]) => texts.map(() => [1, 0, 0, 0])
+ const ranked = await rankToolsByEmbedding('apple', tools, smallEmbed, { topN: 5 })
+ expect(ranked).toEqual([])
+ expect(__internal.CACHE.has('a')).toBe(false)
+ // Next precompute with the new backend re-embeds in the new space.
+ const added = await precomputeToolEmbeddings(tools, smallEmbed)
+ expect(added).toBe(1)
})
})
diff --git a/src/api/agents/__tests__/in-turn-cache.test.ts b/src/api/agents/__tests__/in-turn-cache.test.ts
index c615d79c..0ce2dbfb 100644
--- a/src/api/agents/__tests__/in-turn-cache.test.ts
+++ b/src/api/agents/__tests__/in-turn-cache.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { makeInTurnCacheLookup } from '../in-turn-cache'
-import { useToolAuditStore } from '../../../stores/toolAuditStore'
+import { useToolAuditStore, AUDIT_FULL_RESULT_MAX_CHARS } from '../../../stores/toolAuditStore'
import { stableArgsHash } from '../block-helpers'
import type { ExecutionRequest } from '../tool-executor'
@@ -124,3 +124,88 @@ describe('in-turn-cache — makeInTurnCacheLookup', () => {
expect(lookup(req('new', 'web_search', args), stableArgsHash(args))).toBeUndefined()
})
})
+
+describe('in-turn-cache — non-idempotent tools are never served (#1)', () => {
+ beforeEach(() => useToolAuditStore.getState().clearAll())
+
+ for (const tool of ['shell_execute', 'code_execute', 'run_tests', 'file_write', 'file_edit', 'git_status', 'git_commit']) {
+ it(`never serves a cached ${tool}`, () => {
+ const s = useToolAuditStore.getState()
+ const args = { command: 'npm test' }
+ const id = s.record({ convId: 'c1', toolCallId: 'p', toolName: tool, args, startedAt: 1000 })
+ s.complete(id, { status: 'completed', completedAt: 1100, resultPreview: 'FAIL: 1 failing' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ // Even an identical prior call must re-run, never replay a stale result.
+ expect(lookup(req('new', tool, args), stableArgsHash(args))).toBeUndefined()
+ })
+ }
+})
+
+describe('in-turn-cache — read invalidation after mutation (#1)', () => {
+ beforeEach(() => useToolAuditStore.getState().clearAll())
+
+ it('serves a cached file_read when nothing mutated after it', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/a.ts' }
+ const id = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(id, { status: 'completed', completedAt: 1050, resultPreview: 'const a = 1' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBe('const a = 1')
+ })
+
+ it('invalidates a cached file_read once a file_write ran after it', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/a.ts' }
+ const rid = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(rid, { status: 'completed', completedAt: 1050, resultPreview: 'const a = 1' })
+ // A write lands after the read — the read is now stale.
+ const wid = s.record({ convId: 'c1', toolCallId: 'w1', toolName: 'file_write', args: { path: '/proj/a.ts', content: 'const a = 2' }, startedAt: 1100 })
+ s.complete(wid, { status: 'completed', completedAt: 1150, resultPreview: 'saved' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBeUndefined()
+ })
+
+ it('invalidates a cached file_read after an opaque shell_execute (may touch any path)', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/a.ts' }
+ const rid = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(rid, { status: 'completed', completedAt: 1050, resultPreview: 'old' })
+ const sid = s.record({ convId: 'c1', toolCallId: 's1', toolName: 'shell_execute', args: { command: 'npm run codegen' }, startedAt: 1100 })
+ s.complete(sid, { status: 'completed', completedAt: 1200, resultPreview: 'done' })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBeUndefined()
+ })
+})
+
+describe('in-turn-cache — serves the FULL result, not the panel preview (#9)', () => {
+ beforeEach(() => useToolAuditStore.getState().clearAll())
+
+ it('returns the whole file, not the 500-char clipped preview', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/big.ts' }
+ const big = 'X'.repeat(600) // longer than AUDIT_RESULT_PREVIEW_CHARS (500)
+ const id = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(id, { status: 'completed', completedAt: 1050, resultPreview: big })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ const hit = lookup(req('r2', 'file_read', args), stableArgsHash(args))
+ expect(hit).toBe(big)
+ expect(hit).toHaveLength(600)
+ })
+
+ it('misses (re-reads) when the result exceeds the retained full-result cap', () => {
+ const s = useToolAuditStore.getState()
+ const args = { path: '/proj/huge.log' }
+ const huge = 'Y'.repeat(AUDIT_FULL_RESULT_MAX_CHARS + 1)
+ const id = s.record({ convId: 'c1', toolCallId: 'r1', toolName: 'file_read', args, startedAt: 1000 })
+ s.complete(id, { status: 'completed', completedAt: 1050, resultPreview: huge })
+
+ const lookup = makeInTurnCacheLookup({ convId: 'c1', turnStartMs: 500 })
+ // Not served as a truncated slice — a miss so the executor re-reads.
+ expect(lookup(req('r2', 'file_read', args), stableArgsHash(args))).toBeUndefined()
+ })
+})
diff --git a/src/api/agents/__tests__/side-effect-key.test.ts b/src/api/agents/__tests__/side-effect-key.test.ts
index 7460f128..59b50342 100644
--- a/src/api/agents/__tests__/side-effect-key.test.ts
+++ b/src/api/agents/__tests__/side-effect-key.test.ts
@@ -44,6 +44,19 @@ describe('side-effect-key', () => {
expect(deriveSideEffectKey('code_execute', { code: '1' })).toBe('exec')
})
+ it('repo-mutating + shelling tools also serialize on "exec" (avoid .git/index.lock races)', () => {
+ expect(deriveSideEffectKey('git_commit', { message: 'x' })).toBe('exec')
+ expect(deriveSideEffectKey('git_push', {})).toBe('exec')
+ expect(deriveSideEffectKey('run_tests', {})).toBe('exec')
+ expect(deriveSideEffectKey('shell_execute_background', { command: 'x' })).toBe('exec')
+ })
+
+ it('read-only git tools stay parallel (no key)', () => {
+ expect(deriveSideEffectKey('git_status', {})).toBeUndefined()
+ expect(deriveSideEffectKey('git_log', {})).toBeUndefined()
+ expect(deriveSideEffectKey('git_diff', {})).toBeUndefined()
+ })
+
it('image_generate, video_generate and run_workflow share the "comfyui" queue', () => {
expect(deriveSideEffectKey('image_generate', { prompt: 'x' })).toBe('comfyui')
// video_generate MUST serialize with image_generate (same GPU + VRAM
diff --git a/src/api/agents/embedding-router.ts b/src/api/agents/embedding-router.ts
index 618acd1a..1fc2d613 100644
--- a/src/api/agents/embedding-router.ts
+++ b/src/api/agents/embedding-router.ts
@@ -75,11 +75,16 @@ export async function precomputeToolEmbeddings(
}
function cosine(a: number[], b: number[]): number {
+ // Different-length vectors come from different embedding models — e.g. a
+ // mid-session backend switch between Ollama's nomic-embed-text (768-d) and
+ // the bundled embed server. They live in incompatible spaces, so comparing
+ // the Math.min(a,b) overlap yields a garbage similarity that silently
+ // corrupts the ranking. Refuse instead.
+ if (a.length !== b.length) return 0
let dot = 0
let magA = 0
let magB = 0
- const n = Math.min(a.length, b.length)
- for (let i = 0; i < n; i++) {
+ for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i]
magA += a[i] * a[i]
magB += b[i] * b[i]
@@ -107,6 +112,14 @@ export async function rankToolsByEmbedding(
for (const t of tools) {
const c = CACHE.get(t.name)
if (!c) continue
+ if (c.vector.length !== queryVec.length) {
+ // Cached in a different embedding model's space (dimension differs from
+ // the current backend's query vector). Drop it so the next precompute
+ // pass re-embeds it in the CURRENT space — self-heals a mid-session
+ // backend switch instead of ranking on garbage similarity forever.
+ CACHE.delete(t.name)
+ continue
+ }
scored.push({ tool: t, score: cosine(queryVec, c.vector) })
}
scored.sort((a, b) => b.score - a.score)
diff --git a/src/api/agents/in-turn-cache.ts b/src/api/agents/in-turn-cache.ts
index 0746f798..a1a57964 100644
--- a/src/api/agents/in-turn-cache.ts
+++ b/src/api/agents/in-turn-cache.ts
@@ -32,17 +32,72 @@ export interface InTurnCacheOptions {
* executeParallel's ExecutorRuntime.lookupCache. Returns the cached result
* string when a matching prior call exists within the current turn.
*/
+/**
+ * Tools whose results must NEVER be served from the in-turn cache. These are
+ * non-idempotent (side-effecting or state-dependent): a repeated
+ * shell_execute("npm test") has to actually re-run, a file_write has to
+ * actually write, and git_* reflects mutable working-tree state. Serving a
+ * cached payload here silently breaks the core edit -> test -> verify loop: the
+ * pre-fix test failure from an early iteration would be replayed after the fix
+ * landed, and the model concludes its fix did nothing.
+ */
+const NON_CACHEABLE_TOOLS = new Set<string>([
+ 'file_write',
+ 'file_edit',
+ 'shell_execute',
+ 'shell_execute_background',
+ 'code_execute',
+ 'run_tests',
+])
+
+/** Reads whose cached payload is invalidated by a later workspace mutation. */
+const READ_TOOLS = new Set<string>(['file_read', 'file_list'])
+
+function isNonCacheableTool(name: string): boolean {
+ return NON_CACHEABLE_TOOLS.has(name) || name.startsWith('git_')
+}
+
+/** A workspace-mutating call — same set that is non-cacheable, plus git_*. */
+function isMutatingTool(name: string): boolean {
+ return NON_CACHEABLE_TOOLS.has(name) || name.startsWith('git_')
+}
+
+/**
+ * True when any workspace-mutating call ran after `afterMs` in this turn.
+ * shell_execute can touch any path, so rather than parse an opaque shell
+ * command we conservatively invalidate ALL cached reads on ANY mutation that
+ * happened after the cached read. Re-reading is cheap and always correct.
+ */
+function hasMutationSince(convId: string, afterMs: number): boolean {
+ const list = useToolAuditStore.getState().forConversation(convId)
+ for (const e of list) {
+ if (e.startedAt <= afterMs) continue
+ if (isMutatingTool(e.toolName)) return true
+ }
+ return false
+}
+
export function makeInTurnCacheLookup(opts: InTurnCacheOptions) {
const { convId, turnStartMs } = opts
return (req: ExecutionRequest, argsHash: string): string | undefined => {
- const candidate = useToolAuditStore
- .getState()
- .findCacheCandidate(convId, req.toolName, argsHash, turnStartMs)
- // Only return a cached payload if the prior call actually produced one.
- // Empty strings are cacheable (tool legitimately returned ""); undefined
- // is not (failed calls record no resultPreview).
+ // Never serve non-idempotent tools from cache (see NON_CACHEABLE_TOOLS).
+ if (isNonCacheableTool(req.toolName)) return undefined
+
+ const store = useToolAuditStore.getState()
+ const candidate = store.findCacheCandidate(convId, req.toolName, argsHash, turnStartMs)
if (!candidate) return undefined
- if (typeof candidate.resultPreview !== 'string') return undefined
- return candidate.resultPreview
+
+ // A cached file_read / file_list is stale the moment any mutating call ran
+ // after it. Miss -> the executor re-reads the current bytes.
+ if (READ_TOOLS.has(req.toolName) && hasMutationSince(convId, candidate.startedAt)) {
+ return undefined
+ }
+
+ // Serve the FULL retained result, never the 500-char audit preview. When
+ // the full result was not retained (absent, or clipped for size) treat it
+ // as a miss so the model re-reads the whole file instead of a silently
+ // truncated slice. Empty strings are a legitimate cached payload.
+ if (typeof candidate.fullResult !== 'string') return undefined
+ return candidate.fullResult
}
}
diff --git a/src/api/agents/side-effect-key.ts b/src/api/agents/side-effect-key.ts
index 9922f20e..ab4b2377 100644
--- a/src/api/agents/side-effect-key.ts
+++ b/src/api/agents/side-effect-key.ts
@@ -14,9 +14,11 @@
* - file_write → key is `file_write:<normalized-path>`. Two writes to
* the SAME path serialize; writes to DIFFERENT paths remain parallel.
*
- * - shell_execute, code_execute → key 'exec'. We do not know what a
- * shell command touches, so batch all exec-class calls onto a single
- * queue.
+ * - shell_execute, code_execute, shell_execute_background, run_tests,
+ * git_commit, git_push → key 'exec'. We do not know what a shell command
+ * touches, and concurrent repo writes race on `.git/index.lock`, so batch
+ * all exec-class + repo-mutating calls onto a single queue. Read-only git_*
+ * (git_status/git_log/git_diff) stay parallel.
*
* - image_generate, video_generate, run_workflow → key 'comfyui'. ComfyUI
* serializes internally and workflows do heavy I/O; running in parallel
@@ -34,6 +36,16 @@ export function deriveSideEffectKey(
}
case 'shell_execute':
case 'code_execute':
+ case 'shell_execute_background':
+ case 'run_tests':
+ case 'git_commit':
+ case 'git_push':
+ // Everything that shells out or mutates the repo shares ONE serial queue.
+ // We can't know what a command touches, and two concurrent git writes
+ // (e.g. git_commit + a `git push`, or two git_commits) race on
+ // `.git/index.lock` and one fails. run_tests and shell_execute_background
+ // also shell out, so they must not run against a repo mid-commit. Only the
+ // read-only git_* tools (git_status/git_log/git_diff) stay parallel.
return 'exec'
case 'image_generate':
case 'video_generate':
diff --git a/src/api/agents/sub-agent.ts b/src/api/agents/sub-agent.ts
index 9550188c..7d0e960e 100644
--- a/src/api/agents/sub-agent.ts
+++ b/src/api/agents/sub-agent.ts
@@ -21,13 +21,14 @@ import { explainError as explainToolError } from './error-hints'
// pulls DELEGATE_TASK_TOOL_DEF + buildDelegateExecutor from this file at
// module init.
-/**
- * Max sub-agent nesting depth. Kept for symmetry with the original Phase
- * 13 design; the tool-registry filter (sub-agent never sees
- * `delegate_task`) already enforces non-recursion, so this is a soft
- * safety net rather than the primary guard.
- */
-export const SUB_AGENT_MAX_DEPTH = 2
+// Recursion note: a sub-agent's tool list is filtered so it never SEES
+// `delegate_task`, which is what discourages nesting in practice. It is not a
+// hard block — the runner resolves over the full registry — but the in-flight
+// concurrency cap below (SUB_AGENT_MAX_PARALLEL) plus each sub-agent's tight
+// budget bound the blast radius. (A former SUB_AGENT_MAX_DEPTH constant claimed
+// to enforce a depth limit but was never read; removed in 2.5.9. The design
+// deliberately uses one in-flight counter as the concurrency gate rather than a
+// separate nesting-depth counter, so parallel siblings are not throttled.)
/**
* Max sub-agents in flight at the same time (Bonus, 2026-05). Parallel
@@ -164,14 +165,21 @@ export async function defaultSubAgentRunner(
})
messages.push({ role: 'assistant', content: turn.content || '', tool_calls: turn.toolCalls })
- for (const r of results) {
- const tc = turn.toolCalls.find((t) => t.function.name === r.toolName)
+ // Map each result back to its ORIGINATING call by index. executeParallel
+ // preserves input order (results[i] <-> requests[i] <-> turn.toolCalls[i]),
+ // so zipping by index gives every tool message the correct tool_call_id —
+ // even when the turn fired the same tool twice. The previous find-by-name
+ // matched the FIRST call for both duplicates, leaving the second call's id
+ // with no result; strict OpenAI-compatible providers (lu-cloud/DeepInfra,
+ // openai, anthropic) then 400/422'd on the next turn and delegate_task
+ // aborted. The main loop already handles this the same way (useCodex.ts).
+ results.forEach((r, i) => {
messages.push({
role: 'tool',
content: r.result ?? r.error ?? '(no output)',
- tool_call_id: tc?.id,
+ tool_call_id: turn.toolCalls[i]?.id,
})
- }
+ })
}
return finalContent || '(sub-agent produced no final answer)'
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 70b1f057..19406026 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -8,12 +8,16 @@ import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
import { DELEGATE_TASK_TOOL_DEF, buildDelegateExecutor } from '../agents/sub-agent'
+import { applyUniqueEdit } from '../../lib/surgical-edit'
/**
- * Helper: current chat id as a plain `{ chatId }` fragment to spread into
- * backendCall payloads. Returns `{}` when no agent loop is active — the
- * Rust side then falls back to `agent-workspace/default/` for relative
- * paths (and uses absolute paths as-is regardless).
+ * Helper: current chat id (+ folder workspace) as a fragment to spread into
+ * backendCall payloads. Returns `{}` when no agent loop is active — the Rust
+ * side then falls back to `agent-workspace/default/` as the jail root. NOTE:
+ * absolute paths are NOT used as-is — the backend jails every path (relative OR
+ * absolute) to the resolved workspace root and rejects anything outside it, so
+ * a caller that needs an absolute project path to resolve MUST pass the real
+ * `workingDirectory` here (it becomes the root).
*/
function chatCtx(): { chatId?: string; workingDirectory?: string } {
const id = getActiveChatId()
@@ -92,8 +96,9 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
{
name: 'file_write',
description:
- 'Write a file. Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. '
- + 'To preserve existing content and append, use file_read FIRST then file_write with the combined content. '
+ 'Write a WHOLE file. Use for CREATING a new file or fully replacing one. '
+ + 'To change part of an EXISTING file, PREFER file_edit — it is far cheaper than resending the whole file and never truncates a large one. '
+ + 'Creates parent directories if missing. OVERWRITES existing content — there is NO append mode. '
+ 'PREFER absolute paths. '
+ 'Writes to the same path within one turn are serialized automatically via the sideEffectKey scheduler.',
inputSchema: {
@@ -107,6 +112,26 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
category: 'filesystem',
source: 'builtin',
},
+ {
+ name: 'file_edit',
+ description:
+ 'Make a SURGICAL edit to an existing file: replace old_string with new_string. '
+ + 'PREFER this over file_write for changing an existing file — you send only the lines that change, so it is far cheaper and never truncates a large file. '
+ + 'old_string must match EXACTLY ONCE: copy the exact text (including indentation) from a prior file_read and include enough surrounding lines to be unique. '
+ + 'It FAILS with no change if old_string is missing or matches more than one place — then read the file and retry with more context. '
+ + 'Use file_write instead to create a new file or fully rewrite one.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ path: { type: 'string', description: 'Path to the existing file (absolute preferred)' },
+ old_string: { type: 'string', description: 'Exact text to find — must occur exactly once in the file' },
+ new_string: { type: 'string', description: 'Replacement text' },
+ },
+ required: ['path', 'old_string', 'new_string'],
+ },
+ category: 'filesystem',
+ source: 'builtin',
+ },
{
name: 'file_list',
description:
@@ -667,6 +692,15 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {
async function executeFileRead(args: Record<string, any>): Promise<string> {
const data = await backendCall('fs_read', { path: args.path, ...chatCtx() })
+ // Binary files come back base64-encoded (encoding: 'base64'). Returning that
+ // raw base64 as if it were the file's text is a corruption trap: the model
+ // treats it as content and a later file_write persists the base64 STRING,
+ // silently mangling the binary. Surface a clear marker instead so the model
+ // knows it is binary and leaves it alone.
+ if (data.encoding === 'base64') {
+ const approxBytes = Math.floor((String(data.content || '').length * 3) / 4)
+ return `[binary file — ${formatBytes(approxBytes)}, not shown. This tool reads text only; do not write binary content back through file_write.]`
+ }
return data.content || ''
}
@@ -703,14 +737,62 @@ async function executeFileWrite(args: Record<string, any>): Promise<string> {
return `Created "${name}" (${formatBytes(content.length)}). It is shown to the user right here in the chat with a preview and a Download button — nothing was written to disk. Do not call file_read on it; just tell the user it's ready.`
}
const data = await backendCall('fs_write', { path: args.path, content, ...chatCtx() })
- // Rust returns {status: 'saved', path: <absolute>}. Surface the real path
- // so the model (and the file-change event) knows WHERE the write landed —
- // especially important when chatId is None and Rust routes a relative path
- // to `agent-workspace/default/`.
+ // Rust returns {status: 'saved'|'unchanged', path: <absolute>, bytes}. Surface
+ // the real path so the model (and the file-change event) knows WHERE the write
+ // landed — especially important when chatId is None and Rust routes a relative
+ // path to `agent-workspace/default/`. 'unchanged' means the bytes already
+ // matched (EOL/BOM-normalized), so nothing was rewritten — tell the model so
+ // it doesn't loop trying to "apply" a change that is already in place.
if (data.status === 'saved' && data.path) return `File saved: ${data.path}`
+ if (data.status === 'unchanged' && data.path) return `File already up to date, no changes written: ${data.path}`
return JSON.stringify(data)
}
+async function executeFileEdit(args: Record<string, any>): Promise<string> {
+ // Plain-chat artifact mode has no files on disk — file_edit makes no sense
+ // there. Steer to file_write (which captures a document artifact) instead of
+ // silently reaching into the agent sandbox.
+ if (isChatArtifactMode()) {
+ return 'file_edit is not available in plain chat (there are no files on disk here). Use file_write to create or replace a document.'
+ }
+ const path = typeof args.path === 'string' ? args.path : ''
+ if (!path) return 'Error: file_edit requires a "path".'
+ const oldString = typeof args.old_string === 'string' ? args.old_string : ''
+ const newString = typeof args.new_string === 'string' ? args.new_string : ''
+
+ // Read the CURRENT content (workspace-aware). file_edit only edits an
+ // existing text file — for a new file the model must use file_write.
+ let data: any
+ try {
+ data = await backendCall('fs_read', { path, ...chatCtx() })
+ } catch (e) {
+ return `Error: file_edit could not read ${path} — ${e instanceof Error ? e.message : String(e)}. To create a new file use file_write.`
+ }
+ if (data.encoding === 'base64') return `Error: file_edit cannot edit a binary file (${path}).`
+ const content = typeof data.content === 'string' ? data.content : ''
+
+ const res = applyUniqueEdit(content, oldString, newString)
+ if (!res.ok) {
+ switch (res.reason) {
+ case 'empty_old':
+ return 'Error: file_edit requires a non-empty old_string. To create a new file use file_write.'
+ case 'noop':
+ return 'Error: old_string and new_string are identical — nothing to change.'
+ case 'not_found':
+ return `Error: old_string was not found in ${path}. Read the file and copy the exact text (including indentation) you want to replace.`
+ case 'not_unique':
+ return `Error: old_string matches ${res.matches} places in ${path}. Add surrounding lines so it uniquely identifies ONE location, then retry.`
+ default:
+ return 'Error: file_edit failed.'
+ }
+ }
+
+ const w = await backendCall('fs_write', { path, content: res.content, ...chatCtx() })
+ if (w.status === 'saved' && w.path) return `Edited ${w.path} (1 replacement).`
+ if (w.status === 'unchanged' && w.path) return `No change written to ${w.path} (content already matched).`
+ return JSON.stringify(w)
+}
+
async function executeFileList(args: Record<string, any>): Promise<string> {
const data = await backendCall('fs_list', {
path: args.path,
@@ -968,8 +1050,12 @@ async function executeRunTests(args: Record<string, any>): Promise<string> {
recursive: false,
...chatCtx(),
})
- const names: string[] = Array.isArray(listing.items)
- ? listing.items.map((it: any) => String(it.name ?? '')).filter(Boolean)
+ // fs_list returns { entries, count } — NOT `items`. Reading the wrong
+ // key made `names` always [] → detectRunnerFromFiles([]) = 'unknown' →
+ // empty command → "could not detect a test runner" for every project,
+ // so the advertised auto-detect never once fired.
+ const names: string[] = Array.isArray(listing.entries)
+ ? listing.entries.map((it: any) => String(it.name ?? '')).filter(Boolean)
: []
runner = detectRunnerFromFiles(names)
} catch {
@@ -1176,6 +1262,7 @@ const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string
web_fetch: executeWebFetch,
file_read: executeFileRead,
file_write: executeFileWrite,
+ file_edit: executeFileEdit,
file_list: executeFileList,
file_search: executeFileSearch,
shell_execute: executeShellExecute,
diff --git a/src/components/chat/StagedChangesPanel.tsx b/src/components/chat/StagedChangesPanel.tsx
index a711ff58..1053a9f5 100644
--- a/src/components/chat/StagedChangesPanel.tsx
+++ b/src/components/chat/StagedChangesPanel.tsx
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { Check, X, ChevronDown, ChevronRight, FileText } from 'lucide-react'
import { useStagedChangesStore, type StagedChange } from '../../stores/stagedChangesStore'
import { useChatStore } from '../../stores/chatStore'
-import { toolRegistry } from '../../api/mcp'
+import { backendCall } from '../../api/backend'
import { DiffView } from './DiffView'
import { log } from '../../lib/logger'
@@ -42,13 +42,26 @@ export function StagedChangesPanel({ chatId }: Props) {
if (!chatId) return
setApplying((prev) => new Set(prev).add(change.id))
try {
- await toolRegistry.execute('file_write', {
- // Use the absolute path captured at stage time: by apply time the run's
- // active chat/workspace context is cleared, so a relative path would
- // land in agent-workspace/default/ instead of the project folder. (audit fix)
+ // Write via fs_write DIRECTLY, not the `file_write` model tool. Two
+ // reasons: (1) by apply time the loop's finally has cleared the active
+ // chat/workspace, so file_write's chatCtx() is empty and the write jails
+ // to agent-workspace/default — which REJECTS the absolute project path and
+ // every apply silently fails. (2) file_write deliberately does NOT let its
+ // caller pick the jail root (2.5.7 security review: a prompt-injected model
+ // could set workingDirectory to escape the sandbox). Apply is a trusted,
+ // user-gated UI action, so it is safe for the UI to pass the workspace root
+ // captured at stage time as the jail root.
+ const res = await backendCall<{ status?: string; path?: string }>('fs_write', {
path: change.resolvedPath || change.path,
content: change.newContent,
+ chatId,
+ workingDirectory: change.workingDirectory,
})
+ // 'saved' and 'unchanged' are both success ('unchanged' = the file already
+ // matched byte-for-byte). Anything else is a real failure worth retrying.
+ if (res?.status && res.status !== 'saved' && res.status !== 'unchanged') {
+ throw new Error(`fs_write returned status "${res.status}"`)
+ }
remove(chatId, change.id)
// Mirror the apply in the chat log so the user sees a confirmation
// in the main pane, not just the side-pane disappearing.
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 51ec2e0c..051a409a 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -24,6 +24,7 @@ import { fetchRepoMap, renderRepoMapSection } from '../api/agents/repo-map'
import { isLocalModelByName } from '../api/agents/model-locality'
import { useStagedChangesStore } from '../stores/stagedChangesStore'
import { computeUnifiedDiff } from '../lib/diff'
+import { applyUniqueEdit } from '../lib/surgical-edit'
import { log } from '../lib/logger'
import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
import { isThinkingCompatible, isPlainTextPlanner } from '../lib/model-compatibility'
@@ -40,6 +41,8 @@ import { selectRelevantTools, selectRelevantToolsAsync } from '../lib/tool-selec
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
+import { effectiveContextWindow } from '../lib/context-window'
+import { getModelContextCached } from '../api/ollama'
import { useMemoryStore } from '../stores/memoryStore'
import { extractMemoriesFromPair } from './useMemory'
import type { OllamaChatMessage } from '../types/agent-mode'
@@ -61,7 +64,7 @@ const CODEX_REVIEW_SYSTEM_PROMPT = `You are the Coding Agent in REVIEW MODE —
REVIEW MODE CONTRACT (binding):
- You MAY call: file_read, file_list, file_search, git_status, git_log, git_diff, system_info, process_list, get_current_time, web_fetch, web_search.
-- You MUST NOT call: file_write, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_generate, video_generate, run_workflow, screenshot, delegate_task. If you call them, the harness will reject the call and tell the model "review-only mode" — wasted budget.
+- You MUST NOT call: file_write, file_edit, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_generate, video_generate, run_workflow, screenshot, delegate_task. If you call them, the harness will reject the call and tell the model "review-only mode" — wasted budget.
- Output format: a markdown report with sections "## Summary", "## Findings (priority order)", "## Suggested follow-ups". For each finding cite the file + line range (path:line or path:start-end).
- Be direct. No flattery, no boilerplate. If the code is fine, say so in one sentence and stop.`
@@ -79,12 +82,13 @@ AUTONOMY CONTRACT (read carefully):
Workflow per task:
1. Understand the task (optional brief sentence)
2. Explore the codebase — file_list / file_read / file_search
-3. Implement ALL required changes — file_write, as many calls as needed in one go
+3. Implement ALL required changes — file_edit to change existing files, file_write for new ones; as many calls as needed in one go
4. Verify — shell_execute to run tests, lint, or build
5. Only THEN write a short summary of what you did
Rules:
- Always read a file before modifying it
+- To CHANGE part of an existing file, use file_edit (replace a UNIQUE old_string with new_string) — it is far cheaper and safer than rewriting the whole file with file_write, and never truncates a large file. Use file_write only to CREATE a new file or fully replace one. If file_edit reports the old_string is missing or not unique, read the file and retry with more surrounding lines.
- PATHS: use paths relative to the working directory shown below (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`) — that escapes the workspace and fails.
- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool
- If a command fails, diagnose and retry with a different approach — don't hand back to the user unless truly stuck
@@ -103,6 +107,7 @@ const CODEX_SYSTEM_PROMPT_LEAN = `You are a coding agent in LU. Use tools to do
Rules:
- Read a file before you edit it.
+- To change an existing file use file_edit (replace a unique old_string with new_string), not file_write. Use file_write only to create a new file.
- PATHS: use relative paths (e.g. \`package.json\`, \`.\`). Never start with \`/\` or a drive letter — it escapes the workspace and fails.
- Emit the tool call as your FIRST output — no "Okay, let me…" preamble. One step at a time, as valid JSON.
- After each tool result, if more steps remain, immediately call the next tool. Do not narrate "I will now…" and then stop.
@@ -128,6 +133,7 @@ const CODEX_CATEGORIES = ['filesystem', 'terminal', 'system', 'web', 'image', 'v
// stay allowed so the agent can do its job.
const REVIEW_MODE_FORBIDDEN_TOOLS = new Set([
'file_write',
+ 'file_edit',
'shell_execute',
'code_execute',
'shell_execute_background',
@@ -146,21 +152,29 @@ const REVIEW_MODE_FORBIDDEN_TOOLS = new Set([
'delegate_task',
])
-// `.lurules` reader — backendCall wraps the desktop Tauri `file_read`
-// command. Resolves absolute paths as-is (Bug "doubled path" fix in
-// v2.3 made the drive-letter detection robust), so the absolute lurules
-// path we compute below lands at the user's real `.lurules` file. The
-// reader swallows errors to a null return so loadLurules() can treat
-// "missing file" and "fs error" identically.
-const lurulesReader: RulesReader = {
- async read(path: string): Promise<string | null> {
- try {
- const r = await backendCall<{ content?: string }>('file_read', { path })
- return r?.content ?? null
- } catch {
- return null
- }
- },
+// `.lurules` reader. MUST go through `fs_read` (the workspace-aware command)
+// with the run's chatId + workingDirectory — NOT the older `file_read`, which
+// jails every path to the per-chat sandbox (agent-workspace/<id>) and so
+// REJECTS the absolute `<workDir>/.lurules` path with "escapes the allowed
+// workspace". That silent rejection meant per-repo rules never loaded in a real
+// folder workspace. Threading workingDirectory sets the jail root to the actual
+// project folder, so the absolute rules path resolves. Errors still swallow to
+// null so loadLurules() treats "missing file" and "fs error" identically.
+function makeLurulesReader(chatId: string, workDir: string): RulesReader {
+ return {
+ async read(path: string): Promise<string | null> {
+ try {
+ const r = await backendCall<{ content?: string }>('fs_read', {
+ path,
+ chatId,
+ workingDirectory: workDir,
+ })
+ return r?.content ?? null
+ } catch {
+ return null
+ }
+ },
+ }
}
// Detect when the model emits a re-introduction of itself ("Hello, I am
@@ -388,7 +402,7 @@ export function useCodex() {
// by the reader so the codex loop still starts.
if (workDir && workDir !== '.') {
try {
- const rules = await loadLurules(workDir, lurulesReader)
+ const rules = await loadLurules(workDir, makeLurulesReader(convId, workDir))
if (rules) {
systemPrompt += renderRulesSection(rules)
}
@@ -571,12 +585,22 @@ export function useCodex() {
// Ollama used its small default (~4k) while compaction trimmed to the
// model's max → the history overflowed the real window and weak models
// (gemma4 with Think on) returned EMPTY turns, which the loop misread as
- // "done" and printed a false "Task completed" (David 2026-06-04). Pin a
- // sane floor (user override wins) and compact to it so both agree.
- const numCtx =
- settings.contextWindowOverride && settings.contextWindowOverride > 0
- ? settings.contextWindowOverride
- : 8192
+ // "done" and printed a false "Task completed" (David 2026-06-04). A later
+ // fix pinned a flat 8192 — but that hard cap throttled 32k-capable coding
+ // models (qwen2.5-coder 32k) down to 8k AND drove compaction to trim their
+ // history to ~6.5k. Mirror useAgentChat (David: "muss immer stimmen"): the
+ // user override wins, else the model's REAL context capped for VRAM
+ // (effectiveContextWindow → 16384 on Ollama), floored at 8192 so a
+ // 4k-default model never overflows. Both the num_ctx we send and the
+ // compaction target below derive from this one value, so they always agree.
+ let numCtx: number = settings.contextWindowOverride || 8192
+ if (providerId === 'ollama' && !settings.contextWindowOverride) {
+ try {
+ numCtx = Math.max(effectiveContextWindow(await getModelContextCached(modelToUse), 0), 8192)
+ } catch {
+ // Keep the 8192 floor when the model's context can't be probed.
+ }
+ }
try {
// Agent loop — max 20 iterations (legacy cap) AND AgentBudget cap,
@@ -613,7 +637,14 @@ export function useCodex() {
// Raised again 50 → 200 (v2.5.0 — uselu live-test 1af958b2):
// scaffold-install-fix-verify on 35B local model legitimately
// needs 100+ iterations across multi-file refactors.
- const MAX_CODEX_ITERATIONS = 200
+ // 2.5.9: derive the outer bound from the configured cap instead of a
+ // hardcoded 200 that shadowed it — setting agentMaxIterations above 200
+ // used to do nothing (loop exited at 200) and the budget's halt message
+ // told the user to raise a cap that had no effect. The AgentBudget below
+ // (same cap) still fires its halt message on the final iteration, since it
+ // is checked at the top of the loop body; this bound is the runaway
+ // backstop. Floor of 1 so a stray 0 setting can't zero the loop.
+ const MAX_CODEX_ITERATIONS = Math.max(settings.agentMaxIterations ?? 200, 1)
for (let i = 0; i < MAX_CODEX_ITERATIONS && runningRef.current && !abort.signal.aborted; i++) {
budget.addIteration()
const bx = budget.exceeded()
@@ -1078,7 +1109,7 @@ export function useCodex() {
// workDir=D:/Pictures/foo, p=D:/Pictures/foo/bar.html →
// D:/Pictures/foo/D:/Pictures/foo/bar.html
// which then grew further on retry as the model re-emitted the path.
- if ((toolName === 'file_read' || toolName === 'file_write' || toolName === 'file_list' || toolName === 'file_search') && toolArgs.path) {
+ if ((toolName === 'file_read' || toolName === 'file_write' || toolName === 'file_edit' || toolName === 'file_list' || toolName === 'file_search') && toolArgs.path) {
const p: string = toolArgs.path
const isAbsolute =
/^[a-zA-Z]:[/\\]/.test(p) || // Windows drive letter: C:/ D:\ etc.
@@ -1115,13 +1146,21 @@ export function useCodex() {
// renders as a pure insert). Errors are swallowed — a failing
// pre-read just means the file_change event won't carry a diff,
// never blocks the write.
+ //
+ // MUST use `fs_read` with the run's chatId + workingDirectory. The
+ // older `file_read` jails to the per-chat sandbox and REJECTS the
+ // absolute project path, so every pre-read returned '' and every diff
+ // rendered as a 100% insert — hiding exactly the deletions/overwrites
+ // the user needs to see before approving a staged change.
+ const readCtx: { chatId?: string; workingDirectory?: string } =
+ workDir && workDir !== '.' ? { chatId: convId, workingDirectory: workDir } : { chatId: convId }
const oldContents = new Map<string, string>()
await Promise.all(
batch
- .filter((e) => e.ac.toolName === 'file_write' && typeof e.injectedArgs.path === 'string')
+ .filter((e) => (e.ac.toolName === 'file_write' || e.ac.toolName === 'file_edit') && typeof e.injectedArgs.path === 'string')
.map(async (e) => {
try {
- const r = await backendCall<{ content?: string }>('file_read', { path: e.injectedArgs.path })
+ const r = await backendCall<{ content?: string }>('fs_read', { path: e.injectedArgs.path, ...readCtx })
oldContents.set(e.ac.id, r?.content ?? '')
} catch {
oldContents.set(e.ac.id, '')
@@ -1183,14 +1222,19 @@ export function useCodex() {
// happens later, after this turn's finally clears the active
// chat/workspace context, so a relative path would otherwise route to
// agent-workspace/default/ instead of the real project folder. The
- // bridge uses an absolute path as-is. (v2.5.0 audit fix.)
+ // bridge jails absolute paths to the workspace root, so the pre-read
+ // MUST pass the run's workingDirectory (as its root) — otherwise the
+ // absolute project path is rejected and the staged diff shows a 100%
+ // insert, hiding what will be overwritten. (v2.5.0 + 2.5.9 audit fix.)
const isAbs = /^([a-zA-Z]:[\\/]|[\\/]|\\\\)/.test(path)
const resolvedPath = isAbs || !workDir || workDir === '.'
? path
: `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`
+ const stageReadCtx: { chatId?: string; workingDirectory?: string } =
+ workDir && workDir !== '.' ? { chatId: convId, workingDirectory: workDir } : { chatId: convId }
let oldContent = ''
try {
- const r = await backendCall<{ content?: string }>('file_read', { path: resolvedPath })
+ const r = await backendCall<{ content?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })
oldContent = r?.content ?? ''
} catch {
// New file — leave oldContent empty so the diff renders an
@@ -1200,6 +1244,11 @@ export function useCodex() {
useStagedChangesStore.getState().stage(convId!, {
path,
resolvedPath,
+ // Capture the workspace root so Apply (which runs after the loop's
+ // finally clears the active context) can jail the write to the real
+ // project folder instead of agent-workspace/default. Undefined in
+ // sandbox mode — the per-chat sandbox is the right root there.
+ workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
oldContent,
newContent,
diff,
@@ -1207,9 +1256,56 @@ export function useCodex() {
return `Staged for review: ${path}. The user will apply or reject the change before it lands on disk.`
}
+ // Stage-mode counterpart for surgical edits: resolve old_string ->
+ // new_string against the current file NOW and stage the resulting full
+ // content, so the staged diff and the applied write are the real change
+ // (and a bad edit is reported the same way whether staged or not).
+ const stageFileEdit = async (args: Record<string, any>): Promise<string> => {
+ const path = String(args.path ?? '')
+ if (!path) return 'file_edit: missing path'
+ const oldString = typeof args.old_string === 'string' ? args.old_string : ''
+ const newString = typeof args.new_string === 'string' ? args.new_string : ''
+ const isAbs = /^([a-zA-Z]:[\\/]|[\\/]|\\\\)/.test(path)
+ const resolvedPath = isAbs || !workDir || workDir === '.'
+ ? path
+ : `${workDir.replace(/[\\/]+$/, '')}${workDir.includes('\\') ? '\\' : '/'}${path.replace(/^[\\/]+/, '')}`
+ const stageReadCtx: { chatId?: string; workingDirectory?: string } =
+ workDir && workDir !== '.' ? { chatId: convId, workingDirectory: workDir } : { chatId: convId }
+ let oldContent = ''
+ try {
+ const r = await backendCall<{ content?: string; encoding?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })
+ if (r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`
+ oldContent = r?.content ?? ''
+ } catch {
+ return `file_edit: could not read ${path}. To create a new file use file_write.`
+ }
+ const applied = applyUniqueEdit(oldContent, oldString, newString)
+ if (!applied.ok) {
+ switch (applied.reason) {
+ case 'empty_old': return 'file_edit: old_string must be non-empty. Use file_write to create a new file.'
+ case 'noop': return 'file_edit: old_string and new_string are identical — nothing to change.'
+ case 'not_found': return `file_edit: old_string not found in ${path}. Read the file and copy the exact text you want to replace.`
+ case 'not_unique': return `file_edit: old_string matches ${applied.matches} places in ${path}. Add surrounding lines so it is unique.`
+ default: return 'file_edit: failed.'
+ }
+ }
+ const newContent = applied.content ?? ''
+ const diff = computeUnifiedDiff(path, oldContent, newContent)
+ useStagedChangesStore.getState().stage(convId!, {
+ path,
+ resolvedPath,
+ workingDirectory: workDir && workDir !== '.' ? workDir : undefined,
+ oldContent,
+ newContent,
+ diff,
+ })
+ return `Staged for review: ${path} (surgical edit). The user will apply or reject the change before it lands on disk.`
+ }
+
const dispatchTool = (name: string, args: Record<string, any>): Promise<string> => {
- if (name === 'file_write' && settings.codexStageMode) {
- return stageFileWrite(args)
+ if (settings.codexStageMode) {
+ if (name === 'file_write') return stageFileWrite(args)
+ if (name === 'file_edit') return stageFileEdit(args)
}
return withTimeout(name, args)
}
@@ -1325,6 +1421,26 @@ export function useCodex() {
diff: diff || undefined,
timestamp: Date.now(),
})
+ } else if (entry.ac.toolName === 'file_edit') {
+ // Surgical edit — the tool only received old_string/new_string, so
+ // reconstruct the new content from the pre-read + the unique
+ // replacement to attach a real diff. If the edit did not apply
+ // uniquely the executor already returned an error; skip the diff.
+ const oldText = oldContents.get(entry.ac.id) ?? ''
+ const applied = applyUniqueEdit(
+ oldText,
+ typeof entry.injectedArgs.old_string === 'string' ? entry.injectedArgs.old_string : '',
+ typeof entry.injectedArgs.new_string === 'string' ? entry.injectedArgs.new_string : '',
+ )
+ const diff = applied.ok
+ ? computeUnifiedDiff(entry.injectedArgs.path, oldText, applied.content ?? '')
+ : undefined
+ codexStore.addEvent(convId, {
+ id: uuid(), type: 'file_change', content: resultStr,
+ filePath: entry.injectedArgs.path,
+ diff: diff || undefined,
+ timestamp: Date.now(),
+ })
} else if (isError) {
codexStore.addEvent(convId, {
id: uuid(), type: 'error', content: resultStr, timestamp: Date.now(),
diff --git a/src/lib/__tests__/small-model-mode.test.ts b/src/lib/__tests__/small-model-mode.test.ts
index 6796f07e..3a5646f3 100644
--- a/src/lib/__tests__/small-model-mode.test.ts
+++ b/src/lib/__tests__/small-model-mode.test.ts
@@ -62,6 +62,7 @@ describe('Small-Model Mode — Knob 1: applyMaxTools', () => {
const tools = [
mkTool('file_read', 'read', 'filesystem'),
mkTool('file_write', 'write', 'filesystem'),
+ mkTool('file_edit', 'edit', 'filesystem'),
mkTool('get_current_time', 'time', 'system'),
mkTool('a', 'aaaa'),
mkTool('b', 'bbbb'),
@@ -91,9 +92,9 @@ describe('Small-Model Mode — Knob 1: applyMaxTools', () => {
})
it('fills the non-always slots from rankOrder when provided', () => {
- // 3 ALWAYS_INCLUDE + 1 free slot; rank puts 'f' first → 'f' wins, 'a' loses.
- const out = applyMaxTools(tools, 4, ['f', 'e', 'd', 'c', 'b', 'a'])
- expect(out.length).toBe(4)
+ // 4 ALWAYS_INCLUDE + 1 free slot; rank puts 'f' first → 'f' wins, 'a' loses.
+ const out = applyMaxTools(tools, 5, ['f', 'e', 'd', 'c', 'b', 'a'])
+ expect(out.length).toBe(5)
expect(out.some((t) => t.name === 'f')).toBe(true)
expect(out.some((t) => t.name === 'a')).toBe(false)
})
diff --git a/src/lib/__tests__/surgical-edit.test.ts b/src/lib/__tests__/surgical-edit.test.ts
new file mode 100644
index 00000000..0be7ac4a
--- /dev/null
+++ b/src/lib/__tests__/surgical-edit.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect } from 'vitest'
+import { applyUniqueEdit, countOccurrences } from '../surgical-edit'
+
+describe('surgical-edit — countOccurrences', () => {
+ it('counts non-overlapping occurrences', () => {
+ expect(countOccurrences('a.b.c', '.')).toBe(2)
+ expect(countOccurrences('aaaa', 'aa')).toBe(2) // non-overlapping
+ expect(countOccurrences('hello', 'x')).toBe(0)
+ expect(countOccurrences('anything', '')).toBe(0)
+ })
+})
+
+describe('surgical-edit — applyUniqueEdit', () => {
+ const file = `function greet(name) {\n return "hi " + name\n}\n`
+
+ it('replaces a unique match', () => {
+ const r = applyUniqueEdit(file, 'return "hi " + name', 'return `hi ${name}`')
+ expect(r.ok).toBe(true)
+ expect(r.matches).toBe(1)
+ expect(r.content).toContain('return `hi ${name}`')
+ expect(r.content).not.toContain('"hi "')
+ })
+
+ it('refuses when old_string is not found', () => {
+ const r = applyUniqueEdit(file, 'return "bye"', 'x')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('not_found')
+ expect(r.matches).toBe(0)
+ })
+
+ it('refuses an ambiguous (non-unique) match', () => {
+ const dup = 'const x = 1\nconst x = 1\n'
+ const r = applyUniqueEdit(dup, 'const x = 1', 'const x = 2')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('not_unique')
+ expect(r.matches).toBe(2)
+ })
+
+ it('refuses an empty old_string', () => {
+ const r = applyUniqueEdit(file, '', 'x')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('empty_old')
+ })
+
+ it('refuses a no-op (old === new)', () => {
+ const r = applyUniqueEdit(file, 'greet', 'greet')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('noop')
+ })
+
+ it('inserts $ sequences literally (no capture-group interpretation)', () => {
+ const r = applyUniqueEdit('price = TODO', 'TODO', '"$5.00 ($$ each)"')
+ expect(r.ok).toBe(true)
+ expect(r.content).toBe('price = "$5.00 ($$ each)"')
+ })
+
+ it('handles multiline old_string', () => {
+ const r = applyUniqueEdit(file, '{\n return "hi " + name\n}', '{\n return name.toUpperCase()\n}')
+ expect(r.ok).toBe(true)
+ expect(r.content).toContain('name.toUpperCase()')
+ })
+})
diff --git a/src/lib/__tests__/tool-selection.test.ts b/src/lib/__tests__/tool-selection.test.ts
index e0e0effd..013271ea 100644
--- a/src/lib/__tests__/tool-selection.test.ts
+++ b/src/lib/__tests__/tool-selection.test.ts
@@ -279,4 +279,39 @@ describe('tool-selection', () => {
expect(names).toContain('process_list')
})
})
+
+ // ── Coding intents don't route to web; discovery tools stay (P1 #4) ──
+ describe('coding intent routing', () => {
+ it('a coding search keeps file discovery tools and never web_fetch', () => {
+ // "search the codebase…" used to match the bare 'search' web keyword,
+ // pull web_search+web_fetch, inflate the count past 3 and skip the
+ // file-tool booster — leaving the coding turn with no way to find files.
+ const names = toolNames(
+ selectRelevantTools('search the codebase for the auth handler and refactor it', ALL_TOOLS, ALL_ALLOWED),
+ )
+ expect(names).toContain('file_search')
+ expect(names).toContain('file_list')
+ // The web GROUP must not fire on a bare coding "search" (web_fetch is only
+ // ever added by that group, never by the generic fallback).
+ expect(names).not.toContain('web_fetch')
+ })
+
+ it('"fix the current bug" does not trigger the web group', () => {
+ const names = toolNames(selectRelevantTools('fix the current bug in auth.ts', ALL_TOOLS, ALL_ALLOWED))
+ expect(names).not.toContain('web_fetch')
+ })
+
+ it('a shell-heavy coding turn still gets file discovery (safety net)', () => {
+ // Matches the shell group (count > 3) so the generic <=3 fallback is
+ // skipped; the discovery safety net must still add file_search/file_list.
+ const names = toolNames(
+ selectRelevantTools('run the tests and find the failing spec', ALL_TOOLS, ALL_ALLOWED),
+ )
+ expect(names).toContain('shell_execute')
+ expect(names).toContain('file_search')
+ expect(names).toContain('file_list')
+ // Not forced onto a pure coding turn.
+ expect(names).not.toContain('web_fetch')
+ })
+ })
})
diff --git a/src/lib/context-compaction.ts b/src/lib/context-compaction.ts
index 30da6c63..78cebd73 100644
--- a/src/lib/context-compaction.ts
+++ b/src/lib/context-compaction.ts
@@ -75,14 +75,36 @@ export async function getModelMaxTokens(modelName: string): Promise<number> {
// ── Message Compaction ──────────────────────────────────────────
-const KEEP_RECENT = 4 // Always keep the last N messages untouched
+const KEEP_RECENT = 4 // Always keep at least the last N messages untouched
+
+/**
+ * True for a message that is a tool RESULT — either the native `tool` role or
+ * a Hermes `<tool_response>` carried on a user message. Used to trim a leading
+ * orphan result whose originating tool_call fell outside the kept window.
+ */
+function isToolResultMessage(msg: OllamaChatMessage): boolean {
+ if (msg.role === 'tool') return true
+ if (msg.role === 'user' && typeof msg.content === 'string' && msg.content.includes('<tool_response>')) {
+ return true
+ }
+ return false
+}
/**
* Compact a message array to fit within a token budget.
*
- * - If already within budget, returns messages unchanged.
- * - Otherwise, keeps the system prompt + last KEEP_RECENT messages,
- * and summarizes everything in between.
+ * Strategy — sliding window, lossless on whatever it keeps:
+ * - If already within budget, return messages unchanged.
+ * - Otherwise keep the system prompt + the longest recent SUFFIX that fits,
+ * VERBATIM, and DROP the oldest messages entirely (replaced by a one-line
+ * notice).
+ *
+ * Why not summarize? The previous implementation char-truncated every older
+ * tool result to 80 chars. Inside a single autonomous coding turn that meant an
+ * 80-char slice of a file the agent had read was indistinguishable from the
+ * whole file — so the model edited against content it could no longer see.
+ * Dropping is honest: the model re-reads with file_read when it needs the bytes
+ * again, instead of trusting a lossy stub.
*/
export function compactMessages(
messages: OllamaChatMessage[],
@@ -100,99 +122,36 @@ export function compactMessages(
// If we have fewer messages than KEEP_RECENT, can't compact further
if (nonSystem.length <= KEEP_RECENT) return messages
- // Split: old messages (to compact) + recent messages (to keep)
- const oldMessages = nonSystem.slice(0, -KEEP_RECENT)
- const recentMessages = nonSystem.slice(-KEEP_RECENT)
+ const systemTokens = systemMsg ? estimateMessageTokens([systemMsg]) : 0
+ const budget = Math.max(0, maxTokens - systemTokens)
+
+ // Accumulate a recent suffix that fits, newest-first. Keep at least
+ // KEEP_RECENT messages even when that exceeds budget (recent context is the
+ // most valuable), otherwise stop as soon as the next message would overflow.
+ const kept: OllamaChatMessage[] = []
+ let used = 0
+ for (let i = nonSystem.length - 1; i >= 0; i--) {
+ const t = estimateMessageTokens([nonSystem[i]])
+ if (used + t > budget && kept.length >= KEEP_RECENT) break
+ kept.unshift(nonSystem[i])
+ used += t
+ }
- // Summarize old messages
- const summary = summarizeMessages(oldMessages)
+ // Drop leading orphan tool results (their tool_call fell outside the window)
+ // so strict OpenAI-compatible providers don't reject a result with no call.
+ while (kept.length > 0 && isToolResultMessage(kept[0])) {
+ kept.shift()
+ }
- // Build compacted array
+ const droppedCount = nonSystem.length - kept.length
const compacted: OllamaChatMessage[] = []
-
if (systemMsg) compacted.push(systemMsg)
-
- // Insert summary as a system-level context message
- if (summary) {
+ if (droppedCount > 0) {
compacted.push({
role: 'system',
- content: `[Previous conversation summary]\n${summary}`,
+ content: `[${droppedCount} earlier message${droppedCount === 1 ? '' : 's'} were trimmed to fit the context window. Re-read any file you still need with file_read.]`,
})
}
-
- // Keep recent messages intact
- compacted.push(...recentMessages)
-
+ compacted.push(...kept)
return compacted
}
-
-// ── Message Summarization ───────────────────────────────────────
-
-/**
- * Summarize a sequence of messages into a compact string.
- * Tool call + result pairs become one-liners.
- */
-function summarizeMessages(messages: OllamaChatMessage[]): string {
- const lines: string[] = []
- let i = 0
-
- while (i < messages.length) {
- const msg = messages[i]
-
- if (msg.role === 'user') {
- // User message → short summary
- const content = msg.content.trim()
- if (content.length > 0 && !content.startsWith('<tool_response>')) {
- lines.push(`User asked: ${truncate(content, 80)}`)
- }
- } else if (msg.role === 'assistant') {
- // Check if this is a tool call (next message might be 'tool' or contains tool_response)
- if (msg.tool_calls && msg.tool_calls.length > 0) {
- // Native tool call
- for (const tc of msg.tool_calls) {
- const toolName = tc.function?.name || 'unknown'
- const args = JSON.stringify(tc.function?.arguments || {})
- const argsShort = truncate(args, 60)
-
- // Look ahead for the tool result
- const nextMsg = messages[i + 1]
- if (nextMsg && (nextMsg.role === 'tool' || nextMsg.role === 'user')) {
- const resultShort = truncate(nextMsg.content, 80)
- lines.push(`Used ${toolName}(${argsShort}) → ${resultShort}`)
- i++ // skip the result message
- } else {
- lines.push(`Called ${toolName}(${argsShort})`)
- }
- }
- } else if (msg.content.includes('<tool_call>')) {
- // Hermes XML tool call
- const match = msg.content.match(/"name"\s*:\s*"([^"]+)"/)
- const toolName = match?.[1] || 'tool'
- const nextMsg = messages[i + 1]
- if (nextMsg?.content?.includes('<tool_response>')) {
- const resultShort = truncate(nextMsg.content.replace(/<\/?tool_response>/g, ''), 80)
- lines.push(`Used ${toolName} → ${resultShort}`)
- i++
- } else {
- lines.push(`Called ${toolName}`)
- }
- } else if (msg.content.trim().length > 0) {
- // Regular assistant message
- lines.push(`Assistant: ${truncate(msg.content, 100)}`)
- }
- } else if (msg.role === 'tool') {
- // Standalone tool result (shouldn't happen if paired above, but just in case)
- lines.push(`Tool result: ${truncate(msg.content, 80)}`)
- }
-
- i++
- }
-
- return lines.join('\n')
-}
-
-function truncate(text: string, maxLen: number): string {
- const cleaned = text.replace(/\n/g, ' ').trim()
- if (cleaned.length <= maxLen) return cleaned
- return cleaned.slice(0, maxLen - 3) + '...'
-}
diff --git a/src/lib/surgical-edit.ts b/src/lib/surgical-edit.ts
new file mode 100644
index 00000000..205be7eb
--- /dev/null
+++ b/src/lib/surgical-edit.ts
@@ -0,0 +1,55 @@
+/**
+ * Surgical edit primitive — the core of the `file_edit` tool (2.5.9, M1).
+ *
+ * Replaces exactly ONE unique occurrence of old_string with new_string, or
+ * reports why it could not (empty / no-op / not found / not unique). This is
+ * the small-model-friendly alternative to full-file rewrites: the model sends
+ * only the lines it wants changed, so editing a 2000-line file costs a few
+ * tokens instead of regenerating the whole thing (slow, and prone to
+ * truncation on local models). Aider / Cline / Cursor all edit this way.
+ *
+ * Pure + dependency-free so it can be unit-tested and shared between the tool
+ * executor (api/mcp/builtin-tools.ts) and the diff event emitter (useCodex.ts).
+ */
+
+export type EditFailReason = 'empty_old' | 'noop' | 'not_found' | 'not_unique'
+
+export interface EditOutcome {
+ ok: boolean
+ /** The updated file content — present only when ok. */
+ content?: string
+ /** How many times old_string occurred (0, 1, or >1). */
+ matches: number
+ /** Machine-usable reason when !ok. */
+ reason?: EditFailReason
+}
+
+/** Count NON-overlapping occurrences of `needle` in `haystack`. */
+export function countOccurrences(haystack: string, needle: string): number {
+ if (needle === '') return 0
+ let count = 0
+ let idx = haystack.indexOf(needle)
+ while (idx !== -1) {
+ count++
+ idx = haystack.indexOf(needle, idx + needle.length)
+ }
+ return count
+}
+
+/**
+ * Apply a unique-match replacement. `oldString` must occur exactly once for the
+ * edit to succeed — this is what makes surgical edits safe: an ambiguous match
+ * is refused rather than silently changing the wrong (or every) occurrence.
+ */
+export function applyUniqueEdit(content: string, oldString: string, newString: string): EditOutcome {
+ if (oldString === '') return { ok: false, matches: 0, reason: 'empty_old' }
+ const matches = countOccurrences(content, oldString)
+ if (oldString === newString) return { ok: false, matches, reason: 'noop' }
+ if (matches === 0) return { ok: false, matches: 0, reason: 'not_found' }
+ if (matches > 1) return { ok: false, matches, reason: 'not_unique' }
+ // Exactly one occurrence. Use a FUNCTION replacer so `$&`, `$1`, `$$` etc.
+ // in newString are inserted literally — a plain-string replacement would
+ // interpret them as capture-group references and corrupt the output.
+ const updated = content.replace(oldString, () => newString)
+ return { ok: true, content: updated, matches: 1 }
+}
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index 9a945901..586c899a 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -15,13 +15,18 @@ interface ToolGroup {
const TOOL_GROUPS: ToolGroup[] = [
{
- // Web search intents. German terms included (image group below has them
- // too) — without them a German "such im internet nach…" never surfaced
- // web_search and the model answered from stale training data instead.
- keywords: ['search', 'find online', 'look up', 'google', 'bing', 'duckduckgo', 'internet',
- 'news', 'latest', 'current', 'web search', 'websearch', 'browse', 'website', 'webseite',
+ // Web search intents. Only EXPLICIT web cues route here. Bare 'search',
+ // 'latest', 'current', 'aktuell', 'neueste', 'suche' were removed: they
+ // collide head-on with coding intents ("search the codebase", "fix the
+ // current bug", "the latest changes"), which used to pull web_search+
+ // web_fetch, inflate the selection past 3, and silently skip the file-tool
+ // booster below — leaving a coding turn with no file_search/file_list.
+ // German phrases kept as multi-word cues ("such im internet", "im internet")
+ // so a real "such im internet nach…" still surfaces web_search.
+ keywords: ['find online', 'look up', 'look it up', 'google', 'bing', 'duckduckgo', 'internet',
+ 'news', 'web search', 'websearch', 'search online', 'search the web', 'browse', 'website', 'webseite',
'url', 'http://', 'https://', 'weather', 'wetter',
- 'suche', 'such nach', 'such im', 'recherch', 'nachrichten', 'neueste', 'aktuell'],
+ 'such nach', 'such im', 'im internet', 'recherch', 'nachrichten', 'neueste'],
tools: ['web_search', 'web_fetch'],
},
{
@@ -29,8 +34,11 @@ const TOOL_GROUPS: ToolGroup[] = [
tools: ['file_read'],
},
{
- keywords: ['write', 'create', 'save', 'make a file', 'put', 'generate file', 'output to'],
- tools: ['file_write'],
+ keywords: ['write', 'create', 'save', 'make a file', 'put', 'generate file', 'output to',
+ 'edit', 'modify', 'change', 'replace', 'update', 'refactor', 'rename', 'fix', 'patch'],
+ // file_edit (surgical) is preferred for changing existing files; file_write
+ // for new files / full rewrites. Both surfaced so the model can pick.
+ tools: ['file_write', 'file_edit'],
},
{
keywords: ['list', 'ls', 'dir', 'files in', 'directory', 'folder', 'what files', 'tree'],
@@ -77,7 +85,7 @@ const TOOL_GROUPS: ToolGroup[] = [
// a tool result reveals the user really wanted a file read). Keeping
// `get_current_time` here means the agent NEVER has to fall back to web
// for a trivial date question just because the keyword list missed.
-export const ALWAYS_INCLUDE = ['file_read', 'file_write', 'get_current_time']
+export const ALWAYS_INCLUDE = ['file_read', 'file_write', 'file_edit', 'get_current_time']
/** Tool count at which embedding-based routing becomes worth the round trip. */
export const EMBEDDING_ROUTING_THRESHOLD = 15
@@ -105,9 +113,11 @@ export function selectRelevantTools(
}
}
- // If very few tools matched, include all (model might need flexibility)
- // This handles generic messages like "help me with this project"
- if (selectedNames.size <= 3) {
+ // If nothing beyond the always-included tools matched, include a broad set
+ // (model might need flexibility). Handles generic messages like "help me with
+ // this project". Threshold is ALWAYS_INCLUDE.length so adding an always-tool
+ // (e.g. file_edit) doesn't silently disable this fallback.
+ if (selectedNames.size <= ALWAYS_INCLUDE.length) {
// Include common tools for generic requests
selectedNames.add('shell_execute')
selectedNames.add('file_list')
@@ -115,6 +125,24 @@ export function selectRelevantTools(
selectedNames.add('web_search')
}
+ // Coding-discovery safety net (independent of the total count above). Any
+ // message that surfaced a shell / code / file tool but lacks the file-
+ // discovery pair cannot actually explore the codebase: "run the tests and
+ // find the failing spec" matches shell_execute, pushes the count past 3, and
+ // would otherwise skip the booster — leaving no file_search/file_list. Add
+ // the discovery trio (never web_search) so coding intents can always locate
+ // files, which is exactly what CODEX_SYSTEM_PROMPT tells the model to do.
+ const hasCodeSignal =
+ selectedNames.has('shell_execute') ||
+ selectedNames.has('code_execute') ||
+ selectedNames.has('file_search') ||
+ selectedNames.has('file_list')
+ if (hasCodeSignal) {
+ selectedNames.add('shell_execute')
+ selectedNames.add('file_list')
+ selectedNames.add('file_search')
+ }
+
// Filter by permissions (blocked categories excluded)
const available = allTools.filter(t => permissions[t.category] !== 'blocked')
diff --git a/src/stores/stagedChangesStore.ts b/src/stores/stagedChangesStore.ts
index 479fa620..4239e09d 100644
--- a/src/stores/stagedChangesStore.ts
+++ b/src/stores/stagedChangesStore.ts
@@ -15,6 +15,17 @@ export interface StagedChange {
* where it should. Falls back to `path` (already absolute / no workspace set).
*/
resolvedPath?: string
+ /**
+ * The run's workspace root, captured AT STAGE TIME. Apply runs after the loop
+ * ends, when the active chat/workspace context is cleared — so without this
+ * the write jails to agent-workspace/default and REJECTS the absolute project
+ * path ("escapes the allowed workspace"), silently failing every apply into a
+ * real folder. The apply path (a trusted, user-gated UI action) passes this
+ * as fs_write's working_directory so the jail root is the real project folder.
+ * Undefined for sandbox-mode runs (no real folder), where the per-chat
+ * sandbox is the correct root anyway.
+ */
+ workingDirectory?: string
/** Full file content before the write — empty string when the target didn't exist. */
oldContent: string
/** Full file content the model wants to write. */
diff --git a/src/stores/toolAuditStore.ts b/src/stores/toolAuditStore.ts
index 9af99d89..f0b0f5ad 100644
--- a/src/stores/toolAuditStore.ts
+++ b/src/stores/toolAuditStore.ts
@@ -51,6 +51,14 @@ export interface ToolAuditEntry {
errorHint?: string
/** String preview of result, clipped to keep panel performant. */
resultPreview?: string
+ /**
+ * Full, un-clipped result — the payload the in-turn cache serves so a second
+ * identical read in the same turn does not silently receive the 500-char
+ * `resultPreview` and mistake it for the whole file. Left undefined when the
+ * result exceeds AUDIT_FULL_RESULT_MAX_CHARS (cache misses -> re-read, which
+ * is always correct). Ephemeral, never persisted.
+ */
+ fullResult?: string
/** Raw error string when status=failed. */
error?: string
}
@@ -58,9 +66,17 @@ export interface ToolAuditEntry {
/** Max retained entries per conversation. Oldest evicted on overflow. */
export const AUDIT_MAX_PER_CONV = 500
-/** Max length of result preview kept in the store. */
+/** Max length of result preview kept in the store (debug panel rendering). */
export const AUDIT_RESULT_PREVIEW_CHARS = 500
+/**
+ * Max length of the FULL result retained for the in-turn cache. Bounds worst-
+ * case memory (ring buffer × this) while covering ordinary source files. A
+ * larger result is simply not retained, so a repeat read misses and re-reads
+ * the live bytes rather than serving a truncated slice.
+ */
+export const AUDIT_FULL_RESULT_MAX_CHARS = 262144
+
interface ToolAuditState {
/** convId → entries (newest last for cheap append; query helpers reverse). */
entries: Record<string, ToolAuditEntry[]>
@@ -169,6 +185,11 @@ export const useToolAuditStore = create<ToolAuditState>((set, get) => ({
completedAt,
durationMs,
resultPreview: patch.resultPreview?.slice(0, AUDIT_RESULT_PREVIEW_CHARS),
+ fullResult:
+ typeof patch.resultPreview === 'string' &&
+ patch.resultPreview.length <= AUDIT_FULL_RESULT_MAX_CHARS
+ ? patch.resultPreview
+ : undefined,
}
})
next[convId] = mutated ? updated : list