@jayyuen66/dsh-zvec-grep 0.1.3 → 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,32 @@
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
+
5
31
  ## 0.1.3
6
32
 
7
33
  修复一处**跟着真实宿主语义失效的作业身份判据**(它让重建轮询恒 404、卸载只杀进程不摘作业 ⇒ 官方环缓冲留在宿主内存),并给 `ignoreFiles` 补上起进程之前的**存在性 + 可读性**预检(一条读不成的忽略文件会永久弄坏整棵工作区索引)。测试面从「单测 + mock 宿主」扩到三层:新增真宿主半栈的集成层与直怼真 zg CLI 的点对点层。
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,11 +159,12 @@ 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
 
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,11 +155,12 @@ 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
 
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
@@ -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})",
@@ -257,7 +262,7 @@ const MESSAGES = {
257
262
  fuseDescription: "Fuse all groups into a single ranking",
258
263
  limitDescription: "Max hits per group, 1-50, default 10",
259
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",
260
- 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",
261
266
  globsDescription: "Path globs (e.g. src/**), a single string or an array",
262
267
  globsIndexDescription: "Path globs",
263
268
  insensitiveGlobsDescription: "Case-insensitive globs",
@@ -312,7 +317,7 @@ const MESSAGES = {
312
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.",
313
318
  rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
314
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.",
315
- 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).",
316
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",
317
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",
318
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",
@@ -329,6 +334,7 @@ const MESSAGES = {
329
334
  genericFailure: "zg failed (exit={exit}){detail}",
330
335
  detailPrefix: " details: {detail}",
331
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)",
332
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).",
333
339
  spillNote: " (full output spilled to {path})",
334
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.",
@@ -361,6 +367,10 @@ const MESSAGES = {
361
367
  clientModeInvalid: "invalid zg client mode: {received} (allowed: {allowed})",
362
368
  previewInvalid: "invalid preview mode: {received} (allowed: {allowed})",
363
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",
364
374
  symbolTypeInvalid: "invalid symbol type: {received} (allowed: {allowed}; lowercase only)",
365
375
  rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
366
376
  rootMustBeString: "root must be a string (received {received})",
@@ -578,6 +588,16 @@ function refreshOf(value, messages) {
578
588
  }));
579
589
  return value;
580
590
  }
591
+ /**
592
+ * 这次调用**是不是显式要后台刷新**。宿主用它决定要不要探一发守护进程:缺省走 `wait`,
593
+ * 为一档没人要的取值多起一次进程是白给的开销。
594
+ *
595
+ * 这里只做字面量比较、不校验取值:非法的 `refresh`(如 `"Background"`)由 `refreshOf`
596
+ * 在构造期拒,两处判据不重复,也不会出现「先探了进程再报错」那种顺序依赖。
597
+ */
598
+ function requestsBackgroundRefresh(value) {
599
+ return value === "background";
600
+ }
581
601
  /** 合法符号类型名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
582
602
  const SYMBOL_TYPE_NAMES = Object.keys({
583
603
  module: "module",
@@ -745,12 +765,15 @@ function pushSearchGlobs(parts, args, messages) {
745
765
  function singleText(args, messages) {
746
766
  return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
747
767
  }
748
- function buildIndexedCommand(args, root, messages, mode) {
768
+ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
749
769
  const parts = ["zg", "query"];
750
770
  const { routeCount, dashGuard } = pushQueryArgs(parts, args, messages);
751
771
  if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
752
772
  if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
753
- 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);
754
777
  pushSearchGlobs(parts, args, messages);
755
778
  if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
756
779
  if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
@@ -808,10 +831,14 @@ function buildExhaustiveCommand(args, root, messages, mode) {
808
831
  * `exhaustive` 走 zg 的穷举词法通道(`--rg`):不需要索引,是「工作区尚无索引」时的
809
832
  * 首选路径。选哪条路由由**宿主**判(它才有索引探测能力),本纯函数只按判据构造——
810
833
  * 判据见 host.ts 的 pickExhaustive。
834
+ *
835
+ * `backgroundSupport` 是宿主算得的「后台刷新能不能用」,只有索引通道用得上(穷举通道本就
836
+ * 不接受 refresh)。缺省按**不可用**处理:拿不到判据时把 background 拒掉是安全的一侧,而把
837
+ * 「没算出来」当成「可用」放行等于把一句假话发给模型。
811
838
  */
812
- function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false) {
839
+ function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false, backgroundSupport = "daemon-down") {
813
840
  const root = assertAbsoluteRoot(args.root, messages);
814
- 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);
815
842
  }
816
843
  /** 非负/正整数字符串化;非数值类型或非整数报错(`true` 不算 1)。 */
817
844
  function intFlag(value, name, messages, min) {
@@ -1059,16 +1086,19 @@ function tokenizeShell(command) {
1059
1086
  const state = {
1060
1087
  buffer: "",
1061
1088
  atCommand: true,
1089
+ pipedNext: false,
1062
1090
  quote: ""
1063
1091
  };
1064
1092
  const flush = () => {
1065
1093
  if (state.buffer.length > 0) {
1066
1094
  tokens.push({
1067
1095
  text: state.buffer,
1068
- atCommand: state.atCommand
1096
+ atCommand: state.atCommand,
1097
+ piped: state.pipedNext
1069
1098
  });
1070
1099
  state.buffer = "";
1071
1100
  state.atCommand = false;
1101
+ state.pipedNext = false;
1072
1102
  }
1073
1103
  };
1074
1104
  let index = 0;
@@ -1085,6 +1115,7 @@ function tokenizeShell(command) {
1085
1115
  else if (COMMAND_BREAK_CHARS.has(char)) {
1086
1116
  flush();
1087
1117
  state.atCommand = true;
1118
+ state.pipedNext = char === "|";
1088
1119
  } else if (TOKEN_BREAK_CHARS.has(char)) flush();
1089
1120
  else state.buffer += char;
1090
1121
  index += 1;
@@ -1101,23 +1132,43 @@ function baseName(text) {
1101
1132
  * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
1102
1133
  * env…)之后的第一个实参。
1103
1134
  */
1104
- function commandPositionTokens(tokens) {
1135
+ function commandPositionIndexes(tokens) {
1105
1136
  const out = [];
1106
1137
  let afterPrefix = false;
1107
- for (const token of tokens) {
1138
+ for (const [index, token] of tokens.entries()) {
1108
1139
  const isCommand = token.atCommand || afterPrefix;
1109
- if (isCommand) out.push(token);
1140
+ if (isCommand) out.push(index);
1110
1141
  afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(token.text));
1111
1142
  }
1112
1143
  return out;
1113
1144
  }
1114
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
+ /**
1115
1157
  * 识别 bash/pwsh 命令串里的 grep/rg 检索调用:引号/注释感知切词后,只认
1116
1158
  * **命令位**上的 token 名(basename)精确匹配 grep/egrep/fgrep/rg
1117
- * (大小写不敏感)。管道 `… | grep foo`、绝对路径 `/usr/bin/rg foo`、
1118
- * `git grep foo`、`find … | xargs grep TODO` 均算检索;`--grep=x` 选项、路径
1119
- * 片段(grepbar)、引号内字面量与注释里的 grep 都不算。
1120
- * 已知近似(均为漏拦方向,代价由 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
+ * 已知近似(均为漏拦方向):
1121
1172
  * - --help/--version/-V 豁免按整条命令判断(`rg a --version && grep b c`
1122
1173
  * 复合命令会漏拦 grep);
1123
1174
  * - shell 关键字(`for … ; do grep`、`if … ; then rg`)不是控制符,其后的
@@ -1126,7 +1177,11 @@ function commandPositionTokens(tokens) {
1126
1177
  function isGrepRgCommand(command) {
1127
1178
  const tokens = tokenizeShell(command);
1128
1179
  if (tokens.some((token) => PROBE_FLAGS.has(token.text))) return false;
1129
- 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
+ });
1130
1185
  }
1131
1186
  /** 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。 */
1132
1187
  function normalizeRoot(path) {
@@ -1780,6 +1835,20 @@ function failureDetail(result, messages) {
1780
1835
  function withDetail(detail, prefix) {
1781
1836
  return detail.length > 0 ? fill(prefix, { detail }) : "";
1782
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
+ }
1783
1852
  function shellFailure(result, messages) {
1784
1853
  const runnerFailure = sandboxFailure(result, messages);
1785
1854
  if (runnerFailure !== null) return runnerFailure;
@@ -1794,10 +1863,10 @@ function shellFailure(result, messages) {
1794
1863
  detail: withDetail(detail, messages.detailPrefix)
1795
1864
  });
1796
1865
  if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
1797
- return fill(messages.genericFailure, {
1866
+ return `${fill(messages.genericFailure, {
1798
1867
  exit: result.exitCode,
1799
1868
  detail: withDetail(detail, messages.detailColon)
1800
- });
1869
+ })}${noCodeHint(detail, messages)}`;
1801
1870
  }
1802
1871
  /**
1803
1872
  * 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
@@ -1970,6 +2039,47 @@ function createZgVersionGate(host, config) {
1970
2039
  if (probe !== void 0) throw tooOldZgError(probe, messages);
1971
2040
  } };
1972
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
+ }
1973
2083
  /**
1974
2084
  * zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
1975
2085
  * 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
@@ -2193,16 +2303,44 @@ function indexProbeOf(dir) {
2193
2303
  if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
2194
2304
  return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
2195
2305
  }
2196
- /** 工具入参的 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 判据,放行后登记进白名单(一处三工具共用)。 */
2197
2339
  function rootOf(args, exec, messages, ledger) {
2198
- const cwd = sessionHeaderCwd(exec);
2199
- const root = assertRootExists(resolveRoot(args["root"], cwd, messages), messages);
2200
- if (!ledger.has(root) && (cwd === void 0 || !pathsRelated(root, cwd, messages))) throw new Error(fill(messages.rootNotAuthorized, {
2201
- root,
2202
- cwd: cwd ?? messages.rootNoSession
2203
- }));
2204
- ledger.add(root);
2205
- 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;
2206
2344
  }
2207
2345
  function define(host, spec) {
2208
2346
  const { parameters } = spec;
@@ -2647,9 +2785,9 @@ function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlM
2647
2785
  }
2648
2786
  };
2649
2787
  }
2650
- /** 引导端点:交回本次 apply 生成的 CSRF token 与白名单里观测到的工作区。 */
2651
- function handleRebuildRoots(routes, req, res) {
2652
- const { csrf, ledger, servingNonLoopback } = routes;
2788
+ /** 引导端点:交回本次 apply 生成的 CSRF token、白名单里观测到的工作区,以及守护进程就绪态。 */
2789
+ async function handleRebuildRoots(routes, req, res) {
2790
+ const { csrf, ledger, servingNonLoopback, serverGate } = routes;
2653
2791
  if (!guardTrust(req, res, { servingNonLoopback })) return;
2654
2792
  if (req.method !== "GET" && req.method !== "HEAD") {
2655
2793
  res.setHeader("Allow", "GET");
@@ -2659,10 +2797,12 @@ function handleRebuildRoots(routes, req, res) {
2659
2797
  });
2660
2798
  return;
2661
2799
  }
2800
+ const serverReady = await serverGate.ready();
2662
2801
  sendJson(res, 200, {
2663
2802
  ok: true,
2664
2803
  csrf,
2665
- roots: ledger.list()
2804
+ roots: ledger.list(),
2805
+ serverReady
2666
2806
  });
2667
2807
  }
2668
2808
  /**
@@ -3007,7 +3147,7 @@ function releaseRebuildRecords(routes) {
3007
3147
  }
3008
3148
  /** 设置卡片的「工作区重建」端点组(引导 / 启动 / 轮询)。按语义拆离 apply 主体。 */
3009
3149
  function registerRebuildEndpoints(deps) {
3010
- const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate } = deps;
3150
+ const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate, serverGate } = deps;
3011
3151
  const webServer = host.get("webServer");
3012
3152
  if (!webServer) return;
3013
3153
  const servingNonLoopback = isNonLoopbackBindHost(webServer.host);
@@ -3023,13 +3163,14 @@ function registerRebuildEndpoints(deps) {
3023
3163
  records,
3024
3164
  rebuilds,
3025
3165
  versionGate,
3166
+ serverGate,
3026
3167
  servingNonLoopback
3027
3168
  };
3028
3169
  const disposeRoots = webServer.register({
3029
3170
  kind: "exact",
3030
3171
  path: REBUILD_ROOTS_PATH,
3031
- handler: (req, res) => {
3032
- handleRebuildRoots(routes, req, res);
3172
+ handler: async (req, res) => {
3173
+ await handleRebuildRoots(routes, req, res);
3033
3174
  }
3034
3175
  });
3035
3176
  const disposeRebuild = webServer.register({
@@ -3264,6 +3405,22 @@ function pickExhaustive(value, hasIndex) {
3264
3405
  return !hasIndex;
3265
3406
  }
3266
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
+ /**
3267
3424
  * zg_search 的执行体:登记工作区 → 选通道 → 构造命令 → 前台执行 → 索引通道成功才发配额。
3268
3425
  * @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
3269
3426
  * @param args 官方 deep-frozen 后的工具入参
@@ -3285,7 +3442,8 @@ async function runSearchTool(runtime, args, exec, messages) {
3285
3442
  limit: args["limit"] ?? readDefaultLimit(config)
3286
3443
  };
3287
3444
  await runtime.versionGate.ensure(messages);
3288
- 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));
3289
3447
  const raw = await runForeground(host, command, workdir, config.searchTimeoutMs, {
3290
3448
  signal: exec.signal,
3291
3449
  env: zgEnv(config),
@@ -3406,14 +3564,11 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages) {
3406
3564
  const routes = {
3407
3565
  host: runtime.host,
3408
3566
  config: runtime.config,
3409
- csrf: "",
3410
- ledger: runtime.ledger,
3411
3567
  messages: runtime.messages,
3412
3568
  jobsOf: runtime.jobsOf,
3413
3569
  records: runtime.records,
3414
3570
  rebuilds: runtime.rebuilds,
3415
- versionGate: runtime.versionGate,
3416
- servingNonLoopback: false
3571
+ versionGate: runtime.versionGate
3417
3572
  };
3418
3573
  if (runtime.jobsOf() === void 0) {
3419
3574
  runtime.rebuilds.release(root);
@@ -3462,23 +3617,6 @@ async function runIndexTool(runtime, args, exec, messages) {
3462
3617
  if (rewriting) rebuilds.release(root);
3463
3618
  }
3464
3619
  }
3465
- /**
3466
- * 模型侧的后台建/重建:一次调用把「起进程 + 登记作业 + 挂超时回收」全做完,把可轮询的
3467
- * 作业号交回模型,然后立刻返回。
3468
- *
3469
- * 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
3470
- * 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
3471
- * `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
3472
- * 轮询端点上完全同形——卡片能看见模型起的重建,反之亦然。
3473
- *
3474
- * 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
3475
- * 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
3476
- * @param runtime apply 的运行时依赖
3477
- * @param root 已过授权与存在性预检的工作区
3478
- * @param indexArgs 已归一 root 的索引入参
3479
- * @param messages 本次 execute 现取的文案表
3480
- * @returns 交给官方 output schema 的 `{ text }`
3481
- */
3482
3620
  /** 注册 zg_index:建/重建/删索引。 */
3483
3621
  function registerIndexTool(runtime, registered) {
3484
3622
  define(runtime.host, {
@@ -3512,7 +3650,7 @@ async function runStatusTool(runtime, args, exec, messages) {
3512
3650
  root,
3513
3651
  checkReady
3514
3652
  }, messages, readClientMode(config, messages));
3515
- return { text: await runForeground(host, command, workdir, config.statusTimeoutMs, {
3653
+ return { text: `${await runForeground(host, command, workdir, config.statusTimeoutMs, {
3516
3654
  signal: exec.signal,
3517
3655
  env: zgEnv(config),
3518
3656
  stdoutMaxBytes: config.stdoutMaxBytes,
@@ -3529,9 +3667,8 @@ async function runStatusTool(runtime, args, exec, messages) {
3529
3667
  detail: failure
3530
3668
  })}` : null;
3531
3669
  } } : {}
3532
- }) };
3670
+ })}\n${await runtime.serverGate.ready() ? messages.serverReadyNote : messages.serverUnavailableNote}` };
3533
3671
  }
3534
- /** 注册 zg_status:索引状态。 */
3535
3672
  function registerStatusTool(runtime, registered) {
3536
3673
  define(runtime.host, {
3537
3674
  name: "zg_status",
@@ -3578,28 +3715,23 @@ function registerRoutingSection(host, registered) {
3578
3715
  * 于是 name/arguments/signal/agent 的键名与值域都由宿主声明负责——两个谓词收到的
3579
3716
  * 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
3580
3717
  */
3581
- /** 显式 root 归一后是否就是本会话工作区;解析不了(畸形参数)一律交回 false。 */
3582
- function sameAsSessionRoot(raw, cwd, messages) {
3583
- if (cwd === void 0) return false;
3584
- try {
3585
- return normalizeRoot(resolveRoot(raw, cwd, messages)) === normalizeRoot(cwd);
3586
- } catch {
3587
- return false;
3588
- }
3589
- }
3590
3718
  /** 该不该为这次调用问一句;不该问就交回 undefined(调用方转交 next())。 */
3591
3719
  function explicitRootAsk(execution, ledger, messages) {
3592
3720
  const raw = (isRecord(execution.arguments) ? execution.arguments : void 0)?.["root"];
3593
- const cwd = sessionHeaderCwd(execution);
3594
- 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 : {
3595
3727
  kind: "ask",
3596
3728
  reason: fill(messages.rootApprovalReason, {
3597
- root: raw,
3598
- cwd: cwd ?? messages.rootNoSession
3729
+ root: question.root,
3730
+ cwd: question.cwd
3599
3731
  }),
3600
3732
  displayReason: {
3601
- en: fill(MESSAGES.en.rootApprovalPrompt, { root: raw }),
3602
- 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 })
3603
3735
  }
3604
3736
  };
3605
3737
  }
@@ -3612,11 +3744,14 @@ function explicitRootAsk(execution, ledger, messages) {
3612
3744
  * 用户点「允许一次」才放行;approval 服务缺席、或策略是 `never`(danger-full-access 预设 /
3613
3745
  * 委派子代理)时,宿主把 ask **确定性降级成拒绝**(core/tools 的 serviceAsk)。
3614
3746
  *
3615
- * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且那个 root 既不是本会话工作区、
3616
- * 也不在本包已登记的根集合里。也就是 rootOf() 走「互为祖先/后代」那条放行路径时——
3617
- * 会话开在 /repo/pkg 而模型要去检索 /repo,用户最该被问一句的就是这种。
3747
+ * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且这次调用要靠 rootOf() 的
3748
+ * 「与会话工作区互为祖先/后代」那一条才放行——会话开在 /repo/pkg 而模型要去检索 /repo,
3749
+ * 用户最该被问一句的就是这种。判据与 rootOf **同源于 judgeRoot**,因此两类调用不再被误问:
3750
+ * - 注定被拒的(越界、目录不存在、解析不了、没有会话工作区可作参照):一次确认都换不来放行,
3751
+ * 弹窗只是让用户为一个无法兑现的承诺点按钮;
3752
+ * - 无需授权的(root 就是会话工作区本身、或这台 daemon 已观测过):本来就是用户自己开的路径。
3618
3753
  *
3619
- * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 不存在/越界照样被拒。
3754
+ * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 越界照样被拒。
3620
3755
  * 用户批准只对本次调用生效,不会把那个 root 写进白名单(那是 rootOf 成功后的事)。
3621
3756
  */
3622
3757
  function registerRootApproval(runtime) {
@@ -3665,7 +3800,7 @@ function registerToolGuards(runtime) {
3665
3800
  * @returns {void}
3666
3801
  */
3667
3802
  function registerRebuildRoutes(runtime, csrf) {
3668
- const { config, host, ledger, messages, rebuilds, versionGate } = runtime;
3803
+ const { config, host, ledger, messages, rebuilds, versionGate, serverGate } = runtime;
3669
3804
  host.inject(["webServer"], (child) => {
3670
3805
  registerRebuildEndpoints({
3671
3806
  ctx: child,
@@ -3677,7 +3812,8 @@ function registerRebuildRoutes(runtime, csrf) {
3677
3812
  rebuilds,
3678
3813
  jobsOf: runtime.jobsOf,
3679
3814
  records: runtime.records,
3680
- versionGate
3815
+ versionGate,
3816
+ serverGate
3681
3817
  });
3682
3818
  });
3683
3819
  }
@@ -3696,6 +3832,7 @@ function apply(ctx, config) {
3696
3832
  indexProbe: createIndexProbeCache(indexProbeOf),
3697
3833
  rebuilds: createRebuildRegistry(),
3698
3834
  versionGate: createZgVersionGate(host, config),
3835
+ serverGate: createZgServerGate(host, config),
3699
3836
  jobsOf: () => host.get("jobs"),
3700
3837
  records: /* @__PURE__ */ new Map(),
3701
3838
  sessionParent: (id) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jayyuen66/dsh-zvec-grep",
3
- "version": "0.1.3",
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",