@jayyuen66/dsh-zvec-grep 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,57 @@
2
2
 
3
3
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
4
4
 
5
+ ## 0.1.4
6
+
7
+ 把 **zg 守护进程(server 模式)这一档能力差从「使用限制」变成显式判据**:`--mode auto` 在 daemon 缺席时由上游静默落回 direct(模型逐次冷加载、增量刷新与 `refresh=background` 都不存在),而本包过去既没有一处说明,也没有拦住那个不可能兑现的参数。顺带修掉两处评审确认的缺陷:`requireApprovalForExplicitRoot` 会为**注定被拒**的 root 弹一次换不来放行的确认;两份 README 与 `host.ts` 头注释的配置面数字早已和 schema 脱节(14 vs 16、四个 vs 十枚)。
8
+
9
+ ### Added
10
+
11
+ - **守护进程就绪门槛(`createZgServerGate`)**:按 TTL(60 秒)缓存 `zg server status --check-ready` 的**退出码**(上游契约:就绪 0、未就绪以「zvec-grep server is not ready」非零退出;读 stdout 那份状态表不行,它给人看、不在本包的依赖契约里)。探测失败一律折成「未就绪」,**绝不外抛**基础设施故障,也绝不影响 `wait` / `off` / 穷举检索这些照常能用的通道。本包**不代为 `zg server on`**:那会在用户机器上落下 detached 长驻进程与 token 文件,属该由用户点头的动作。
12
+ - **`refresh=background` 收口(`BackgroundSupport` 三档)**:不可用时在**命令构造期**就拒,并区分两种成因各给一句诚实文案——守护进程缺席(出路是 `zg server on`)与部署把 `clientMode` 钉死 `direct`(此时叫用户起 daemon 是指错方向,出路是回行 config 改模式)。旧行为是让命令照发、由 zg 把刷新整个关掉、只留一行 stderr warning:退出码照旧 0、命中照旧出,唯独「后台在刷新」这件事是假的。判据只有 `backgroundSupportFor` 一处,模式与探测两步都由宿主算(纯构造器只按它折成拒绝);没人要这一档时不起探测,穷举通道也不起(它本就不接受 `refresh`)。
13
+ - **就绪态回显两处**:`zg_status` 的输出尾部各说一句(就绪讲能拿到什么,未就绪讲后果与出路),设置卡新增一行;重建期那条「合成投影」不补——它的契约本就是不启任何子进程。引导端点 `rebuild-roots` 的应答新增 `serverReady`,卡片判据收在可单测的 `daemonNoteKey`:应答里**没有这一位**(旧版 host)时不渲染,而不是把「不知道」显示成「未就绪」。
14
+ - **无 `Code:` 行的失败补一句 `--debug` 指引**:上游不带 `--debug` 时会把 `MODEL2VEC_DOWNLOAD_FAILED` 与 `INDEXING.FILES_FAILED` 塌成一句无码文案(首次下载 embedding 权重正落在这一档),而本包所有按码归因都读那一行 `Code:`。现在只有「非零退出、有输出、却没有 `Code:` 行」那一支补指引;空输出不补(谈不上「塌成一句」),带码的不补(归因本就够)。本包**不默认带** `--debug`:它明显拉长输出,而这三个工具的回显预算是给模型读的。
15
+ - **文档数字的门禁**:`test/readme-parity.test.ts` 新增一条,把中英两份声明的「字段总数 / 卡上 volatile 数 / 非 volatile 部署值数」与导出 `Config` 的实际形状逐一对齐(第三枚是可推导的:总数 - volatile)。原有的结构对等门只能抓到「一侧多了一节」,抓不到两侧一起写错——这次正是两侧一起错。
16
+
17
+ ### Fixed
18
+
19
+ - **`requireApprovalForExplicitRoot` 不再为注定被拒的调用发问**。旧判据是「显式 root 既不是会话工作区、也不在 ledger」,于是对 `/etc`、相对路径、盘上不存在、没有会话工作区可作参照这些 `rootOf` **一律拒**的调用也弹一次确认;用户点「允许一次」之后照样被拒(那道闸刻意只加不减),确认成了让人为一个无法兑现的承诺点按钮。现在发问判据与 `rootOf` **同源**:两者共用同一个 `judgeRoot`,只有「靠与会话工作区互为祖先/后代这一条才放行」的调用才发问。同时删掉 `sameAsSessionRoot` 那第二条判据(它比 `judgeRoot` 宽,正是漏问/误问两侧漂移的来源)。
20
+ - **search-first 门禁不再误拦「管道下游、只过滤上游输出」的 grep**。`isGrepRgCommand` 原先把命令位上的 grep/rg 一律判成检索,于是 `ps aux | grep node`、`env | grep KEY`、`dscacheutil -q host | grep ip_address`(实测被拦)这类**根本不读文件系统**的调用也被要求「先 zg_search」——门禁要建立的「已用语义检索定向」那条证据链对它无从谈起。现在 token 多带一档「是否由 `|` 喂入」(只有管道算,`;` 与 `&&` 之后的命令不算),管道下游那一支还要**后随实参里出现路径形状的操作数**(`/x`、`a/b`、`.`、`..`;旗标不算)才判为检索,带路径的管道调用照旧算。副作用方向是漏拦:`cat a.txt | grep foo` 因上游确实读了工作区文件而被放行,与 `hasExternalTarget` 的既有取舍同侧,代价由 systemPrompt 路由文本兜底。
21
+ - **`startBackgroundIndex` 不再构造哑值依赖**。它不是 HTTP 请求,过去要凑出 `RebuildRoutes` 就得给 `csrf` 塞空串、给 `servingNonLoopback` 塞 `false`——两个「没被用到」只靠下游恰好不读它们来保证的占位值。现在把起一条 `zg index` 写操作所需的依赖收窄成 `IndexWriteRoutes`(`RebuildRoutes extends` 它),哑值在类型上不再可能被构造出来。
22
+ - **删掉 `startBackgroundIndex` 那份重复的 JSDoc**:同一段 17 行文档在文件里出现两次,第二份悬在 `registerIndexTool` 头上,指向的却不是它下面那个函数。
23
+
24
+ ### Changed
25
+
26
+ - 引导端点 `/_dsh/zvec-grep/rebuild-roots` 的 handler 转为 async(就绪态要在**信任闸门与方法判定之后**才取,被拒的请求不起子进程)。官方 `WebRoute.handler` 本就允许 `void | Promise<void>`,另两条路由一直是 async 形态。
27
+ - `buildSearchCommand` 新增第五位 `backgroundSupport`(缺省 `daemon-down`:拿不到判据时保守拒绝,而不是把一句假话发给模型);`lib/cli.ts` 导出 `requestsBackgroundRefresh` 供宿主判「要不要探」。
28
+ - 两份 README:`--mode direct` 的过时说法改成按实现的 `auto` 口径并新增「守护进程(server 模式)」一节;配置面数字改成 16 / 6 / 10;`refresh` 与 `requireApprovalForExplicitRoot` 两节跟着上面的行为重写;`host.ts` 头注释同样对齐。
29
+ - 集成层新增一条按环境自适应的用例:`clientMode=auto` 时断言跟着**这台机器上守护进程的真实就绪态**给期望值(无条件式断言,不分支),另有一条钉死 `clientMode=direct` 时「命令根本没发出去」。
30
+
31
+ ## 0.1.3
32
+
33
+ 修复一处**跟着真实宿主语义失效的作业身份判据**(它让重建轮询恒 404、卸载只杀进程不摘作业 ⇒ 官方环缓冲留在宿主内存),并给 `ignoreFiles` 补上起进程之前的**存在性 + 可读性**预检(一条读不成的忽略文件会永久弄坏整棵工作区索引)。测试面从「单测 + mock 宿主」扩到三层:新增真宿主半栈的集成层与直怼真 zg CLI 的点对点层。
34
+
35
+ ### Fixed
36
+
37
+ - **作业身份改用投影值,不再比注册表实例引用**。旧 `sameJob` 的一半判据是 `state.owner === ctx.get("jobs")`,而真实 cordis 每读一次服务都新建一枚 traceable 代理 ⇒ 同一枚注册表的两次读也不 `===`,该判据在真实宿主上**恒为假**(mock 上下文里恒真,故单测全绿、线上全崩)。后果有三:轮询端点对每条活着的重建恒回 404;卸载 / 超时臂只 `killProc` 而从不 `jobs.remove` ⇒ 官方环缓冲留在宿主内存里(内存泄露);「同根第二条启动复用在跑那条」的 follow 恒不生效。现改用官方 `JobView` 上三段**值稳定**的投影(`kind` / `label` / `startedAt`)做身份——`JobView` 虽每次新建对象,这三个原始值却跨读恒定。`startedAt` 未盖章时用占位 `0`(官方签的是 `Date.now()`,永不为 0),保证 `start` 同步跑第一拍时不会把同 id 的另一条作业误认成自己的。
38
+ - **`ignoreFiles` 预检补上「可读性」这半段,并与「是否存在」合成一次判定**。原判据只查 `statSync().isFile()`,而它对 mode 000 / 他人属主的文件照样返回 `true`(stat 只要父目录可搜索、不要文件本身可读);真 zg 去 open 它会 `EACCES` ⇒ 整次索引失败并把这条坏路径**写进工作区索引状态**,此后这棵树上的 `zg index` / `zg status` 都报同一个错,`--reset-paths` 清不掉,只有 `zg_index drop` 能救——与「文件不存在」是同一种永久损坏,却漏过了预检。现以 `accessSync(R_OK)` 在前、`isFile()` 在后合成一次 try:`accessSync` 与 zg 的读权限同 uid 同源(root 下两者都放行、非 root 下两者都拒),只查权限位、不读内容,没有 `readFileSync` 那种把大文件整段读进内存的代价。**刻意不拆成「不存在」与「读不了」两条独立分支 / 两句文案**:可读性那一档在 windows(chmod 只翻只读位、属主仍读得了)与 root(绕过 DAC)下造不出文件来触发,拆成独立分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口);合成一条 catch 后由跨平台的「不存在」这一档钉住,三种成因(ENOENT / EISDIR / EACCES)共用一句「不是一份存在且当前进程可读的文件」文案。
39
+ - **`drop` 那一臂不再被 `ignoreFiles` 预检误拒**。`--drop` 的命令只有 `zg index <root> --drop --yes`,`ignoreFiles` 被 `buildIndexCommand` 静默丢掉、根本不进 zg(也就无从损坏索引);而预检原先无条件先跑,于是 `drop:true` + 一条坏 `ignoreFiles` 会被「请给一个真实存在的忽略文件」这句误导文案拦下一次合法的删索引。现 `drop` 为真时整段跳过预检,判 `drop` 用与构造器**同一个** `boolOf`,两处口径不漂。
40
+
41
+ ### Added
42
+
43
+ - **`ignoreFiles` 可用性预检(`assertIgnoreFilesExist`)**:模型够得着 `ignoreFiles` 这个参数,而一条读不成的忽略文件会永久弄坏工作区索引,属于必须在起进程之前拦下的那一类。前台索引、模型侧后台索引、设置卡重建这三条起 `zg index` 的路径共用同一道预检(卡片那条不带 `ignoreFiles`,天然空转);`drop` 为真时整段跳过(见上)。三种不可用成因合成一句「不是存在且可读的文件」文案,双语,并写明代价与出路。
44
+ - **测试分三层**。原来只有 `test/*.test.ts`(单测 + 一枚 mock 宿主上下文)。新增:
45
+ - `test/integration/*`:真宿主半栈——官方 cordis `Context` + `dsh-tools` 的 `ToolRuntime`(含 pre-execute 瀑布与官方 JSON Schema 子集校验)+ `dsh-subprocess-local` / `dsh-bash-local` 的本地 bash 执行器(真 spawn / 真 deadline / 真 stdout 上限与 spill / 真凭据擦除)+ `dsh-jobs-local` 的 `LocalJobRegistry`(真环 / 真泵 / 真容量)+ 真 `node:http` 监听的 `dsh-host-webserver` + timer + approval,把插件挂进官方调用管线(`ctx.tools.execute()` / 真 `fetch`)驱动。宿主契约的缺陷都出在这一层:mock 上下文只会同意本包已经相信的事(`ctx.get("jobs") === ctx.get("jobs")` 在替身里恒真、真实 cordis 恒假,正是上面那条 Fixed 的成因)。
46
+ - `test/e2e/zg-cli.test.ts`:既无插件也无替身,只把 `lib/cli.ts` 造出的命令行喂给**真 zg CLI**,钉它的旗标面、输出形状、错误码,以及「坏 `ignoreFiles` 会弄坏整棵树」这类上游事实(含 ENOENT 与 EACCES 两档)。
47
+ - **两层按环境 gate,而非无条件跑**:真-zg 的 integration + e2e 整体 `describe.skipIf(!zgAvailable())`——CI 的干净 runner 没装真 zg,硬跑会以「command not found」变红而不是跳过;本机装了 zg 才跑。本包自己的判据另由 `test/host.test.ts` 的 mock 宿主独立钉到 100%(`assertIgnoreFilesExist`:drop 跳过 / 不存在 / 读不了 / 放行,绝对与相对两种写法都覆盖),所以这两层在 CI 跳过后覆盖率不塌;「读不了」那档再按 `canMakeUnreadableFile()`(root 或 windows 造不出属主读不了的文件)单独跳过,也不依赖它保覆盖率。
48
+ - 两份 README 各补一段「测试分三层」的说明。
49
+
50
+ ### Changed
51
+
52
+ - `devDependencies` 补 `@deepseek-ai/dsh-bash-local` / `dsh-http-proxy` / `dsh-subprocess-local` / `dsh-timeout`(真宿主台架的传递依赖,均**不进** `dependencies`)。
53
+ - `pnpm-workspace.yaml` 的 `allowBuilds` 把 `@deepseek-ai/dsh-subprocess-local` / `koffi` / `node-pty` 显式记为 `false`。这三枚是集测台架经 `dsh-subprocess-local` 传递引入的原生模块(各带安装脚本),而 pnpm 12 默认拦截未声明的构建脚本 ⇒ CI 那步 `pnpm install --frozen-lockfile` 以 `ERR_PNPM_IGNORED_BUILDS` 退出 1(本机因 `.modules.yaml` 早记下 ignoredBuilds 决定反而不报)。但本包根本用不到它们的构建产物:`dsh-subprocess-local` 经 `dsh-lazy-require` 惰性加载 `node-pty` / `koffi`,集成用例走的是 bash 执行路径、从不 require(本机 `.modules.yaml` 记的正是 ignoredBuilds,600 用例照绿)。显式 `false` 让 pnpm 跳过构建且不计入 ignoredBuilds(源码实测:唯有 `allowBuild()` 返回 `undefined` 的未声明档才报错),CI 也因此不必为用不到的原生模块在 windows 那一格背上 node-gyp 编译。`esbuild: true` 那条不动(vite 传递引入,确实要它落平台二进制)。
54
+ - `oxlint.config.ts` 的 `syncWrites` 声明 `chmodSync`(用例造 mode 000 的不可读忽略文件)与 `accessSync`(只读权限探针;共享基线的只读豁免表恰好没收录它,故经本包这唯一的 sync 例外口子声明)。
55
+
5
56
  ## 0.1.2
6
57
 
7
58
  宿主生态跟到 `0.2.1-alpha.2`,并把一处**跟着宿主变更而失效的安全判据**改回可用。这一版还补上了发布面与装载面的门禁,以及中英两份 README。
package/README.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  ### What it does
6
6
 
7
- - Adds semantic workspace search to dsh sessions: registers three model tools, zg_search / zg_index / zg_status, which drive the zg CLI (BM25 + vector + RRF hybrid) through the host shell with `--mode direct`.
7
+ - Adds semantic workspace search to dsh sessions: registers three model tools, zg_search / zg_index / zg_status, which drive the zg CLI (BM25 + vector + RRF hybrid) through the host shell. The transport mode defaults to `--mode auto`: server when the daemon is ready, and zg **silently falls back to direct** when it is not (upstream only probes readiness and never starts a daemon; neither does this package — see "Daemon (server mode)").
8
8
  - Injects one systemPrompt rule section (`zvec-grep-routing`, order 1550) plus two tools.guard layers: safety backstop for zg_* and the search-first gate (in an indexed workspace, grep/rg requires a prior successful zg_search).
9
- - Ships a web settings card: default embedding, limit, search-first quota/window, and a "rebuild workspace" button.
9
+ - Ships a web settings card: default embedding, limit, search-first quota/window, daemon readiness, and a "rebuild workspace" button.
10
10
 
11
11
  ### Installation
12
12
 
@@ -39,7 +39,7 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
39
39
  - `globs` / `insensitiveGlobs` / `fileTypes` / `excludedFileTypes` accept a **single string** as well as an array of strings, matching zg's own contract for those fields (128 items max, 1024 chars per item).
40
40
  - `symbolTypes` is bound to zg's real closed set and accepts **lowercase only**: `module` / `class` / `interface` / `function` / `value` / `alias`. zg itself exits non-zero on `--symbol-type Class` (`Unsupported symbol type: Class`); the plugin refuses before assembling the command and lists the allowed values. It does not fold case — silently lowercasing would rewrite a constraint the model did not write.
41
41
  - `preview` has three levels: `none` anchor line only / `short` anchor plus a bounded context window / `full` the whole chunk. **Default short**, so every hit carries a bounded source snippet.
42
- - `refresh` has three levels: `wait` refresh to the latest before searching (**default**) / `off` do not refresh / `background` hand it to the daemon. `background` only holds in daemon mode: in direct mode zg does not fail, it degrades to `off` and writes `warning: --refresh background requires Server mode; Direct mode uses --refresh off` to stderr — this package echoes stderr verbatim, so that line reaches the model on its own.
42
+ - `refresh` has three levels: `wait` refreshes to the latest before searching (**default**) / `off` does not refresh / `background` hands it to the daemon. `background` requires a **ready daemon**: when that is not the case it is refused **before the command is built**, with the way out named, instead of letting zg switch refreshing entirely off and leave only `warning: --refresh background requires Server mode; Direct mode uses --refresh off` on stderr — that path exits 0 with normal hits while the one thing it claims ("refreshing in the background") is false. The two kinds of unavailability get separate wording: without a daemon the way out is `zg server on`; when the deployment pins `clientMode` to `direct`, saying that would point the wrong way, and the fix is setting the mode back to auto/server in the row config.
43
43
  - A **hit summary** is appended at the end of the output with two separately reported counts: `grouped` (the sum of each query group's `hits:`) and `N distinct location(s) after dedup` (keyed by relative path + line range). They are split because one location is hit by several groups at once (rank and `matchedBy` differ per group), so a plain sum counts the same location repeatedly and passes itself off as the hit total.
44
44
  - When some group's hit count equals `--limit`, that is reported as an **observation only**, with an explicit note that zg provides no truncation signal and the summary does not assert one. When the host truncates stdout at its cap, a "covers only the kept part" note is added.
45
45
  - zg_index: confirm is required and must be true (rejected twice, by the required check and by the guard).
@@ -68,17 +68,17 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
68
68
 
69
69
  ### Settings and search roots
70
70
 
71
- - Namespace `zvec-grep`, fourteen fields with built-in defaults, six of them volatile and on the card.
71
+ - Namespace `zvec-grep`, 16 fields with built-in defaults, 6 of them volatile and on the card.
72
72
  - defaultEmbedding=local/qwen3-embedding-0.6b, defaultLimit=10 (1-50), hfEndpoint=a China-reachable HF-compatible mirror base (set another mirror or leave empty for the official HF).
73
73
  - enforceSearchFirst=true, grepBudgetPerSearch=3 (1-20), unlockWindowMin=10 (1-240).
74
- - Additional **non-volatile deployment values** are not on the settings card: change them only via the line config in cordis.yml. The "5 minutes / 10 minutes / 60 seconds / 400000 bytes" in the tools section are their defaults.
74
+ - Additional **non-volatile deployment values**, 10 of them, are not on the settings card: change them only via the line config in cordis.yml. The "5 minutes / 10 minutes / 60 seconds / 400000 bytes" in the tools section are their defaults.
75
75
  - searchTimeoutMs=300000, statusTimeoutMs=60000, indexTimeoutMs=600000 (also the background rebuild kill-timer duration), stdoutMaxBytes=400000 (each with a minimum of 1), clientMode=auto, rebuildWaitMs=120000.
76
76
  - Remote embedding, three values, all **off by default**: `allowRemoteEmbedding=false`, `remoteEmbeddingEndpoint=""`, `remoteEmbeddingApiKeyFrom=""`.
77
77
  - While it is off, an explicit embedding reference must be in the local catalog at **command-assembly time**.
78
78
  - Once open, the endpoint and the credential reach the zg child process **only through environment variables** (`ZVEC_GREP_ENDPOINT` / `ZVEC_GREP_API_KEY`) and **never through argv** — this plugin reuses the whole command string as a background-job label that is echoed on the card, so a key in argv would land in the UI, in logs, and in the process table.
79
79
  - The credential value holds the **name** of the environment variable in the host process that holds the credential (e.g. `ZVEC_GREP_API_KEY`), not the credential itself: the host's subprocess layer scrubs inherited names matching KEY/SECRET/TOKEN, so only an explicit forward from this plugin reaches zg — and recording just the name also keeps the secret out of the plugin's own config file.
80
80
  - This plugin does **not** pass `--allow-remote` for you: zg still requires the user to run `zg auth grant <root> --capability embedding --scope workspace` once, and that per-root authorization is not something a plugin should do on the user's behalf.
81
- - `requireApprovalForExplicitRoot=false`: when on, an explicit `root` on any of the three zg tools that is neither the current session workspace nor already registered in this session triggers one user confirmation through the official `tools/pre-execute → {kind:'ask'} → ctx.approval` seam. It defaults to off, and three boundaries are known in advance: the `danger-full-access` preset sets `approval/policy` to `never` (the ask is deterministically rejected), delegated subagents are pinned to `approvalPolicy: 'never'` (**the switch has no effect inside a subagent**), and with no approval service installed the ask fails closed to a denial. This confirmation **only ever adds** a step: `rootOf`'s authorization predicate is unchanged, so an out-of-scope root is still refused even after the user approves.
81
+ - `requireApprovalForExplicitRoot=false`: when on, an explicit `root` triggers one user confirmation through the official `tools/pre-execute → {kind:'ask'} → ctx.approval` seam **only for calls that `rootOf` would let through via its "ancestor or descendant of the session workspace" branch**. The ask and `rootOf` share one predicate (`judgeRoot`), so two kinds of calls are no longer bothered: ones that will be refused anyway (out of scope, missing directory, unparseable, no session workspace to compare against) — where an approval can never buy a pass — and ones that need no authorization at all (the session workspace itself, or a root this daemon already observed). It defaults to off, and three boundaries are known in advance: the `danger-full-access` preset sets `approval/policy` to `never` (the ask is deterministically rejected), delegated subagents are pinned to `approvalPolicy: 'never'` (**the switch has no effect inside a subagent**), and with no approval service installed the ask fails closed to a denial. This confirmation **only ever adds** a step: `rootOf`'s authorization predicate is unchanged, so an out-of-scope root is still refused even after the user approves.
82
82
  - Precedence: runtime settings values > the line config of the bundle/user layer > built-in base; explicitly absent fields in the line config do not override the base.
83
83
  - Volatile fields are read via `config.<field>.get()`; the non-volatile deployment values are plain values and skip `.get()`.
84
84
  - Root validation: must be an absolute path starting with `/`, lexically normalised (empty and `.` segments folded).
@@ -103,12 +103,21 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
103
103
  - `--help`/`--version`/`-V`, `echo "grep x"` and `git commit -m "use rg"` do not.
104
104
  - With a sandboxed executor, runner failure, policy denial and a genuine zg failure are told apart, and incomplete results are flagged explicitly.
105
105
 
106
+ ### Daemon (server mode)
107
+
108
+ - This is not a "somewhat faster" distinction. The two sides of `--mode auto` are two capability surfaces: direct builds and closes the engine on every `zg query` and **cold-loads the embedding model each time**, while watcher-driven incremental index refresh, `refresh=background` and a resident model pool **only exist in server mode**. Upstream only probes readiness for `auto`; it never starts a daemon for you.
109
+ - This package **does not start a long-lived process on the user's behalf**: `zg server on` leaves a detached process and a token file on the machine, which is an action the user should own, not a decision a plugin makes for a deployment. What the package does instead is make the difference **explicit**, rather than leaving it hidden behind usage limits like "the search timeout is 5 minutes" and "recent edits are not findable":
110
+ - It caches the **exit code** of `zg server status --check-ready` for a 60-second TTL (0 = ready, non-zero = not ready; reading the stdout table would not do — it is formatted for humans and is not part of this package's dependency contract). A failed probe is recorded as "not ready" and never surfaces as an infrastructure error.
111
+ - That judgment gates `refresh=background` (see the tools section) and is echoed once at the tail of `zg_status` output and once on the settings card. A request rejected by the trust gate never triggers a probe, and neither does the rebuild-time synthetic projection, whose contract is to start no subprocess at all.
112
+ - The card's `serverReady` is only ever `true` / `false`. An older host response simply has no such field, and the card renders **nothing** for that arm instead of claiming "not ready".
113
+ - To actually get the benefits: run `zg server on` in a terminal (`zg server off` / `zg server status` cover stop and state). This package reads that readiness; it does not own the daemon's lifecycle.
114
+
106
115
  ### Public interface
107
116
 
108
117
  - Every handler opens with `guardTrust(req, res, { servingNonLoopback })` (`shared/lib/trust`); failing any leg yields `403` with `{ ok:false, error: ... }`.
109
118
  - Order of legs: Host authority -> the `sec-fetch-site` allowlist -> a verbatim `origin` vs Host compare. The two rejection sentences are `"untrusted host authority"` and `"cross-origin request rejected"`.
110
119
  - `servingNonLoopback` is computed by `isNonLoopbackBindHost(webServer.host)` from the bound address itself - the host only rejects wildcard listeners, while binding a concrete IPv4/IPv6 of a local interface is a legitimate configuration, and a literal comparison would read that surface as loopback. A wrong method yields `405` carrying `Allow` plus `{ ok:false, error:"GET only" | "POST only" }` - no longer an empty reply.
111
- - `GET /_dsh/zvec-grep/rebuild-roots`: returns only this plugin's own data (a CSRF token regenerated on every apply, plus the observed workspace list); GET/HEAD allowed, 403 when the gate above rejects it.
120
+ - `GET /_dsh/zvec-grep/rebuild-roots`: returns only this plugin's own data (a CSRF token regenerated on every apply, the observed workspace list, and the daemon readiness the card shows); GET/HEAD allowed, 403 when the gate above rejects it. The readiness probe runs **after** both gates, so a rejected request never starts a subprocess.
112
121
  - `POST /_dsh/zvec-grep/rebuild?root=...`: gate + header `x-zvec-grep-csrf` + body <= 4096 bytes + root in the whitelist + directory exists; returns `{ ok, jobId }`, otherwise 405/403/400/500.
113
122
  - `/_dsh/zvec-grep/rebuild-status?jobId=...`: polled behind the gate (the card polls every 2 seconds); returns status/exitCode/root/output (plus sandbox when present); an unknown jobId gets a 404 explaining it left the 10-record settled window.
114
123
  - Also a systemPrompt section `zvec-grep-routing` (order 1550) and the settings namespace `zvec-grep`.
@@ -150,14 +159,16 @@ What is not retained, stated plainly: the output ring keeps **UTF-8 bytes** (mea
150
159
  ### FAQ
151
160
 
152
161
  - grep/rg refused with "no zg_search has run yet": that is the search-first gate; run zg_search. The same applies once the quota is spent or expired — re-search with a sharper query/fts to refresh it, no need to disable the plugin.
153
- - Search times out: the default `--refresh wait` refreshes the existing index synchronously; narrow the range with globs/fileTypes or lower the limit, or fall back to a hand-written literal search.
162
+ - Search times out: the default `--refresh wait` refreshes the existing index synchronously; narrow the range with globs/fileTypes or lower the limit, or fall back to a hand-written literal search. To make the timeout itself smaller, start the daemon (see "Daemon (server mode)") — direct mode cold-loads the embedding model on every call, which is exactly why that budget sits at 5 minutes.
154
163
  - The rebuild button answers 403 "root is not in the workspace whitelist this daemon observed": that directory never had a session in this daemon; start one there first, or let the model call zg_index with confirm=true.
155
164
  - The card reports a failed rebuild although zg looks finished: success is "completed with exit 0" — exit 127 (zg not installed) also lands in completed, so read the tail of the output.
156
165
  - A root that was never indexed: zg_search fails loudly instead of silently building the index; building happens only via zg_index on an explicit user request.
157
166
  - Changed the embedding but semantic hits are missing: switching embedding only takes effect after a rebuild with rebuild=true.
167
+ - A zg failure comes back as one line with no `Code:` field: without `--debug` upstream collapses two failure kinds (weight download, indexing files) into a bare sentence, which is exactly where this package's attribution-by-code stops working. Such replies therefore append one line pointing at `--debug`. The package does **not** pass `--debug` by default: it visibly lengthens output, and these three tools share a bounded echo (stdout 400000 bytes) meant for a model. Failures that do carry a `Code:` line get no such note.
158
168
 
159
169
  ### Development
160
170
 
171
+ - Tests come in three tiers. `test/*.test.ts` (unit + a mocked host context) pins this package's own pure logic; `test/integration/*` boots **real** host services (`dsh-tools` ToolRuntime, `dsh-subprocess-local` + `dsh-bash-local`, `dsh-jobs-local`, `dsh-host-webserver` over real HTTP, the timer and approval services) and drives the plugin through `ctx.tools.execute()` / actual `fetch`; `test/e2e/zg-cli.test.ts` has no plugin and no mock at all - it feeds the commands `lib/cli.ts` builds to the **real zg CLI** and pins its output shapes, error codes and flag surface. The middle tier is where host-contract bugs surface: a mocked context can only agree with what this package already believes (e.g. `ctx.get("jobs") === ctx.get("jobs")` holds for a mock but is false in real cordis, which reads a service through a fresh traceable proxy per call).
161
172
  - `npm run check` is the single gate to run before publishing: typecheck (both tsconfigs) + `oxlint` + rebuild both bundles + `vitest run --coverage` + `oxfmt --check`.
162
173
  - Coverage runs under a **100% global threshold** (statements/branches/functions/lines): any line or branch that no test pins turns the suite red by design.
163
174
  - `npm run build` / `npm run build:client` produce `host.js` / `client.js`, and neither is committed - `prepare` and `prepack` rebuild them, while `test/build-host.test.ts` / `test/build-client.test.ts` compare the on-disk bundle against an in-memory build byte for byte, so a stale bundle fails the suite. Never hand-edit the bundles: the published entry *is* the built artifact, because Node refuses to strip types for a `.ts` sitting inside `node_modules`.
package/README.zh-CN.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  ### 它做什么
6
6
 
7
- - 给 dsh 会话接上工作区语义检索:注册 zg_search / zg_index / zg_status 三个模型工具,底层经宿主 shell 以 `--mode direct` 调 zg CLI(BM25 + 向量 + RRF 混合检索)。
7
+ - 给 dsh 会话接上工作区语义检索:注册 zg_search / zg_index / zg_status 三个模型工具,底层经宿主 shell 调 zg CLI(BM25 + 向量 + RRF 混合检索)。传输模式缺省 `--mode auto`:守护进程就绪就走 server,缺席时 zg **静默落回 direct**(上游只做就绪探测、不代为拉起,本包也不起,见「守护进程」一节)。
8
8
  - 注入一段 systemPrompt 硬规则(`zvec-grep-routing`,order 1550)+ 两道 tools.guard:zg_* 安全兜底与 search-first 门禁(已建索引的工作区里,grep/rg 前必须先有一次成功的 zg_search)。
9
- - 附带 web 端设置卡:默认 embedding、limit、search-first 配额/时效,以及「工作区重建」按钮。
9
+ - 附带 web 端设置卡:默认 embedding、limit、search-first 配额/时效,守护进程就绪态一行,以及「工作区重建」按钮。
10
10
 
11
11
  ### 安装
12
12
 
@@ -36,7 +36,7 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
36
36
  - `globs` / `insensitiveGlobs` / `fileTypes` / `excludedFileTypes` 既收**单个字符串**也收字符串数组(与上游 zg 对这几项的对外契约一致,最多 128 项、单项 <= 1024 字符)。
37
37
  - `symbolTypes` 绑定 zg 的真实闭集,取值**只认小写**:`module` / `class` / `interface` / `function` / `value` / `alias`。zg 侧 `--symbol-type Class` 会以非零码退出(`Unsupported symbol type: Class`),插件在构造命令前就拦下并列出合法取值;不做大小写折叠——悄悄改成小写等于替模型改了它没写的约束。
38
38
  - `preview` 三档:`none` 只给锚点行 / `short` 锚点加一段有界上下文 / `full` 整段源码,**默认 short**,每条命中自带有界源码片段。
39
- - `refresh` 三档:`wait` 等索引刷到最新(**默认**)/ `off` 不刷新 / `background` 交给守护进程后台刷新。`background` 只在守护进程模式下成立:直连模式下 zg 不报错,而是降级成 `off` 并往 stderr 打一行 `warning: --refresh background requires Server mode; Direct mode uses --refresh off`——本包把 stderr 原样回显,那一行会自己到模型眼前。
39
+ - `refresh` 三档:`wait` 等索引刷到最新(**默认**)/ `off` 不刷新 / `background` 交给守护进程后台刷新。`background` 要有**就绪的守护进程**才给:不可用时在**构造命令前**就拒并点名出路,而不是让 zg 把刷新整个关掉、只在 stderr 留一行 `warning: --refresh background requires Server mode; Direct mode uses --refresh off`——那条路退出码照旧 0、命中照旧出,唯独「后台在刷新」是假的。两种不可用各有各的文案:守护进程缺席时出路是 `zg server on`;部署把 `clientMode` 钉死 `direct` 时那么说就是指错方向,出路是回行 config 把模式改回 auto/server。
40
40
  - 输出尾部附一行**命中摘要**,两栏口径分开给:`分组计数合计`(各查询组 `hits:` 之和)与`去重后 N 个不同位置`(按「相对路径 + 行号范围」去重)。分栏是因为同一处代码会被多组各命中一次(名次与匹配来源逐组变化),直接求和会把同一处位置重复计入、冒充命中总数。
41
41
  - 某组命中数正好等于 `--limit` 时只作**观察陈述**并显式说明「zg 不提供截断信号,此处不作断言」——zg 的输出没有任何截断标记,不能把"可能还有未显示的命中"说成事实。输出被宿主按 stdout 上限截尾时另附「只含保留部分」。
42
42
  - zg_index:confirm 必填且必须为 true(required 校验 + guard 双层拒绝)。
@@ -65,16 +65,16 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
65
65
 
66
66
  ### 设置项与检索根
67
67
 
68
- - 命名空间 `zvec-grep` 由宿主**隐式**注册(0.1.7 起 = profile 条目 id,插件侧不再有 `settings.register`);schema 共十四个字段,其中卡上那六枚标 `.volatile()`,内置默认逐字段写在 `.default()` 上。
68
+ - 命名空间 `zvec-grep` 由宿主**隐式**注册(0.1.7 起 = profile 条目 id,插件侧不再有 `settings.register`);schema 共 16 个字段,其中卡上那 6 枚标 `.volatile()`,内置默认逐字段写在 `.default()` 上。
69
69
  - defaultEmbedding=local/qwen3-embedding-0.6b、defaultLimit=10(1-50)、hfEndpoint=国内可达的 HF 兼容镜像基址(可改成别的镜像或留空走官方 HF)。
70
70
  - enforceSearchFirst=true、grepBudgetPerSearch=3(1-20)、unlockWindowMin=10(1-240)。
71
- - 另有**非 volatile 部署值**(不进设置卡,只在 cordis.yml 的行 config 里改值;上面工具一节的「5 分钟 / 10 分钟 / 60 秒 / 400000 字节」就是它们的默认):searchTimeoutMs=300000、statusTimeoutMs=60000、indexTimeoutMs=600000(也是后台重建 kill 定时器的时长)、stdoutMaxBytes=400000、clientMode=auto、rebuildWaitMs=120000,超时/缓冲几项均最小 1。
71
+ - 另有**非 volatile 部署值**,共 10 枚(不进设置卡,只在 cordis.yml 的行 config 里改值;上面工具一节的「5 分钟 / 10 分钟 / 60 秒 / 400000 字节」就是它们的默认):searchTimeoutMs=300000、statusTimeoutMs=60000、indexTimeoutMs=600000(也是后台重建 kill 定时器的时长)、stdoutMaxBytes=400000、clientMode=auto、rebuildWaitMs=120000,超时/缓冲几项均最小 1;再加远程 embedding 三件套与 requireApprovalForExplicitRoot(各见下面两小节)。
72
72
  - 远程 embedding 三件套,默认**全关**:`allowRemoteEmbedding=false`、`remoteEmbeddingEndpoint=""`、`remoteEmbeddingApiKeyFrom=""`。
73
73
  - 关着的时候,显式 embedding 引用在**命令构造期**就必须落在本地候选清单里。
74
74
  - 打开后端点与凭据**只经环境变量**下发给 zg 子进程(`ZVEC_GREP_ENDPOINT` / `ZVEC_GREP_API_KEY`),**绝不进 argv**——本包把整条命令当作业 label 回显给卡片,argv 里的密钥会进界面、进日志、进 `ps` 的进程表。
75
75
  - 凭据那项填的是**宿主进程里那个装凭据的环境变量名**(如 `ZVEC_GREP_API_KEY`),不是密钥本身:宿主 subprocess 层会把名字含 KEY/SECRET/TOKEN 的继承变量剔掉,必须由本插件显式转发才到得了 zg;只记名字也让密钥不必落进插件配置文件。
76
76
  - 本插件**不自动传 `--allow-remote`**:zg 还要用户自己跑一次 `zg auth grant <root> --capability embedding --scope workspace` 才肯发请求,那道按 root 的授权本插件不代劳。
77
- - `requireApprovalForExplicitRoot=false`:打开后,三个 zg 工具里**显式给了 root**、且那个 root 既不是本会话工作区、也不在本会话已登记范围内时,会经官方 `tools/pre-execute → {kind:'ask'} → ctx.approval` 弹一次用户确认。默认关,且有三个已知边界:`danger-full-access` 预设把 `approval/policy` 写成 `never`(ask 会被确定性拒绝)、委派子代理被钉死 `approvalPolicy: 'never'`(**该开关对子代理无效**)、宿主没装 approval 服务时 fail-closed 成拒绝。这道确认**只加不减**:`rootOf` 的授权判据一字未改,越界的 root 即便「用户已批准」照旧被拒。
77
+ - `requireApprovalForExplicitRoot=false`:打开后,三个 zg 工具里**显式给了 root**、且这次调用要靠 `rootOf` 的「与会话工作区互为祖先/后代」那一条才放行时,会经官方 `tools/pre-execute → {kind:'ask'} → ctx.approval` 弹一次用户确认。发问判据与 `rootOf` **同源**(同一个 `judgeRoot`),所以两类调用不再被打扰:注定被拒的(越界 / 目录不存在 / 解析不了 / 没有会话工作区可作参照)——那一次确认换个不来放行;本就无需授权的(root 就是会话工作区本身、或这台 daemon 已观测过)。默认关,且有三个已知边界:`danger-full-access` 预设把 `approval/policy` 写成 `never`(ask 会被确定性拒绝)、委派子代理被钉死 `approvalPolicy: 'never'`(**该开关对子代理无效**)、宿主没装 approval 服务时 fail-closed 成拒绝。这道确认**只加不减**:`rootOf` 的授权判据一字未改,越界的 root 即便「用户已批准」照旧被拒。
78
78
  - 优先级:设置里的运行时值 > 组合包层/用户层行的 config > schema 的 `.default()`;行 config 中显式缺省的字段不覆盖默认。读侧是 `config.<field>.get()`(volatile 引用,卡上改完下一个事件即生效);非 volatile 部署值是普通值形态,不经 `.get()`。
79
79
  - root 校验:必须是以 `/` 开头的绝对路径,词典归一折叠空段与 `.`。
80
80
  - 拒绝空串、非字符串、含 NUL、相对路径、越出文件系统根的 `..`,归一后为 `/` 也拒。
@@ -98,12 +98,21 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
98
98
  - `--help`/`--version`/`-V`、`echo "grep x"`、`git commit -m "use rg"` 不算。
99
99
  - 有沙箱执行器时会区分 runner 失败、策略拒绝与 zg 自身失败,并在结果里显式打「可能不完整」标记。
100
100
 
101
+ ### 守护进程(server 模式)
102
+
103
+ - 这一档不是「快一点」的区别。`--mode auto` 的两侧是两种能力面:direct 每发 `zg query` 都要新建再关闭一次引擎、**embedding 模型逐次冷加载**;而索引的增量刷新(watcher)、`refresh=background` 与常驻模型池**只在 server 模式下存在**。上游对 `auto` 只做就绪探测、不会替用户拉起 daemon。
104
+ - 本包**不代为起一个长驻进程**:`zg server on` 会在用户机器上落下 detached 进程与 token 文件,那是该由用户点头的动作,不是插件替部署做的决定。本包做的是把这一档**显式化**,不再让它藏在「检索超时给 5 分钟」和「改动搜不到」这类使用限制背后:
105
+ - 按 TTL(60 秒)缓存 `zg server status --check-ready` 的**退出码**(就绪 0、未就绪非零;读 stdout 文本不行,那是给人看的状态表、不在本包的依赖契约里)。探测失败一律按未就绪收口,**绝不外抛**基础设施故障。
106
+ - 据此收口 `refresh=background`(见工具一节),并在 `zg_status` 的输出尾部与设置卡各回显一行就绪态。被信任闸门拒掉的请求不起探测;重建期那条「合成投影」也不起(它本来的契约就是不启子进程)。
107
+ - 设置卡的 `serverReady` 只可能是 `true` / `false`;旧版 host 的应答里根本没有这一位,卡片对「未知」的那一臂**不显示**,而不是把它说成「未就绪」。
108
+ - 想把红利拿到手:在持有终端时执行 `zg server on`(起停与状态另有 `zg server off` / `zg server status`)。本包只读它的就绪态,不拥有它的生命周期。
109
+
101
110
  ### 对外接口
102
111
 
103
112
  - 三条路由的 handler 第一句都是 `guardTrust(req, res, { servingNonLoopback })`(`shared/lib/trust`),任一判据不过即 `403` + `{ ok:false, error: ... }`。
104
113
  - 判据次序:Host 权威 → `sec-fetch-site` 白名单 → `origin` 与 Host 逐字比对;两句错误文本是 `"untrusted host authority"` 与 `"cross-origin request rejected"`。
105
114
  - `servingNonLoopback` 由 `isNonLoopbackBindHost(webServer.host)` 按**绑定地址本身**算出(宿主只拒通配地址,绑本机网卡的具体 IPv4/IPv6 是合法配置,比字面量会漏判这一面);非本方法的 `405` 带 `Allow` 与 `{ ok:false, error:"GET only" | "POST only" }`,不再是空回显。
106
- - `GET /_dsh/zvec-grep/rebuild-roots`:只回本包自己的数据(每次 apply 重新生成的 CSRF token + 已观测工作区列表),允许 GET/HEAD,过不了上面那道闸门即 403。
115
+ - `GET /_dsh/zvec-grep/rebuild-roots`:只回本包自己的数据(每次 apply 重新生成的 CSRF token + 已观测工作区列表 + 卡片要显示的那行守护进程就绪态),允许 GET/HEAD,过不了上面那道闸门即 403。就绪探测排在**两道闸门之后**,被拒的请求不起子进程。
107
116
  - `POST /_dsh/zvec-grep/rebuild?root=...`:闸门 + 头 `x-zvec-grep-csrf` + body <= 4096 字节 + root 命中白名单 + 目录存在,成功回 `{ ok, jobId }`;否则 405/403/400/500。
108
117
  - `/_dsh/zvec-grep/rebuild-status?jobId=...`:闸门后轮询(卡片每 2 秒一次),回 status/exitCode/root/output(有沙箱时带 sandbox),未知 jobId 回 404 并说明多半是出了本包那条 10 条落定窗口。
109
118
  - 另有 systemPrompt 段 `zvec-grep-routing`(order 1550)与 settings 命名空间 `zvec-grep`。
@@ -146,14 +155,16 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
146
155
  ### 常见问题
147
156
 
148
157
  - grep/rg 被拒且提示「尚未执行过 zg_search」:这是 search-first 门禁,先 zg_search;配额用尽或过期同理,换个更准的 query/fts 重搜即可续上,不必关插件。
149
- - 检索超时:默认 `--refresh wait` 会同步刷新既有索引,大工作区请用 globs/fileTypes 缩小范围或调小 limit,也可先手写字面检索。
158
+ - 检索超时:默认 `--refresh wait` 会同步刷新既有索引,大工作区请用 globs/fileTypes 缩小范围或调小 limit,也可先手写字面检索;想让超时这件事本身变小,就起守护进程(见「守护进程」一节)——直连模式每次都要冷加载 embedding 模型,那才是超时预算被抬到 5 分钟的原因。
150
159
  - 重建按钮回 403「root 不在本 daemon 观测到的工作区白名单内」:该目录从未在本 daemon 开过会话;先在该目录起会话,或让模型带 confirm=true 调 zg_index。
151
160
  - 卡片显示重建失败而 zg 看着像跑完了:成功判据是 completed 且 exit 0——exit 127(zg 没装)也落在 completed,看输出尾部原因。
152
161
  - 从未建索引的 root:zg_search 明确报错而不是静默建索引;建索引只在用户明确要求时由 zg_index 做。
153
162
  - 换了 embedding 却搜不到语义结果:切换 embedding 必须 rebuild=true 重建后才生效。
163
+ - zg 失败只回显一句没有 `Code:` 的文案:上游在不带 `--debug` 时会把两类失败(权重下载失败、索引文件失败)塌成一句话,本包那套按码归因正好在这条链上失效。所以这种失败的回显尾部会补一句「可加 `--debug` 复跑」的指引——本包**不默认带** `--debug`:它会明显拉长输出,而这三条工具的回显有界(stdout 400000 字节)是给模型读的。已有 `Code:` 行的失败不补这一句。
154
164
 
155
165
  ### 开发
156
166
 
167
+ - 测试分三层。`test/*.test.ts`(单测 + mock 宿主上下文)钉本包自己的纯逻辑;`test/integration/*` 起**真**宿主服务(`dsh-tools` 的 ToolRuntime、`dsh-subprocess-local` + `dsh-bash-local`、`dsh-jobs-local`、真 HTTP 的 `dsh-host-webserver`、timer 与 approval),把插件挂进官方调用管线(`ctx.tools.execute()` / 真 `fetch`)驱动;`test/e2e/zg-cli.test.ts` 既没有插件也没有替身,只把 `lib/cli.ts` 造出的命令行喂给**真 zg CLI**,钉它的输出形状、错误码与旗标面。宿主契约的缺陷都出在中间那层:mock 上下文只会同意本包已经相信的事(例如 `ctx.get("jobs") === ctx.get("jobs")` 在替身里恒真,而真实 cordis 每次读服务都新建一枚 traceable 代理,该等式恒假)。
157
168
  - `npm run check` 是发布前的一条门:typecheck(两侧 tsconfig)+ `oxlint` + 重建两个 bundle + `vitest run --coverage` + `oxfmt --check`。
158
169
  - 覆盖率按**全局 100% 阈值**跑(stmts/branches/funcs/lines):任何一行或分支没被用例钉住,套件当场红——这是本仓的既定质量门,不是巧合。
159
170
  - `npm run build` / `npm run build:client` 产出 `host.js` / `client.js`,两者**都不入库**:`prepare` 与 `prepack` 现产,而 `test/build-host.test.ts` / `test/build-client.test.ts` 拿磁盘产物与内存构建逐字节比,产物过期即变红。发布物不手改——发布入口本就是构建产物,因为 Node 对躺在 `node_modules` 里的 `.ts` 直接拒绝类型剥离。
package/client.js CHANGED
@@ -99,6 +99,19 @@ function e$1(e) {
99
99
  //#endregion
100
100
  //#region lib/card-logic.ts
101
101
  /**
102
+ * 引导端点交回的守护进程就绪态该显示哪一行。
103
+ *
104
+ * `undefined` 是**必要**的一臂,不是兜底:旧版 host 的应答里没有 `serverReady` 这个字段,
105
+ * 而「应答里没写」与「写了未就绪」是两件事——把前者显示成后者,卡片就在用户眼前谎称了一次
106
+ * 「没有守护进程」。判据收在可单测的这一层,client 只负责渲染它选出来的那一行。
107
+ */
108
+ function daemonNoteKey(ready) {
109
+ let key;
110
+ if (ready === true) key = "daemonReadyNote";
111
+ else if (ready === false) key = "daemonOfflineNote";
112
+ return key;
113
+ }
114
+ /**
102
115
  * 把 settings scope 桥成 { getSnapshot, subscribe } store。
103
116
  * 缓存必须 per-scope(闭包内):模块全局会在多 scope 交错 getSnapshot 时互相
104
117
  * 冲 memo,导致 useSyncExternalStore 每次拿到新引用 → 无限重渲染。
@@ -287,6 +300,8 @@ const UI_MESSAGES = {
287
300
  windowHint: "超过该时长未再次 zg_search,配额整体过期;清空恢复默认 10",
288
301
  windowInvalid: "解锁时效必须是 {min}-{max} 的整数",
289
302
  rebuildLabel: "工作区重建(切换 embedding 并保存后执行)",
303
+ daemonReadyNote: "守护进程:就绪 —— 检索可走 server 模式,索引有增量刷新与后台刷新,embedding 模型池常驻。",
304
+ daemonOfflineNote: "守护进程:未就绪 —— 检索按直连模式逐次冷加载 embedding 模型(大工作区更慢),refresh=background 与索引增量刷新不可用;需要时在终端执行 `zg server on`。",
290
305
  rebuildHint: "以当前默认模型重建:{embedding};等价于 zg index --rebuild。{roots}",
291
306
  rootsNoteWith: "候选工作区来自本 daemon 已打开过的会话(服务端白名单)。",
292
307
  rootsNoteEmpty: "尚无可选工作区:先在该工作区里开一个会话(任一次工具调用即登记)。",
@@ -337,6 +352,8 @@ const UI_MESSAGES = {
337
352
  windowHint: "Without another zg_search inside this window the whole quota expires; clear to restore the default 10",
338
353
  windowInvalid: "the unlock window must be an integer between {min} and {max}",
339
354
  rebuildLabel: "Workspace rebuild (run after switching embedding and saving)",
355
+ daemonReadyNote: "Daemon: ready — searches can use server mode, with incremental and background index refreshing and a resident embedding model pool.",
356
+ daemonOfflineNote: "Daemon: not ready — searches run in direct mode and cold-load the embedding model every call (slower on large workspaces); refresh=background and incremental index refresh are unavailable. Run `zg server on` in a terminal when you want it.",
340
357
  rebuildHint: "Rebuild with the current default model: {embedding}; same as zg index --rebuild. {roots}",
341
358
  rootsNoteWith: "Candidates come from sessions this daemon already opened (server-side whitelist).",
342
359
  rootsNoteEmpty: "No workspace to pick yet: open a session in that workspace first (any tool call registers it).",
@@ -702,6 +719,21 @@ function buildRebuildRow(deps) {
702
719
  }, rebuild.phase === "running" ? t("rebuildRunning") : t("rebuildButton"));
703
720
  return (0, react.createElement)("div", { className: "zgc-row" }, rebuildLabel, rebuildHint, rootDatalist, rebuildInput, rebuildButton);
704
721
  }
722
+ /**
723
+ * 守护进程(`zg server`)就绪态一行,取自 rebuild-roots 引导端点。
724
+ *
725
+ * 为什么值得单独占一行:daemon 缺席时检索按直连模式逐次冷加载 embedding 模型,而
726
+ * `refresh=background`、索引增量刷新与常驻模型池都不存在——本包因此在命令构造期就拒
727
+ * background。把这一档摆在「工作区重建」旁边,用户才不至于从「检索怎么这么慢」倒推。
728
+ * `undefined` 那一档**不渲染**:旧版 host 的应答没有这个字段,说成「未就绪」是谎称。
729
+ */
730
+ function buildDaemonNote(deps) {
731
+ const { t } = deps;
732
+ const key = daemonNoteKey(deps.serverReady);
733
+ if (key === void 0) return null;
734
+ const note = (0, react.createElement)("div", { className: "zgc-hint" }, t(key));
735
+ return (0, react.createElement)("div", { className: "zgc-row" }, note);
736
+ }
705
737
  /** 重建状态节点:phase 非 idle 才出现;done 且无输出时给一句「已完成」。 */
706
738
  function buildRebuildStatusRow(deps) {
707
739
  const { rebuild, t } = deps;
@@ -748,6 +780,7 @@ function buildCardBody(deps) {
748
780
  onSave: deps.onSave,
749
781
  onDiscard: deps.onDiscard
750
782
  }),
783
+ buildDaemonNote(deps),
751
784
  buildRebuildRow(deps)
752
785
  ];
753
786
  const status = buildRebuildStatusRow(deps);
@@ -786,14 +819,16 @@ async function requestJson(url, t, init) {
786
819
  }
787
820
  const NO_ACCESS = {
788
821
  csrf: "",
789
- roots: []
822
+ roots: [],
823
+ serverReady: void 0
790
824
  };
791
- /** 引导端点应答 → { csrf, roots }(字段缺失/类型不对一律当作没拿到)。 */
825
+ /** 引导端点应答 → { csrf, roots, serverReady }(字段缺失/类型不对一律当作没拿到)。 */
792
826
  function readAccess(body) {
793
- const { csrf, roots } = body;
827
+ const { csrf, roots, serverReady } = body;
794
828
  return {
795
829
  csrf: typeof csrf === "string" ? csrf : "",
796
- roots: Array.isArray(roots) ? roots.filter((item) => typeof item === "string") : []
830
+ roots: Array.isArray(roots) ? roots.filter((item) => typeof item === "string") : [],
831
+ serverReady: typeof serverReady === "boolean" ? serverReady : void 0
797
832
  };
798
833
  }
799
834
  /**
@@ -895,6 +930,7 @@ function useRebuild(t) {
895
930
  return {
896
931
  root,
897
932
  roots: access.roots,
933
+ serverReady: access.serverReady,
898
934
  state: rebuild,
899
935
  setRoot,
900
936
  start
@@ -954,6 +990,7 @@ function ZgCard(props) {
954
990
  fields,
955
991
  writable,
956
992
  roots: rebuildView.roots,
993
+ serverReady: rebuildView.serverReady,
957
994
  root: rebuildView.root,
958
995
  rebuild: rebuildView.state,
959
996
  dirty,
package/host.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // GENERATED by build-host.mjs — edit host.ts / lib/*.ts, then run `node build-host.mjs`.
2
2
  import Schema from "@deepseek-ai/schemastery";
3
- import { existsSync, readFileSync } from "node:fs";
3
+ import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { guardBody, queryParam, sendJson } from "@jayyuen66/dsh-plugin-shared/lib/http";
@@ -109,7 +109,7 @@ const MESSAGES = {
109
109
  fuseDescription: "融合所有组为单一排名",
110
110
  limitDescription: "每组最大条数 1-50,默认 10",
111
111
  previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short 给锚点加一段有界上下文、full 给整段源码。默认 short",
112
- refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。注意 background 只在守护进程模式下成立,直连模式下 zg 会降级成 off 并在 stderr 提示",
112
+ refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。background 只在守护进程就绪时可用:没有守护进程时这一档在命令构造前就被拒绝(直连模式下 zg 只会静默关掉刷新并留一行 stderr warning,那等于把「没刷新」说成「后台在刷」),要它请先在终端执行 `zg server on`",
113
113
  globsDescription: "路径 glob(如 src/**),单个字符串或数组",
114
114
  globsIndexDescription: "路径 glob",
115
115
  insensitiveGlobsDescription: "大小写不敏感 glob",
@@ -164,7 +164,7 @@ const MESSAGES = {
164
164
  rebuildWaitTimeout: "等待 {root} 的重建完成超时(约 {seconds} 秒),重建可能仍在进行;请稍后重试。本次不会发放 grep/rg 配额——重建期间索引不可读,先等它结束。",
165
165
  rebuildWaitAborted: "等待 {root} 的重建完成时被中止。",
166
166
  statusRebuilding: "{root} 正在重建中(作业 {jobId})。重建期间索引不可读,检索会自动等待它完成后重试。如需查看实时输出,请在设置卡的工作区重建面板里观察。此刻即使问「索引是否就绪」也是否定的答案——重建落定后再问。",
167
- statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail}",
167
+ statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail} 若刷新反复失败(报告里出现 `read only mode` 一类写入被拒的措辞),那是该索引自身的状态问题,重建即可恢复:zg_index(root=\"…\", confirm=true, rebuild=true)。",
168
168
  checkReadyDescription: "就绪判定:就绪报告照常给出,另行判定索引是否 ready 并在结论里明说。未就绪不是执行失败,报告仍会返回",
169
169
  traceDescription: "排障用:每条命中附一行检索轨迹,说明它被哪几路召回、在各组里名次如何,并给出分值。输出会明显变长;穷举检索(rg)模式不支持该参数",
170
170
  indexBackgroundStarted: "已在后台为 {root} 启动索引(作业 {jobId}),命令:{command}。索引落定前该根的语义检索会等它完成再重试,grep/rg 在这段时间不受门禁限制。用 zg_status 查就绪与否;本次调用不发放 grep/rg 配额",
@@ -181,6 +181,7 @@ const MESSAGES = {
181
181
  genericFailure: "zg 执行失败(exit={exit}){detail}",
182
182
  detailPrefix: " 详情:{detail}",
183
183
  detailColon: ":{detail}",
184
+ noErrorCodeHint: "(这条失败没有 zg 的结构化 `Code:` 行,本包无法按码归因。上游不带 `--debug` 时会把部分失败塌成一句无码文本;要拿到可归因的完整输出,请让持有终端的用户把同一条命令加上 `--debug` 复跑一次)",
184
185
  outputTruncated: "[zvec-grep] 注意:输出超过 {maxBytes} 字节上限,已截断,仅保留尾部{spill}。如需完整结果请缩小检索范围(更精确的 query / 更小的 limit / 更窄的 root)。",
185
186
  spillNote: "(完整输出已落盘:{path})",
186
187
  sandboxWarning: "[zvec-grep] 警告:{denied}——下面的结果可能缺少被拒读写的文件,别把它当成全工作区的完整检索结论。",
@@ -213,6 +214,10 @@ const MESSAGES = {
213
214
  clientModeInvalid: "zg 传输模式非法:{received}(合法取值:{allowed})",
214
215
  previewInvalid: "预览档位非法:{received}(合法取值:{allowed})",
215
216
  refreshInvalid: "刷新策略非法:{received}(合法取值:{allowed})",
217
+ refreshBackgroundNeedsServer: "{root} 没有可用的 zg 守护进程,`refresh=background` 因此被拒绝——它只在守护进程模式下成立。缺了守护进程时这次调用要的是 background,而上游只会往 stderr 打一行 warning 就把**刷新整个关掉**,所以这里不再替它把「没刷新」说成「后台在刷」。两条出路:按默认 refresh=wait(检索前同步刷到最新,直连模式可用),或在持有终端时先执行 `zg server on` 再来要后台刷新——后者还会顺带带来索引增量刷新与常驻的模型池。",
218
+ refreshBackgroundPinnedDirect: "{root} 这次检索把 `refresh=background` 拒绝了:本 daemon 的传输模式被部署钉死在 direct(行 config 的 `clientMode: direct`),而后台刷新只在 server 模式下存在。这一档**不是**起一个守护进程能解决的——出路是把行 config 的 clientMode 改回 auto 或 server,或按缺省的 refresh=wait 检索。",
219
+ serverReadyNote: "[zvec-grep] 守护进程:就绪(检索可走 server 模式:索引增量刷新、embedding 模型池常驻)",
220
+ serverUnavailableNote: "[zvec-grep] 守护进程:未就绪。检索因此按直连模式逐次冷加载 embedding 模型(大工作区会更慢,且 refresh=background 不可用);需要增量索引与常驻模型池时,请在持有终端执行 `zg server on`",
216
221
  symbolTypeInvalid: "符号类型非法:{received}(合法取值:{allowed},只接受小写)",
217
222
  rootEscapesFs: "root 含越界的 .. 段:{path}",
218
223
  rootMustBeString: "root 必须是字符串(收到 {received})",
@@ -230,6 +235,7 @@ const MESSAGES = {
230
235
  exhaustiveConflicts: "穷举检索(rg=true)与下列索引侧参数互斥:{names}。穷举是纯词法匹配,不支持这些参数;把它们去掉,或先建索引(zg_index)再用索引检索",
231
236
  embeddingNotAllowed: "embedding 引用 {reference} 不在本地候选清单内,而本部署未开放远程 embedding。远程 embedding 会把工作区内容送到外部端点,必须由用户在部署配置里显式开放(allowRemoteEmbedding),本插件不接受模型侧开启。可选本地模型:{choices}。若用户确已自行配好远程凭据(zg config provider set / zg auth grant <root> --capability embedding --scope workspace),请在插件部署配置里打开对应开关后重试。",
232
237
  dropWithResetPaths: "drop 与 resetPaths 互斥:--drop 整条命令只有删除索引一件事,resetPaths 无处安放(上游 zg 也拒这一对)。要清继承的文件选择设置,请不要传 drop。",
238
+ ignoreFileMissing: "ignoreFiles 里的 {path} 在 {root} 下不是一份「存在且当前进程可读的文件」(不存在、是目录、或有文件但读不了都算)。上游 zg 遇到读不成的忽略文件不会按「没有这条规则」继续,而是整次索引失败(ENOENT / EISDIR / EACCES),并把这条坏路径写进工作区索引状态——此后这条树上的 zg index / zg status 都会报同一个错,--reset-paths 也清不掉,只有 zg_index drop 能救。请给一个真实存在、当前用户可读的忽略文件路径。",
233
239
  exhaustiveFallbackNote: "[zvec-grep] 该工作区(含向上各级)尚无 zg 索引,已自动改用穷举词法检索(rg 模式)。结果是逐行字面匹配,不是语义相关度排序;需要语义检索请先 zg_index 建索引。",
234
240
  rgDescription: "穷举词法检索(对应 zg query --rg):不需要索引,逐行字面匹配。留空则在工作区无索引时自动改用它、有索引时照常走索引检索。显式 false 可要求只用索引检索(无索引即报错)。它不支持 preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries,且不发放 grep/rg 配额",
235
241
  intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
@@ -256,7 +262,7 @@ const MESSAGES = {
256
262
  fuseDescription: "Fuse all groups into a single ranking",
257
263
  limitDescription: "Max hits per group, 1-50, default 10",
258
264
  previewDescription: "How much source each hit carries: none anchor line only, short anchor plus a bounded context window, full the whole chunk. Default short",
259
- refreshDescription: "How the index is refreshed before searching: wait refresh to the latest (default), off does not refresh, background hands it to the daemon. Note that background only holds in daemon mode; in direct mode zg degrades it to off and says so on stderr",
265
+ refreshDescription: "How the index is refreshed before searching: wait refreshes to the latest (default), off does not refresh, background hands it to the daemon. background needs a ready daemon: without one it is refused before the command is built (in direct mode zg silently turns refreshing off and leaves one stderr warning, which would report \"refreshing in the background\" when nothing refreshes) — run `zg server on` in a terminal to get it",
260
266
  globsDescription: "Path globs (e.g. src/**), a single string or an array",
261
267
  globsIndexDescription: "Path globs",
262
268
  insensitiveGlobsDescription: "Case-insensitive globs",
@@ -311,7 +317,7 @@ const MESSAGES = {
311
317
  rebuildWaitTimeout: "timed out after about {seconds}s waiting for the rebuild of {root}; it may still be running. Retry later. No grep/rg quota is granted: the index is unreadable while the rebuild runs.",
312
318
  rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
313
319
  statusRebuilding: "{root} is being rebuilt (job {jobId}). The index is unreadable while the rebuild runs; searches wait for it to finish and retry. Watch live output in the settings card rebuild panel. Asking whether the index is ready right now would get a negative answer anyway — ask again once the rebuild settles.",
314
- statusNotReady: "[zvec-grep] the index for {root} is **not ready** (the full zg readiness report is above). This is not an execution failure, it is the conclusion checkReady=true asked for: {detail}",
320
+ statusNotReady: "[zvec-grep] the index for {root} is **not ready** (the full zg readiness report is above). This is not an execution failure, it is the conclusion checkReady=true asked for: {detail} If refreshes keep failing (wording like `read only mode` means writes are refused), that is the index's own state — rebuild it to recover: zg_index(root=\"…\", confirm=true, rebuild=true).",
315
321
  checkReadyDescription: "Readiness verdict: the readiness report is still returned, and the tool additionally states whether the index is ready. Not-ready is not an execution failure — the report still comes back",
316
322
  traceDescription: "For troubleshooting: every hit carries a search trace saying which routes recalled it, its rank in each group, and its score. Output gets noticeably longer; exhaustive (rg) search does not support this parameter",
317
323
  indexBackgroundStarted: "Indexing for {root} started in the background (job {jobId}), command: {command}. Until it settles, semantic search on that root waits for it and retries, and grep/rg are not subject to the gate during that window. Use zg_status to check readiness; this call grants no grep/rg quota",
@@ -328,6 +334,7 @@ const MESSAGES = {
328
334
  genericFailure: "zg failed (exit={exit}){detail}",
329
335
  detailPrefix: " details: {detail}",
330
336
  detailColon: ": {detail}",
337
+ noErrorCodeHint: "(this failure carries no structured `Code:` line from zg, so it cannot be attributed by code. Without `--debug` upstream collapses some failures into a single uncode line — have a user with a terminal re-run the same command with `--debug` for attributable output)",
331
338
  outputTruncated: "[zvec-grep] note: output exceeded the {maxBytes} byte limit and was truncated, only the tail is kept{spill}. Narrow the search for full results (sharper query / smaller limit / narrower root).",
332
339
  spillNote: " (full output spilled to {path})",
333
340
  sandboxWarning: "[zvec-grep] warning: {denied} — the result below may be missing files that were denied; do not treat it as a complete whole-workspace conclusion.",
@@ -360,6 +367,10 @@ const MESSAGES = {
360
367
  clientModeInvalid: "invalid zg client mode: {received} (allowed: {allowed})",
361
368
  previewInvalid: "invalid preview mode: {received} (allowed: {allowed})",
362
369
  refreshInvalid: "invalid refresh policy: {received} (allowed: {allowed})",
370
+ refreshBackgroundNeedsServer: "{root} has no available zvec-grep daemon, so `refresh=background` was refused — it only holds in server mode. Without a daemon the CLI prints one stderr warning and silently turns refreshing **off**, which this plugin will not report as \"refreshing in the background\". Either keep the default refresh=wait (synchronous refresh before the search, works in direct mode) or run `zg server on` in a terminal first — the daemon also brings incremental indexing and a resident embedding model pool.",
371
+ refreshBackgroundPinnedDirect: "{root}: `refresh=background` was refused because this daemon's transport mode is pinned to direct by the deployment (the row config's `clientMode: direct`), while background refreshing only exists in server mode. Starting a daemon would not help here — either set clientMode back to auto/server in the row config, or search with the default refresh=wait.",
372
+ serverReadyNote: "[zvec-grep] daemon: ready (searches can use server mode: incremental index refresh, resident embedding model pool)",
373
+ serverUnavailableNote: "[zvec-grep] daemon: not ready. Searches therefore run in direct mode and cold-load the embedding model every call (slower on large workspaces, and refresh=background is unavailable); run `zg server on` in a terminal for incremental indexing and a resident model pool",
363
374
  symbolTypeInvalid: "invalid symbol type: {received} (allowed: {allowed}; lowercase only)",
364
375
  rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
365
376
  rootMustBeString: "root must be a string (received {received})",
@@ -377,6 +388,7 @@ const MESSAGES = {
377
388
  exhaustiveConflicts: "exhaustive search (rg=true) conflicts with these indexed-search parameters: {names}. Exhaustive search is pure lexical matching and does not support them; drop them, or build an index first (zg_index) and search the index",
378
389
  embeddingNotAllowed: "embedding reference {reference} is not in the local catalog, and this deployment has not enabled remote embedding. Remote embedding sends workspace content to an external endpoint and must be turned on explicitly by the user in the deployment config (allowRemoteEmbedding); this plugin never lets the model side enable it. Local choices: {choices}. If the user has already set up remote credentials themselves (zg config provider set / zg auth grant <root> --capability embedding --scope workspace), enable the matching deployment setting and retry.",
379
390
  dropWithResetPaths: "drop conflicts with resetPaths: --drop does nothing but delete the index, so resetPaths has nowhere to go (upstream zg rejects the pair too). To clear inherited file-selection settings, do not pass drop.",
391
+ ignoreFileMissing: "{path} under {root} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). Upstream zg does not treat a failed ignore-file read as \"no such rule\": the whole indexing run fails (ENOENT / EISDIR / EACCES) and the bad path is written into the workspace index state, after which every zg index / zg status on that tree reports the same error — even --reset-paths cannot clear it, only zg_index drop can. Give a path that really exists and that the current user can read.",
380
392
  exhaustiveFallbackNote: "[zvec-grep] This workspace (and every directory above it) has no zg index, so the search fell back to exhaustive lexical matching (rg mode). Results are literal line matches, not ranked by semantic relevance; run zg_index first if you need semantic search.",
381
393
  rgDescription: "Exhaustive lexical search (zg query --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries, and it grants no grep/rg quota",
382
394
  intWithReceived: "{name} must be an integer >= {min} (received {received})",
@@ -576,6 +588,16 @@ function refreshOf(value, messages) {
576
588
  }));
577
589
  return value;
578
590
  }
591
+ /**
592
+ * 这次调用**是不是显式要后台刷新**。宿主用它决定要不要探一发守护进程:缺省走 `wait`,
593
+ * 为一档没人要的取值多起一次进程是白给的开销。
594
+ *
595
+ * 这里只做字面量比较、不校验取值:非法的 `refresh`(如 `"Background"`)由 `refreshOf`
596
+ * 在构造期拒,两处判据不重复,也不会出现「先探了进程再报错」那种顺序依赖。
597
+ */
598
+ function requestsBackgroundRefresh(value) {
599
+ return value === "background";
600
+ }
579
601
  /** 合法符号类型名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
580
602
  const SYMBOL_TYPE_NAMES = Object.keys({
581
603
  module: "module",
@@ -743,12 +765,15 @@ function pushSearchGlobs(parts, args, messages) {
743
765
  function singleText(args, messages) {
744
766
  return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
745
767
  }
746
- function buildIndexedCommand(args, root, messages, mode) {
768
+ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
747
769
  const parts = ["zg", "query"];
748
770
  const { routeCount, dashGuard } = pushQueryArgs(parts, args, messages);
749
771
  if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
750
772
  if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
751
- parts.push("--limit", String(clampLimit(args.limit)), "--preview", previewOf(args.preview, messages), "--refresh", refreshOf(args.refresh, messages));
773
+ const refresh = refreshOf(args.refresh, messages);
774
+ if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
775
+ if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
776
+ parts.push("--limit", String(clampLimit(args.limit)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
752
777
  pushSearchGlobs(parts, args, messages);
753
778
  if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
754
779
  if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
@@ -806,10 +831,14 @@ function buildExhaustiveCommand(args, root, messages, mode) {
806
831
  * `exhaustive` 走 zg 的穷举词法通道(`--rg`):不需要索引,是「工作区尚无索引」时的
807
832
  * 首选路径。选哪条路由由**宿主**判(它才有索引探测能力),本纯函数只按判据构造——
808
833
  * 判据见 host.ts 的 pickExhaustive。
834
+ *
835
+ * `backgroundSupport` 是宿主算得的「后台刷新能不能用」,只有索引通道用得上(穷举通道本就
836
+ * 不接受 refresh)。缺省按**不可用**处理:拿不到判据时把 background 拒掉是安全的一侧,而把
837
+ * 「没算出来」当成「可用」放行等于把一句假话发给模型。
809
838
  */
810
- function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false) {
839
+ function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false, backgroundSupport = "daemon-down") {
811
840
  const root = assertAbsoluteRoot(args.root, messages);
812
- return exhaustive ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode);
841
+ return exhaustive ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode, backgroundSupport);
813
842
  }
814
843
  /** 非负/正整数字符串化;非数值类型或非整数报错(`true` 不算 1)。 */
815
844
  function intFlag(value, name, messages, min) {
@@ -1057,16 +1086,19 @@ function tokenizeShell(command) {
1057
1086
  const state = {
1058
1087
  buffer: "",
1059
1088
  atCommand: true,
1089
+ pipedNext: false,
1060
1090
  quote: ""
1061
1091
  };
1062
1092
  const flush = () => {
1063
1093
  if (state.buffer.length > 0) {
1064
1094
  tokens.push({
1065
1095
  text: state.buffer,
1066
- atCommand: state.atCommand
1096
+ atCommand: state.atCommand,
1097
+ piped: state.pipedNext
1067
1098
  });
1068
1099
  state.buffer = "";
1069
1100
  state.atCommand = false;
1101
+ state.pipedNext = false;
1070
1102
  }
1071
1103
  };
1072
1104
  let index = 0;
@@ -1083,6 +1115,7 @@ function tokenizeShell(command) {
1083
1115
  else if (COMMAND_BREAK_CHARS.has(char)) {
1084
1116
  flush();
1085
1117
  state.atCommand = true;
1118
+ state.pipedNext = char === "|";
1086
1119
  } else if (TOKEN_BREAK_CHARS.has(char)) flush();
1087
1120
  else state.buffer += char;
1088
1121
  index += 1;
@@ -1099,23 +1132,43 @@ function baseName(text) {
1099
1132
  * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
1100
1133
  * env…)之后的第一个实参。
1101
1134
  */
1102
- function commandPositionTokens(tokens) {
1135
+ function commandPositionIndexes(tokens) {
1103
1136
  const out = [];
1104
1137
  let afterPrefix = false;
1105
- for (const token of tokens) {
1138
+ for (const [index, token] of tokens.entries()) {
1106
1139
  const isCommand = token.atCommand || afterPrefix;
1107
- if (isCommand) out.push(token);
1140
+ if (isCommand) out.push(index);
1108
1141
  afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(token.text));
1109
1142
  }
1110
1143
  return out;
1111
1144
  }
1112
1145
  /**
1146
+ * 该命令位 token 之后的实参里是否出现路径形状的操作数(旗标不算)。
1147
+ * `.` 与 `..` 都算:`grep foo .` 检索的就是当前工作区。
1148
+ */
1149
+ function hasPathOperand(tokens, from) {
1150
+ for (const token of tokens.slice(from + 1)) {
1151
+ if (token.atCommand) break;
1152
+ if (!token.text.startsWith("-") && (token.text.startsWith("/") || token.text.includes("/") || token.text === "." || token.text === "..")) return true;
1153
+ }
1154
+ return false;
1155
+ }
1156
+ /**
1113
1157
  * 识别 bash/pwsh 命令串里的 grep/rg 检索调用:引号/注释感知切词后,只认
1114
1158
  * **命令位**上的 token 名(basename)精确匹配 grep/egrep/fgrep/rg
1115
- * (大小写不敏感)。管道 `… | grep foo`、绝对路径 `/usr/bin/rg foo`、
1116
- * `git grep foo`、`find … | xargs grep TODO` 均算检索;`--grep=x` 选项、路径
1117
- * 片段(grepbar)、引号内字面量与注释里的 grep 都不算。
1118
- * 已知近似(均为漏拦方向,代价由 systemPrompt 路由文本兜底):
1159
+ * (大小写不敏感)。绝对路径 `/usr/bin/rg foo`、`git grep foo`、
1160
+ * `find … | xargs grep TODO` 均算检索;`--grep=x` 选项、路径片段(grepbar)、
1161
+ * 引号内字面量与注释里的 grep 都不算。
1162
+ *
1163
+ * **管道下游且不带路径操作数的那一类不算检索**(`ps aux | grep node`、
1164
+ * `dscacheutil -q host | grep ip_address`、`env | grep KEY`):它的输入是上一段
1165
+ * 命令的 stdout,不检索文件系统,门禁要求的「先语义检索」对它无从谈起
1166
+ * (实测:本机用 `dscacheutil … | grep` 查 DNS 被拦,属误拦)。
1167
+ * 带路径操作数的管道调用照旧算检索;`cat a.txt | grep foo` 按此判据会被放行
1168
+ * (上游确实读了工作区文件)——方向是漏拦,与 hasExternalTarget 的既有取舍同侧,
1169
+ * 代价由 systemPrompt 路由文本兜底。
1170
+ *
1171
+ * 已知近似(均为漏拦方向):
1119
1172
  * - --help/--version/-V 豁免按整条命令判断(`rg a --version && grep b c`
1120
1173
  * 复合命令会漏拦 grep);
1121
1174
  * - shell 关键字(`for … ; do grep`、`if … ; then rg`)不是控制符,其后的
@@ -1124,7 +1177,11 @@ function commandPositionTokens(tokens) {
1124
1177
  function isGrepRgCommand(command) {
1125
1178
  const tokens = tokenizeShell(command);
1126
1179
  if (tokens.some((token) => PROBE_FLAGS.has(token.text))) return false;
1127
- return commandPositionTokens(tokens).some((token) => GREP_COMMAND_NAMES.has(baseName(token.text)));
1180
+ return commandPositionIndexes(tokens).some((index) => {
1181
+ const token = tokens[index];
1182
+ if (token === void 0 || !GREP_COMMAND_NAMES.has(baseName(token.text))) return false;
1183
+ return !(token.piped && !hasPathOperand(tokens, index));
1184
+ });
1128
1185
  }
1129
1186
  /** 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。 */
1130
1187
  function normalizeRoot(path) {
@@ -1778,6 +1835,20 @@ function failureDetail(result, messages) {
1778
1835
  function withDetail(detail, prefix) {
1779
1836
  return detail.length > 0 ? fill(prefix, { detail }) : "";
1780
1837
  }
1838
+ /**
1839
+ * zg 的结构化失败在 stderr 上以一行 `Code: <CODE>` 交出错误码(上游 `src/cli/errors.ts`),
1840
+ * 本包所有按码归因的判据都读那一行。**缺了这一行**就意味着这次失败没有可机读的码,而上游
1841
+ * 恰好有两类塌法会长这样:不带 `--debug` 时 `MODEL2VEC_DOWNLOAD_FAILED` 与
1842
+ * `INDEXING.FILES_FAILED` 被折成一句无码文案(首次下载 embedding 权重正落在这一档)。
1843
+ * 这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
1844
+ *
1845
+ * 空 detail 不补:什么都没打出来时谈不上「上游把原因塌成了一句」,那条指引只会占住回显预算。
1846
+ * 已有 `Code:` 行时也不补:那时归因本就够了。
1847
+ */
1848
+ const STRUCTURED_ERROR_CODE = /^\s*Code:/imu;
1849
+ function noCodeHint(detail, messages) {
1850
+ return detail.length === 0 || STRUCTURED_ERROR_CODE.test(detail) ? "" : `\n${messages.noErrorCodeHint}`;
1851
+ }
1781
1852
  function shellFailure(result, messages) {
1782
1853
  const runnerFailure = sandboxFailure(result, messages);
1783
1854
  if (runnerFailure !== null) return runnerFailure;
@@ -1792,10 +1863,10 @@ function shellFailure(result, messages) {
1792
1863
  detail: withDetail(detail, messages.detailPrefix)
1793
1864
  });
1794
1865
  if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
1795
- return fill(messages.genericFailure, {
1866
+ return `${fill(messages.genericFailure, {
1796
1867
  exit: result.exitCode,
1797
1868
  detail: withDetail(detail, messages.detailColon)
1798
- });
1869
+ })}${noCodeHint(detail, messages)}`;
1799
1870
  }
1800
1871
  /**
1801
1872
  * 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
@@ -1968,6 +2039,47 @@ function createZgVersionGate(host, config) {
1968
2039
  if (probe !== void 0) throw tooOldZgError(probe, messages);
1969
2040
  } };
1970
2041
  }
2042
+ /** 就绪态缓存时长:daemon 可被随时 `zg server on/off` 起停,比版本探测勤得多。 */
2043
+ const SERVER_READY_TTL_MS = 6e4;
2044
+ /** 探测自身超时:`zg server status` 是纯读,不该借检索超时。 */
2045
+ const SERVER_READY_PROBE_TIMEOUT_MS = 1e4;
2046
+ /** 就绪探测命令行:`--check-ready` 把「就绪与否」 expressed 成退出码。 */
2047
+ const SERVER_READY_COMMAND = "zg server status --check-ready";
2048
+ /** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。 */
2049
+ async function probeServerReady(host, config) {
2050
+ try {
2051
+ const env = zgEnv(config);
2052
+ const spec = host.shell.resolve({
2053
+ command: SERVER_READY_COMMAND,
2054
+ workdir: tmpdir(),
2055
+ timeoutMs: SERVER_READY_PROBE_TIMEOUT_MS,
2056
+ stdoutMaxBytes: config.stdoutMaxBytes,
2057
+ ...env ? { env } : {}
2058
+ });
2059
+ return (await (await host.shell.execute(spec)).result()).exitCode === 0;
2060
+ } catch {
2061
+ return false;
2062
+ }
2063
+ }
2064
+ /**
2065
+ * 建这道门槛。缓存挂闭包(随 apply 生死),TTL 到期后重探。
2066
+ *
2067
+ * **并发不合并**:两条检索同时撞上 TTL 边界会各探一次,多起一发纯读进程而已——
2068
+ * 换来的是没有「在途 Promise 该不该共享」这层状态可测(与版本门槛同一口径)。
2069
+ */
2070
+ function createZgServerGate(host, config) {
2071
+ let cachedAt = 0;
2072
+ let cachedReady = false;
2073
+ let probed = false;
2074
+ return { async ready() {
2075
+ const now = Date.now();
2076
+ if (probed && now - cachedAt < SERVER_READY_TTL_MS) return cachedReady;
2077
+ cachedReady = await probeServerReady(host, config);
2078
+ cachedAt = now;
2079
+ probed = true;
2080
+ return cachedReady;
2081
+ } };
2082
+ }
1971
2083
  /**
1972
2084
  * zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
1973
2085
  * 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
@@ -2191,16 +2303,44 @@ function indexProbeOf(dir) {
2191
2303
  if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
2192
2304
  return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
2193
2305
  }
2194
- /** 工具入参的 root:显式值 > 会话工作区,再过存在性预检(一处三工具共用)。 */
2306
+ /** root 判据的单一来源:显式值 > 会话工作区 → 存在性 → 授权(已观测 / 同一棵树)。 */
2307
+ function judgeRoot(rawRoot, cwd, messages, ledger) {
2308
+ let resolved;
2309
+ try {
2310
+ resolved = assertRootExists(resolveRoot(rawRoot, cwd, messages), messages);
2311
+ } catch (error) {
2312
+ return {
2313
+ allowed: false,
2314
+ reason: errorText(error)
2315
+ };
2316
+ }
2317
+ if (cwd !== void 0 && normalizeRoot(resolved) === normalizeRoot(cwd) || ledger.has(resolved)) return {
2318
+ allowed: true,
2319
+ root: resolved,
2320
+ question: void 0
2321
+ };
2322
+ if (cwd !== void 0 && pathsRelated(resolved, cwd, messages)) return {
2323
+ allowed: true,
2324
+ root: resolved,
2325
+ question: {
2326
+ root: resolved,
2327
+ cwd
2328
+ }
2329
+ };
2330
+ return {
2331
+ allowed: false,
2332
+ reason: fill(messages.rootNotAuthorized, {
2333
+ root: resolved,
2334
+ cwd: cwd ?? messages.rootNoSession
2335
+ })
2336
+ };
2337
+ }
2338
+ /** 工具入参的 root:过 root 判据,放行后登记进白名单(一处三工具共用)。 */
2195
2339
  function rootOf(args, exec, messages, ledger) {
2196
- const cwd = sessionHeaderCwd(exec);
2197
- const root = assertRootExists(resolveRoot(args["root"], cwd, messages), messages);
2198
- if (!ledger.has(root) && (cwd === void 0 || !pathsRelated(root, cwd, messages))) throw new Error(fill(messages.rootNotAuthorized, {
2199
- root,
2200
- cwd: cwd ?? messages.rootNoSession
2201
- }));
2202
- ledger.add(root);
2203
- return root;
2340
+ const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger);
2341
+ if (!decision.allowed) throw new Error(decision.reason);
2342
+ ledger.add(decision.root);
2343
+ return decision.root;
2204
2344
  }
2205
2345
  function define(host, spec) {
2206
2346
  const { parameters } = spec;
@@ -2278,18 +2418,38 @@ const REBUILD_JOB_KIND = "zvec-grep-rebuild";
2278
2418
  const REBUILD_HISTORY_MAX = 10;
2279
2419
  /** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
2280
2420
  const JOB_OUT_VIEW_CHARS = 4e3;
2421
+ /** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
2422
+ function identityOf(view) {
2423
+ return {
2424
+ kind: view.kind,
2425
+ label: view.label,
2426
+ startedAt: view.startedAt
2427
+ };
2428
+ }
2429
+ /** 两段身份证是否同一回事(三段全同才算)。 */
2430
+ function sameIdentity(left, right) {
2431
+ return left.kind === right.kind && left.label === right.label && left.startedAt === right.startedAt;
2432
+ }
2433
+ /**
2434
+ * 身份证尚未盖章时的占位出生时刻。
2435
+ *
2436
+ * `startedAt` 由官方签发(`Date.now()`,永不为 0),而 kind/label 在 `start` 之前就已
2437
+ * 已知——那正是本包递给官方的那份规格。于是"start 的同步块里就跑到了 `run()`"那一档读取
2438
+ * (官方 `start` 会同步跑第一拍)比对时必然落到"对不上":那一刻还没有可比的出生时刻,
2439
+ * 不该把同 id 的另一条作业当成自己的收走。
2440
+ */
2441
+ const UNSIGNED_STARTED_AT = 0;
2281
2442
  /**
2282
2443
  * 名册里那条 id 是不是**我们**的那条作业。
2283
2444
  *
2284
2445
  * 只比 id 不够:计数器是注册表的实例字段(实测两枚实例对同一 kind 都从 1 开始),换一枚
2285
- * 实例就重名。出生时刻由官方签(`Date.now()`),跨实例撞上同一毫秒的机会与"用户在服务重载后
2286
- * 一毫秒内又起一次重建"同阶,而那已经是另一次用户意图,卡片 404 重来即可。
2446
+ * 实例就重名;那时同 id 指向的是另一条作业(另一棵树/另一条命令),旧卡片跟上去就是串台。
2287
2447
  * @param state 这条记录的状态盒
2288
2448
  * @param view 名册里同 id 的那条投影
2289
2449
  * @returns 同一条作业
2290
2450
  */
2291
- function sameJob(state, view, live) {
2292
- return state.owner === live && state.bornAt === view.startedAt;
2451
+ function sameJob(state, view) {
2452
+ return sameIdentity(state.identity, identityOf(view));
2293
2453
  }
2294
2454
  /** 终止重建进程:kill 异常忽略(进程可能已自然退出/已被回收)。 */
2295
2455
  function killProc(proc) {
@@ -2449,7 +2609,7 @@ function followRunningRebuild(jobs, records, res, root) {
2449
2609
  const following = [...records.values()].find((record) => {
2450
2610
  if (record.root !== root) return false;
2451
2611
  const view = jobView(jobs, record.id);
2452
- return view !== null && sameJob(record.state, view, jobs) && isLiveStatus(view.status);
2612
+ return view !== null && sameJob(record.state, view) && isLiveStatus(view.status);
2453
2613
  });
2454
2614
  if (following === void 0) return false;
2455
2615
  sendJson(res, 200, {
@@ -2625,9 +2785,9 @@ function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlM
2625
2785
  }
2626
2786
  };
2627
2787
  }
2628
- /** 引导端点:交回本次 apply 生成的 CSRF token 与白名单里观测到的工作区。 */
2629
- function handleRebuildRoots(routes, req, res) {
2630
- const { csrf, ledger, servingNonLoopback } = routes;
2788
+ /** 引导端点:交回本次 apply 生成的 CSRF token、白名单里观测到的工作区,以及守护进程就绪态。 */
2789
+ async function handleRebuildRoots(routes, req, res) {
2790
+ const { csrf, ledger, servingNonLoopback, serverGate } = routes;
2631
2791
  if (!guardTrust(req, res, { servingNonLoopback })) return;
2632
2792
  if (req.method !== "GET" && req.method !== "HEAD") {
2633
2793
  res.setHeader("Allow", "GET");
@@ -2637,10 +2797,12 @@ function handleRebuildRoots(routes, req, res) {
2637
2797
  });
2638
2798
  return;
2639
2799
  }
2800
+ const serverReady = await serverGate.ready();
2640
2801
  sendJson(res, 200, {
2641
2802
  ok: true,
2642
2803
  csrf,
2643
- roots: ledger.list()
2804
+ roots: ledger.list(),
2805
+ serverReady
2644
2806
  });
2645
2807
  }
2646
2808
  /**
@@ -2663,7 +2825,7 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2663
2825
  const live = jobsOf();
2664
2826
  if (live === void 0) return null;
2665
2827
  const view = jobView(live, handle.id);
2666
- if (view === null || !sameJob(state, view, live)) return null;
2828
+ if (view === null || !sameJob(state, view)) return null;
2667
2829
  return {
2668
2830
  jobs: live,
2669
2831
  status: view.status
@@ -2699,6 +2861,49 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2699
2861
  };
2700
2862
  }
2701
2863
  /**
2864
+ * `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
2865
+ *
2866
+ * 为什么必须预检(全部实测,见 test/e2e/zg-cli.test.ts):真 zg 遇到读不成的 ignore 文件
2867
+ * **不是**按"没有这条规则"继续,而是整次索引失败(`ZVEC_GREP.ENGINE.INDEXING.WORKSPACE_FAILED`,
2868
+ * 原因是 ENOENT / EACCES / EISDIR),并且那个坏路径会**写进工作区索引的状态**——此后这条树上的
2869
+ * `zg index` 与 `zg status` 都报同一个错,`--reset-paths` 清不掉,只有 `zg_index drop`(整棵
2870
+ * 索引删掉重来)能救。一个拼错的文件名、一个存在但读不了的文件(mode 000 / 他人属主,用绝对路径
2871
+ * 还够得着系统文件)、或一个目录,就把用户的工作区索引弄坏,属于必须在起进程之前拦下的那一类。
2872
+ *
2873
+ * 判据「读得了 + 是文件」合成**一次** try(accessSync 在前):`statSync().isFile()` 对 mode 000
2874
+ * 的文件照样返回 true(stat 只要父目录可搜索、不要文件本身可读),故先 `accessSync(R_OK)` 补上
2875
+ * "当前进程真能 open 来读"这半段——它与 zg 的读权限同 uid 同源(root 下两者都放行、非 root 下
2876
+ * 两者都拒);再用 `isFile()` 挡掉目录。**不拆成「不存在」与「读不了」两条独立分支**:可读性那
2877
+ * 一档在 windows(chmod 只翻只读位,属主仍读得了)与 root(绕过 DAC)下根本造不出来,拆成独立
2878
+ * 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
2879
+ * 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
2880
+ *
2881
+ * drop 那一臂整段跳过:`--drop` 的命令只有 `zg index <root> --drop --yes`,ignoreFiles 被
2882
+ * buildIndexCommand 静默丢掉、根本不进 zg(见 lib/cli.ts 的 drop 分支),预检它没有意义,还会
2883
+ * 拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。判 drop 用与构造器**同一个**
2884
+ * `boolOf`,两处口径不会漂。
2885
+ * @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
2886
+ * @param root 已归一的工作区根(相对路径按它解析)
2887
+ * @param messages 文案表
2888
+ * @returns {void}
2889
+ * @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项)
2890
+ */
2891
+ function assertIgnoreFilesExist(args, root, messages) {
2892
+ if (boolOf(args.drop, "drop", messages)) return;
2893
+ for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
2894
+ const target = entry.startsWith("/") ? entry : `${root}/${entry}`;
2895
+ let usable = false;
2896
+ try {
2897
+ accessSync(target, constants.R_OK);
2898
+ usable = statSync(target).isFile();
2899
+ } catch {}
2900
+ if (!usable) throw new Error(fill(messages.ignoreFileMissing, {
2901
+ path: entry,
2902
+ root
2903
+ }));
2904
+ }
2905
+ }
2906
+ /**
2702
2907
  * 起一条 `zg index`:命令构造 + resolve + execute 三步。
2703
2908
  *
2704
2909
  * 设置卡重建端点与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
@@ -2721,6 +2926,7 @@ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
2721
2926
  let spawned;
2722
2927
  try {
2723
2928
  await routes.versionGate.ensure(started);
2929
+ assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started), started);
2724
2930
  const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
2725
2931
  const env = zgEnv(config);
2726
2932
  const spec = host.shell.resolve({
@@ -2767,18 +2973,20 @@ function attachIndexWrite(routes, root, started, spawned) {
2767
2973
  }
2768
2974
  pruneRebuildHistory(starting, records);
2769
2975
  const state = {
2770
- bornAt: 0,
2771
- owner: null,
2976
+ identity: {
2977
+ kind: REBUILD_JOB_KIND,
2978
+ label: command,
2979
+ startedAt: UNSIGNED_STARTED_AT
2980
+ },
2772
2981
  lost: false,
2773
2982
  timeoutNote: null
2774
2983
  };
2775
2984
  let jobId;
2776
2985
  try {
2777
2986
  jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
2778
- state.bornAt = starting.get(jobId).startedAt;
2779
- state.owner = starting;
2987
+ state.identity = identityOf(starting.get(jobId));
2780
2988
  const clashed = records.get(jobId);
2781
- if (clashed !== void 0 && clashed.state.owner !== starting) {
2989
+ if (clashed !== void 0 && !sameIdentity(clashed.state.identity, state.identity)) {
2782
2990
  killProc(proc);
2783
2991
  return {
2784
2992
  error: started.endpointRegistryReplaced,
@@ -2896,7 +3104,7 @@ function handleRebuildStatus(routes, req, res) {
2896
3104
  });
2897
3105
  return;
2898
3106
  }
2899
- if (!sameJob(record.state, output.view, jobs)) {
3107
+ if (!sameJob(record.state, output.view)) {
2900
3108
  sendJson(res, 404, {
2901
3109
  ok: false,
2902
3110
  error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
@@ -2931,7 +3139,7 @@ function releaseRebuildRecords(routes) {
2931
3139
  if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
2932
3140
  else for (const record of records.values()) {
2933
3141
  const view = jobView(jobs, record.id);
2934
- if (view === null || !sameJob(record.state, view, jobs)) killProc(record.proc);
3142
+ if (view === null || !sameJob(record.state, view)) killProc(record.proc);
2935
3143
  else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
2936
3144
  else jobs.remove(record.id);
2937
3145
  }
@@ -2939,7 +3147,7 @@ function releaseRebuildRecords(routes) {
2939
3147
  }
2940
3148
  /** 设置卡片的「工作区重建」端点组(引导 / 启动 / 轮询)。按语义拆离 apply 主体。 */
2941
3149
  function registerRebuildEndpoints(deps) {
2942
- const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate } = deps;
3150
+ const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate, serverGate } = deps;
2943
3151
  const webServer = host.get("webServer");
2944
3152
  if (!webServer) return;
2945
3153
  const servingNonLoopback = isNonLoopbackBindHost(webServer.host);
@@ -2955,13 +3163,14 @@ function registerRebuildEndpoints(deps) {
2955
3163
  records,
2956
3164
  rebuilds,
2957
3165
  versionGate,
3166
+ serverGate,
2958
3167
  servingNonLoopback
2959
3168
  };
2960
3169
  const disposeRoots = webServer.register({
2961
3170
  kind: "exact",
2962
3171
  path: REBUILD_ROOTS_PATH,
2963
- handler: (req, res) => {
2964
- handleRebuildRoots(routes, req, res);
3172
+ handler: async (req, res) => {
3173
+ await handleRebuildRoots(routes, req, res);
2965
3174
  }
2966
3175
  });
2967
3176
  const disposeRebuild = webServer.register({
@@ -3196,6 +3405,22 @@ function pickExhaustive(value, hasIndex) {
3196
3405
  return !hasIndex;
3197
3406
  }
3198
3407
  /**
3408
+ * 这次检索能不能用 `refresh=background`(取值语义见 lib/cli.ts 的 BackgroundSupport)。
3409
+ *
3410
+ * 要同时看两件事:**传输模式有没有被部署钉死在 direct**,以及**守护进程是否就绪**。
3411
+ * 钉死 direct 时后者根本无从生效,此时还叫用户去 `zg server on` 是指错方向;而守护进程
3412
+ * 缺席时叫他去起一个是有效的。两档各有各的文案,但判据只有这一处。
3413
+ *
3414
+ * 没人要这一档时交回 `daemon-down`——构造器只在 `refresh` 真的是 background 时才读它,
3415
+ * 于是「不为没人要的档位起一发探测」与「拿不到判据时保守拒绝」两头同时成立,不必再引入
3416
+ * 第三种「不适用」状态。探测结果与 zg_status 的回显、设置卡的引导端点共用同一份 TTL 缓存。
3417
+ */
3418
+ async function backgroundSupportFor(runtime, rawRefresh, mode, exhaustive) {
3419
+ if (exhaustive || !requestsBackgroundRefresh(rawRefresh)) return "daemon-down";
3420
+ if (mode === "direct") return "mode-direct";
3421
+ return await runtime.serverGate.ready() ? "available" : "daemon-down";
3422
+ }
3423
+ /**
3199
3424
  * zg_search 的执行体:登记工作区 → 选通道 → 构造命令 → 前台执行 → 索引通道成功才发配额。
3200
3425
  * @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
3201
3426
  * @param args 官方 deep-frozen 后的工具入参
@@ -3217,7 +3442,8 @@ async function runSearchTool(runtime, args, exec, messages) {
3217
3442
  limit: args["limit"] ?? readDefaultLimit(config)
3218
3443
  };
3219
3444
  await runtime.versionGate.ensure(messages);
3220
- const { command, workdir } = buildSearchCommand(searchArgs, messages, readClientMode(config, messages), exhaustive);
3445
+ const mode = readClientMode(config, messages);
3446
+ const { command, workdir } = buildSearchCommand(searchArgs, messages, mode, exhaustive, await backgroundSupportFor(runtime, args["refresh"], mode, exhaustive));
3221
3447
  const raw = await runForeground(host, command, workdir, config.searchTimeoutMs, {
3222
3448
  signal: exec.signal,
3223
3449
  env: zgEnv(config),
@@ -3338,14 +3564,11 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages) {
3338
3564
  const routes = {
3339
3565
  host: runtime.host,
3340
3566
  config: runtime.config,
3341
- csrf: "",
3342
- ledger: runtime.ledger,
3343
3567
  messages: runtime.messages,
3344
3568
  jobsOf: runtime.jobsOf,
3345
3569
  records: runtime.records,
3346
3570
  rebuilds: runtime.rebuilds,
3347
- versionGate: runtime.versionGate,
3348
- servingNonLoopback: false
3571
+ versionGate: runtime.versionGate
3349
3572
  };
3350
3573
  if (runtime.jobsOf() === void 0) {
3351
3574
  runtime.rebuilds.release(root);
@@ -3382,6 +3605,7 @@ async function runIndexTool(runtime, args, exec, messages) {
3382
3605
  if (rewriting && rebuilds.claim(root, "tool") === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
3383
3606
  if (background) return startBackgroundIndex(runtime, root, indexArgs, messages);
3384
3607
  try {
3608
+ assertIgnoreFilesExist(indexArgs, root, messages);
3385
3609
  const { command, workdir } = buildIndexCommand(indexArgs, readDefaultEmbedding(config), messages, readClientMode(config, messages), allowRemoteEmbedding(config));
3386
3610
  return { text: await runForeground(host, command, workdir, config.indexTimeoutMs, {
3387
3611
  signal: exec.signal,
@@ -3393,23 +3617,6 @@ async function runIndexTool(runtime, args, exec, messages) {
3393
3617
  if (rewriting) rebuilds.release(root);
3394
3618
  }
3395
3619
  }
3396
- /**
3397
- * 模型侧的后台建/重建:一次调用把「起进程 + 登记作业 + 挂超时回收」全做完,把可轮询的
3398
- * 作业号交回模型,然后立刻返回。
3399
- *
3400
- * 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
3401
- * 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
3402
- * `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
3403
- * 轮询端点上完全同形——卡片能看见模型起的重建,反之亦然。
3404
- *
3405
- * 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
3406
- * 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
3407
- * @param runtime apply 的运行时依赖
3408
- * @param root 已过授权与存在性预检的工作区
3409
- * @param indexArgs 已归一 root 的索引入参
3410
- * @param messages 本次 execute 现取的文案表
3411
- * @returns 交给官方 output schema 的 `{ text }`
3412
- */
3413
3620
  /** 注册 zg_index:建/重建/删索引。 */
3414
3621
  function registerIndexTool(runtime, registered) {
3415
3622
  define(runtime.host, {
@@ -3443,7 +3650,7 @@ async function runStatusTool(runtime, args, exec, messages) {
3443
3650
  root,
3444
3651
  checkReady
3445
3652
  }, messages, readClientMode(config, messages));
3446
- return { text: await runForeground(host, command, workdir, config.statusTimeoutMs, {
3653
+ return { text: `${await runForeground(host, command, workdir, config.statusTimeoutMs, {
3447
3654
  signal: exec.signal,
3448
3655
  env: zgEnv(config),
3449
3656
  stdoutMaxBytes: config.stdoutMaxBytes,
@@ -3460,9 +3667,8 @@ async function runStatusTool(runtime, args, exec, messages) {
3460
3667
  detail: failure
3461
3668
  })}` : null;
3462
3669
  } } : {}
3463
- }) };
3670
+ })}\n${await runtime.serverGate.ready() ? messages.serverReadyNote : messages.serverUnavailableNote}` };
3464
3671
  }
3465
- /** 注册 zg_status:索引状态。 */
3466
3672
  function registerStatusTool(runtime, registered) {
3467
3673
  define(runtime.host, {
3468
3674
  name: "zg_status",
@@ -3509,28 +3715,23 @@ function registerRoutingSection(host, registered) {
3509
3715
  * 于是 name/arguments/signal/agent 的键名与值域都由宿主声明负责——两个谓词收到的
3510
3716
  * 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
3511
3717
  */
3512
- /** 显式 root 归一后是否就是本会话工作区;解析不了(畸形参数)一律交回 false。 */
3513
- function sameAsSessionRoot(raw, cwd, messages) {
3514
- if (cwd === void 0) return false;
3515
- try {
3516
- return normalizeRoot(resolveRoot(raw, cwd, messages)) === normalizeRoot(cwd);
3517
- } catch {
3518
- return false;
3519
- }
3520
- }
3521
3718
  /** 该不该为这次调用问一句;不该问就交回 undefined(调用方转交 next())。 */
3522
3719
  function explicitRootAsk(execution, ledger, messages) {
3523
3720
  const raw = (isRecord(execution.arguments) ? execution.arguments : void 0)?.["root"];
3524
- const cwd = sessionHeaderCwd(execution);
3525
- return typeof raw !== "string" || raw.trim().length === 0 || sameAsSessionRoot(raw, cwd, messages) || cwd !== void 0 && ledger.has(raw) ? void 0 : {
3721
+ let question;
3722
+ if (typeof raw === "string" && raw.trim().length > 0) {
3723
+ const decision = judgeRoot(raw, sessionHeaderCwd(execution), messages, ledger);
3724
+ question = decision.allowed ? decision.question : void 0;
3725
+ }
3726
+ return question === void 0 ? void 0 : {
3526
3727
  kind: "ask",
3527
3728
  reason: fill(messages.rootApprovalReason, {
3528
- root: raw,
3529
- cwd: cwd ?? messages.rootNoSession
3729
+ root: question.root,
3730
+ cwd: question.cwd
3530
3731
  }),
3531
3732
  displayReason: {
3532
- en: fill(MESSAGES.en.rootApprovalPrompt, { root: raw }),
3533
- zh: fill(MESSAGES.zh.rootApprovalPrompt, { root: raw })
3733
+ en: fill(MESSAGES.en.rootApprovalPrompt, { root: question.root }),
3734
+ zh: fill(MESSAGES.zh.rootApprovalPrompt, { root: question.root })
3534
3735
  }
3535
3736
  };
3536
3737
  }
@@ -3543,11 +3744,14 @@ function explicitRootAsk(execution, ledger, messages) {
3543
3744
  * 用户点「允许一次」才放行;approval 服务缺席、或策略是 `never`(danger-full-access 预设 /
3544
3745
  * 委派子代理)时,宿主把 ask **确定性降级成拒绝**(core/tools 的 serviceAsk)。
3545
3746
  *
3546
- * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且那个 root 既不是本会话工作区、
3547
- * 也不在本包已登记的根集合里。也就是 rootOf() 走「互为祖先/后代」那条放行路径时——
3548
- * 会话开在 /repo/pkg 而模型要去检索 /repo,用户最该被问一句的就是这种。
3747
+ * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且这次调用要靠 rootOf() 的
3748
+ * 「与会话工作区互为祖先/后代」那一条才放行——会话开在 /repo/pkg 而模型要去检索 /repo,
3749
+ * 用户最该被问一句的就是这种。判据与 rootOf **同源于 judgeRoot**,因此两类调用不再被误问:
3750
+ * - 注定被拒的(越界、目录不存在、解析不了、没有会话工作区可作参照):一次确认都换不来放行,
3751
+ * 弹窗只是让用户为一个无法兑现的承诺点按钮;
3752
+ * - 无需授权的(root 就是会话工作区本身、或这台 daemon 已观测过):本来就是用户自己开的路径。
3549
3753
  *
3550
- * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 不存在/越界照样被拒。
3754
+ * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 越界照样被拒。
3551
3755
  * 用户批准只对本次调用生效,不会把那个 root 写进白名单(那是 rootOf 成功后的事)。
3552
3756
  */
3553
3757
  function registerRootApproval(runtime) {
@@ -3596,7 +3800,7 @@ function registerToolGuards(runtime) {
3596
3800
  * @returns {void}
3597
3801
  */
3598
3802
  function registerRebuildRoutes(runtime, csrf) {
3599
- const { config, host, ledger, messages, rebuilds, versionGate } = runtime;
3803
+ const { config, host, ledger, messages, rebuilds, versionGate, serverGate } = runtime;
3600
3804
  host.inject(["webServer"], (child) => {
3601
3805
  registerRebuildEndpoints({
3602
3806
  ctx: child,
@@ -3608,7 +3812,8 @@ function registerRebuildRoutes(runtime, csrf) {
3608
3812
  rebuilds,
3609
3813
  jobsOf: runtime.jobsOf,
3610
3814
  records: runtime.records,
3611
- versionGate
3815
+ versionGate,
3816
+ serverGate
3612
3817
  });
3613
3818
  });
3614
3819
  }
@@ -3627,6 +3832,7 @@ function apply(ctx, config) {
3627
3832
  indexProbe: createIndexProbeCache(indexProbeOf),
3628
3833
  rebuilds: createRebuildRegistry(),
3629
3834
  versionGate: createZgVersionGate(host, config),
3835
+ serverGate: createZgServerGate(host, config),
3630
3836
  jobsOf: () => host.get("jobs"),
3631
3837
  records: /* @__PURE__ */ new Map(),
3632
3838
  sessionParent: (id) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jayyuen66/dsh-zvec-grep",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "dsh 工作区语义检索插件(zg):zg_search / zg_index / zg_status + 本地 embedding 设置卡片 + systemPrompt 路由规则 + guard 安全兜底。",
5
5
  "keywords": [
6
6
  "cordis",
@@ -50,6 +50,7 @@
50
50
  "@deepseek-ai/cordis": "4.0.5-alpha.1",
51
51
  "@deepseek-ai/cordis-plugin-timer": "1.1.7-alpha.1",
52
52
  "@deepseek-ai/dsh-api-remotes": "0.2.1-alpha.2",
53
+ "@deepseek-ai/dsh-bash-local": "0.2.1-alpha.2",
53
54
  "@deepseek-ai/dsh-client-locale": "0.2.1-alpha.2",
54
55
  "@deepseek-ai/dsh-client-store": "0.2.1-alpha.2",
55
56
  "@deepseek-ai/dsh-client-ui-layout": "0.2.1-alpha.2",
@@ -58,6 +59,7 @@
58
59
  "@deepseek-ai/dsh-client-ui-settings": "0.2.1-alpha.2",
59
60
  "@deepseek-ai/dsh-client-ui-slots": "0.2.1-alpha.2",
60
61
  "@deepseek-ai/dsh-host-webserver": "0.2.1-alpha.2",
62
+ "@deepseek-ai/dsh-http-proxy": "0.2.1-alpha.2",
61
63
  "@deepseek-ai/dsh-jobs": "0.2.1-alpha.2",
62
64
  "@deepseek-ai/dsh-jobs-local": "0.2.1-alpha.2",
63
65
  "@deepseek-ai/dsh-llm": "0.2.1-alpha.2",
@@ -70,7 +72,9 @@
70
72
  "@deepseek-ai/dsh-settings": "0.2.1-alpha.2",
71
73
  "@deepseek-ai/dsh-shell": "0.2.1-alpha.2",
72
74
  "@deepseek-ai/dsh-subprocess": "0.2.1-alpha.2",
75
+ "@deepseek-ai/dsh-subprocess-local": "0.2.1-alpha.2",
73
76
  "@deepseek-ai/dsh-system-prompt": "0.2.1-alpha.2",
77
+ "@deepseek-ai/dsh-timeout": "0.2.1-alpha.2",
74
78
  "@deepseek-ai/dsh-tools": "0.2.1-alpha.2",
75
79
  "@deepseek-ai/dsh-user-approval": "0.2.1-alpha.2",
76
80
  "@deepseek-ai/schemastery": "3.18.5-alpha.1",