From 194099e7f3d8c5c633ab4e6fb51f7d5f09dee0d8 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 02:10:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(search):=20fs.search=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=90=8D=E6=90=9C=E7=B4=A2=E4=BC=98=E5=85=88=E7=94=A8=20fd/rg?= =?UTF-8?q?=EF=BC=8C=E7=BC=BA=E5=A4=B1/=E5=A4=B1=E8=B4=A5=E5=9B=9E?= =?UTF-8?q?=E9=80=80=20JS=20=E9=81=8D=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit issue #203:十万级目录下纯 JS 递归遍历是秒级,10 万条访问预算一顶结果 还被静默截断。现在启动后惰性探测一次本机 fd / rg(每个候选 `--version` 500ms 内验证通过才算数,进程内缓存),探到就用引擎输出,探不到或运行失败 整段回退原来的遍历(导出为 `searchFilesPlain`);坏二进制在进程内禁用, 超时只降级本次(树大 ≠ 二进制坏)。 为什么按 dev 现状重写而不是机械解冲突(PR #303 的落点全部复核过): - **#801 的必填 `dirs` 是语义级冲突,必须扩引擎契约**。dev 的 `FsSearchResult` 多了 `dirs`(`TreePanel` 用它把命中行当目录导航,否则 `fs.read` 报 “is a directory”),而 PR 的引擎侧只产出 `{paths, truncated}`,`searchFilesPlain` 的空查询也还在返回两字段形状; 照搬会让 #801 修的 bug 在引擎路径上静默回退。收口:fd 用第二次 `--type d` 调用取目录子集(fd 自己不做标注),rg 由文件路径倒推匹配的 目录段(`deriveRgMatches`),dispatch 再把 `dirs` 收敛成 `matches` 的 子集。残留差异只有**空目录在 rg 下不可见**(没有文件路径能带上它)。 - **rg 的路径级 glob 补成三个**:PR 的 `**/**/**` 缺一个直接子文件 (`util/helper.ts` 是最常见形态),只加 `**` 会让这类目录命中在 rg-only 机器上凭空消失;`**/*/*` + `**/*/**` 两条并用(对真实 rg 15 实测:单用任一条都丢结果)。 - **`bundledRgCandidates` 的路径推导按真机布局改写**:npm/pnpm 把 `@vscode/ripgrep--` 提升到 `@deepseek-ai` 的**同级**, 不存在 `/@deepseek-ai/dsh/node_modules/@vscode/...`;候选根改成 「从 CLI 入口(argv[1])向上逐级 `node_modules`」+ 各包管理器全局前缀, 桌面壳那种「自带依赖树 + 外部 node」的布局才探得到捆绑 rg(实测命中)。 - **丢掉 abort 形参**:`src/index.ts` 的生产路径不传 signal(PR 里也只有 测试在用),单为测试保留一条贯穿三层的通道不划算;引擎子进程由 15s 内部超时兜底。 - **文档锚点按 dev 重锚**:README 的 v0.12.3 条目已随发布历史迁到 CHANGELOG(新增 Unreleased 条目),AGENTS §2 的引擎门禁入口挂到现有 ci-windows 段落,指南 §14 参考实现行补 `src/search-engines.ts`。 - 未新增任何依赖:`@vscode/ripgrep` 只作为**路径**探测,不做模块导入。 Windows 侧由既有 ci-windows lane 承载:`choco install fd ripgrep` 把真 二进制放进 PATH,套件后 `pnpm check:engines`(`scripts/win-engine-check.mjs --assert`,import `src/search-engines.ts` 取插件自己的 argv)断言 `--path-separator /` 的输出不含 `\`/CR、非 ASCII 文件名命中;引擎缺失则 跳过(fd 在 ubuntu lane 与多数开发机上都没有)。 测试:`tests/search-engines.spec.ts`(探测缓存 / 运行失败禁用 / 超时不禁 用 / argv 对称性与噪声目录排除 / `deriveRgMatches` / 捆绑 rg 候选推导 / 真引擎在场时的端到端——缺席即返回),`tests/fs-search.spec.ts` 拆成 「直接钉遍历」+「注入假引擎的 dispatch 组」(引擎优先、`dirs` 透传与 子集收敛、预算透传、运行失败回退并禁用)。真机核对:本仓库上 rg 路径与 JS 遍历对 `locales` / `util` / `client` / `src` / `e2e` 五个查询的 matches 与 dirs **逐项一致**。 Refs #303 Co-authored-by: Cold Cloud <64406210+yanzhaohui1999@users.noreply.github.com> --- .github/workflows/ci.yml | 19 ++ AGENTS.md | 2 +- CHANGELOG.md | 5 + docs/external-plugin-guide.md | 2 +- package.json | 1 + scripts/win-engine-check.mjs | 81 ++++++ src/fs-search.ts | 91 ++++-- src/search-debug.ts | 39 +++ src/search-engines.ts | 524 ++++++++++++++++++++++++++++++++++ tests/fs-search.spec.ts | 209 ++++++++++++-- tests/search-engines.spec.ts | 449 +++++++++++++++++++++++++++++ 11 files changed, 1367 insertions(+), 55 deletions(-) create mode 100644 scripts/win-engine-check.mjs create mode 100644 src/search-debug.ts create mode 100644 src/search-engines.ts create mode 100644 tests/search-engines.spec.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 16fb24a5..589016eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -63,6 +63,12 @@ jobs: # runs the same typecheck / test / build / consumer-type-surface steps on # a real Windows runtime. The plugin-mount lane (real DSH + Playwright # Chromium) stays ubuntu-only and is deliberately NOT mirrored here. + # + # It also carries the search-engine gate: real fd/ripgrep binaries land on + # PATH (choco) before the suite runs, and the output-shape assertions run + # against them afterwards. Windows is where the engine output format bites + # hardest (backslash separators, CR line endings, console code pages); + # docs/ci-windows.md holds the red lines. ci-windows: runs-on: windows-latest timeout-minutes: 30 @@ -90,6 +96,12 @@ jobs: run: | git config --global user.name "dsh-better-sidebar-ci" git config --global user.email "ci@dsh.invalid" + # Real engine binaries for the output-shape assertions below. The probe + # inside src/search-engines.ts reads PATH, so the whole suite runs with + # engines present here; the specs never depend on that (they inject + # their own probes, and the one real-engine case skips when absent). + - name: Install fd / ripgrep (choco) + run: choco install fd ripgrep -y --no-progress - name: Install dependencies run: pnpm install --frozen-lockfile - name: Typecheck @@ -122,6 +134,13 @@ jobs: run: pnpm build - name: Check consumer type surface run: pnpm check:consumer-types + # Output-shape assertions on the REAL engine binaries installed above: + # the plugin's own argv must produce '/'-separated, CR-free paths and + # hit a non-ASCII file name. An engine that is absent skips (so the + # script stays runnable on a dev machine); an assertion failure exits + # non-zero. + - name: Engine output-shape assertions (real fd/rg) + run: pnpm check:engines # Pack the plugin as an npm tarball, mount it into a REAL DSH instance # through the official `dsh plugin --profile web add` channel, and render diff --git a/AGENTS.md b/AGENTS.md index bf86c0c5..caaa8d28 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,7 @@ 「npm 打包 → 真实挂载 → 无头渲染」门禁(证明打包产物在真实 DSH 挂载后不 crash):`pnpm build && pnpm pack` 产 tarball → `scripts/e2e-mount.sh` 装进全新 scratch profile(`dsh plugin --profile web add `)并启动真实 `dsh web`(keyless,`--port 0`)→ `tests/e2e/mount.e2e.ts`(Playwright)断言 `[data-dsh-better-sidebar]` 挂载、无错误条/pageerror/console 错误,展开 DSH 原生右侧栏后经其 guide 页逐个打开本插件贡献的 tab 类型**以及宿主自己的终端条目**(必须恰好 1 条——多于 1 条即意味着插件又在遮蔽宿主),再经插件文件树(原生 `files` kind 接管)打开 seed 文件强制加载 editor chunk(`client-editor.js`),并跑 mermaid / README 预览与 sidechat 宿主路由烟测。**`tests/e2e/native-reload.e2e.ts` 是同一 lane 里的第二条门**:它 `utimesSync` 已安装的 `lib/client.js`(**在钉住的宿主 0.1.7-rc.1 上**:HMR 每 500ms stat-poll,rev = `mtime/ctime/size` 的 sha1;DSH 源码树的新版本改成只比 `mtime+size` 并对**内容**取 sha1——pin 上调时这个触发器必须同步复核,否则该用例会红在替换断言上而不是静默失效)触发**页面内条目替换**,断言替换前后都无 `native register … error`、无诊断条、且 `files` 接管重新可用——这是唯一能在部署层复现「teardown 期间注册把 id 孤儿化」(见 §3.4 第 9 条)的用例,v0.22.0 上连续 3 次运行全红、修复后连续 3 次全绿。**`browser` 不在这个清单里,而是显式断言缺席**:DSH 0.1.7 的 `ui-sidebar-browser` 只在 desktop profile 挂载(`web-app` 的 patch 里 `disabled: ctx.get('profileContext')?.name !== 'desktop'`),lane 全走 web profile,钉住「没有」比默默放过更能暴露宿主立场的变化。 -本地:`pnpm build && pnpm pack && pnpm exec playwright install chromium && pnpm test:mount`(`DSH_CMD` 未设时 `scripts/e2e-common.sh` 回退的 npx 钉版是 `DSH_NPX_SPEC`,默认 `@deepseek-ai/dsh@0.2.0-rc.1`——**不钉就会解析 `latest`,而 `latest` 仍是 0.1.7-rc.2**;本机 pnpm 的 registry 是 npmmirror,新预发布常滞后,装不到时用 `pnpm install --registry https://registry.npmjs.org` 一次性覆盖)。CI 钉 `@deepseek-ai/dsh@0.2.0-rc.1`(**pin 一律写精确版本号,不要写 dist-tag**:0.1.7-rc.1 上线时 `alpha` 指的是 **0.1.7-alpha.2**,而 0.2.0-rc.1 只挂在 `next` 上;peer 下限 `^0.2.0-rc.1`)。该步骤用 `NODE_OPTIONS=--max-old-space-size=4096`:钉版自身的传递依赖是浮动 `^` 范围,上游分阶段发布预发布版时(rc.2 于 2026-09-10 的 14:43–14:57 逐包上线)npm 会组出混合 peer 图,3062 条 ERESOLVE 后 OOM(exit 134);另一个失败模式是对未发布兄弟包 ETARGET,靠「钉一个已完整发布的版本」修掉。**不要加 `--legacy-peer-deps`**:它跳过的正是全局安装必须提供的 peer,`@deepseek-ai/dsh-app-boot` 在 boot 时 require 的 `@deepseek-ai/cordis-plugin-group` 是 peer 而非 dependency,加了它 CLI 直接 `ERR_MODULE_NOT_FOUND`(实测过一次,见 rc.2 计划 C 节)。`ci-windows` 的 `Test` 跑 `pnpm test:windows`(`--maxWorkers=1`)而非 `pnpm test`——多个 spec 真起进程(`smoke` / `install-powershell` / `git`),2 核 runner 上并行起 ConPTY / 冷启 `powershell.exe` 是超时与 worker 静默死亡的放大器;`vitest.config.ts` 的全局 `testTimeout: 15_000`(默认 5000 在 Windows 上对真起进程的用例太低,三个不同文件先后翻车)是配套的一半。e2e spec 命名 `*.e2e.ts` + vitest `exclude` 双保险;**改 `exclude` 必须保留默认排除项**(exclude 整体替换默认值)。 +本地:`pnpm build && pnpm pack && pnpm exec playwright install chromium && pnpm test:mount`(`DSH_CMD` 未设时 `scripts/e2e-common.sh` 回退的 npx 钉版是 `DSH_NPX_SPEC`,默认 `@deepseek-ai/dsh@0.2.0-rc.1`——**不钉就会解析 `latest`,而 `latest` 仍是 0.1.7-rc.2**;本机 pnpm 的 registry 是 npmmirror,新预发布常滞后,装不到时用 `pnpm install --registry https://registry.npmjs.org` 一次性覆盖)。CI 钉 `@deepseek-ai/dsh@0.2.0-rc.1`(**pin 一律写精确版本号,不要写 dist-tag**:0.1.7-rc.1 上线时 `alpha` 指的是 **0.1.7-alpha.2**,而 0.2.0-rc.1 只挂在 `next` 上;peer 下限 `^0.2.0-rc.1`)。该步骤用 `NODE_OPTIONS=--max-old-space-size=4096`:钉版自身的传递依赖是浮动 `^` 范围,上游分阶段发布预发布版时(rc.2 于 2026-09-10 的 14:43–14:57 逐包上线)npm 会组出混合 peer 图,3062 条 ERESOLVE 后 OOM(exit 134);另一个失败模式是对未发布兄弟包 ETARGET,靠「钉一个已完整发布的版本」修掉。**不要加 `--legacy-peer-deps`**:它跳过的正是全局安装必须提供的 peer,`@deepseek-ai/dsh-app-boot` 在 boot 时 require 的 `@deepseek-ai/cordis-plugin-group` 是 peer 而非 dependency,加了它 CLI 直接 `ERR_MODULE_NOT_FOUND`(实测过一次,见 rc.2 计划 C 节)。`ci-windows` 的 `Test` 跑 `pnpm test:windows`(`--maxWorkers=1`)而非 `pnpm test`——多个 spec 真起进程(`smoke` / `install-powershell` / `git`),2 核 runner 上并行起 ConPTY / 冷启 `powershell.exe` 是超时与 worker 静默死亡的放大器;`vitest.config.ts` 的全局 `testTimeout: 15_000`(默认 5000 在 Windows 上对真起进程的用例太低,三个不同文件先后翻车)是配套的一半。e2e spec 命名 `*.e2e.ts` + vitest `exclude` 双保险;**改 `exclude` 必须保留默认排除项**(exclude 整体替换默认值)。同一条 lane 还承载**搜索引擎门禁**:`choco install fd ripgrep` 把真二进制放进 PATH(整条套件因此在引擎在场的环境下跑),套件后跑 `pnpm check:engines`(`scripts/win-engine-check.mjs --assert`)对**插件自己的 argv** 做字节级断言——`--path-separator /` 的输出不得含 `\` 与 CR、非 ASCII 文件名必须命中;引擎缺失则跳过(`fd` 在 ubuntu lane 与多数开发机上都没有,所以 `tests/search-engines.spec.ts` 全部走注入钩子,唯一一条真引擎用例自己探测并在缺席时直接返回)。脚本 import `src/search-engines.ts` 取 argv,改 argv 不会让门禁断言一个没人跑的形态(Node 22 需要 `--experimental-strip-types`,已封进 `check:engines`)。 --- diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cd44246..06e52923 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ > 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。 +### Unreleased + +- 🔍 **文件搜索优先走本机原生引擎(fd / ripgrep),缺失或失败自动回退 JS 遍历**([#203](https://github.com/omdsh-dev/DSH-better-sidebar/issues/203),PR [#303](https://github.com/omdsh-dev/DSH-better-sidebar/pull/303) 重写落地):`fs.search` 之前是纯 JS 递归遍历,十万级目录秒级、10 万条访问预算一顶就静默截断。现在启动后惰性探测一次(每个候选二进制 `--version` 500ms 内验证通过才用,进程内缓存),探到就用引擎,探不到/运行失败回退原遍历;rg 优先用 DSH 自己捆绑的 `@vscode/ripgrep`(agent 侧搜索工具同一个二进制,从 CLI 入口的依赖树推导候选路径),fd 走 `--fixed-strings` 字面量匹配。噪声目录排除名单单源化到 `SKIP_DIR_NAMES`(18 项,walk 与两条 argv 共用),引擎输出统一归一化成 walk 契约(根相对、`/` 分隔、大小写不敏感),**路由与客户端零改动**。**目录命中按 #801 的契约同时产出 `dirs`**:fd 用 `--type d` 直接列目录,rg 由文件路径倒推匹配的目录段(`deriveRgMatches`)——唯一残留差异是**空目录在 rg 下不可见**(已记录)。运行失败禁用该引擎(坏二进制不该拖慢后续搜索),**超时只降级本次**(树太大不等于二进制坏)。调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,默认完全静默。Windows 侧由 `ci-windows` lane 承载:`choco install fd ripgrep` + `pnpm check:engines` 对插件自己的 argv 做字节级断言(不得含 `\`/CR、非 ASCII 文件名必须命中)。 +- 🧪 测试:`tests/search-engines.spec.ts`(探测缓存 / 失败禁用 / 超时不禁用 / argv 对称性 / `deriveRgMatches` / 捆绑 rg 候选路径推导 / 真引擎在场时的端到端),`tests/fs-search.spec.ts` 的 dispatch 组(引擎优先、`dirs` 透传、预算透传、运行失败回退并禁用)。 + ### v0.24.1 > 🎁 **本版包含从 v0.22.1 起的全部内容**(v0.23.0 的文件页 / 文件变动页 UI/UX 重构与性能打磨、v0.24.0 的 DSH 0.2.0-rc.1 支持线前移,以及本节的修复)。 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index a325d8d1..19ed5bf0 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -1166,7 +1166,7 @@ better-sidebar 的内置 tab 和 viewer 就是参考实现("吃狗粮"), - **`src/client/SideCardSection.tsx`**:声明式设置页(注册表驱动清单 + 嵌套设置行 + 开关持久化) - **`src/client/api.ts`**:`/sidebar` API 的封装(复制其 fetch 模式到你的插件) - **`src/client/plugins-tabs.ts`** / **`plugins-viewers.ts`**:推荐插件目录(「添加插件」弹窗数据源;加一条数据即上架,`tests/plugin-list.spec.ts` 守护) -- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`**:文件树 / 树面板 / host 文件名搜索(`fs.search`;`tests/fs-search.spec.ts`) +- **`src/client/FileTree.tsx`** / **`TreePanel.tsx`** / **`src/fs-search.ts`** / **`src/search-engines.ts`**:文件树 / 树面板 / host 文件名搜索(`fs.search`:优先探测本机 fd / rg(DSH 自带 ripgrep 优先),缺失或运行失败回退 JS 遍历;`dirs` 让目录命中行导航文件树而不是当文件打开——`tests/fs-search.spec.ts` / `tests/search-engines.spec.ts`;调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,缺省 `~/.dsh`) - **`src/client/markdown-html.ts`** / **`MarkdownHtml.tsx`** / **`md-toc.tsx`**:markdown 内嵌 HTML 管线与目录大纲(注意 `md-toc.tsx` 头注释的「子组件读父 ref 为 null」时序陷阱) - **`src/agent-opens.ts`** / **`/sidebar/ws/agent-opens`**:模型主动打开(`sidebar_open` 工具 + `agentOpenTools` 设置,默认关闭);文件夹窗口 = `meta.dir: true` 的 editor tab([设计文档](plans/2026-08-23-agent-open-tools-design.md)) - **`tests/service.spec.ts`** / **`tests/builtins.spec.ts`**:注册表生命周期 / 匹配算法 / dedupe / createTab / 启用态 gating;内置清单断言(5 tab + 3 viewer + 声明式元数据,并显式断言 image / pdf / binary-download **不在**内置清单里、但作为公开契约仍可被第三方注册) diff --git a/package.json b/package.json index 1f6c1397..4b5ad168 100644 --- a/package.json +++ b/package.json @@ -89,6 +89,7 @@ "test:mount:aggregate": "bash scripts/e2e-aggregate-mount.sh", "clean": "node -e \"require('node:fs').rmSync('lib',{recursive:true,force:true})\"", "check:consumer-types": "bash scripts/check-consumer-types.sh", + "check:engines": "node --experimental-strip-types scripts/win-engine-check.mjs --assert", "lint": "eslint ." }, "license": "MIT", diff --git a/scripts/win-engine-check.mjs b/scripts/win-engine-check.mjs new file mode 100644 index 00000000..db83a0c3 --- /dev/null +++ b/scripts/win-engine-check.mjs @@ -0,0 +1,81 @@ +/** + * Engine output-shape gate for the fd / ripgrep binaries behind fs.search's + * file-name search. `node scripts/win-engine-check.mjs` prints what each + * installed engine emits (human inspection); `--assert` turns it into the + * CI gate the ci-windows lane runs after `choco install fd ripgrep`. + * + * The assertions cover exactly what the plugin's own argvs promise: + * + * - `--path-separator /` output carries no '\' and no CR — on Windows rg + * emits '\' paths in cmd/PowerShell and CRLF line endings, so without the + * pin every result path would leak a backslash into the walk contract. + * - A non-ASCII file name comes back through the UTF-8 pipeline instead of + * the console code page. + * + * A missing engine SKIPS (the script stays runnable on a dev machine and on + * the ubuntu lane, where fd is absent); an assertion failure exits non-zero. + * The argv strings come from src/search-engines.ts itself, so a changed argv + * cannot leave this gate asserting a shape nothing runs any more — hence the + * `pnpm check:engines` wrapper (`--experimental-strip-types`; on Node ≥ 23 + * plain `node scripts/win-engine-check.mjs --assert` works too). + */ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fdArgv, rgArgv } from '../src/search-engines.ts' + +const assertMode = process.argv.includes('--assert') + +/** Every run builds its own scratch tree (a runner and a dev machine share no fixed path). */ +const scratch = mkdtempSync(join(tmpdir(), 'dsh-engine-check-')) +mkdirSync(join(scratch, 'src')) +writeFileSync(join(scratch, 'README.md'), 'readme') +writeFileSync(join(scratch, 'src', 'a.ts'), 'code') +writeFileSync(join(scratch, '中文文件名.ts'), 'code') + +let failed = false + +function run(label, binary, args, { checkUnicode = false } = {}) { + let stdout + try { + stdout = execFileSync(binary, args, { cwd: scratch, encoding: 'buffer' }) + } catch (error) { + // A missing engine is a SKIP, not a failure: fd is absent on the ubuntu + // lane and on most dev machines. + console.log(`=== ${label} (${binary}) SKIPPED ===`) + console.log(String(error.stderr ?? error.message).split('\n')[0]) + return + } + const hasBackslash = stdout.includes(92) + const hasCR = stdout.includes(13) + const text = stdout.toString('utf8') + console.log(`=== ${label} (${binary}) ===`) + console.log('backslash:', hasBackslash, '| CR:', hasCR) + console.log('raw:', JSON.stringify(text)) + if (!assertMode) return + if (hasBackslash || hasCR) { + console.error(`ASSERT FAIL: ${label} leaked backslash/CR into output`) + failed = true + } + if (checkUnicode && !text.includes('中文文件名.ts')) { + console.error(`ASSERT FAIL: ${label} missed the non-ASCII file name`) + failed = true + } +} + +if (process.argv.includes('--probe')) { + // --probe: what the plugin's own argv produces for a query that hits a + // directory, a file and a non-ASCII name. Manual, not asserted. + run('rg argv (query=util)', 'rg', rgArgv('util'), { checkUnicode: false }) + run('fd argv (query=util)', 'fd', fdArgv(10, 'util')) +} else { + run('rg argv (query=中文)', 'rg', rgArgv('中文'), { checkUnicode: true }) + run('fd argv (query=中文)', 'fd', fdArgv(10, '中文'), { checkUnicode: true }) + // A query with no non-ASCII bytes still exercises the path-separator pin. + run('rg argv (query=a)', 'rg', rgArgv('a')) + run('fd argv (query=a)', 'fd', fdArgv(10, 'a')) +} + +rmSync(scratch, { recursive: true, force: true }) +if (failed) process.exit(1) diff --git a/src/fs-search.ts b/src/fs-search.ts index ee9cf2c3..0cdd80b7 100644 --- a/src/fs-search.ts +++ b/src/fs-search.ts @@ -15,10 +15,18 @@ * A hit can be a DIRECTORY (the list shows where matches live), so the result * separates them: `fs.read` refuses a directory, and the client must navigate * the tree for those rows instead of opening them as files. + * + * `searchFiles` (the dispatch the fs.search route calls) first tries the + * probed native engines (fd / rg — see search-engines.ts); when none are + * available or all failed at runtime it falls back to this walk (exported as + * `searchFilesPlain` for tests). Both paths fill the same contract. */ import type { Dirent } from 'node:fs' import { opendir, stat } from 'node:fs/promises' import { join, relative, sep } from 'node:path' +import { homedir } from 'node:os' +import { SKIP_DIR_NAMES, runEngine, usableEngines } from './search-engines.ts' +import { debugLog } from './search-debug.ts' /** One search: the relative paths of the matching entries (dirs included so * the client can hint where matches live) plus the truncation flag. */ @@ -47,28 +55,23 @@ const DEFAULT_MAX_VISITED = 100_000 * Directory names that are never useful filename-search results and would * burn the visit budget before the walk reaches project files. Compared * case-insensitively so `Node_Modules` / `.GIT` stay skipped on every - * platform. The directory itself is neither matched nor descended. + * platform. The name list lives in search-engines.ts (SKIP_DIR_NAMES) — the + * engine argvs exclude the same names so the fallback and the engines return + * the same result shape. An entry with a skip name is neither matched nor + * descended — including a worktree-style `.git` FILE, which the engine + * excludes cover as well. */ -const SEARCH_SKIP_DIRS = new Set([ - '.git', - 'node_modules', - '.pnpm-store', - '.yarn', - '.turbo', - '.turbopack', - '.next', - '.nuxt', - '.output', - '.cache', - '.parcel-cache', - 'coverage', - 'dist', - 'build', - 'out', - '.umi', - '.umi-production', - '.dumi', -]) +const SEARCH_SKIP_DIRS = new Set(SKIP_DIR_NAMES) + +/** Shorten an absolute search root for log lines: ~/ for the config home. */ +function relRoot(root: string): string { + const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME.trim() !== '' + ? process.env.DSH_HOME + : homedir() + if (root === home) return '~' + const boundary = home.endsWith(sep) ? home : home + sep + return root.startsWith(boundary) ? `~${root.slice(home.length)}` : root +} /** * Whether one matched entry is a DIRECTORY, following symlinks the way the @@ -84,8 +87,8 @@ async function isDirectoryEntry(absolute: string, dirent: Dirent): Promise { +export async function searchFilesPlain(root: string, query: string, opts: FsSearchOptions = {}): Promise { const needle = query.trim().toLowerCase() if (needle === '') return { matches: [], dirs: [], truncated: false } const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES @@ -115,8 +118,11 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt truncated = true return } - // Dependency / VCS / build-output forests: never matched, never descended. - if (dirent.isDirectory() && SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue + // Dependency / VCS / build-output forests: never matched, never + // descended. A worktree-style `.git` FILE (pointer to the real + // gitdir) is VCS noise too — the name check covers both shapes, + // parity with the engines' .git exclusion (SKIP_DIR_NAMES). + if (SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue const absolute = join(dir, dirent.name) if (dirent.name.toLowerCase().includes(needle)) { const hit = join(relative(root, dir), dirent.name) @@ -140,3 +146,36 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt const normalize = (path: string): string => path.split(sep).join('/') return { matches: matches.sort().map(normalize), dirs: dirs.sort().map(normalize), truncated } } + +/** + * The fs.search dispatch: native engines first (when verified and healthy), + * the plain walk as fallback. Engine output is normalized onto the walk + * contract — root-relative, '/'-separated, sorted, and split into + * matches/dirs — so the route and the client stay unchanged. A blank query + * matches nothing and touches neither the engines nor the filesystem. + */ +export async function searchFiles(root: string, query: string, opts: FsSearchOptions = {}): Promise { + const needle = query.trim() + if (needle === '') return { matches: [], dirs: [], truncated: false } + const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES + const started = performance.now() + for (const probe of await usableEngines()) { + try { + const result = await runEngine(probe, root, needle, maxMatches) + // The engine's own cap is a sentinel (maxMatches + 1) proving there is + // more; slice back to the caller's budget and re-derive the directory + // subset from what was kept, so dirs never names a dropped row. + const matches = [...result.paths].sort().slice(0, maxMatches) + const kept = new Set(matches) + const dirs = [...new Set(result.dirs)].filter(dir => kept.has(dir)).sort() + debugLog(`[dsh-search] engine=${probe.engine} bin=${probe.binary} root=${relRoot(root)} query="${needle}" hits=${matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`) + return { matches, dirs, truncated: result.truncated } + } catch { + // runEngine already recorded the failure (broken engine or timeout); + // the next engine — or the walk below — gets its turn. + } + } + const result = await searchFilesPlain(root, query, opts) + debugLog(`[dsh-search] engine=plain root=${relRoot(root)} query="${needle}" hits=${result.matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`) + return result +} diff --git a/src/search-debug.ts b/src/search-debug.ts new file mode 100644 index 00000000..c6b068b3 --- /dev/null +++ b/src/search-debug.ts @@ -0,0 +1,39 @@ +/** + * Gated debug instrumentation for the fs.search engine pipeline (host half). + * Off by default: with DSH_SEARCH_DEBUG unset nothing is logged, nothing + * touches the disk, and no console output is emitted. Setting + * `DSH_SEARCH_DEBUG=1` in the dsh web environment appends one line per + * probe/search/engine-failure to `/search-debug.log` and mirrors + * it to the host console. + * + * The log file lives under $DSH_HOME (the DSH config dir) when set, exactly + * like pty-deps.ts resolves it; otherwise it falls back to `~/.dsh`. A + * missing/unwritable log dir must never break a search — write errors are + * swallowed. + * + * The flag is read once at module load: toggling it requires restarting the + * host, the same as any other host-side change. + */ +import { appendFileSync } from 'node:fs' +import { join } from 'node:path' +import { homedir } from 'node:os' + +const SEARCH_DEBUG = process.env.DSH_SEARCH_DEBUG === '1' + +const LOG_FILE = join( + process.env.DSH_HOME !== undefined && process.env.DSH_HOME.trim() !== '' + ? process.env.DSH_HOME + : join(homedir(), '.dsh'), + 'search-debug.log', +) + +/** Append one debug line (gated; no-op unless DSH_SEARCH_DEBUG=1). */ +export function debugLog(msg: string): void { + if (!SEARCH_DEBUG) return + try { + appendFileSync(LOG_FILE, `[${new Date().toISOString()}] ${msg}\n`) + } catch { + // A missing/unwritable log path must never break a search. + } + console.log(msg) +} diff --git a/src/search-engines.ts b/src/search-engines.ts new file mode 100644 index 00000000..1ad6c25c --- /dev/null +++ b/src/search-engines.ts @@ -0,0 +1,524 @@ +/** + * Optional native search engines (fd / ripgrep) behind the editor's file-name + * search (fs.search). The probe runs lazily once per process: each candidate + * binary is verified with `--version` under a 500ms budget so a dead path is + * never used. Engine stdout streams are always capped (fd's --max-results + * included; rg is capped by killing the child). + * + * Engine output is normalized to the walk contract (see fs-search.ts): + * root-relative, '/'-separated paths, case-insensitive NAME matching, sorted + * by the caller, plus the directory/file split the client needs. fd reports + * directories natively (`--type d`); rg --files reports files only, so + * `deriveRgMatches` turns a matching path segment into the directory hit the + * walk would have reported — the one real gap left is an EMPTY directory + * whose name matches (no file path carries it, so rg cannot see it; fd and + * the walk both report it). + * + * A runtime failure disables that engine for the rest of the process (a + * broken binary must not slow every later search); the caller falls back to + * the plain walk. A timeout is NOT a failure: it means this tree was too + * large, so it must not strip every other root of the engine. Hooks are + * swappable for tests (setEngineHooks). + */ +import { spawn, type ChildProcess } from 'node:child_process' +import { createInterface } from 'node:readline' +import { dirname, join, sep } from 'node:path' +import { homedir } from 'node:os' +import { debugLog } from './search-debug.ts' + +export type Engine = 'fd' | 'rg' + +/** A probed, verified engine binary. */ +export interface EngineProbe { + engine: Engine + binary: string +} + +/** The engine output contract: root-relative, '/'-separated, UNSORTED. */ +export interface EngineResult { + /** Every matching entry (files and directories). */ + paths: string[] + /** The subset of `paths` that are directories. */ + dirs: string[] + /** true when the match cap cut the stream short. */ + truncated: boolean +} + +const PROBE_TIMEOUT_MS = 500 +const ENGINE_TIMEOUT_MS = 15_000 + +const PATH_SEPARATOR = process.platform === 'win32' ? ';' : ':' + +/** + * Where DeepSeek Harness keeps its own `@vscode/ripgrep` platform package + * (`@vscode/ripgrep--/bin/rg` — the binary the harness's + * agent-side search tools run on, so the sidebar search should prefer it + * over a random PATH rg). The roots below are PACKAGE-MANAGER ROOTS (the + * directory holding `@vscode/`), not `/@deepseek-ai/dsh/node_modules` + * style dependency dirs: npm and pnpm hoist the platform package next to + * `@deepseek-ai`, not under it (verified against a real install: the + * profile tree carries `/node_modules/@vscode/ripgrep-<…>` and no + * `@deepseek-ai/dsh/node_modules` at all). Both shapes are still probed — + * a tree that did not hoist keeps the package under the CLI. Deriving "the + * node_modules that provided @deepseek-ai/dsh" from the running paths also + * covers pnpm's `.pnpm/node_modules` hoist layer for free (verified on + * fnm/pnpm: execPath `.../node/versions/v22/bin/node` walks + * `bin/node_modules` → `versions/node_modules` → … → `.pnpm/node_modules`), + * and `modulePath` (the CLI entry, `…/@deepseek-ai/dsh/lib/bin.js`) covers + * a desktop shell whose bundled tree sits next to a node it did not ship — + * a Homebrew node + this checkout's dependency tree is exactly that layout + * (verified: the candidate resolves to the bundled rg on macOS). + * Wrong guesses are cheap: every candidate goes through verify() and + * unusable ones are dropped. + */ +export function bundledRgCandidates( + platform: NodeJS.Platform, + arch: string, + execPath: string, + env: NodeJS.ProcessEnv, + home: string, + modulePath: string | undefined = process.argv[1], +): string[] { + const binName = platform === 'win32' ? 'rg.exe' : 'rg' + const platformPkg = `@vscode/ripgrep-${platform}-${arch}` + const roots: string[] = [] + const addRoot = (root: string): void => { + if (root !== '' && !roots.includes(root)) roots.push(root) + } + // Every node_modules directory on the way up from a path inside the DSH + // install: the CLI entry (argv[1] = …/@deepseek-ai/dsh/lib/bin.js) finds + // the tree that actually provided @deepseek-ai/dsh — a desktop shell's + // bundled tree, a project-local install, a checkout — even when the node + // executable itself lives elsewhere (Homebrew node + a bundled tree). + const walkRoots = (start: string): void => { + if (start === '') return + let current = dirname(start) + while (current !== dirname(current)) { + if (current.endsWith(`${sep}node_modules`)) addRoot(current) + current = dirname(current) + } + } + if (modulePath !== undefined && modulePath !== '') walkRoots(modulePath) + walkRoots(execPath) + // npm global installs. POSIX: /lib/node_modules with the executable + // at /bin/node. Windows npm has NO lib/ layer — packages land in + // %APPDATA%\npm\node_modules (nvm-windows keeps the same %APPDATA%\npm). + if (platform === 'win32') { + if (env.APPDATA !== undefined && env.APPDATA !== '') { + addRoot(join(env.APPDATA, 'npm', 'node_modules')) + } + } else { + addRoot(join(dirname(dirname(execPath)), 'lib', 'node_modules')) + // Homebrew and pnpm global layouts missed by the execPath derivation. + addRoot('/opt/homebrew/lib/node_modules') + addRoot('/usr/local/lib/node_modules') + } + // The DSH profile layout: plugins and the host CLI share one tree. + addRoot(join(home, '.dsh', 'profiles', 'node_modules')) + const candidates: string[] = [] + const seen = new Set() + for (const root of roots) { + for (const candidate of [ + join(root, platformPkg, 'bin', binName), + // A dependency tree that did NOT hoist (pnpm's strict layout, npm with + // a conflicting top-level @vscode/ripgrep). + join(root, '@deepseek-ai', 'dsh', 'node_modules', platformPkg, 'bin', binName), + ]) { + if (!seen.has(candidate)) { + seen.add(candidate) + candidates.push(candidate) + } + } + } + return candidates +} + +/** Candidate binaries for one engine: the harness's bundled rg, then PATH + * entries, then fixed well-known locations. A PATH that misses Homebrew + * (seen in launchd-spawned processes) is covered by the fixed paths. */ +function candidates(engine: Engine): string[] { + const env = process.env + const pathNames: Record = { + fd: ['fd', 'fdfind'], + rg: ['rg'], + } + const out: string[] = [] + if (engine === 'rg') { + out.push(...bundledRgCandidates(process.platform, process.arch, process.execPath, env, homedir())) + } + for (const name of pathNames[engine]) { + if (env.PATH !== undefined && env.PATH !== '') { + for (const dir of env.PATH.split(PATH_SEPARATOR)) { + if (dir !== '') out.push(join(dir, name)) + } + } + } + if (engine === 'fd') { + out.push('/opt/homebrew/bin/fd', '/usr/local/bin/fd', '/usr/bin/fd', join(homedir(), '.cargo/bin/fd')) + } else { + out.push('/opt/homebrew/bin/rg', '/usr/local/bin/rg', '/usr/bin/rg') + } + return out +} + +/** Verify one binary actually runs (a broken install must not be used). */ +function verify(binary: string): Promise { + return new Promise((resolve) => { + let settled = false + const finish = (ok: boolean): void => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(ok) + } + let child: ChildProcess + try { + child = spawn(binary, ['--version'], { stdio: 'ignore' }) + } catch { + finish(false) + return + } + const timer = setTimeout(() => { + child.kill() + finish(false) + }, PROBE_TIMEOUT_MS) + child.once('error', () => { finish(false) }) + child.once('exit', (code) => { finish(code === 0) }) + }) +} + +/** Escape glob metacharacters so a query matches literally inside -g. + * Braces are metacharacters too ({a,b} alternation): an unbalanced '{' + * makes rg fail to parse the glob (exit 2 → the engine looks broken), and + * a balanced one silently matches a DIFFERENT literal ('a{b}' searches + * 'ab'). Verified against rg 15: '\{' is a valid brace escape. */ +export function escapeGlob(query: string): string { + // The output is a GLOB string, not a regex: rg globs are gitignore-style, + // so '[' opens a character class and MUST be escaped there even though + // escaping it is unnecessary inside this regex's own character class. + // eslint-disable-next-line no-useless-escape + return query.replace(/[\[\]{}*?\\]/g, '\\$&') +} + +/** Directory names that are never useful filename-search results (VCS + * internals, dependency forests, package-manager stores, build caches). + * The plain walk in fs-search.ts builds its case-insensitive skip set + * from this list, and BOTH engine argvs exclude every name — with + * --no-ignore active an rg/fd run would otherwise re-enter node_modules + * and regress the budget-saving behavior of the walk. Excludes are + * matched case-insensitively (fd honors --ignore-case; rg uses --iglob), + * mirroring the walk's toLowerCase comparison. */ +export const SKIP_DIR_NAMES: readonly string[] = [ + '.git', + 'node_modules', + '.pnpm-store', + '.yarn', + '.turbo', + '.turbopack', + '.next', + '.nuxt', + '.output', + '.cache', + '.parcel-cache', + 'coverage', + 'dist', + 'build', + 'out', + '.umi', + '.umi-production', + '.dumi', +] + +/** A timeout means the tree is too big, not that the binary is broken — + * it must not disable the engine for every other search root. */ +export class EngineTimeoutError extends Error {} + +/** Stream a child's stdout line-by-line, capped at `max` lines (the child is + * killed past the cap so a huge result set never buffers into memory). */ +function streamLines( + child: ChildProcess, + max: number, +): Promise<{ lines: string[]; truncated: boolean }> { + return new Promise((resolve, reject) => { + const lines: string[] = [] + let truncated = false + let closed = false + const finish = (error: unknown): void => { + if (closed) return + closed = true + clearTimeout(timer) + if (error !== undefined) { + child.kill() + reject(error) + } else { + resolve({ lines, truncated }) + } + } + const timer = setTimeout(() => { finish(new EngineTimeoutError('search engine timed out')) }, ENGINE_TIMEOUT_MS) + child.once('error', (error) => { finish(error) }) + child.once('exit', (code) => { + if (truncated) { + finish(undefined) + } else if (code !== 0 && code !== 1) { + // rg exits 1 when nothing matched — that is a successful empty run, + // not an error (fd exits 0 either way). + finish(new Error(`search engine exited with ${String(code)}`)) + } else { + finish(undefined) + } + }) + const stdout = child.stdout + if (stdout === null) { + finish(new Error('search engine stdout unavailable')) + return + } + const rl = createInterface({ input: stdout }) + rl.on('line', (line) => { + if (line === '' || truncated) return + lines.push(line) + if (lines.length > max) { + truncated = true + child.kill() + } + }) + }) +} + +/** Normalize one engine's stdout lines to the walk contract: root-relative, + * '/'-separated, no leading './'. fd/rg emit relative paths with the + * PLATFORM separator; the walk contract is '/'-separated on every platform. + * `separator` defaults to the platform separator — pass '\\' to model + * Windows engine output (rg on Windows emits '\' paths and '.\' prefixes; + * Windows file names can never contain '\' or '/', so the substitution is + * lossless there). A trailing '\r' is also stripped: Windows engines emit + * CRLF line endings, and while readline usually swallows the CR, a leftover + * one must never leak into a path (safe on every platform — a POSIX file + * whose name ends in CR is pathological). */ +export function normalizeEnginePaths(lines: readonly string[], separator: string = sep): string[] { + const out: string[] = [] + for (const line of lines) { + if (line === '') continue + const trimmed = line.endsWith('\r') ? line.slice(0, -1) : line + if (trimmed === '') continue + // A leading '.\' becomes './' after the separator substitution below; + // the './' prefix strip then covers both POSIX and Windows output. + const normalized = trimmed.split(separator).join('/') + const clean = normalized.startsWith('./') ? normalized.slice(2) : normalized + if (clean !== '' && clean !== '.') out.push(clean) + } + return out +} + +/** The fd argv: the query as a literal substring, every SKIP_DIR_NAMES + * excluded (a bare name excludes the entry at any depth; a worktree-style + * `.git` FILE is covered too — verified against real fd), '/' separators + * pinned, and --max-results one ABOVE the stream sentinel (cap + 1) so a + * full result set overflows into the same truncation detected for rg + * (see runChild). Directory matches are read from a second invocation + * (`type: 'd'`, see runChild) because fd cannot label its matches. */ +export function fdArgv(cap: number, query: string, type?: 'd'): string[] { + return [ + '--hidden', '--no-ignore', + ...SKIP_DIR_NAMES.flatMap(name => ['--exclude', name]), + '--fixed-strings', '--ignore-case', + ...(type === undefined ? [] : ['--type', type]), + '--path-separator', '/', '--max-results', String(cap + 1), query, '.', + ] +} + +/** The rg argv: --files listing filtered by a case-insensitive literal-name + * glob, '/' separators pinned (rg emits '\' in cmd/PowerShell on Windows, + * '/' in Git Bash — rg#501; the flag exists since rg 0.8, a build without + * it fails at spawn and is disabled at runtime). Every SKIP_DIR_NAME gets + * a glob pair: a '-anywhere' glob prunes the directory tree, and the second + * entry-only glob excludes an entry NAMED the skip word itself — a git + * worktree has a `.git` FILE (not a directory) at its root, and the + * directory-exclusion glob requires a path segment AFTER the word so it + * does not cover the pointer file (verified against real rg). fd's + * --exclude and the plain walk both skip it without the extra glob. */ +export function rgArgv(query: string): string[] { + const skipGlobs = SKIP_DIR_NAMES.flatMap(name => [ + '--iglob', `!**/${name}/**`, + '--iglob', `!**/${name}`, + ]) + const escaped = escapeGlob(query) + return [ + '--files', '--hidden', '--no-ignore', + ...skipGlobs, + // Three query globs. The slash-free form matches BASENAMES only (rg + // follows gitignore semantics — no '/' in the pattern means basename + // match, verified on real rg 15: 'util/helper.ts' never matches + // '*util*'). The other two admit files whose PATH carries a matching + // segment, so deriveRgMatches can turn that into the directory match the + // walk/fd contract reports: one '/*' level catches a DIRECT child + // ('util/helper.ts' — the most common hit), '**' catches everything + // deeper. Both are needed: '**' alone skips the direct child, '/*' + // alone skips the nested one (verified against real rg 15). + '--iglob', `*${escaped}*`, + '--iglob', `**/*${escaped}*/*`, + '--iglob', `**/*${escaped}*/**`, + '--path-separator', '/', + '.', + ] +} + +/** rg reports FILES only (`rg --files` never emits a directory line), while + * the walk contract matches entry names — files AND directories. Every rg + * line is a file path whose glob already guarantees the query appears + * somewhere in it, so: a basename hit stays a file match, and a matching + * DIRECTORY segment is derived as a directory match (a directory named X + * holding at least one file surfaces exactly as fd/walk report it). + * EMPTY directories stay invisible to rg — no file path carries them — + * the one gap left versus fd and the walk. Both lists are sorted and + * capped at the same sentinel (maxMatches + 1, the caller slices back and + * re-derives the directory subset from what it keeps, so `dirs` stays a + * subset of `matches`); `truncated` is raised when the derived set exceeded + * the budget — the budget, not the engine, cut the result short (runChild + * ORs it with the stream's own sentinel). */ +export function deriveRgMatches( + paths: readonly string[], + query: string, + maxMatches: number, +): { paths: string[]; dirs: string[]; truncated: boolean } { + const needle = query.toLowerCase() + const files = new Set() + const dirs = new Set() + for (const path of paths) { + const segments = path.split('/') + const base = segments[segments.length - 1] + if (base !== undefined && base.toLowerCase().includes(needle)) files.add(path) + let prefix = '' + for (let index = 0; index < segments.length - 1; index += 1) { + const segment = segments[index] + if (segment === undefined) continue + prefix = prefix === '' ? segment : `${prefix}/${segment}` + if (segment.toLowerCase().includes(needle)) dirs.add(prefix) + } + } + const derived = [...new Set([...files, ...dirs])].sort() + return { + paths: derived.slice(0, maxMatches + 1), + dirs: [...dirs].sort().slice(0, maxMatches + 1), + truncated: derived.length > maxMatches, + } +} + +/** One child invocation per engine, emitting normalized relative paths. + * fd needs two runs to fill the walk contract: the plain literal match (both + * files and directories — the walk's own shape) and a `--type d` run for the + * directory subset. rg's query globs admit basename hits AND files under + * matching directories; deriveRgMatches converts the latter into the + * directory matches the walk contract reports and drops nothing else. + * + * Truncation symmetry: `streamLines` marks truncated when the stream + * exceeds `cap = maxMatches + 1` lines (the +1 is a sentinel proving + * "there is more"). rg has no --max-results so it naturally overflows + * into the sentinel; fd MUST NOT cap at `cap` (it would stop exactly at + * the sentinel and never be seen as truncated) — pin its --max-results + * one higher (maxMatches + 2) so a full result set trips the same + * sentinel and both engines report truncated identically, with the + * caller slicing back to maxMatches. */ +function runChild( + probe: EngineProbe, + root: string, + query: string, + maxMatches: number, +): Promise { + const cap = maxMatches + 1 + if (probe.engine === 'rg') { + const child = spawn(probe.binary, rgArgv(query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + return streamLines(child, cap).then(({ lines, truncated }) => { + const derived = deriveRgMatches(normalizeEnginePaths(lines), query, maxMatches) + return { paths: derived.paths, dirs: derived.dirs, truncated: truncated || derived.truncated } + }) + } + const child = spawn(probe.binary, fdArgv(cap, query), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + const dirChild = spawn(probe.binary, fdArgv(cap, query, 'd'), { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }) + return Promise.all([ + streamLines(child, cap), + // Only the directory subset is kept: fd already labels it, and its + // truncation must not affect the match list's own sentinel. + streamLines(dirChild, cap).catch(() => ({ lines: [], truncated: false })), + ]).then(([matches, dirs]) => { + const paths = normalizeEnginePaths(matches.lines) + const dirSet = new Set(normalizeEnginePaths(dirs.lines)) + return { + paths, + dirs: paths.filter(path => dirSet.has(path)), + truncated: matches.truncated, + } + }) +} + +let prober = (): Promise => probeOnce() +let runner = runChild +/** Engines failed at runtime: skipped for the rest of this process. */ +const broken = new Set() +let probePromise: Promise | null = null + +/** Probe once per process (lazy): each engine's first working candidate. */ +async function probeOnce(): Promise { + const found: EngineProbe[] = [] + for (const engine of ['fd', 'rg'] as const) { + for (const binary of candidates(engine)) { + if (await verify(binary)) { + found.push({ engine, binary }) + break + } + } + } + const names = found.length > 0 ? found.map(p => `${p.engine}(${p.binary})`).join(', ') : 'none (plain-walk fallback)' + debugLog(`[dsh-search] engines probed: ${names}`) + return found +} + +/** The verified engines for this process (cached across searches). */ +export function probeEngines(): Promise { + probePromise ??= prober() + return probePromise +} + +/** Run one engine and get capped, normalized matches; a runtime failure + * disables that engine for the rest of the process (a broken binary must + * not slow every later search) — but a TIMEOUT does not: a timeout means + * THIS tree was too big, while the broken-set is per-engine, so disabling + * here would strip every other (small) root of the engine over one huge + * directory. */ +export async function runEngine( + probe: EngineProbe, + root: string, + query: string, + maxMatches: number, +): Promise { + try { + return await runner(probe, root, query, maxMatches) + } catch (error) { + if (error instanceof EngineTimeoutError) { + debugLog(`[dsh-search] engine ${probe.engine} timed out (tree too large), falling back`) + } else { + broken.add(probe.engine) + debugLog(`[dsh-search] engine ${probe.engine} failed at runtime, disabled: ${error instanceof Error ? error.message : String(error)}`) + } + throw error + } +} + +/** The engines a caller may actually try (verified, not broken). */ +export async function usableEngines(): Promise { + const probes = await probeEngines() + return probes.filter((probe) => !broken.has(probe.engine)) +} + +/** Test seam: replace the probe / child-runner implementations. */ +export function setEngineHooks(next: { prober?: typeof prober; runner?: typeof runner }): void { + if (next.prober !== undefined) prober = next.prober + if (next.runner !== undefined) runner = next.runner +} + +/** Reset probe cache, broken-set and hooks (test isolation). */ +export function resetEngines(): void { + probePromise = null + broken.clear() + prober = (): Promise => probeOnce() + runner = runChild +} diff --git a/tests/fs-search.spec.ts b/tests/fs-search.spec.ts index 515bdfe2..8a6a1f08 100644 --- a/tests/fs-search.spec.ts +++ b/tests/fs-search.spec.ts @@ -4,13 +4,18 @@ * RELATIVE to the root ('/'-separated); noise directories (`.git`, * `node_modules`, build caches) are skipped, symlinked directories are * never descended (cycle safety), and the maxMatches/maxVisited budgets - * stop a runaway walk with `truncated: true`. + * stop a runaway walk with `truncated: true`. `searchFiles` is the dispatch + * the route calls (native engines first, this walk as fallback) — the walk + * itself is pinned directly as `searchFilesPlain`, and the dispatch cases + * below inject fake engines so no machine binary is required. */ -import { describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { searchFiles } from '../src/fs-search.ts' +import { searchFiles, searchFilesPlain } from '../src/fs-search.ts' +import type { EngineProbe } from '../src/search-engines.ts' +import { resetEngines, setEngineHooks } from '../src/search-engines.ts' /** * Symlink creation needs extra privileges on Windows; the symlink case skips @@ -45,13 +50,24 @@ function makeFixture(): string { } describe('fs-search', () => { + // The walk is pinned directly; the dispatch is exercised in its own block + // below with injected engines. This hook keeps any accidental probe out of + // these cases (CI has no fd, real machines may). + beforeEach(() => { + setEngineHooks({ prober: async () => [] }) + }) + + afterEach(() => { + resetEngines() + }) + it('matches name substrings and reports root-relative /-separated paths', async () => { const dir = makeFixture() try { - const result = await searchFiles(dir, 'util') + const result = await searchFilesPlain(dir, 'util') expect(result).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) // A multi-level match list is sorted and relative (never absolute). - const md = await searchFiles(dir, '.md') + const md = await searchFilesPlain(dir, '.md') expect(md.truncated).toBe(false) expect(md.matches).toEqual(['README.md', 'docs/guide.md']) for (const match of md.matches) { @@ -66,15 +82,15 @@ describe('fs-search', () => { it('matches case-insensitively on the entry name', async () => { const dir = makeFixture() try { - expect((await searchFiles(dir, 'index.ts')).matches).toEqual(['src/Index.TS']) - expect((await searchFiles(dir, 'INDEX.TS')).matches).toEqual(['src/Index.TS']) - const dirHit = await searchFiles(dir, 'SRC') + expect((await searchFilesPlain(dir, 'index.ts')).matches).toEqual(['src/Index.TS']) + expect((await searchFilesPlain(dir, 'INDEX.TS')).matches).toEqual(['src/Index.TS']) + const dirHit = await searchFilesPlain(dir, 'SRC') // Directory names match too (the client can hint where matches live)… expect(dirHit.matches).toEqual(['src']) // …and they are reported as directories, so the list navigates the tree // instead of opening one as a file (`fs.read` refuses a directory). expect(dirHit).toEqual({ matches: ['src'], dirs: ['src'], truncated: false }) - expect((await searchFiles(dir, 'util')).dirs).toEqual([]) + expect((await searchFilesPlain(dir, 'util')).dirs).toEqual([]) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -84,9 +100,25 @@ describe('fs-search', () => { const dir = makeFixture() try { // 'readme' would hit .git/objects/readme-pack if the walk entered .git. - expect((await searchFiles(dir, 'readme')).matches).toEqual(['README.md']) - expect((await searchFiles(dir, 'config')).matches).toEqual([]) - expect((await searchFiles(dir, '.git')).matches).toEqual([]) + expect((await searchFilesPlain(dir, 'readme')).matches).toEqual(['README.md']) + expect((await searchFilesPlain(dir, 'config')).matches).toEqual([]) + expect((await searchFilesPlain(dir, '.git')).matches).toEqual([]) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + // A git worktree carries a `.git` FILE (a pointer to the real gitdir), not + // a directory. It is VCS-internal noise exactly like the .git directory and + // must never surface as a match — parity with fd's --exclude .git and rg's + // '!**/.git' glob pair. + it('never matches a worktree-style .git file', async () => { + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-search-')) + try { + writeFileSync(join(dir, '.git'), 'gitdir: /elsewhere/.git/worktrees/wt') + writeFileSync(join(dir, 'util.ts'), 'code') + expect(await searchFilesPlain(dir, '.git')).toEqual({ matches: [], dirs: [], truncated: false }) + expect((await searchFilesPlain(dir, 'util')).matches).toEqual(['util.ts']) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -102,12 +134,12 @@ describe('fs-search', () => { writeFileSync(join(dir, 'web', 'app.ts'), 'src') // A match hidden behind node_modules / dist must not appear; project // files after those forests must still be reachable within budget. - expect((await searchFiles(dir, 'guide')).matches).toEqual(['docs/guide.md']) - expect((await searchFiles(dir, 'left-pad')).matches).toEqual([]) - expect((await searchFiles(dir, 'bundle')).matches).toEqual([]) - expect((await searchFiles(dir, 'app.ts')).matches).toEqual(['web/app.ts']) - expect((await searchFiles(dir, 'node_modules')).matches).toEqual([]) - expect((await searchFiles(dir, 'dist')).matches).toEqual([]) + expect((await searchFilesPlain(dir, 'guide')).matches).toEqual(['docs/guide.md']) + expect((await searchFilesPlain(dir, 'left-pad')).matches).toEqual([]) + expect((await searchFilesPlain(dir, 'bundle')).matches).toEqual([]) + expect((await searchFilesPlain(dir, 'app.ts')).matches).toEqual(['web/app.ts']) + expect((await searchFilesPlain(dir, 'node_modules')).matches).toEqual([]) + expect((await searchFilesPlain(dir, 'dist')).matches).toEqual([]) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -116,8 +148,8 @@ describe('fs-search', () => { it('an empty (or whitespace) query matches nothing without walking', async () => { const dir = makeFixture() try { - expect(await searchFiles(dir, '')).toEqual({ matches: [], dirs: [], truncated: false }) - expect(await searchFiles(dir, ' ')).toEqual({ matches: [], dirs: [], truncated: false }) + expect(await searchFilesPlain(dir, '')).toEqual({ matches: [], dirs: [], truncated: false }) + expect(await searchFilesPlain(dir, ' ')).toEqual({ matches: [], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -130,7 +162,7 @@ describe('fs-search', () => { // src would duplicate its matches. Neither must be entered. symlinkSync(dir, join(dir, 'loop')) symlinkSync(join(dir, 'src'), join(dir, 'src-link')) - const result = await searchFiles(dir, 'util') + const result = await searchFilesPlain(dir, 'util') expect(result).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) @@ -144,11 +176,11 @@ describe('fs-search', () => { symlinkSync(join(dir, 'README.md'), join(dir, 'readme-link.md')) // `fs.read` stats through the link, so a link to a directory must be // reported as a directory row too; a link to a file stays a file hit. - expect(await searchFiles(dir, 'src-link')).toEqual({ matches: ['src-link'], dirs: ['src-link'], truncated: false }) - expect(await searchFiles(dir, 'readme-link')).toEqual({ matches: ['readme-link.md'], dirs: [], truncated: false }) + expect(await searchFilesPlain(dir, 'src-link')).toEqual({ matches: ['src-link'], dirs: ['src-link'], truncated: false }) + expect(await searchFilesPlain(dir, 'readme-link')).toEqual({ matches: ['readme-link.md'], dirs: [], truncated: false }) // A dangling link cannot be classified, so it stays a plain entry. symlinkSync(join(dir, 'gone'), join(dir, 'dangling-link')) - expect(await searchFiles(dir, 'dangling-link')).toEqual({ matches: ['dangling-link'], dirs: [], truncated: false }) + expect(await searchFilesPlain(dir, 'dangling-link')).toEqual({ matches: ['dangling-link'], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -160,7 +192,7 @@ describe('fs-search', () => { for (let index = 0; index < 5; index += 1) { writeFileSync(join(dir, `match-${index}.txt`), 'x') } - const result = await searchFiles(dir, 'match', { maxMatches: 2 }) + const result = await searchFilesPlain(dir, 'match', { maxMatches: 2 }) expect(result.truncated).toBe(true) expect(result.matches.length).toBe(2) } finally { @@ -175,7 +207,7 @@ describe('fs-search', () => { writeFileSync(join(dir, `file-${index}.txt`), 'x') } // The walk visits more entries than the budget allows and gives up. - const result = await searchFiles(dir, 'nomatch', { maxVisited: 3 }) + const result = await searchFilesPlain(dir, 'nomatch', { maxVisited: 3 }) expect(result.truncated).toBe(true) expect(result.matches).toEqual([]) } finally { @@ -187,7 +219,130 @@ describe('fs-search', () => { const dir = makeFixture() try { const missing = join(dir, 'does-not-exist') - expect(await searchFiles(missing, 'x')).toEqual({ matches: [], dirs: [], truncated: false }) + expect(await searchFilesPlain(missing, 'x')).toEqual({ matches: [], dirs: [], truncated: false }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +/** The fs.search dispatch: engine-first with the plain walk as fallback. */ +describe('fs-search dispatch', () => { + const fakeFd: EngineProbe = { engine: 'fd', binary: '/fake/fd' } + + afterEach(() => { + resetEngines() + }) + + it('routes to the probed engine and normalizes its output', async () => { + setEngineHooks({ + prober: async () => [fakeFd], + runner: async (_probe, _root, query) => { + expect(query).toBe('util') + // The engine contract already carries the dirs split. + return { paths: ['src/util.ts', 'README.md'], dirs: [], truncated: false } + }, + }) + expect(await searchFiles('/workspace', 'util')).toEqual({ + matches: ['README.md', 'src/util.ts'], + dirs: [], + truncated: false, + }) + }) + + // The dispatch must hand the engine the CALLER's budgets, not its own + // defaults: the route's maxMatches is what caps the flat list. + it('passes the caller budgets through to the engine', async () => { + let seen: number | undefined + setEngineHooks({ + prober: async () => [fakeFd], + runner: async (_probe, _root, _query, maxMatches) => { + seen = maxMatches + return { paths: [], dirs: [], truncated: false } + }, + }) + await searchFiles('/workspace', 'util', { maxMatches: 7 }) + expect(seen).toBe(7) + }) + + // #801: a directory hit must reach the client in `dirs` (it navigates the + // tree) instead of being opened as a file. The engine output supplies the + // split, and it has to survive the dispatch verbatim. + it('forwards directory hits so the client navigates instead of opening them', async () => { + setEngineHooks({ + prober: async () => [fakeFd], + runner: async () => ({ paths: ['src', 'src/util.ts'], dirs: ['src'], truncated: false }), + }) + expect(await searchFiles('/workspace', 'util')).toEqual({ + matches: ['src', 'src/util.ts'], + dirs: ['src'], + truncated: false, + }) + }) + + it('an empty query never touches the engines', async () => { + let probed = false + setEngineHooks({ + prober: async () => { probed = true; return [fakeFd] }, + runner: async () => ({ paths: [], dirs: [], truncated: false }), + }) + expect(await searchFiles('/workspace', ' ')).toEqual({ matches: [], dirs: [], truncated: false }) + expect(probed).toBe(false) + }) + + it('caps engine output at maxMatches and reports truncated', async () => { + setEngineHooks({ + prober: async () => [fakeFd], + runner: async () => ({ paths: ['a', 'b', 'c'], dirs: [], truncated: true }), + }) + expect(await searchFiles('/workspace', 'x', { maxMatches: 2 })).toEqual({ + matches: ['a', 'b'], + dirs: [], + truncated: true, + }) + }) + + // The engine's cap is a sentinel (maxMatches + 1), so a truncated run can + // carry a directory row the slice just dropped. `dirs` is the DIRECTORY + // SUBSET of `matches` (TreePanel's `dirHits` lookup depends on it), so the + // dispatch re-derives it from what it kept. + it('never reports a directory that the match slice dropped', async () => { + setEngineHooks({ + prober: async () => [fakeFd], + runner: async () => ({ paths: ['a-dir', 'a-file', 'b'], dirs: ['a-dir', 'b'], truncated: true }), + }) + expect(await searchFiles('/workspace', 'x', { maxMatches: 2 })).toEqual({ + matches: ['a-dir', 'a-file'], + dirs: ['a-dir'], + truncated: true, + }) + }) + + it('falls back to the plain walk when the engine fails at runtime', async () => { + const dir = makeFixture() + try { + setEngineHooks({ + prober: async () => [fakeFd], + runner: async () => { throw new Error('engine exploded') }, + }) + expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) + // The failed engine is disabled for the rest of the process. + let attempts = 0 + setEngineHooks({ + runner: async () => { attempts += 1; return { paths: [], dirs: [], truncated: false } }, + }) + expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) + expect(attempts).toBe(0) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it('uses the plain walk when no engine is probed', async () => { + const dir = makeFixture() + try { + setEngineHooks({ prober: async () => [] }) + expect(await searchFiles(dir, 'util')).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } diff --git a/tests/search-engines.spec.ts b/tests/search-engines.spec.ts new file mode 100644 index 00000000..c89e3ffe --- /dev/null +++ b/tests/search-engines.spec.ts @@ -0,0 +1,449 @@ +/** + * search-engines: the native-engine probe and runner behind fs.search. + * The probe is process-cached (verified binaries only); a runtime failure + * disables one engine without disturbing the others, while a TIMEOUT only + * degrades that one search. `normalizeEnginePaths` re-bases raw stdout lines + * onto the walk contract (root-relative, '/'-separated, no './' prefix) and + * `deriveRgMatches` supplies the directory hits `rg --files` cannot report. + * Child processes are exercised entirely through injected hooks — CI + * machines have no fd (and only sometimes rg), and the probe/runner contracts + * are what the dispatch depends on. + */ +import { afterEach, describe, expect, it } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { searchFiles } from '../src/fs-search.ts' +import { + bundledRgCandidates, + deriveRgMatches, + EngineTimeoutError, + escapeGlob, + fdArgv, + normalizeEnginePaths, + probeEngines, + resetEngines, + rgArgv, + runEngine, + setEngineHooks, + SKIP_DIR_NAMES, + usableEngines, +} from '../src/search-engines.ts' +import type { EngineProbe } from '../src/search-engines.ts' + +const fdProbe: EngineProbe = { engine: 'fd', binary: '/fake/fd' } +const rgProbe: EngineProbe = { engine: 'rg', binary: '/fake/rg' } + +describe('normalizeEnginePaths', () => { + it('keeps root-relative /-separated lines as-is (fd contract)', () => { + expect(normalizeEnginePaths(['src/util.ts', 'README.md'])).toEqual([ + 'src/util.ts', + 'README.md', + ]) + }) + + it('strips a leading ./ from engine output', () => { + expect(normalizeEnginePaths(['./src/a.ts', './b.ts'])).toEqual([ + 'src/a.ts', + 'b.ts', + ]) + }) + + it('drops empty lines and the bare root', () => { + expect(normalizeEnginePaths(['', '.', 'src/x.ts'])).toEqual(['src/x.ts']) + }) + + // Windows shape (rg emits '\'-separated paths with a '.\' prefix and CRLF + // line endings): all of it must still land on the '/'-separated walk contract. + it('normalizes Windows engine output: backslash separators + .\\ prefix (rg shape)', () => { + expect(normalizeEnginePaths(['src\\util.ts', '.\\README.md'], '\\')).toEqual([ + 'src/util.ts', + 'README.md', + ]) + }) + + it('strips a trailing CR from engine lines (Windows CRLF endings)', () => { + expect(normalizeEnginePaths(['src/util.ts\r', './b.ts\r'])).toEqual([ + 'src/util.ts', + 'b.ts', + ]) + // Same protection applies to the Windows shape. + expect(normalizeEnginePaths(['src\\util.ts\r', '.\\docs\\guide.md\r'], '\\')).toEqual([ + 'src/util.ts', + 'docs/guide.md', + ]) + }) +}) + +describe('deriveRgMatches', () => { + // rg --files never emits a directory line: a matching DIRECTORY segment + // must be derived from the file path so rg-only machines see the same + // results as fd / the plain walk (which both report directory names). + it('keeps basename hits and derives matching directory segments', () => { + expect(deriveRgMatches( + ['src/util.ts', 'util/helper.ts', 'web/dist/bundle.js'], + 'util', + 10, + )).toEqual({ paths: ['src/util.ts', 'util'], dirs: ['util'], truncated: false }) + }) + + // fs-search's contract: dirs is the DIRECTORY SUBSET of matches — the + // client navigates those rows instead of opening them as files. + it('reports every derived directory as a subset of the matches', () => { + const result = deriveRgMatches(['a/util/x.ts', 'b/util/y.ts'], 'util', 10) + expect(result.paths).toEqual(['a/util', 'b/util']) + expect(result.dirs).toEqual(['a/util', 'b/util']) + for (const dir of result.dirs) expect(result.paths).toContain(dir) + }) + + // The direct-child shape ('util/helper.ts') is the most common one there + // is: its directory must be derived, not only the deeper nesting. + it('derives a directory that holds the matching file directly', () => { + expect(deriveRgMatches(['util/helper.ts'], 'util', 10)).toEqual({ + paths: ['util'], + dirs: ['util'], + truncated: false, + }) + }) + + it('dedupes repeated matching segments across lines', () => { + expect(deriveRgMatches(['lib/a/x.ts', 'lib/a/y.ts'], 'lib', 10)).toEqual({ + paths: ['lib'], + dirs: ['lib'], + truncated: false, + }) + }) + + it('matches case-insensitively (walk parity)', () => { + expect(deriveRgMatches(['SRC/Util.ts'], 'UTIL', 10)).toEqual({ + paths: ['SRC/Util.ts'], + dirs: [], + truncated: false, + }) + }) + + it('caps the derived set at maxMatches + 1 and raises truncated', () => { + // 4 derived entries ('a' + 3 files) over a budget of 2: the budget, not + // the engine, cut the result short — same sentinel semantics as the + // fd/rg stream (cap = maxMatches + 1, caller slices back). + expect(deriveRgMatches(['a/a1', 'a/a2', 'a/a3'], 'a', 2)).toEqual({ + paths: ['a', 'a/a1', 'a/a2'], + dirs: ['a'], + truncated: true, + }) + }) + + // Both lists carry the same sentinel cap, so a truncated run never hands + // the caller an unbounded directory list; the dispatch slices `paths` back + // to maxMatches and re-derives `dirs` from what it kept (see the + // fs-search dispatch cases). + it('caps dirs at the same sentinel as paths', () => { + const result = deriveRgMatches(['a1/x', 'a2/x', 'a3/x'], 'a', 1) + // Here every hit is the derived directory itself ('x' carries no 'a'), + // so the sorted union is a1, a2, a3 — the sentinel keeps two. + expect(result.paths).toEqual(['a1', 'a2']) + expect(result.dirs).toEqual(['a1', 'a2']) + expect(result.truncated).toBe(true) + }) + + it('derives both the directory and the basename hit from one line', () => { + // 'util/util.ts': basename hit keeps the file, the 'util' segment + // derives the directory — runChild ORs this with the stream's own + // truncation flag (a stream-truncated run with a small derived set + // stays true). + expect(deriveRgMatches(['util/util.ts'], 'util', 10)).toEqual({ + paths: ['util', 'util/util.ts'], + dirs: ['util'], + truncated: false, + }) + }) +}) + +describe('escapeGlob', () => { + it('escapes glob metacharacters for rg -g literal matching', () => { + expect(escapeGlob('a*b?c[d]')).toBe('a\\*b\\?c\\[d\\]') + }) + + // '{' is globset alternation syntax: unbalanced it breaks the glob parse + // (rg exits 2 → the engine looks broken and gets disabled process-wide), + // balanced 'a{b}' silently searches 'ab' instead of the literal. Both + // verified against real rg 15; '\{' is the accepted escape. + it('escapes braces so alternation syntax cannot hijack a literal query', () => { + expect(escapeGlob('a{b}')).toBe('a\\{b\\}') + expect(escapeGlob('{')).toBe('\\{') + expect(escapeGlob('util{bar')).toBe('util\\{bar') + }) +}) + +describe('engine argv symmetry', () => { + it('fd --max-results sits one ABOVE the sentinel (cap + 1) so full result sets trip truncation', () => { + // cap = maxMatches + 1 is the stream sentinel: the runner marks + // truncated when a line arrives past it. fd must not stop AT the + // sentinel (never seen as truncated) — it caps one line higher. + const argv = fdArgv(201, 'util') + expect(argv).toContain('--max-results') + expect(argv[argv.indexOf('--max-results') + 1]).toBe('202') + expect(argv).toContain('--fixed-strings') + expect(argv).toContain('--path-separator') + }) + + it('fd argv keeps the literal-fixed, hidden, no-ignore contract', () => { + const argv = fdArgv(10, 'a*b') + expect(argv.slice(0, 2)).toEqual(['--hidden', '--no-ignore']) + expect(argv).toContain('--fixed-strings') + expect(argv).toContain('--ignore-case') + expect(argv).toContain('--path-separator') + expect(argv).toContain('/') + expect(argv[argv.length - 2]).toBe('a*b') // literal, unescaped + expect(argv[argv.length - 1]).toBe('.') + }) + + // fd cannot label its matches, so the directory subset comes from a second + // invocation restricted to directories. The filter must not disturb the + // sentinel/truncation contract of the main run. + it('fd --type d marks the directory-only invocation', () => { + const argv = fdArgv(10, 'util', 'd') + expect(argv[argv.indexOf('--type') + 1]).toBe('d') + expect(argv).toContain('--max-results') + // The plain invocation carries no --type at all. + expect(fdArgv(10, 'util')).not.toContain('--type') + }) + + // --no-ignore bypasses .gitignore: without explicit excludes the engines + // would re-enter node_modules etc. and regress the walk's budget savings. + // fd excludes each skip name at any depth (incl. a worktree .git FILE); + // rg needs the directory glob + entry-only glob pair per name. + it('fd and rg exclude every SKIP_DIR_NAMES entry (walk parity)', () => { + const fd = fdArgv(10, 'util') + const fdExcludes: (string | undefined)[] = [] + for (let index = 0; index < fd.length; index += 1) { + if (fd[index] === '--exclude') fdExcludes.push(fd[index + 1]) + } + expect(fdExcludes).toEqual([...SKIP_DIR_NAMES]) + + const rg = rgArgv('util') + const rgIglobs: (string | undefined)[] = [] + for (let index = 0; index < rg.length; index += 1) { + if (rg[index] === '--iglob') rgIglobs.push(rg[index + 1]) + } + for (const name of SKIP_DIR_NAMES) { + expect(rgIglobs).toContain(`!**/${name}/**`) + expect(rgIglobs).toContain(`!**/${name}`) + } + // The query iglobs are the last ones (skip globs precede them), still + // case-insensitive and escaped: basename form + both path-level forms. + expect(rgIglobs.slice(-3)).toEqual(['*util*', '**/*util*/*', '**/*util*/**']) + }) + + // rg's path-level globs decide which DIRECTORY hits are derivable at all: + // '**' alone misses a direct child ('util/helper.ts' — the most common + // shape there is), '/*' alone misses everything deeper. Both are pinned + // here because dropping either silently loses directory matches on + // rg-only machines (verified against real rg 15). + it('rg argv carries both path-level globs (direct child + any depth)', () => { + const argv = rgArgv('util') + expect(argv).toContain('**/*util*/*') + expect(argv).toContain('**/*util*/**') + }) + + it('rg argv escapes glob metacharacters and pins / separators', () => { + const argv = rgArgv('a*b') + expect(argv).toContain('--files') + expect(argv).toContain('--path-separator') + expect(argv[argv.indexOf('--path-separator') + 1]).toBe('/') + expect(argv).toContain('*a\\*b*') + expect(argv[argv.length - 1]).toBe('.') + }) + + // A git worktree has a `.git` FILE at its root: '!**/.git/**' needs a + // path segment AFTER .git, so the pointer file itself leaks through + // (verified against real rg). fd's --exclude .git covers both shapes; + // rg needs the second entry-only glob for parity. + it('rg argv excludes .git directories AND a bare worktree .git file', () => { + const argv = rgArgv('util') + expect(argv).toContain('--iglob') + expect(argv).toContain('!**/.git/**') + expect(argv).toContain('!**/.git') + }) +}) + +describe('bundledRgCandidates', () => { + // npm/pnpm hoist @vscode/ripgrep-- NEXT TO @deepseek-ai, + // never under @deepseek-ai/dsh/node_modules — the derivation must point at + // the package-manager root that really holds the binary. + it('derives the POSIX npm global layout from execPath (darwin)', () => { + const paths = bundledRgCandidates( + 'darwin', 'arm64', + '/opt/homebrew/bin/node', + {}, '/Users/me', undefined, + ) + expect(paths).toContain(join( + '/opt/homebrew/lib/node_modules', + '@vscode/ripgrep-darwin-arm64/bin/rg', + )) + }) + + // A tree that did NOT hoist (pnpm's strict layout) keeps the platform + // package under the CLI's own node_modules — still a candidate. + it('also covers the non-hoisted /@deepseek-ai/dsh/node_modules layout', () => { + const paths = bundledRgCandidates('darwin', 'arm64', '/usr/local/bin/node', {}, '/Users/me', undefined) + expect(paths).toContain(join( + '/usr/local/lib/node_modules', + '@deepseek-ai/dsh/node_modules', + '@vscode/ripgrep-darwin-arm64/bin/rg', + )) + }) + + // The dependency tree that provided @deepseek-ai/dsh may sit at ANY + // node_modules level above the CLI entry — a bundled desktop shell's own + // tree, a checkout, a project-local install — even when the node running + // it lives elsewhere (Homebrew node + this repo's bundled tree). + it('walks every node_modules level above the CLI entry (argv[1])', () => { + const paths = bundledRgCandidates( + 'darwin', 'arm64', + '/opt/homebrew/Cellar/node/26.9.0/bin/node', + {}, '/Users/me', + '/Applications/Dsh.app/Contents/Resources/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', + ) + expect(paths).toContain(join( + '/Applications/Dsh.app/Contents/Resources/dsh/node_modules', + '@vscode/ripgrep-darwin-arm64/bin/rg', + )) + }) + + // Windows npm has NO lib/ layer: the global prefix is %APPDATA%\npm, so + // the execPath derivation used on POSIX would resolve to a bogus + // C:\lib\node_modules\… path. The probe itself must cover the real shape. + it('derives the Windows npm global layout from %APPDATA% (win32)', () => { + const paths = bundledRgCandidates( + 'win32', 'x64', + 'C:\\Program Files\\nodejs\\node.exe', + { APPDATA: 'C:\\Users\\me\\AppData\\Roaming' }, 'C:\\Users\\me', undefined, + ) + // join() renders the platform separator, so this also validates the + // real backslash shape on Windows CI. + expect(paths).toContain(join( + 'C:\\Users\\me\\AppData\\Roaming', 'npm', 'node_modules', + '@vscode', 'ripgrep-win32-x64', 'bin', 'rg.exe', + )) + }) + + it('covers the DSH profile layout under ~/.dsh on every platform', () => { + const darwin = bundledRgCandidates('darwin', 'arm64', '/usr/local/bin/node', {}, '/Users/me', undefined) + expect(darwin).toContain(join( + '/Users/me/.dsh/profiles/node_modules', + '@vscode', 'ripgrep-darwin-arm64', 'bin', 'rg', + )) + // Windows: node:path is platform-bound, so a test on POSIX cannot pin + // the exact backslash shape — assert the layout structure (a real + // Windows CI/true-positive run pins the literal '\\' separators). + const win = bundledRgCandidates('win32', 'x64', 'C:\\node.exe', {}, 'C:\\Users\\me', undefined) + expect(win.some(path => path.includes('.dsh') && path.includes('@vscode'))).toBe(true) + }) + + it('dedupes identical candidates across derivations', () => { + const paths = bundledRgCandidates( + 'darwin', 'arm64', + '/usr/local/bin/node', + {}, '/Users/me', undefined, + ) + // /usr/local/bin/node → /usr/local/lib/node_modules AND the fixed + // /usr/local/lib/node_modules root — the same file must appear once. + const duplicates = paths.filter((path, index) => paths.indexOf(path) !== index) + expect(duplicates).toEqual([]) + }) + + it('drops APPDATA roots when the env var is absent (win32)', () => { + const paths = bundledRgCandidates('win32', 'x64', 'C:\\node.exe', {}, 'C:\\Users\\me', undefined) + expect(paths.some(path => path.includes('AppData'))).toBe(false) + // The fixed profile root survives. + expect(paths.some(path => path.includes('.dsh'))).toBe(true) + }) +}) + +describe('probe cache and broken-disable', () => { + afterEach(() => { + resetEngines() + }) + + it('caches the probe result across calls', async () => { + let calls = 0 + setEngineHooks({ prober: async () => { calls += 1; return [fdProbe] } }) + expect(await probeEngines()).toBe(await probeEngines()) + expect(calls).toBe(1) + }) + + it('usableEngines hides engines broken at runtime', async () => { + setEngineHooks({ prober: async () => [fdProbe, rgProbe] }) + setEngineHooks({ + runner: async () => { throw new Error('boom') }, + }) + await runEngine(fdProbe, '/w', 'x', 10).catch(() => { + /* the failing runner above */ + }) + const usable = await usableEngines() + expect(usable.map(probe => probe.engine)).toEqual(['rg']) + }) + + // A timeout means THIS tree was too big — the broken-set is per-engine, + // so disabling here would strip every other root of the engine over one + // huge directory. The engine must stay usable after a timeout. + it('a timed-out run does not disable the engine', async () => { + setEngineHooks({ prober: async () => [fdProbe] }) + setEngineHooks({ + runner: async () => { throw new EngineTimeoutError('search engine timed out') }, + }) + await runEngine(fdProbe, '/huge-tree', 'x', 10).catch(() => { + /* expected failure */ + }) + expect((await usableEngines()).map(probe => probe.engine)).toEqual(['fd']) + }) +}) + +/** + * The REAL engines, when this machine has one (a CI runner usually has + * neither and only the injected-hook contracts above run — that is why this + * is a conditional block, not a fixture of the suite). It pins the properties + * the injected hooks cannot: the shipped argvs actually parse, the literals + * really are literal, the noise dirs really are excluded, and the directory + * subset survives the real stdout pipeline. + */ +describe('real engines (only when installed)', () => { + afterEach(() => { + resetEngines() + }) + + it('matches literals, splits dirs, skips noise when an engine is installed', async () => { + resetEngines() + const engines = await probeEngines() + if (engines.length === 0) return + const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-engine-real-')) + try { + mkdirSync(join(dir, 'src', 'util'), { recursive: true }) + // A DIRECT child of the matching directory (rg's '**/*util*/*' glob is + // what makes this one reachable at all). + mkdirSync(join(dir, 'web', 'comp-util'), { recursive: true }) + mkdirSync(join(dir, 'node_modules', 'util-dep'), { recursive: true }) + writeFileSync(join(dir, 'src', 'util', 'util-helper.ts'), 'x') + writeFileSync(join(dir, 'web', 'comp-util', 'component.tsx'), 'x') + writeFileSync(join(dir, 'node_modules', 'util-dep', 'index.js'), 'x') + // A '*' is a literal here (--fixed-strings for fd, escaped glob for + // rg): it must match the file that really contains it and nothing else. + writeFileSync(join(dir, 'a*b.ts'), 'x') + writeFileSync(join(dir, 'anb.ts'), 'x') + + // Directory hits are derived from the file paths (rg) or read from + // fd's directory listing: one nested match, one direct child, and the + // node_modules copy stays invisible either way. + const dirHit = await searchFiles(dir, 'util') + expect(dirHit.matches).toEqual(['src/util', 'src/util/util-helper.ts', 'web/comp-util']) + expect(dirHit.dirs).toEqual(['src/util', 'web/comp-util']) + expect(dirHit.truncated).toBe(false) + + const star = await searchFiles(dir, 'a*b') + expect(star.matches).toEqual(['a*b.ts']) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +})