π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent): stop todo lists resetting, and make grep results engine-independent (#17877)
Arvin Xu9b9f6b96c819
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 083a00eaa46..592c31d9bf7 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -200,6 +200,7 @@ export class ServerToolTransport implements ToolTransport {// Assistant message owning this tool call (β source user message).assistantMessageId: context.parentMessageId,clientIp: context.state.metadata?.clientIp,+ currentTodos: context.currentTodos,deviceCapable: context.state.metadata?.executionPlan? isDeviceCapablePlan(context.state.metadata.executionPlan): undefined,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.tsindex e7243c19186..72bd61e8eb0 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts@@ -60,6 +60,22 @@ vi.mock('model-bank', () => ({LOBE_DEFAULT_MODEL_LIST: mockBuiltinModels,}));+// Plan documents are the todo runtime's optional mirror; a topic that never ran+// `createPlan` simply has none. Model that here so the todo tests exercise the+// message-history path the tool context is supposed to supply.+const mockFindPlanByTopic = vi.hoisted(() => vi.fn().mockResolvedValue(null));+const mockUpdatePlanMetadata = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));++vi.mock('../lobeAgentPlan', () => ({+ createServerPlanRuntimeService: () => ({+ createPlan: vi.fn(),+ findPlanById: vi.fn(),+ findPlanByTopic: mockFindPlanByTopic,+ updatePlan: vi.fn(),+ updatePlanMetadata: mockUpdatePlanMetadata,+ }),+}));+const { lobeAgentRuntime } = await import('../lobeAgent');describe('lobeAgentRuntime', () => {@@ -604,4 +620,42 @@ describe('lobeAgentRuntime', () => {expect(run).not.toHaveBeenCalled();});});++ describe('todos', () => {+ const todoContext: ToolExecutionContext = {+ ...baseContext,+ currentTodos: [+ { status: 'completed', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ { status: 'todo', text: 'write report' },+ ],+ topicId: 'topic-1',+ };++ it('applies operations against ctx.currentTodos when no plan document exists', async () => {+ // Regression: the runtime used to drop `ctx` and resolve todos from the+ // plan document alone. With no document the list came back empty, every+ // index went out of bounds, and the agent got "No operations applied."+ // plus an empty list β which then overwrote the message-history copy.+ const runtime = lobeAgentRuntime.factory(todoContext);++ const result = await runtime.updateTodos(+ { operations: [{ index: 1, type: 'processing' }] },+ todoContext,+ );++ expect(result.content).not.toContain('No operations applied.');+ expect(result.state.todos.items).toHaveLength(3);+ expect(result.state.todos.items[1].status).toBe('processing');+ });++ it('appends to ctx.currentTodos instead of restarting the list', async () => {+ const runtime = lobeAgentRuntime.factory(todoContext);++ const result = await runtime.createTodos({ adds: ['publish report'] }, todoContext);++ expect(result.state.todos.items).toHaveLength(4);+ expect(result.state.todos.items[3].text).toBe('publish report');+ });+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex fd0cc499ee0..b11bc70745f 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -122,20 +122,33 @@ class LobeAgentExecutionRuntime {// ==================== Plan / Todo (delegated to PlanExecutionRuntime) ====================- createPlan = (params: any) =>- this.planRuntime.createPlan(params, { messageId: this.messageId, topicId: this.topicId });+ /**+ * Todo APIs read their prior state from `ctx.currentTodos` (rebuilt from+ * message history by the runtime executors). Without it the runtime falls back+ * to the topic's plan document, which only exists once `createPlan` has run β+ * so a plain `createTodos` β `updateTodos` sequence would see an empty list,+ * drop every index-based operation, and answer "No operations applied.".+ */+ private planContext = (ctx?: ToolExecutionContext) => ({+ currentTodos: ctx?.currentTodos,+ messageId: this.messageId,+ topicId: this.topicId,+ });++ createPlan = (params: any, ctx?: ToolExecutionContext) =>+ this.planRuntime.createPlan(params, this.planContext(ctx));- updatePlan = (params: any) =>- this.planRuntime.updatePlan(params, { messageId: this.messageId, topicId: this.topicId });+ updatePlan = (params: any, ctx?: ToolExecutionContext) =>+ this.planRuntime.updatePlan(params, this.planContext(ctx));- createTodos = (params: any) =>- this.planRuntime.createTodos(params, { messageId: this.messageId, topicId: this.topicId });+ createTodos = (params: any, ctx?: ToolExecutionContext) =>+ this.planRuntime.createTodos(params, this.planContext(ctx));- updateTodos = (params: any) =>- this.planRuntime.updateTodos(params, { messageId: this.messageId, topicId: this.topicId });+ updateTodos = (params: any, ctx?: ToolExecutionContext) =>+ this.planRuntime.updateTodos(params, this.planContext(ctx));- clearTodos = (params: any) =>- this.planRuntime.clearTodos(params, { messageId: this.messageId, topicId: this.topicId });+ clearTodos = (params: any, ctx?: ToolExecutionContext) =>+ this.planRuntime.clearTodos(params, this.planContext(ctx));// ==================== Sub-agent (async suspend/resume) ====================diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 845c0c62fc9..5f1a0d396f1 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -5,6 +5,7 @@ import {type ClientSecretPayload,type ExecSubAgentParams,type StepActivatedSkill,+ type StepContextTodoItem,type WorkRegistrationIntent,} from '@lobechat/types';@@ -173,6 +174,15 @@ export interface ToolExecutionContext {assistantMessageId?: string;/** Originating request IP propagated through the operation metadata. */clientIp?: string;+ /**+ * Todo items as of this tool call, reconstructed from the operation's message+ * history by the runtime executors β the tool-execution counterpart of what+ * `serverCallLlmContextBuilder` feeds the prompt. The lobe-agent runtime needs+ * it because its own store (the topic's plan document) only exists after+ * `createPlan`, so an agent that only ever calls `createTodos` would otherwise+ * read back an empty list on every subsequent call.+ */+ currentTodos?: StepContextTodoItem[];/*** Whether the run's execution plan is device-capable (`device` or* `device-unrouted`) β derived from `state.metadata.executionPlan` by thediff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.tsindex 533a25cf8ed..43ecd80d343 100644--- a/packages/agent-runtime/src/executors/tool.test.ts+++ b/packages/agent-runtime/src/executors/tool.test.ts@@ -596,4 +596,68 @@ describe('tool executors', () => {expect(registeredIntent.args).toEqual(skillIntent.args);});});++ describe('todo state forwarding', () => {+ // Todo-mutating tools (lobe-agent createTodos/updateTodos) persist their own+ // copy into a plan document that only exists after `createPlan`. Message+ // history is the store that always exists, so the run context must carry it+ // β otherwise `updateTodos` reloads an empty list and silently drops every+ // index-based operation.+ const stateWithTodos = () =>+ createState({+ messages: [+ {+ content: 'todo tool result',+ id: 'tool-msg-0',+ plugin: { apiName: 'createTodos', identifier: 'lobe-agent', type: 'builtin' },+ pluginState: {+ todos: {+ items: [+ { status: 'completed', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ ],+ updatedAt: '2026-07-09T00:00:00.000Z',+ },+ },+ role: 'tool',+ },+ ] as unknown as AgentState['messages'],+ });++ it('forwards todos rebuilt from message history to the tool transport', async () => {+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall('tool-call-1', 'lobe-agent'),+ },+ type: 'call_tool',+ };++ await callTool(host)(instruction, stateWithTodos());++ expect(runTool).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ currentTodos: [+ { status: 'completed', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ ],+ }),+ );+ });++ it('leaves currentTodos undefined when no todo state exists yet', async () => {+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {+ payload: {+ parentMessageId: 'assistant-msg-1',+ toolCalling: createToolCall(),+ },+ type: 'call_tool',+ };++ await callTool(host)(instruction, createState());++ expect(runTool.mock.calls[0][1].currentTodos).toBeUndefined();+ });+ });});diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.tsindex 5aef9f0b910..5abd200e51b 100644--- a/packages/agent-runtime/src/executors/tool.ts+++ b/packages/agent-runtime/src/executors/tool.ts@@ -14,7 +14,7 @@ import type {AgentState,InstructionExecutor,} from '../types';-import { extractActivatedSkillsFromMessages } from '../utils';+import { extractActivatedSkillsFromMessages, extractTodosFromMessages } from '../utils';const TOOL_EXECUTION_PHASE = 'tool_execution';const TOOL_MESSAGE_PERSIST_PHASE = 'tool_message_persist';@@ -162,6 +162,11 @@ const createRunContext = ({agentId: host.operation.agentId ?? state.metadata?.agentId,assistantMessageId: parentMessageId,callIndex: resolveCallIndex(state, toolName),+ // Todo state is reconstructed from message history for the same reason the+ // prompt side does it (`serverCallLlmContextBuilder`): the plan document is+ // a best-effort mirror that only exists once `createPlan` has run, so the+ // tool-execution side must not treat it as the source of truth.+ currentTodos: extractTodosFromMessages(state.messages)?.items,effectiveManifestMap: buildEffectiveManifestMap(state),groupId: host.operation.groupId ?? state.metadata?.groupId,messageId: state.metadata?.sourceMessageId,diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.tsindex 2ee7f441b0d..54e8826d12e 100644--- a/packages/agent-runtime/src/transport/tool.ts+++ b/packages/agent-runtime/src/transport/tool.ts@@ -1,4 +1,9 @@-import type { ChatToolPayload, RuntimeStepContext, WorkRegistrationIntent } from '@lobechat/types';+import type {+ ChatToolPayload,+ RuntimeStepContext,+ StepContextTodoItem,+ WorkRegistrationIntent,+} from '@lobechat/types';import type { AgentState } from '../types';import type { RuntimeRetryKind } from '../utils';@@ -68,6 +73,12 @@ export interface ToolRunContext {agentId?: string;assistantMessageId?: string;callIndex: number;+ /**+ * Todo items as of this tool call, reconstructed from message history. Tool+ * runtimes that mutate todos need it because their own persistence (the plan+ * document) is optional β see `PlanExecutionRuntime.resolveExistingTodos`.+ */+ currentTodos?: StepContextTodoItem[];effectiveManifestMap: Record<string, any>;groupId?: string;messageId?: string;diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.tsindex f822593cc87..e6c3a42b5aa 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.ts@@ -89,7 +89,12 @@ export class PlanExecutionRuntime {}private async resolveExistingTodos(context: PlanRuntimeContext): Promise<TodoItem[]> {- if (context.currentTodos) return context.currentTodos;+ // Only `undefined` means "caller doesn't know" β an empty array is a real+ // answer. After `clearTodos`, message history legitimately reports `[]`, and+ // treating that as missing would reload the plan document and resurrect the+ // items the agent just cleared (the plan document is a best-effort mirror+ // whose sync failure is swallowed, so it can easily still hold them).+ if (context.currentTodos !== undefined) return context.currentTodos;if (!context.topicId) return [];const plan = await this.service.findPlanByTopic(context.topicId);return readTodosFromPlan(plan);diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/serverTodoPersistence.test.ts b/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/serverTodoPersistence.test.tsnew file mode 100644index 00000000000..9660d6b6e3a--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/serverTodoPersistence.test.ts@@ -0,0 +1,110 @@+import { describe, expect, it, vi } from 'vitest';++import type { PlanRuntimeService } from './index';+import { PlanExecutionRuntime } from './index';++/**+ * Todos have two stores with different lifetimes:+ *+ * - the topic's plan document β a mirror that only exists once `createPlan` ran;+ * - the tool message's `pluginState.todos` β always written, and the thing the+ * prompt side reads back via `extractTodosFromMessages`.+ *+ * The server tool-execution path used to pass neither, so it read the plan+ * document only. An agent that called `createTodos` without `createPlan` had no+ * document, so every later `updateTodos` reloaded an empty list, dropped its+ * index-based operations out of bounds, and answered "No operations applied." β+ * then wrote that empty list back into `pluginState`, wiping the message-history+ * copy as well.+ */+const createService = (planTodos?: { status: string; text: string }[]) =>+ ({+ createPlan: vi.fn(),+ findPlanById: vi.fn(),+ findPlanByTopic: vi.fn().mockResolvedValue(+ planTodos+ ? {+ content: null,+ createdAt: new Date(0),+ description: null,+ id: 'doc_1',+ metadata: { todos: { items: planTodos, updatedAt: '2026-01-01T00:00:00.000Z' } },+ title: null,+ updatedAt: new Date(0),+ }+ : null,+ ),+ updatePlan: vi.fn(),+ updatePlanMetadata: vi.fn(),+ }) as unknown as PlanRuntimeService;++describe('PlanExecutionRuntime todo resolution', () => {+ it('applies operations against currentTodos when the topic has no plan document', async () => {+ const runtime = new PlanExecutionRuntime(createService());++ const updated = await runtime.updateTodos(+ { operations: [{ index: 0, type: 'complete' }] },+ {+ currentTodos: [+ { status: 'todo', text: 'env setup' },+ { status: 'todo', text: 'run case 1' },+ { status: 'todo', text: 'write report' },+ ],+ messageId: 'msg_1',+ topicId: 'tpc_1',+ },+ );++ expect(updated.content).not.toContain('No operations applied.');+ expect((updated.state as any).todos.items).toHaveLength(3);+ expect((updated.state as any).todos.items[0].status).toBe('completed');+ });++ it('falls back to the plan document only when currentTodos is undefined', async () => {+ const runtime = new PlanExecutionRuntime(+ createService([+ { status: 'todo', text: 'restored from plan' },+ { status: 'todo', text: 'second item' },+ ]),+ );++ const updated = await runtime.updateTodos(+ { operations: [{ index: 1, type: 'complete' }] },+ { messageId: 'msg_1', topicId: 'tpc_1' },+ );++ expect(updated.content).not.toContain('No operations applied.');+ expect((updated.state as any).todos.items).toHaveLength(2);+ expect((updated.state as any).todos.items[1].status).toBe('completed');+ });++ it('keeps an explicitly cleared list cleared even if the plan mirror is stale', async () => {+ // `syncTodosToPlan` swallows its errors, so the plan document can still hold+ // the items `clearTodos` just removed. An empty `currentTodos` is the agent's+ // real answer β treating it as "unknown" resurrects those items.+ const runtime = new PlanExecutionRuntime(+ createService([+ { status: 'todo', text: 'stale item from the mirror' },+ { status: 'todo', text: 'another stale item' },+ ]),+ );++ const created = await runtime.createTodos(+ { adds: ['a fresh item'] },+ { currentTodos: [], messageId: 'msg_1', topicId: 'tpc_1' },+ );++ expect((created.state as any).todos.items).toEqual([{ status: 'todo', text: 'a fresh item' }]);+ });++ it('still reports the full list in state so pluginState never regresses to empty', async () => {+ const runtime = new PlanExecutionRuntime(createService());++ const created = await runtime.createTodos(+ { adds: ['env setup', 'run case 1'] },+ { messageId: 'msg_1', topicId: 'tpc_1' },+ );++ expect((created.state as any).todos.items).toHaveLength(2);+ });+});diff --git a/packages/local-file-shell/src/contentSearch/__tests__/buildArtifactExclusion.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/buildArtifactExclusion.test.tsnew file mode 100644index 00000000000..6c799bd44ff--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/__tests__/buildArtifactExclusion.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';++import type { GrepContentParams, GrepContentResult } from '../../types';+import { BaseContentSearch } from '../base';++vi.mock('../../logger', () => ({+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+}));++vi.mock('fast-glob', () => ({ default: vi.fn().mockResolvedValue([]) }));++class TestContentSearch extends BaseContentSearch {+ async grep(params: GrepContentParams): Promise<GrepContentResult> {+ return this.grepWithNodejs(params);+ }++ async checkToolAvailable(): Promise<boolean> {+ return true;+ }++ public testBuildGrepArgs(+ tool: 'ag' | 'grep' | 'rg',+ params: GrepContentParams,+ target?: string,+ ): string[] {+ return this.buildGrepArgs(tool, params, target);+ }++ public testGetDefaultIgnorePatterns(): string[] {+ return this.getDefaultIgnorePatterns();+ }+}++const argsFor = (tool: 'ag' | 'grep' | 'rg') =>+ new TestContentSearch()+ .testBuildGrepArgs(tool, {+ output_mode: 'files_with_matches',+ pattern: 'com.apple.security',+ } as GrepContentParams)+ .join(' ');++/**+ * Build output must be excluded because *git* ignores it, never because its+ * directory happens to be called `dist` / `build` / `out`. Those names are only+ * usually generated β this repo tracks `apps/desktop/build/entitlements.mac.plist`+ * β and `rg`'s `--glob` overrides all ignore logic, so hardcoding them silently+ * makes checked-in files unfindable on every engine.+ */+const NEVER_HARDCODED = ['.next', 'dist', 'build', 'out', 'coverage', '.turbo', '.cache'];++describe('unconditional search exclusions', () => {+ it.each(['rg', 'ag', 'grep'] as const)('excludes only node_modules and .git for %s', (tool) => {+ const joined = argsFor(tool);++ expect(joined).toContain('node_modules');+ expect(joined).toContain('.git');+ });++ it.each(['rg', 'ag', 'grep'] as const)(+ 'does not hide directories that may be tracked (%s)',+ (tool) => {+ const joined = argsFor(tool);++ for (const dir of NEVER_HARDCODED) {+ expect(joined, `${tool} must not hardcode an exclusion for ${dir}`).not.toContain(+ `${dir}/**`,+ );+ expect(joined, `${tool} must not hardcode an exclusion for ${dir}`).not.toContain(+ `-dir ${dir}`,+ );+ }+ },+ );++ it('keeps the nodejs fallback ignore patterns just as narrow', () => {+ const patterns = new TestContentSearch().testGetDefaultIgnorePatterns();++ expect(patterns).toEqual(['**/node_modules/**', '**/.git/**']);+ });+});++describe('single-file targets', () => {+ it.each([+ ['rg', '-H'],+ ['grep', '-H'],+ ['ag', '--filename'],+ ] as const)('forces the filename prefix for %s', (tool, flag) => {+ const withFile = new TestContentSearch().testBuildGrepArgs(+ tool,+ { output_mode: 'content', pattern: 'needle' } as GrepContentParams,+ './a.ts',+ );+ const withDir = new TestContentSearch().testBuildGrepArgs(tool, {+ output_mode: 'content',+ pattern: 'needle',+ } as GrepContentParams);++ expect(withFile).toContain(flag);+ // A directory search already prefixes filenames; don't add redundant flags.+ expect(withDir).not.toContain(flag);+ });++ it('keeps the target relative so an explicitly scoped excluded dir still works', () => {+ const args = new TestContentSearch().testBuildGrepArgs(+ 'rg',+ { output_mode: 'files_with_matches', pattern: 'needle' } as GrepContentParams,+ '.',+ );++ expect(args.at(-1)).toBe('.');+ });+});diff --git a/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.tsnew file mode 100644index 00000000000..22320782ce9--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/__tests__/enginePathParity.test.ts@@ -0,0 +1,193 @@+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { execa } from 'execa';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import type { GrepContentParams, GrepContentResult } from '../../types';+import { UnixContentSearch } from '../impl/unix';++/**+ * Integration guard for the invariant this module keeps getting wrong: **which+ * engine ran must not change what the caller gets back.**+ *+ * Three ways it used to leak through, all observed in one real agent run:+ * - external tools emitted `./rel/path` while the Node fallback emitted absolute+ * paths, so the agent resolved results against the wrong root and hit ENOENT;+ * - `grep` and the Node fallback ignored `.gitignore`, flooding results with+ * build output the other engines never surface;+ * - one failed call permanently pinned the shared instance to the Node fallback,+ * so every later search silently changed behaviour.+ */+class ForcedEngine extends UnixContentSearch {+ constructor(private readonly forced: 'grep' | 'nodejs' | 'rg') {+ super();+ }++ async grep(params: GrepContentParams): Promise<GrepContentResult> {+ return this.forced === 'nodejs'+ ? (this as any).grepWithNodejs(params)+ : (this as any).grepWithExternalTool(this.forced, params);+ }++ get engine() {+ return (this as any).currentTool;+ }++ setEngine(tool: string) {+ (this as any).currentTool = tool;+ }+}++const hasTool = async (tool: string) => {+ try {+ await execa('which', [tool], { timeout: 3000 });+ return true;+ } catch {+ return false;+ }+};++let repo: string;+let engines: Array<'grep' | 'nodejs' | 'rg'>;++beforeAll(async () => {+ repo = await mkdtemp(path.join(tmpdir(), 'content-search-parity-'));+ await mkdir(path.join(repo, 'dist', 'sub'), { recursive: true });+ await mkdir(path.join(repo, 'src'), { recursive: true });+ await mkdir(path.join(repo, 'build'), { recursive: true });+ await writeFile(path.join(repo, '.gitignore'), 'dist/\n*.log\n');+ await writeFile(path.join(repo, 'src', 'a.ts'), 'needle\n');+ await writeFile(path.join(repo, 'src', 'noisy.log'), 'needle\n');+ await writeFile(path.join(repo, 'dist', 'b.js'), 'needle\n');+ await writeFile(path.join(repo, 'dist', 'sub', 'c.js'), 'needle\n');+ // A *tracked* `build/` β the shape of `apps/desktop/build/entitlements.mac.plist`.+ await writeFile(path.join(repo, 'build', 'entitlements.plist'), 'needle\n');+ await execa('git', ['init', '-q'], { cwd: repo });++ engines = ['nodejs'];+ if (await hasTool('rg')) engines.push('rg');+ if (await hasTool('grep')) engines.push('grep');+}, 60_000);++afterAll(async () => {+ if (repo) await rm(repo, { force: true, recursive: true });+});++const search = (engine: 'grep' | 'nodejs' | 'rg', params: GrepContentParams) =>+ new ForcedEngine(engine).grep(params);++describe('content search engine parity', () => {+ it('returns the same gitignore-respecting result set from every engine', async () => {+ const results = await Promise.all(+ engines.map(async (engine) => {+ const r = await search(engine, {+ output_mode: 'files_with_matches',+ pattern: 'needle',+ scope: repo,+ } as GrepContentParams);+ return [engine, [...r.matches].sort()] as const;+ }),+ );++ // `dist/` and `*.log` are gitignored and must go; the tracked `build/` must+ // stay, because only git decides what is build output β not the folder name.+ for (const [engine, matches] of results) {+ expect(matches, `${engine} should honour .gitignore`).toEqual([+ path.join(repo, 'build', 'entitlements.plist'),+ path.join(repo, 'src', 'a.ts'),+ ]);+ }+ }, 60_000);++ it('does not hide a tracked directory whose name looks like build output', async () => {+ // Regression: a hardcoded `!**/build/**` made every engine skip this file,+ // even though git tracks it.+ const tracked = path.join(repo, 'build', 'entitlements.plist');++ for (const engine of engines) {+ const r = await search(engine, {+ output_mode: 'files_with_matches',+ pattern: 'needle',+ scope: repo,+ } as GrepContentParams);++ expect(r.matches, `${engine} hid a tracked build/ file`).toContain(tracked);+ }+ }, 60_000);++ it('returns absolute paths from every engine', async () => {+ for (const engine of engines) {+ const r = await search(engine, {+ output_mode: 'files_with_matches',+ pattern: 'needle',+ scope: repo,+ } as GrepContentParams);++ for (const match of r.matches) {+ expect(path.isAbsolute(match), `${engine} returned a relative path: ${match}`).toBe(true);+ }+ }+ }, 60_000);++ it('still searches a directory the caller explicitly scopes into, even if ignored', async () => {+ for (const engine of engines) {+ const r = await search(engine, {+ output_mode: 'files_with_matches',+ pattern: 'needle',+ scope: path.join(repo, 'dist'),+ } as GrepContentParams);++ expect(+ [...r.matches].sort(),+ `${engine} should search an explicitly scoped ignored dir`,+ ).toEqual([path.join(repo, 'dist', 'b.js'), path.join(repo, 'dist', 'sub', 'c.js')]);+ }+ }, 60_000);++ it('prefixes the file path when scope names a single file', async () => {+ const file = path.join(repo, 'src', 'a.ts');++ for (const engine of engines) {+ const r = await search(engine, {+ '-n': true,+ 'output_mode': 'content',+ 'pattern': 'needle',+ 'scope': file,+ } as GrepContentParams);++ expect(r.matches.length, `${engine} found nothing in a file-scoped search`).toBeGreaterThan(+ 0,+ );+ for (const match of r.matches) {+ expect(match.startsWith(file), `${engine} dropped the filename prefix: ${match}`).toBe(+ true,+ );+ }+ }+ }, 60_000);+});++describe('engine downgrade', () => {+ it('does not pin the shared instance to the fallback after a file-scoped call', async () => {+ if (!(await hasTool('rg'))) return;++ const impl = new ForcedEngine('rg');+ impl.setEngine('rg');++ // Scoping at a file used to make execa throw (its `cwd` must be a directory).+ // The catch overwrote `currentTool`, so from then on every search in the+ // process ran on the Node fallback β no ignore files, different path shape.+ await impl+ .grep({+ '-n': true,+ 'output_mode': 'content',+ 'pattern': 'needle',+ 'scope': path.join(repo, 'src', 'a.ts'),+ } as GrepContentParams)+ .catch(() => undefined);++ expect(impl.engine).toBe('rg');+ }, 60_000);+});diff --git a/packages/local-file-shell/src/contentSearch/base.ts b/packages/local-file-shell/src/contentSearch/base.tsindex 327749a4bda..a6428110032 100644--- a/packages/local-file-shell/src/contentSearch/base.ts+++ b/packages/local-file-shell/src/contentSearch/base.ts@@ -5,9 +5,29 @@ import fg from 'fast-glob';import { createLogger } from '../logger';import type { ToolDetector } from '../toolDetector';import type { GrepContentParams, GrepContentResult } from '../types';+import { filterGitIgnored } from './gitIgnore';const logger = createLogger('contentSearch:base');+/**+ * Directories excluded unconditionally, regardless of what the repo ignores.+ *+ * Deliberately limited to two names that are never checked in. It is tempting to+ * add the usual build output here (`dist`, `build`, `out`, `.next`, β¦), but those+ * names are only *usually* generated: this repo tracks+ * `apps/desktop/build/entitlements.mac.plist`, and `rg`'s `--glob` overrides all+ * ignore logic, so a hardcoded `!**\/build\/**` silently makes tracked files+ * unfindable on every engine.+ *+ * What actually belongs out of the results is "whatever git ignores", and+ * `filterGitIgnored` answers that exactly β including this repo's `.next`. Guess+ * nothing here; ask git there.+ *+ * Entries are matched relative to the search root, so explicitly scoping a+ * search *into* one of these directories still works.+ */+const EXCLUDED_DIRS = ['node_modules', '.git'] as const;+/*** Content search tool type*/@@ -46,12 +66,28 @@ export abstract class BaseContentSearch {}/**- * Build command-line arguments for grep tools+ * Build command-line arguments for grep tools.+ *+ * `target` is what the tool is pointed at, resolved *relative to the cwd the+ * caller will run it in* β `.` for a directory search, `./<file>` when `scope`+ * names a single file. It must stay relative: an absolute target would be+ * matched by the `EXCLUDED_DIRS` globs below, so deliberately searching inside+ * e.g. `dist/` would return nothing.*/- protected buildGrepArgs(tool: 'ag' | 'grep' | 'rg', params: GrepContentParams): string[] {+ protected buildGrepArgs(+ tool: 'ag' | 'grep' | 'rg',+ params: GrepContentParams,+ target = '.',+ ): string[] {const { pattern, output_mode = 'files_with_matches' } = params;const args: string[] = [];+ // Every one of these tools drops the filename prefix when handed a single+ // file, which would emit bare `12:text` lines the caller cannot attribute to+ // a path. Force it back on so a file-scoped search stays parseable β and+ // stays consistent with the Node fallback, which always prefixes.+ const singleFile = target !== '.';+// When the caller's glob references a dot-prefixed segment (e.g.// `.github/workflows/*.yml`), rg and ag both default to skipping hidden// paths and would silently return zero results. `.git/` is still excluded@@ -60,6 +96,7 @@ export abstract class BaseContentSearch {switch (tool) {case 'rg': {+ if (singleFile) args.push('-H');if (params['-i']) args.push('-i');if (params['-n']) args.push('-n');if (params['-A']) args.push('-A', String(params['-A']));@@ -81,11 +118,13 @@ export abstract class BaseContentSearch {}}- args.push('--glob', '!**/node_modules/**', '--glob', '!**/.git/**', pattern, '.');+ for (const dir of EXCLUDED_DIRS) args.push('--glob', `!**/${dir}/**`);+ args.push(pattern, target);break;}case 'ag': {+ if (singleFile) args.push('--filename');if (params['-i']) args.push('-i');if (params['-A']) args.push('-A', String(params['-A']));if (params['-B']) args.push('-B', String(params['-B']));@@ -104,12 +143,14 @@ export abstract class BaseContentSearch {}}- args.push('--ignore-dir', 'node_modules', '--ignore-dir', '.git', pattern, '.');+ for (const dir of EXCLUDED_DIRS) args.push('--ignore-dir', dir);+ args.push(pattern, target);break;}case 'grep': {args.push('-r');+ if (singleFile) args.push('-H');if (params['-i']) args.push('-i');if (params['-n']) args.push('-n');if (params['-A']) args.push('-A', String(params['-A']));@@ -129,7 +170,8 @@ export abstract class BaseContentSearch {}}- args.push('--exclude-dir', 'node_modules', '--exclude-dir', '.git', '-E', pattern, '.');+ for (const dir of EXCLUDED_DIRS) args.push('--exclude-dir', dir);+ args.push('-E', pattern, target);break;}}@@ -170,6 +212,12 @@ export abstract class BaseContentSearch {const ext = `.${params.type}`;filesToSearch = filesToSearch.filter((file) => file.endsWith(ext));}++ // `EXCLUDED_DIRS` above keeps traversal cheap; this drops whatever else the+ // repo ignores (`*.log`, generated fixtures, β¦) so the Node fallback answers+ // the same question `rg` would. Filtering the file list rather than the+ // match list also avoids reading files we are about to discard.+ filesToSearch = await filterGitIgnored(searchPath, filesToSearch);}logger.debug(`${logPrefix} Found ${filesToSearch.length} files to search`);@@ -248,6 +296,6 @@ export abstract class BaseContentSearch {* Can be overridden by subclasses for platform-specific patterns*/protected getDefaultIgnorePatterns(): string[] {- return ['**/node_modules/**', '**/.git/**'];+ return EXCLUDED_DIRS.map((dir) => `**/${dir}/**`);}}diff --git a/packages/local-file-shell/src/contentSearch/gitIgnore.ts b/packages/local-file-shell/src/contentSearch/gitIgnore.tsnew file mode 100644index 00000000000..a48cac47735--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/gitIgnore.ts@@ -0,0 +1,118 @@+import path from 'node:path';++import { execa } from 'execa';++import { createLogger } from '../logger';++const logger = createLogger('contentSearch:gitIgnore');++/**+ * Drop results that git would ignore.+ *+ * `rg` and `ag` read ignore files themselves; `grep` and the Node fallback have+ * no such notion, so the same query returns different results depending on which+ * engine ran. Rather than reimplement gitignore semantics (nested ignore files,+ * negations, `.git/info/exclude`, `core.excludesFile`), shell out to+ * `git check-ignore`, which *is* the semantics.+ *+ * Exactly one `git` process per search: `searchPath` rides along in the same+ * `--stdin` batch as the results, so the "is the search root itself ignored?"+ * question is answered without a second spawn. `rg`/`ag` searches never reach+ * this code at all, so the common path pays nothing.+ *+ * Best-effort by design: outside a repo, or when git is unavailable, the caller+ * keeps its unfiltered results. This is a noise filter, not a security boundary.+ */+export const filterGitIgnored = async (+ searchPath: string,+ absolutePaths: string[],+): Promise<string[]> => {+ if (absolutePaths.length === 0) return absolutePaths;++ const unique = [...new Set(absolutePaths)];++ try {+ // `check-ignore` needs a repo cwd; a non-repo exits 128 and we bail below.+ // Run from `searchPath` (the caller always passes a directory) rather than+ // its parent: for a repo-root search the parent is outside the repo, and git+ // would answer 128 for everything. Absolute inputs are classified the same+ // from any cwd inside the repo, including from within an ignored directory.+ const { stdout, exitCode } = await execa(+ 'git',+ ['check-ignore', '--no-index', '--stdin', '-z'],+ {+ cwd: searchPath,+ input: [searchPath, ...unique].join('\0'),+ reject: false,+ stripFinalNewline: false,+ },+ );++ // 0 = some paths ignored, 1 = none ignored, anything else (128 = not a repo,+ // 127 = git missing) means we cannot answer and must not drop anything.+ if (exitCode !== 0 && exitCode !== 1) return absolutePaths;++ const ignored = new Set(stdout.split('\0').filter(Boolean));+ if (ignored.size === 0) return absolutePaths;++ // An explicitly requested root wins over the ignore rules β the same call+ // `rg <ignored-dir>` honours. Without this, deliberately searching `dist/`+ // would come back empty from every engine except ripgrep.+ if (ignored.has(searchPath)) return absolutePaths;++ return absolutePaths.filter((p) => !ignored.has(p));+ } catch (error) {+ logger.debug('git check-ignore unavailable, keeping unfiltered results:', error);+ return absolutePaths;+ }+};++/**+ * Apply {@link filterGitIgnored} to match lines that carry a leading file path+ * (`<abs path>`, `<abs path>:12:text`, `<abs path>:3`).+ *+ * The path is split off at the first `:` that follows the search root, so+ * Windows drive letters and `:`-bearing match text both survive intact.+ */+export const filterGitIgnoredMatches = async (+ searchPath: string,+ matches: string[],+): Promise<string[]> => {+ if (matches.length === 0) return matches;++ const pathOf = (line: string): string | undefined => {+ if (!line.startsWith(searchPath)) return undefined;+ const rest = line.slice(searchPath.length);+ const sep = rest.indexOf(':');+ return sep === -1 ? line : searchPath + rest.slice(0, sep);+ };++ const filePaths = matches.map(pathOf).filter((p): p is string => !!p);+ if (filePaths.length === 0) return matches;++ const kept = new Set(await filterGitIgnored(searchPath, filePaths));++ return matches.filter((line) => {+ const p = pathOf(line);+ // Context/separator lines (`--`) carry no path β keep them.+ return p === undefined || kept.has(p);+ });+};++/**+ * Resolve an external tool's `./`-relative output line against the search root.+ *+ * External tools run with `cwd = searchPath` and search `.`, so every line they+ * emit starts with `./` β for *all* output modes (`./f.ts`, `./f.ts:12:text`,+ * `./f.ts:3`). Rewriting only that prefix therefore normalises every mode without+ * having to parse `:`/`-` separators, and leaves context separators (`--`) alone.+ *+ * The Node fallback already yields absolute paths, so after this the engine no+ * longer decides the shape of what the caller gets back.+ */+export const toAbsoluteMatchLine = (searchPath: string, line: string): string => {+ // `./` on unix, `.\` from ripgrep on Windows.+ if (!line.startsWith('./') && !line.startsWith('.\\')) return line;+ const root = searchPath.endsWith(path.sep) ? searchPath.slice(0, -1) : searchPath;+ return `${root}${path.sep}${line.slice(2)}`;+};diff --git a/packages/local-file-shell/src/contentSearch/impl/unix.ts b/packages/local-file-shell/src/contentSearch/impl/unix.tsindex 48470685d01..fc5c4466649 100644--- a/packages/local-file-shell/src/contentSearch/impl/unix.ts+++ b/packages/local-file-shell/src/contentSearch/impl/unix.ts@@ -1,9 +1,13 @@+import { stat } from 'node:fs/promises';+import path from 'node:path';+import { execa } from 'execa';import { createLogger } from '../../logger';import type { ToolDetector } from '../../toolDetector';import type { GrepContentParams, GrepContentResult } from '../../types';import { BaseContentSearch } from '../base';+import { filterGitIgnoredMatches, toAbsoluteMatchLine } from '../gitIgnore';const logger = createLogger('contentSearch:unix');@@ -75,6 +79,23 @@ export abstract class UnixContentSearch extends BaseContentSearch {return 'nodejs';}+ /**+ * Persist a downgrade only when the tool is genuinely gone from the system.+ *+ * A single failing call (an unreadable directory, a pattern the tool rejects)+ * used to overwrite `this.currentTool`, and since the desktop keeps one+ * instance for the whole app session every later search silently ran on the+ * Node fallback β no ignore-file support, different path shape, far slower.+ * Fall back for *this* call, but only make it stick if `rg`/`ag`/`grep`+ * really is unavailable.+ */+ private async demoteIfToolMissing(tool: UnixContentSearchTool): Promise<void> {+ if (tool === 'nodejs') return;+ if (await this.checkToolAvailable(tool)) return;+ this.currentTool = await this.fallbackToNextTool(tool);+ logger.info(`${tool} is unavailable; downgrading future searches to ${this.currentTool}`);+ }+async grep(params: GrepContentParams): Promise<GrepContentResult> {const { tool: preferredTool } = params;const logPrefix = `[grepContent: ${params.pattern}]`;@@ -143,12 +164,19 @@ export abstract class UnixContentSearch extends BaseContentSearch {const searchPath = this.resolveSearchPath(params);const logPrefix = `[grepContent:${tool}]`;+ // A `scope` pointing at a single file is a normal, documented call β but+ // it used to be fatal here, because execa's `cwd` must be a directory. The+ // resulting throw dropped the call to the Node fallback *and* poisoned the+ // cached engine for every later search. Search the file from its parent+ // directory instead.+ const searchRoot = (await this.isFile(searchPath)) ? path.dirname(searchPath) : searchPath;+try {- const args = this.buildGrepArgs(tool, params);+ const args = this.buildGrepArgs(tool, params, this.searchTarget(searchPath, searchRoot));logger.debug(`${logPrefix} Executing: ${tool} ${args.join(' ')}`);const { stdout, stderr, exitCode } = await execa(tool, args, {- cwd: searchPath,+ cwd: searchRoot,reject: false,stdin: 'ignore',});@@ -157,7 +185,13 @@ export abstract class UnixContentSearch extends BaseContentSearch {logger.warn(`${logPrefix} Tool exited with code ${exitCode}: ${stderr}`);}- const lines = stdout.trim().split('\n').filter(Boolean);+ // Normalise to absolute before anything else looks at these lines, so the+ // caller gets the same path shape the Node fallback produces.+ const lines = stdout+ .trim()+ .split('\n')+ .filter(Boolean)+ .map((line) => toAbsoluteMatchLine(searchRoot, line));let matches: string[] = [];let totalMatches = 0;@@ -189,6 +223,13 @@ export abstract class UnixContentSearch extends BaseContentSearch {}}+ // `rg`/`ag` already honour ignore files; `grep` has no such notion, so+ // filter its output through git to match what the other engines return.+ if (tool === 'grep') {+ matches = await filterGitIgnoredMatches(searchRoot, matches);+ totalMatches = Math.min(totalMatches, matches.length);+ }+if (params.head_limit && matches.length > params.head_limit) {matches = matches.slice(0, params.head_limit);}@@ -206,12 +247,26 @@ export abstract class UnixContentSearch extends BaseContentSearch {};} catch (error) {logger.warn(`${logPrefix} External tool failed, falling back to next tool:`, error);- this.currentTool = await this.fallbackToNextTool(tool as UnixContentSearchTool);- logger.info(`Falling back to: ${this.currentTool}`);- return this.grepWithTool(this.currentTool, params);+ await this.demoteIfToolMissing(tool as UnixContentSearchTool);+ const next = await this.fallbackToNextTool(tool as UnixContentSearchTool);+ logger.info(`Falling back to: ${next} (for this call)`);+ return this.grepWithTool(next, params);}}+ private async isFile(target: string): Promise<boolean> {+ try {+ return (await stat(target)).isFile();+ } catch {+ return false;+ }+ }++ /** `.` for a directory search; the file's own name when `scope` names a file. */+ private searchTarget(searchPath: string, searchRoot: string): string {+ return searchPath === searchRoot ? '.' : `./${path.basename(searchPath)}`;+ }+protected async getActualMatchCount(tool: 'ag' | 'grep' | 'rg',params: GrepContentParams,diff --git a/packages/local-file-shell/src/contentSearch/impl/windows.ts b/packages/local-file-shell/src/contentSearch/impl/windows.tsindex c6c9edcf5c3..daf45b2a0e2 100644--- a/packages/local-file-shell/src/contentSearch/impl/windows.ts+++ b/packages/local-file-shell/src/contentSearch/impl/windows.ts@@ -4,6 +4,7 @@ import { createLogger } from '../../logger';import type { ToolDetector } from '../../toolDetector';import type { GrepContentParams, GrepContentResult } from '../../types';import { BaseContentSearch } from '../base';+import { toAbsoluteMatchLine } from '../gitIgnore';const logger = createLogger('contentSearch:windows');@@ -136,7 +137,14 @@ export class WindowsContentSearchImpl extends BaseContentSearch {logger.warn(`${logPrefix} rg exited with code ${exitCode}: ${stderr}`);}- const lines = stdout.trim().split('\n').filter(Boolean);+ // Same normalisation as the unix impl: rg runs with `cwd = searchPath`+ // and searches `.`, so its output is relative β make it absolute so the+ // engine no longer decides the path shape callers receive.+ const lines = stdout+ .trim()+ .split('\n')+ .filter(Boolean)+ .map((line) => toAbsoluteMatchLine(searchPath, line));let matches: string[] = [];let totalMatches = 0;