π€― 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(local-system): report a search scope that does not exist (#18564)
Arvin Xu8868088ec2fa
diff --git a/packages/local-file-shell/src/contentSearch/__tests__/missingScope.test.ts b/packages/local-file-shell/src/contentSearch/__tests__/missingScope.test.tsnew file mode 100644index 00000000000..9a3c5fca0bc--- /dev/null+++ b/packages/local-file-shell/src/contentSearch/__tests__/missingScope.test.ts@@ -0,0 +1,123 @@+import fs from 'node:fs';+import { stat } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterAll, describe, expect, it } from 'vitest';++import { globLocalFiles } from '../../file/glob';+import { createFileSearchModule } from '../../fileSearch';+import { MacOSContentSearchImpl } from '../impl/macOS';+import type { UnixContentSearch } from '../impl/unix';++/**+ * A scope that doesn't exist used to be indistinguishable from "nothing+ * matched": `rg` gets an unusable cwd and prints nothing, `fast-glob` returns an+ * empty list. The agent then concludes the CODE is missing and starts revising+ * the pattern β the one hypothesis the search never had evidence for. Both+ * search families must name the missing directory instead.+ */+describe('missing search scope', () => {+ const missingScope = path.join(os.tmpdir(), 'lobehub-missing-scope-fixture', 'src', 'locales');+ const realScope = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-scope-'));++ afterAll(() => {+ fs.rmSync(realScope, { force: true, recursive: true });+ });++ it('should report a grep scope that does not exist', async () => {+ const impl = new MacOSContentSearchImpl();++ const result = await impl.grep({+ output_mode: 'content',+ pattern: 'anything',+ scope: missingScope,+ });++ expect(result.success).toBe(false);+ expect(result.error).toBe(`Search scope does not exist: ${missingScope}`);+ expect(result.total_matches).toBe(0);+ });++ it('should still search a scope that exists', async () => {+ fs.writeFileSync(path.join(realScope, 'chat.json'), '{ "tps": "tok/s" }');+ const impl = new MacOSContentSearchImpl();++ const result = await impl.grep({+ output_mode: 'content',+ pattern: 'tps',+ scope: realScope,+ });++ expect(result.success).toBe(true);+ expect(result.total_matches).toBe(1);+ });++ it('should report a glob scope that does not exist', async () => {+ const result = await createFileSearchModule().glob({+ pattern: '**/*.json',+ scope: missingScope,+ });++ expect(result.success).toBe(false);+ expect(result.error).toBe(`Search scope does not exist: ${missingScope}`);+ expect(result.total_files).toBe(0);+ });++ it('should report a missing scope from the standalone fast-glob helper', async () => {+ const result = await globLocalFiles({ pattern: '**/*.json', scope: missingScope });++ expect(result.success).toBe(false);+ expect(result.error).toBe(`Search scope does not exist: ${missingScope}`);+ });++ // `stat` failing is not the same as the path being gone. An unreadable parent+ // (EACCES), a symlink loop, a transient fd exhaustion β all throw for a scope+ // that exists, and answering "does not exist" there is a confidently wrong+ // diagnosis, which is worse than the vague one this guard replaces. Those+ // reach the engine, whose own error is the accurate one.+ it.skipIf(process.getuid?.() === 0)(+ 'should not claim a scope is missing when it merely cannot be read',+ async () => {+ const lockedParent = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-locked-'));+ const child = path.join(lockedParent, 'repo');+ fs.mkdirSync(child);+ fs.chmodSync(lockedParent, 0o000);++ try {+ // Precondition: the scope EXISTS, but stat'ing it fails with something+ // other than ENOENT β otherwise this case proves nothing.+ const statCode = await stat(child).then(+ () => undefined,+ (error: NodeJS.ErrnoException) => error.code,+ );+ expect(statCode).toBe('EACCES');++ const grep = await new MacOSContentSearchImpl().grep({+ output_mode: 'content',+ pattern: 'anything',+ scope: child,+ });+ const glob = await globLocalFiles({ pattern: '**/*', scope: child });++ expect(grep.error ?? '').not.toContain('does not exist');+ expect(glob.error ?? '').not.toContain('does not exist');+ } finally {+ fs.chmodSync(lockedParent, 0o700);+ fs.rmSync(lockedParent, { force: true, recursive: true });+ }+ },+ );++ // A file-scoped search is a documented call shape, not a missing scope.+ it('should accept a scope pointing at a single file', async () => {+ const file = path.join(realScope, 'single.json');+ fs.writeFileSync(file, '{ "tps": "tok/s" }');+ const impl: UnixContentSearch = new MacOSContentSearchImpl();++ const result = await impl.grep({ output_mode: 'content', pattern: 'tps', scope: file });++ expect(result.success).toBe(true);+ expect(result.total_matches).toBe(1);+ });+});diff --git a/packages/local-file-shell/src/contentSearch/base.ts b/packages/local-file-shell/src/contentSearch/base.tsindex a6428110032..ec6dc0866c5 100644--- a/packages/local-file-shell/src/contentSearch/base.ts+++ b/packages/local-file-shell/src/contentSearch/base.ts@@ -2,6 +2,8 @@ import { readFile, stat } from 'node:fs/promises';import fg from 'fast-glob';+import { expandTilde } from '../file/expandTilde';+import { isMissingPath } from '../file/isMissingPath';import { createLogger } from '../logger';import type { ToolDetector } from '../toolDetector';import type { GrepContentParams, GrepContentResult } from '../types';@@ -65,6 +67,37 @@ export abstract class BaseContentSearch {return params.path ?? params.scope ?? params.cwd ?? process.cwd();}+ /**+ * The result to return when `scope` points at nothing.+ *+ * Every engine answers a non-existent search root with "no matches": `rg` gets+ * an unusable `cwd` and produces empty stdout, the Node fallback throws and is+ * swallowed by the caller's catch. An agent that mistypes a directory+ * (`src/locales` instead of `locales/`) therefore reads "Found 0 matches" and+ * concludes the CODE doesn't exist β the one answer the search cannot support.+ * Report the missing scope by name so the next call fixes the path instead of+ * the hypothesis.+ *+ * Only a path that is definitively absent short-circuits: a scope that exists+ * but cannot be stat'd (an unreadable parent, a transient fd exhaustion) still+ * goes to the engine, whose own error is the accurate one. Claiming "does not+ * exist" there would be a confidently wrong diagnosis β exactly what this+ * guard exists to remove.+ */+ protected async missingScopeResult(+ params: GrepContentParams,+ ): Promise<GrepContentResult | undefined> {+ const searchPath = expandTilde(this.resolveSearchPath(params))!;+ if (!(await isMissingPath(searchPath))) return undefined;++ return {+ error: `Search scope does not exist: ${searchPath}`,+ matches: [],+ success: false,+ total_matches: 0,+ };+ }+/*** Build command-line arguments for grep tools.*diff --git a/packages/local-file-shell/src/contentSearch/impl/unix.ts b/packages/local-file-shell/src/contentSearch/impl/unix.tsindex a8f66e77a3f..1185ecac07c 100644--- a/packages/local-file-shell/src/contentSearch/impl/unix.ts+++ b/packages/local-file-shell/src/contentSearch/impl/unix.ts@@ -100,6 +100,12 @@ export abstract class UnixContentSearch extends BaseContentSearch {const { tool: preferredTool } = params;const logPrefix = `[grepContent: ${params.pattern}]`;+ const missingScope = await this.missingScopeResult(params);+ if (missingScope) {+ logger.warn(`${logPrefix} ${missingScope.error}`);+ return missingScope;+ }+try {if (preferredTool && ['rg', 'ag', 'grep'].includes(preferredTool)) {logger.debug(`${logPrefix} Using preferred tool: ${preferredTool}`);diff --git a/packages/local-file-shell/src/contentSearch/impl/windows.ts b/packages/local-file-shell/src/contentSearch/impl/windows.tsindex daf45b2a0e2..41c4b6f980b 100644--- a/packages/local-file-shell/src/contentSearch/impl/windows.ts+++ b/packages/local-file-shell/src/contentSearch/impl/windows.ts@@ -74,6 +74,12 @@ export class WindowsContentSearchImpl extends BaseContentSearch {const { tool: preferredTool } = params;const logPrefix = `[grepContent: ${params.pattern}]`;+ const missingScope = await this.missingScopeResult(params);+ if (missingScope) {+ logger.warn(`${logPrefix} ${missingScope.error}`);+ return missingScope;+ }+try {if (preferredTool === 'rg') {if (await this.checkToolAvailable('rg')) {diff --git a/packages/local-file-shell/src/file/glob.ts b/packages/local-file-shell/src/file/glob.tsindex 834471b0fdb..a083eb0bef4 100644--- a/packages/local-file-shell/src/file/glob.ts+++ b/packages/local-file-shell/src/file/glob.ts@@ -3,6 +3,7 @@ import fg from 'fast-glob';import type { GlobFilesParams, GlobFilesResult } from '../types';import { expandTilde } from './expandTilde';import { hasHiddenSegment } from './hasHiddenSegment';+import { isMissingPath } from './isMissingPath';/*** Lightweight glob β backed by `fast-glob` only. For the platform-aware@@ -14,10 +15,25 @@ export async function globLocalFiles({cwd,scope,}: GlobFilesParams): Promise<GlobFilesResult> {+ // `fast-glob` answers a non-existent root with an empty list, which reads as+ // "the pattern matched nothing" β the caller then revises the pattern instead+ // of the path. Name the missing scope; a root that merely cannot be stat'd is+ // left for `fg` to fail on, since only it knows what actually went wrong.+ const searchRoot = expandTilde(scope ?? cwd);+ if (searchRoot && (await isMissingPath(searchRoot))) {+ return {+ engine: 'fast-glob',+ error: `Search scope does not exist: ${searchRoot}`,+ files: [],+ success: false,+ total_files: 0,+ };+ }+try {const wantsHidden = hasHiddenSegment(pattern);const files = await fg(pattern, {- cwd: expandTilde(scope ?? cwd) || process.cwd(),+ cwd: searchRoot || process.cwd(),dot: wantsHidden,ignore: ['**/node_modules/**', '**/.git/**'],});diff --git a/packages/local-file-shell/src/file/isMissingPath.ts b/packages/local-file-shell/src/file/isMissingPath.tsnew file mode 100644index 00000000000..4935168974d--- /dev/null+++ b/packages/local-file-shell/src/file/isMissingPath.ts@@ -0,0 +1,21 @@+import { stat } from 'node:fs/promises';++/**+ * Whether a path is definitively absent.+ *+ * `stat` failing is not the same as the path being gone: an unreadable parent+ * (EACCES/EPERM), a symlink loop (ELOOP) or a transient fd exhaustion (EMFILE)+ * all throw for a path that exists. Reporting those as "does not exist" would+ * hand the caller a confidently wrong diagnosis β worse than the vague one it+ * replaces β so only the two codes that actually mean "no such path" count,+ * and everything else is left for the real operation to fail on and report.+ */+export const isMissingPath = async (target: string): Promise<boolean> => {+ try {+ await stat(target);+ return false;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException).code;+ return code === 'ENOENT' || code === 'ENOTDIR';+ }+};diff --git a/packages/local-file-shell/src/fileSearch/base.ts b/packages/local-file-shell/src/fileSearch/base.tsindex 7d06ac28b44..de7937ad2d5 100644--- a/packages/local-file-shell/src/fileSearch/base.ts+++ b/packages/local-file-shell/src/fileSearch/base.ts@@ -1,6 +1,8 @@import { stat } from 'node:fs/promises';import path from 'node:path';+import { expandTilde } from '../file/expandTilde';+import { isMissingPath } from '../file/isMissingPath';import type { ToolDetector } from '../toolDetector';import type { FileResult, GlobFilesParams, GlobFilesResult, SearchFilesParams } from '../types';@@ -158,6 +160,31 @@ export abstract class BaseFileSearch {return Math.floor(limit);}+ /**+ * The result to return when the glob `scope` points at nothing.+ *+ * `fast-glob` (and `fd`) answer a non-existent root with an empty list, which+ * is indistinguishable from "the pattern matched nothing" β so an agent that+ * mistypes a directory reads the answer as "these files don't exist" and+ * revises the wrong hypothesis. Name the missing scope instead.+ *+ * Only a definitively absent path short-circuits β see the same guard in+ * `BaseContentSearch` for why an unreadable one must reach the engine.+ */+ protected async missingScopeResult(+ params: GlobFilesParams,+ ): Promise<GlobFilesResult | undefined> {+ const searchPath = expandTilde(params.scope || params.cwd);+ if (!searchPath || !(await isMissingPath(searchPath))) return undefined;++ return {+ error: `Search scope does not exist: ${searchPath}`,+ files: [],+ success: false,+ total_files: 0,+ };+ }+abstract search(options: SearchFilesParams): Promise<FileResult[]>;abstract glob(params: GlobFilesParams): Promise<GlobFilesResult>;diff --git a/packages/local-file-shell/src/fileSearch/impl/unix.ts b/packages/local-file-shell/src/fileSearch/impl/unix.tsindex e5096b79b7e..b3d6bc8a234 100644--- a/packages/local-file-shell/src/fileSearch/impl/unix.ts+++ b/packages/local-file-shell/src/fileSearch/impl/unix.ts@@ -249,6 +249,12 @@ export abstract class UnixFileSearch extends BaseFileSearch {* Uses fd when available; falls back to fast-glob to preserve globstar semantics.*/async glob(params: GlobFilesParams): Promise<GlobFilesResult> {+ const missingScope = await this.missingScopeResult(params);+ if (missingScope) {+ logger.warn(`[glob: ${params.pattern}] ${missingScope.error}`);+ return missingScope;+ }+const tool = await this.determineBestUnixTool();const globTool = tool === 'find' ? 'fast-glob' : tool;logger.info(`Using glob tool: ${globTool}`);diff --git a/packages/local-file-shell/src/fileSearch/impl/windows.ts b/packages/local-file-shell/src/fileSearch/impl/windows.tsindex 6715a868e9f..b73385a820a 100644--- a/packages/local-file-shell/src/fileSearch/impl/windows.ts+++ b/packages/local-file-shell/src/fileSearch/impl/windows.ts@@ -254,6 +254,12 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {}async glob(params: GlobFilesParams): Promise<GlobFilesResult> {+ const missingScope = await this.missingScopeResult(params);+ if (missingScope) {+ logger.warn(`[glob: ${params.pattern}] ${missingScope.error}`);+ return missingScope;+ }+if (await this.checkToolAvailable('fd')) {logger.info('Using glob tool: fd');return this.globWithFd(params);