@jayyuen66/dsh-zvec-grep 0.1.3 → 0.1.5

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.
Files changed (6) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +42 -26
  3. package/README.zh-CN.md +44 -26
  4. package/client.js +221 -137
  5. package/host.js +1361 -1291
  6. package/package.json +48 -43
package/CHANGELOG.md CHANGED
@@ -2,6 +2,46 @@
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.5-rc
6
+
7
+ 把 **Windows 的支持范围说清楚,并让 CI 按这个范围分工**。直接起因是 `b121e91`(0.1.4)推上去之后 `gate (windows-latest, 22)` 交了 184 条失败:唯一成因是 root 判据只认以 `/` 开头的绝对路径,而 win32 上 `os.tmpdir()` 交回盘符形态(`C:\Users\RUNNER~1\AppData\Local\Temp\…`),凡是要在盘上造真实工作区的用例都在 `rootOf` 先被拒、根本走不到被测行为。**这不是 0.1.4 改出来的**(184 条里 173 条的用例在 0.1.3 就存在,两版对 win32 也只保护了「造不出属主不可读文件」那一档),而是这一格的结果第一次被端上来。
8
+
9
+ ### Changed
10
+
11
+ - **CI 两格分工**:ubuntu 格跑 `pnpm run check`(全部门禁,含四项 100% 覆盖率);其余平台跑新增的 `pnpm run check:platform`——同一套 typecheck / lint / 两个 bundle / 全量用例 / `oxfmt`,只是不判覆盖率。理由写在 `ci.yml` 的注释里:需要盘上真根的用例在 win32 整块跳过之后,`host.ts` 的覆盖率本就到不了 100%,把阈值调低等于把 ubuntu 格的真约束改成装饰。
12
+ - **`test/host.test.ts` 按平台跳过 24 个 suite**(谓词收成一处 `realRootUnavailable = process.platform === "win32"`,各 suite 写 `describe.skipIf(realRootUnavailable)(…)`)。写成字面上的 `describe.skipIf` 而不是包一层别名:oxlint 的 vitest 规则按 `describe` 识别 suite,别名会让整文件被当成一个作用域,实测冒出 221 条 `consistent-test-it` 噪声。**没有**跳过在 win32 上原样通过的那 6 个 suite(信任闸门、白名单有效期、hitSummary、探测缓存、render 全性、隐式注册验收)——跳掉一条本来会绿的用例就是抹掉真实信号。
13
+ - 两份 README 新增「支持面 / Support surface」一节:本包是 POSIX-only,Windows 宿主下三个 zg 工具在 `rootOf` 当场拒并说明原因(fail-fast,不会拿错位路径去拼命令、也不会把错路结果当正常检索交回模型);真要支持 Windows 得动 root 归一、第二套命令形态(pwsh/cmd 的引号与 `bash -c` 不同义)、门禁的 `/` 切词与 `manifest.json` 的 `rootPaths` 比对,属设计变更。
14
+
15
+ ### Fixed
16
+
17
+ - 新增 `test:platform` / `check:platform` 两个脚本,让「不判覆盖率的那套门禁」在 package.json 里单源,CI 只挑命令——避免 workflow 里内联一串命令、日后与本地脚本各走各的。
18
+
19
+ ## 0.1.4
20
+
21
+ 把 **zg 守护进程(server 模式)这一档能力差从「使用限制」变成显式判据**:`--mode auto` 在 daemon 缺席时由上游静默落回 direct(模型逐次冷加载、增量刷新与 `refresh=background` 都不存在),而本包过去既没有一处说明,也没有拦住那个不可能兑现的参数。顺带修掉两处评审确认的缺陷:`requireApprovalForExplicitRoot` 会为**注定被拒**的 root 弹一次换不来放行的确认;两份 README 与 `host.ts` 头注释的配置面数字早已和 schema 脱节(14 vs 16、四个 vs 十枚)。
22
+
23
+ ### Added
24
+
25
+ - **守护进程就绪门槛(`createZgServerGate`)**:按 TTL(60 秒)缓存 `zg server status --check-ready` 的**退出码**(上游契约:就绪 0、未就绪以「zvec-grep server is not ready」非零退出;读 stdout 那份状态表不行,它给人看、不在本包的依赖契约里)。探测失败一律折成「未就绪」,**绝不外抛**基础设施故障,也绝不影响 `wait` / `off` / 穷举检索这些照常能用的通道。本包**不代为 `zg server on`**:那会在用户机器上落下 detached 长驻进程与 token 文件,属该由用户点头的动作。
26
+ - **`refresh=background` 收口(`BackgroundSupport` 三档)**:不可用时在**命令构造期**就拒,并区分两种成因各给一句诚实文案——守护进程缺席(出路是 `zg server on`)与部署把 `clientMode` 钉死 `direct`(此时叫用户起 daemon 是指错方向,出路是回行 config 改模式)。旧行为是让命令照发、由 zg 把刷新整个关掉、只留一行 stderr warning:退出码照旧 0、命中照旧出,唯独「后台在刷新」这件事是假的。判据只有 `backgroundSupportFor` 一处,模式与探测两步都由宿主算(纯构造器只按它折成拒绝);没人要这一档时不起探测,穷举通道也不起(它本就不接受 `refresh`)。
27
+ - **就绪态回显两处**:`zg_status` 的输出尾部各说一句(就绪讲能拿到什么,未就绪讲后果与出路),设置卡新增一行;重建期那条「合成投影」不补——它的契约本就是不启任何子进程。引导端点 `rebuild-roots` 的应答新增 `serverReady`,卡片判据收在可单测的 `daemonNoteKey`:应答里**没有这一位**(旧版 host)时不渲染,而不是把「不知道」显示成「未就绪」。
28
+ - **无 `Code:` 行的失败补一句 `--debug` 指引**:上游不带 `--debug` 时会把 `MODEL2VEC_DOWNLOAD_FAILED` 与 `INDEXING.FILES_FAILED` 塌成一句无码文案(首次下载 embedding 权重正落在这一档),而本包所有按码归因都读那一行 `Code:`。现在只有「非零退出、有输出、却没有 `Code:` 行」那一支补指引;空输出不补(谈不上「塌成一句」),带码的不补(归因本就够)。本包**不默认带** `--debug`:它明显拉长输出,而这三个工具的回显预算是给模型读的。
29
+ - **文档数字的门禁**:`test/readme-parity.test.ts` 新增一条,把中英两份声明的「字段总数 / 卡上 volatile 数 / 非 volatile 部署值数」与导出 `Config` 的实际形状逐一对齐(第三枚是可推导的:总数 - volatile)。原有的结构对等门只能抓到「一侧多了一节」,抓不到两侧一起写错——这次正是两侧一起错。
30
+
31
+ ### Fixed
32
+
33
+ - **`requireApprovalForExplicitRoot` 不再为注定被拒的调用发问**。旧判据是「显式 root 既不是会话工作区、也不在 ledger」,于是对 `/etc`、相对路径、盘上不存在、没有会话工作区可作参照这些 `rootOf` **一律拒**的调用也弹一次确认;用户点「允许一次」之后照样被拒(那道闸刻意只加不减),确认成了让人为一个无法兑现的承诺点按钮。现在发问判据与 `rootOf` **同源**:两者共用同一个 `judgeRoot`,只有「靠与会话工作区互为祖先/后代这一条才放行」的调用才发问。同时删掉 `sameAsSessionRoot` 那第二条判据(它比 `judgeRoot` 宽,正是漏问/误问两侧漂移的来源)。
34
+ - **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 路由文本兜底。
35
+ - **`startBackgroundIndex` 不再构造哑值依赖**。它不是 HTTP 请求,过去要凑出 `RebuildRoutes` 就得给 `csrf` 塞空串、给 `servingNonLoopback` 塞 `false`——两个「没被用到」只靠下游恰好不读它们来保证的占位值。现在把起一条 `zg index` 写操作所需的依赖收窄成 `IndexWriteRoutes`(`RebuildRoutes extends` 它),哑值在类型上不再可能被构造出来。
36
+ - **删掉 `startBackgroundIndex` 那份重复的 JSDoc**:同一段 17 行文档在文件里出现两次,第二份悬在 `registerIndexTool` 头上,指向的却不是它下面那个函数。
37
+
38
+ ### Changed
39
+
40
+ - 引导端点 `/_dsh/zvec-grep/rebuild-roots` 的 handler 转为 async(就绪态要在**信任闸门与方法判定之后**才取,被拒的请求不起子进程)。官方 `WebRoute.handler` 本就允许 `void | Promise<void>`,另两条路由一直是 async 形态。
41
+ - `buildSearchCommand` 新增第五位 `backgroundSupport`(缺省 `daemon-down`:拿不到判据时保守拒绝,而不是把一句假话发给模型);`lib/cli.ts` 导出 `requestsBackgroundRefresh` 供宿主判「要不要探」。
42
+ - 两份 README:`--mode direct` 的过时说法改成按实现的 `auto` 口径并新增「守护进程(server 模式)」一节;配置面数字改成 16 / 6 / 10;`refresh` 与 `requireApprovalForExplicitRoot` 两节跟着上面的行为重写;`host.ts` 头注释同样对齐。
43
+ - 集成层新增一条按环境自适应的用例:`clientMode=auto` 时断言跟着**这台机器上守护进程的真实就绪态**给期望值(无条件式断言,不分支),另有一条钉死 `clientMode=direct` 时「命令根本没发出去」。
44
+
5
45
  ## 0.1.3
6
46
 
7
47
  修复一处**跟着真实宿主语义失效的作业身份判据**(它让重建轮询恒 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
 
@@ -15,7 +15,7 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
15
15
  ```
16
16
 
17
17
  - The packages are on the public npm registry, so no credentials are needed; the published artifact only carries host.js, client.js and cordis.patch.yml (the files field in package.json).
18
- - Runtime value imports are `@jayyuen66/dsh-plugin-shared` (lib/http, lib/locale, lib/text) and `@deepseek-ai/schemastery` (the host's fork — the only one whose resolve wraps `.volatile()` fields into `Volatile` references).
18
+ - Runtime value imports are `@jayyuen66/dsh-plugin-shared` (`lib/locale`, `lib/text`, `lib/record`, `lib/errors`, `lib/job-outcome`, `lib/card-diff`), `@deepseek-ai/schemastery` (the host's fork — the only one whose resolve wraps `.volatile()` fields into `Volatile` references) and `@deepseek-ai/dsh-typert-protocol` (the Remote base class — `TypertRemoteService` is a **class** to `extends`, so there is no type-only way to take it; it is a required peer plus the same exact pin in devDependencies).
19
19
  - shared's own `lib/text` value-imports `@deepseek-ai/dsh-output-retention`, so that host package has to be supplied too, on the same terms as `schemastery`: a required `peerDependency` plus the same exact pin in `devDependencies`, **never** in `dependencies`. Only a gate can hold this line - with the entry missing, typecheck, build and tests are all green and the failure shows up after installation as ERR_MODULE_NOT_FOUND.
20
20
  - Missing either one is `ERR_MODULE_NOT_FOUND` at load, not a graceful downgrade — that is also why the fork cannot be swapped for public `schemastery`.
21
21
  - Only the shared package sits in `dependencies`. `@deepseek-ai/schemastery` is a host package, so it is declared as a **required `peerDependency`** and repeated at the same exact pin in `devDependencies` for this repository's own typecheck/build/tests — never in `dependencies`. That is not a style preference: consumer profiles install with `nodeLinker: hoisted` and `autoInstallPeers: false`, so a host package listed under `dependencies` is written into the profile as a **real directory**, coexisting with the copy the host process already loaded. `@deepseek-ai/dsh-tools` keys its `TOOL_RUNTIME_SCHEDULER` with a plain `Symbol` (not `Symbol.for`), so symbol identity is per module instance: the host's `dsh-agent-loop` gets `undefined` and **every native tool call throws** `Cannot read properties of undefined (reading 'prepare')` — the whole profile loses its tools. Build, typecheck and tests all stay green right up to that point, which is why the invariant is pinned in `test/publish-manifest.test.ts`.
@@ -24,13 +24,20 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
24
24
 
25
25
  - add/remove maintain the registration line `- id: zvec-grep` (name points at this package) from the in-package cordis.patch.yml, which `dsh.bundle.patch` in `package.json` points at.
26
26
  - Host compatibility is judged on the **peer declarations**, not on `engines.dsh`: before composition the host compares `@deepseek-ai/dsh` and every `@deepseek-ai/dsh-*` range against the current runtime version, prereleases included (the rule is owned by the dsh-app-boot README). A mismatch denies that entry; a bundle without an exemption is skipped whole and listed under `skippedBundles`.
27
- - This package pins every `dsh-*` **exactly** (a requirement of `test/publish-manifest.test.ts`, because "a second copy of the host type surface" is worse than a version conflict), so a host **newer than `0.2.1-alpha.2` also needs approval**. The escape hatch is the one the host prints: `dsh plugin --profile web allow-version @jayyuen66/dsh-zvec-grep@<version> --dsh-version <exact version> --accept-risk`.
28
- - `engines.dsh` is a declaration that nothing reads; keeping it at `>= 0.2.1-alpha.2` only avoids leaving two contradictory numbers behind.
27
+ - This package pins every `dsh-*` **exactly** (a requirement of `test/publish-manifest.test.ts`, because "a second copy of the host type surface" is worse than a version conflict), so a host **newer than `0.2.1-rc.2` also needs approval**. The escape hatch is the one the host prints: `dsh plugin --profile web allow-version @jayyuen66/dsh-zvec-grep@<version> --dsh-version <exact version> --accept-risk`.
28
+ - `engines.dsh` is a declaration that nothing reads; keeping it at `>= 0.2.1-rc.2` only avoids leaving two contradictory numbers behind.
29
29
  - `dsh.client.platform` is web with immediately set, so the card's client half is delivered by the host; bundle installation goes through pnpm (>= 12.3.0).
30
30
  - apply needs the settings/shell/tools/systemPrompt/timer surfaces: all five sit in `inject`, so a missing one keeps cordis from activating the entry (the startup diagnostic prints `pending (waiting for service: …)`).
31
31
  - The guard inside apply is the second layer: a malformed ctx throws `required services … missing`.
32
- - The three `/_dsh/zvec-grep/*` routes hang off an `inject(["webServer"])` child fiber: with no webServer (a TUI host) the child never activates, so those routes simply do not exist while the tools keep working.
33
- - On the real host webServer arrives about a second after this entry, which is why it must be a dependency and not a one-off `ctx.get`.
32
+ - The rebuild read surface is an official Typert Remote namespace installed on the apply fiber (`installRebuildRemote`, `lib/rebuild-remote.ts`), so it needs no `webServer` and no child fiber: on a TUI host with no web layer the service still registers, and the card simply has no place to render.
33
+ - The status poll is the client's own timer (`REBUILD_POLL_MS = 2000` in `src/client-entry.ts`), not a server push, and every read is answered by a result object rather than by a thrown error — see Public interface.
34
+
35
+ ### Support surface
36
+
37
+ - **POSIX hosts (Linux / macOS).** The root predicate accepts only absolute paths starting with `/` (`assertAbsoluteRoot` in `lib/cli.ts`), the command line is POSIX-shaped (`shq()` single-quote escaping plus the whole string handed to `bash -c`), and index probing plus the `rootPaths` comparison inside the manifest split on `/` as well.
38
+ - **Windows hosts are out of scope**, and the failure mode is **fail-fast, not drift**: when the session workspace looks like `C:\Users\…`, all three zg tools refuse right in `rootOf` and say why ("root must be an absolute path starting with /"). The plugin never builds a `zg` command from a mismatched path and never hands a wrong-path result back to the model as if it were a real search. The card's "rebuild workspace" runs into the same root gate.
39
+ - Real Windows support would mean changing the predicate itself rather than translating paths in front of it: root normalization (drive letters and UNC), a second command form (pwsh/cmd quoting is not `bash -c`), the `/`-based grep tokenizer and path-shape rules in the gate, and the `rootPaths` coverage check against `<root>/.zvec-grep/manifest.json`. That is a design change; this package does not do it and does not pretend to.
40
+ - The CI matrix therefore splits in two: **the ubuntu job is the full gate** (including the four 100% coverage thresholds); **other platforms run only the parts that do not need a workspace on disk** — the "same source, two byte shapes" product / line-ending / `path.sep` drift — and **do not judge coverage**, because suites needing a real root skip wholesale on win32 (`realRootUnavailable` in `test/host.test.ts`) and `host.ts` could not reach 100% afterwards. The reasoning is written into `.github/workflows/ci.yml`.
34
41
 
35
42
  ### Tools exposed to the model
36
43
 
@@ -39,12 +46,12 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
39
46
  - `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
47
  - `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
48
  - `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.
49
+ - `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
50
  - 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
51
  - 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
52
  - zg_index: confirm is required and must be true (rejected twice, by the required check and by the guard).
46
53
  - `background=true` runs a **model-side background index**: one call spawns the zg process, registers it in the host job registry, attaches the timeout reaper, hands back a pollable job id and **returns immediately**. Building an index may download embedding weights and take a long time, so background execution keeps the tool call from hanging.
47
- - It does not depend on a host job tool: that tool is disabled in the web plane, so the model-side route is simply unavailable. The plugin reuses the **same** spawn/register/claim steps as the settings card (one shared function, not a copy), so jobs started from either side are identical in the registry, the status projection and the polling endpoint — the card sees model-started indexing and vice versa.
54
+ - It does not depend on a host job tool: that tool is disabled in the web plane, so the model-side route is simply unavailable. The plugin reuses the **same** spawn/register/claim steps as the settings card (one shared function, not a copy), so jobs started from either side are identical in the registry, the status projection and the `status` read — the card sees model-started indexing and vice versa.
48
55
  - The claim is mutually exclusive with the card's rebuild, across both entry points: while an index write is running for a root, the model side and the card side both follow that one instead of each starting a second zg against the same index.
49
56
  - When the host job registry is absent it **does not spawn at all** and fails immediately: a zg with no ring, no capacity and nobody to reap it is worse than not starting — it would hold the root's write lock forever and block every later index operation on that tree.
50
57
  - Until it settles, semantic search on that root waits for it and retries automatically, and grep/rg are not subject to the gate during that window.
@@ -68,17 +75,17 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
68
75
 
69
76
  ### Settings and search roots
70
77
 
71
- - Namespace `zvec-grep`, fourteen fields with built-in defaults, six of them volatile and on the card.
78
+ - Namespace `zvec-grep`, 16 fields with built-in defaults, 6 of them volatile and on the card.
72
79
  - 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
80
  - 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.
81
+ - 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
82
  - 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
83
  - Remote embedding, three values, all **off by default**: `allowRemoteEmbedding=false`, `remoteEmbeddingEndpoint=""`, `remoteEmbeddingApiKeyFrom=""`.
77
84
  - While it is off, an explicit embedding reference must be in the local catalog at **command-assembly time**.
78
85
  - 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
86
  - 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
87
  - 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.
88
+ - `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
89
  - 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
90
  - Volatile fields are read via `config.<field>.get()`; the non-volatile deployment values are plain values and skip `.get()`.
84
91
  - Root validation: must be an absolute path starting with `/`, lexically normalised (empty and `.` segments folded).
@@ -103,18 +110,26 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
103
110
  - `--help`/`--version`/`-V`, `echo "grep x"` and `git commit -m "use rg"` do not.
104
111
  - With a sandboxed executor, runner failure, policy denial and a genuine zg failure are told apart, and incomplete results are flagged explicitly.
105
112
 
113
+ ### Daemon (server mode)
114
+
115
+ - 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.
116
+ - 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":
117
+ - 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.
118
+ - 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. Only `roots()` issues the probe: `rebuild` and `status` never start one, and neither does the rebuild-time synthetic projection, whose contract is to start no subprocess at all.
119
+ - 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".
120
+ - 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.
121
+
106
122
  ### Public interface
107
123
 
108
- - Every handler opens with `guardTrust(req, res, { servingNonLoopback })` (`shared/lib/trust`); failing any leg yields `403` with `{ ok:false, error: ... }`.
109
- - 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
- - `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.
112
- - `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
- - `/_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.
124
+ - The rebuild surface is one **official Typert Remote namespace**, `zvecGrepRebuild` (`REBUILD_REMOTE_NAMESPACE` in `lib/rebuild-shape.ts`); its three methods are marked programmatically (`markRemote` in `lib/rebuild-remote.ts`) and installed on the apply fiber. There are no `/_dsh/*` routes, no CSRF token and no package-owned body cap any more: authentication, the Host / DNS-rebinding / Origin checks and the request-size limit belong to the host's `/api` gateway, and this package no longer declares a `webServer` dependency at all.
125
+ - `roots()` → `{ roots, serverReady }`: the whitelisted workspaces this daemon actually observed, plus the daemon-readiness line for the card. The `zg server status --check-ready` probe is issued **here and nowhere else**, off the same 60-second TTL cache the tools use. `serverReady` is `undefined` when the probe cannot answer, and the card renders nothing for that arm rather than "not ready".
126
+ - `rebuild({ root })` → `{ ok: true, jobId, reused? }` or `{ ok: false, error, status }`. What is enforced is unchanged from the HTTP version, because those rules guard the action, not the transport: a non-`/`-rooted path is refused (`assertAbsoluteRoot`), a root outside the observed whitelist is refused, a root whose directory disappeared is refused, and with no host `jobs` service **nothing is spawned** (the 503 arm). The per-root claim is taken before the first `await` and is the only mutex, so a second click follows the running rebuild (`reused: true`) or, when nothing can be followed, is refused instead of starting a second `zg` against the same index. The version gate and the ignore-file preflight run before the command is built; a failed start returns its code and releases the claim, so the tree is never left permanently "rebuilding".
127
+ - `status({ jobId })` → `{ status, exitCode, root, output }` (plus `sandbox` when present) or `{ ok: false, error, status: 404 | 503 }`. It resolves only ids present in this package's side table — the last 10 settled records (`REBUILD_HISTORY_MAX`), running records are never displaced — so somebody else's job (the host's `bash-1`, say) cannot be read through it. The three 404 arms are "the window moved on", "the registry row no longer holds it" and "the identity triple (kind / label / startedAt) does not match this record"; the 503 arm is the registry disappearing between starts. The card polls it every 2 seconds (`REBUILD_POLL_MS = 2000`).
128
+ - The `status` inside a refusal is a **retained semantic code, not an HTTP status**: the gateway frames the reply, so a refusal arrives as an ordinary result object, the client renders `error`, and the number exists so the tests can pin which rule fired. None of these three methods throws through the gateway — a rejected Remote call would look to the card like one generic failure, stop the polling and hide a rebuild that is still running.
114
129
  - Also a systemPrompt section `zvec-grep-routing` (order 1550) and the settings namespace `zvec-grep`.
130
+ - The client half (`src/rebuild-reader.ts`) `$mount`s three hand-written descriptors (`kind: "direct"`, `result: { mode: "src-json" }`, strict codecs on the two request bodies), memoised so the mount happens once, then reads the derived key `remote.zvecGrepRebuild`. With no host `remote` service there is no reader at all; with the service present but the namespace unmounted the read throws `… 未提供`, and the card renders the `rebuildUnavailable` line instead of going blank.
115
131
  - How many rebuilds run at once is decided by the **host registry** (measured default: the unowned bucket holds 10); this package no longer carries its own concurrency cap.
116
- When it is full, `POST /rebuild` answers 500 with the official message that names the limit - it no longer kills a rebuild that is already running.
117
- - `rebuild-status` only resolves jobIds present in this package's side table: the last 10 **settled** records are kept (older ones are removed from the registry => 404); running records are never displaced.
132
+ When it is full, `rebuild` returns a refusal carrying the official message that names the limit - it never kills a rebuild that is already running.
118
133
 
119
134
  ### The background job surface (official `ctx.jobs`)
120
135
 
@@ -122,16 +137,16 @@ This package no longer ships a job registry: a "rebuild workspace" run is one **
122
137
 
123
138
  | Aspect | Fact |
124
139
  | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
125
- | The model can see it | The official `job_list` / `job_output` / `job_kill` tools now list the rebuild, with the exit code / signal name carried in the job's `detail` (same shape the host's own bash tool uses - measured in `plugins/docs/harness/f3-equiv/probe-jobs.mjs`). Output rides the official **pull source** (`proc.observed[*].readFrom`), so the ring advances on the registry's own cadence - **even with the settings panel closed** - and the observer never steals bytes from `readOutput()` (the d.ts says so verbatim). The controller is attached only for the instant of `start` and detached right after (see the cross-package rule) |
126
- | Unowned means visible to every session | The registry isolates by owner, and an unowned job can be `list`ed / `read` / `kill`ed by any caller. This is a known, accepted exposure of this wave - the card is a webServer producer outside any session, and owned jobs would need the `dsh-agent` registry (measured unavailable). Rolling this adoption back is the only way to close it. Note `/_dsh/zvec-grep/rebuild-status` still only answers for ids in this package's side table, so somebody else's job (the host's `bash-1`, say) cannot be read through it |
140
+ | The model can see it | The official `job_list` / `job_output` / `job_kill` tools now list the rebuild, with the exit code / signal name carried in the job's `detail` (same shape the host's own bash tool uses). Output rides the official **pull source** (`proc.observed[*].readFrom`), so the ring advances on the registry's own cadence - **even with the settings panel closed** - and the observer never steals bytes from `readOutput()` (the d.ts says so verbatim). The controller is attached only for the instant of `start` and detached right after (see the cross-package rule) |
141
+ | Unowned means visible to every session | The registry isolates by owner, and an unowned job can be `list`ed / `read` / `kill`ed by any caller. This is a known, accepted exposure of this wave - the card reaches the registry through the Remote service, outside any session, and owned jobs would need the `dsh-agent` registry (measured unavailable). Rolling this adoption back is the only way to close it. Note the `status` read still only answers for ids in this package's side table, so somebody else's job (the host's `bash-1`, say) cannot be read through it |
127
142
  | Two more status words | `stopping` (cancellation issued, process not finished settling - the card shows it as still running) and `failed` (the registry's own verdict - it gets its own message instead of rendering as "exit code null") |
128
143
 
129
- What is not retained, stated plainly: the output ring keeps **UTF-8 bytes** (measured host default 262144), while the card's 4000-character tail window and its `shown/total` count **UTF-16 code units** - two unit systems, each doing its own job. `total` therefore counts code units **inside the retention window** (the official byte total lives in `view.output.total`, different unit, never mixed), and for CJK output that window is about **1/3 smaller** than what this package kept before the adoption - the price of using the official ring. The two loss marks say different things: "truncated" = the ring evicted its head (`view.output.earliest > 0`, simply not visible any more), "buffer overflow" = the executor's reader reported lossy or threw outright (bytes really are gone; a spill file may exist). The timeout notice and the sandbox facts are deliberately **not** written into the ring: the ring belongs to the registry's pump, and the registry drops every write after settlement (measured), so the endpoint synthesises both at projection time and they can never be lost by arriving late. **Polling never throws through**: when the `jobs` service is reloaded (or somebody else reclaimed the record) the status endpoint answers **404** rather than letting the official `unknown job` error escape - the host's catch for a throwing handler logs one line and, while no header has gone out yet, writes a bare **400** with no body and no content-type (it only destroys the socket once headers were sent: installed dsh-host-webserver `lib/index.js:246-256`), which would put the card into its terminal `error` phase, stop the polling and hide a rebuild that is still running.
144
+ What is not retained, stated plainly: the output ring keeps **UTF-8 bytes** (measured host default 262144), while the card's 4000-character tail window and its `shown/total` count **UTF-16 code units** - two unit systems, each doing its own job. `total` therefore counts code units **inside the retention window** (the official byte total lives in `view.output.total`, different unit, never mixed), and for CJK output that window is about **1/3 smaller** than what this package kept before the adoption - the price of using the official ring. The two loss marks say different things: "truncated" = the ring evicted its head (`view.output.earliest > 0`, simply not visible any more), "buffer overflow" = the executor's reader reported lossy or threw outright (bytes really are gone; a spill file may exist). The timeout notice and the sandbox facts are deliberately **not** written into the ring: the ring belongs to the registry's pump, and the registry drops every write after settlement (measured), so the `status` read synthesises both at projection time and they can never be lost by arriving late. **Polling never throws through**: when the `jobs` service is reloaded (or somebody else reclaimed the record), `readRebuildOutput` folds the official `unknown job` error into `null` and the read answers a refusal (`status: 404`) rather than letting the exception reach the gateway — a rejected invocation is just one generic failure to the card, which would stop the polling and hide a rebuild that is still running.
130
145
 
131
146
  ### Data and privacy
132
147
 
133
148
  - The only on-disk shape of the index is the `.zvec-grep/` directory under the searched root, written by zg (a read-only sandbox cannot write it, and the result says the index may be incomplete).
134
- - Two rebuild paths: the model-side `zg_index` (rebuild=true, confirm=true), or the card's "rebuild workspace" button through the rebuild route above; deleting is `zg_index` with drop=true (assembled as `zg index <root> --drop --yes`).
149
+ - Two rebuild paths: the model-side `zg_index` (rebuild=true, confirm=true), or the card's "rebuild workspace" button, which calls the `rebuild` method above; deleting is `zg_index` with drop=true (assembled as `zg index <root> --drop --yes`).
135
150
  - The package itself writes no files (its only fs calls are the index probe: existsSync plus one manifest read) and puts nothing in the host data directory `$DSH_HOME` (`<dsh data dir>`).
136
151
  - The probe does not merely check that `.zvec-grep/manifest.json` exists: it **parses** the manifest and confirms its `rootPaths` really covers this directory. Two real situations are misread as "indexed" by an existence-only check while search would necessarily fail — the file is there but is not a manifest (a truncated write, or something else occupying the name), and the manifest is there but its root path points elsewhere. If the gate still blocked grep/rg on that basis, both search and the gate would be deadlocked.
137
152
  - Only two fields are checked: `manifestVersion` (**strictly equal to 1**) and `rootPaths` (a non-empty array whose entries each carry a non-empty `absolutePath`). A version mismatch makes upstream throw `MANIFEST.INVALID` on read, meaning not a single search can succeed in that directory — a lenient check would only trap the user in a corner where the gate blocks grep/rg while every search is bound to fail. Embedding / policy fields are deliberately **not** checked — when those change the index still works, so calling it "no index" would be wrong.
@@ -150,11 +165,12 @@ What is not retained, stated plainly: the output ring keeps **UTF-8 bytes** (mea
150
165
  ### FAQ
151
166
 
152
167
  - 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.
154
- - 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.
168
+ - 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.
169
+ - The rebuild button refuses with "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
170
  - 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
171
  - 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
172
  - Changed the embedding but semantic hits are missing: switching embedding only takes effect after a rebuild with rebuild=true.
173
+ - 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
174
 
159
175
  ### Development
160
176
 
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
 
@@ -15,7 +15,7 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
15
15
  ```
16
16
 
17
17
  - 包在公共 npm 上,安装不需要凭据;发布态产物只有 host.js、client.js、cordis.patch.yml(package.json 的 files)。
18
- - 运行期值 import `@jayyuen66/dsh-plugin-shared`(lib/http、lib/locale、lib/text)与 `@deepseek-ai/schemastery`(宿主 fork:0.1.7 的 `.volatile()` 解析只有它有实现,公共 schemastery 既没这个方法、解析出的也仍是普通值),装不上就是 ERR_MODULE_NOT_FOUND。
18
+ - 运行期值 import `@jayyuen66/dsh-plugin-shared`(`lib/locale`、`lib/text`、`lib/record`、`lib/errors`、`lib/job-outcome`、`lib/card-diff`)、`@deepseek-ai/schemastery`(宿主 fork:0.1.7 的 `.volatile()` 解析只有它有实现,公共 schemastery 既没这个方法、解析出的也仍是普通值)与 `@deepseek-ai/dsh-typert-protocol`(Remote 基类:`TypertRemoteService` 是个**要 `extends` 的类**,没有 type-only 的取法,因此落必需 peer 并在 devDependencies 里同版精确钉),装不上就是 ERR_MODULE_NOT_FOUND。
19
19
  - shared 的 `lib/text` 自己值导入 `@deepseek-ai/dsh-output-retention`,所以那枚宿主包也得在提供面上:本包按 `schemastery` 同一口径处理(非 optional `peerDependencies` + `devDependencies` 同枚精确版本,**不进 `dependencies`**)。这条只能靠门禁钉:漏它时本包的类型检查、构建与测试全绿,故障只在装出去之后以 ERR_MODULE_NOT_FOUND 出现。
20
20
  - 只有 shared 那枚在 `dependencies` 里。`@deepseek-ai/schemastery` 是宿主包:声明为**非 optional 的 `peerDependencies`**,并在 `devDependencies` 里以同一枚精确版本再写一份给本包的编译与测试用——它**不进 `dependencies`**。这条不是风格偏好:消费侧 profile 的安装布局是 `nodeLinker: hoisted` 且 `autoInstallPeers: false`,宿主包一旦进了 `dependencies` 就会被落成真实目录,与宿主进程已加载的那份并存;而 `@deepseek-ai/dsh-tools` 的 `TOOL_RUNTIME_SCHEDULER` 是普通 `Symbol`(不是 `Symbol.for`),符号身份按模块实例计算,宿主 `dsh-agent-loop` 于是读到 `undefined`,每一次原生工具调用都抛 `Cannot read properties of undefined (reading 'prepare')`,整个 profile 的工具一起失效——本包的构建、类型检查与测试在这之前全部照绿。判据钉在 `test/publish-manifest.test.ts`。
21
21
 
@@ -23,11 +23,19 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
23
23
 
24
24
  - add/remove 按包内 cordis.patch.yml 维护注册行 `- id: zvec-grep`(name 指向本包);该文件由 `package.json` 的 `dsh.bundle.patch` 指向。
25
25
  - 宿主兼容性按 **peer 声明**判,不按 `engines.dsh`:装配前逐条比对 `@deepseek-ai/dsh` 与每一枚 `@deepseek-ai/dsh-*` 的区间与当前 runtime 版本,prerelease 也参与匹配(官方口径见 dsh-app-boot README)。不符即该条目被拒;组合包(bundle)没有豁免时整枚跳过并列进 `skippedBundles`。
26
- - 本包把 `dsh-*` 一律**精确钉**(`test/publish-manifest.test.ts` 的要求,理由是「装出第二份宿主类型面」比版本冲突更坏),所以**高于 `0.2.1-alpha.2` 的宿主同样需要授权**,出路是宿主点名的那句:`dsh plugin --profile web allow-version @jayyuen66/dsh-zvec-grep@<版本> --dsh-version <确切版本> --accept-risk`。
27
- - `engines.dsh` 只是声明,无人读;`>= 0.2.1-alpha.2` 与 peer 同值仅为不留下互相矛盾的数。
26
+ - 本包把 `dsh-*` 一律**精确钉**(`test/publish-manifest.test.ts` 的要求,理由是「装出第二份宿主类型面」比版本冲突更坏),所以**高于 `0.2.1-rc.2` 的宿主同样需要授权**,出路是宿主点名的那句:`dsh plugin --profile web allow-version @jayyuen66/dsh-zvec-grep@<版本> --dsh-version <确切版本> --accept-risk`。
27
+ - `engines.dsh` 只是声明,无人读;`>= 0.2.1-rc.2` 与 peer 同值仅为不留下互相矛盾的数。
28
28
  - `dsh.client.platform` 为 web 且 immediately,设置卡的 client 半随宿主下发;bundle 安装走 pnpm(>= 12.3.0)。
29
29
  - apply 需要 settings/shell/tools/systemPrompt/timer 五个服务面:它们都在 `inject` 里,缺任一 cordis 就不激活本条目(宿主启动诊断点名 `pending (waiting for service: …)`);apply 里的守卫再兜一层,ctx 形状不对时抛 `required services … missing`。
30
- - 三条 `/_dsh/zvec-grep/*` 端点挂在 `inject(["webServer"])` 的子 fiber 上:宿主没有 webServer(如 TUI)时子 fiber 不激活,端点不存在而工具照常。真实宿主上 webServer 比本条目晚到位约 1 秒,所以这里必须是依赖、不能只在 apply 里 `ctx.get` 读一次。
30
+ - 设置卡的读面是一枚官方 Typert Remote 命名空间,由 `installRebuildRemote` 注册在 apply fiber 上(`lib/rebuild-remote.ts`),因此不需要 `webServer`、也没有子 fiber:宿主没有 web 层(如 TUI)时服务照旧注册,只是卡片没有地方渲染。
31
+ - 状态轮询是客户端自己的定时器(`src/client-entry.ts` 的 `REBUILD_POLL_MS = 2000`),不是服务端推送;每次读都以结果对象回答,不抛错——见「对外接口」。
32
+
33
+ ### 支持面
34
+
35
+ - **POSIX 宿主(Linux / macOS)**。root 判据只认以 `/` 开头的绝对路径(`lib/cli.ts` 的 `assertAbsoluteRoot`),命令行也是 POSIX 形态(`shq()` 单引号转义 + 整串交给 `bash -c`),索引探测与清单里的 `rootPaths` 比对同样按 `/` 分隔。
36
+ - **Windows 宿主不在支持面内**,而且是 **fail-fast,不是静默走偏**:会话工作区长成 `C:\Users\…` 时,三个 zg 工具都在 `rootOf` 当场拒掉并说清原因(「root 必须是绝对路径(以 / 开头)」),不会拿一个错位的路径去拼 `zg` 命令、也不会把结果当成一次正常检索交回模型;设置卡的「工作区重建」同样过不去 root 那关。
37
+ - 真要在 Windows 上支持,要动的是判据本身而不是加一层路径转换:root 归一(盘符与 UNC)、第二套命令形态(pwsh/cmd 的引号规则与 `bash -c` 不同义)、门禁里那套按 `/` 的 grep 切词与路径形状判据、以及 `<root>/.zvec-grep/manifest.json` 的 `rootPaths` 覆盖判据。这属设计变更,本包没做,也不假装能做。
38
+ - CI 矩阵因此分两手:**ubuntu 格是全部门禁**(含四项 100% 覆盖率);**windows 格只跑不依赖真工作区的部分**与「同一份源码两种字节」的产物 / 换行 / `path.sep` 漂移,**不判覆盖率**——需要盘上真根的用例在 win32 整块跳过(`test/host.test.ts` 的 `realRootUnavailable`),跳过之后 `host.ts` 本就无从到 100%。判据与理由写在 `.github/workflows/ci.yml`。
31
39
 
32
40
  ### 提供给模型的工具
33
41
 
@@ -36,12 +44,12 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
36
44
  - `globs` / `insensitiveGlobs` / `fileTypes` / `excludedFileTypes` 既收**单个字符串**也收字符串数组(与上游 zg 对这几项的对外契约一致,最多 128 项、单项 <= 1024 字符)。
37
45
  - `symbolTypes` 绑定 zg 的真实闭集,取值**只认小写**:`module` / `class` / `interface` / `function` / `value` / `alias`。zg 侧 `--symbol-type Class` 会以非零码退出(`Unsupported symbol type: Class`),插件在构造命令前就拦下并列出合法取值;不做大小写折叠——悄悄改成小写等于替模型改了它没写的约束。
38
46
  - `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 原样回显,那一行会自己到模型眼前。
47
+ - `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
48
  - 输出尾部附一行**命中摘要**,两栏口径分开给:`分组计数合计`(各查询组 `hits:` 之和)与`去重后 N 个不同位置`(按「相对路径 + 行号范围」去重)。分栏是因为同一处代码会被多组各命中一次(名次与匹配来源逐组变化),直接求和会把同一处位置重复计入、冒充命中总数。
41
49
  - 某组命中数正好等于 `--limit` 时只作**观察陈述**并显式说明「zg 不提供截断信号,此处不作断言」——zg 的输出没有任何截断标记,不能把"可能还有未显示的命中"说成事实。输出被宿主按 stdout 上限截尾时另附「只含保留部分」。
42
50
  - zg_index:confirm 必填且必须为 true(required 校验 + guard 双层拒绝)。
43
51
  - `background=true` 走**模型侧后台索引**:一次调用把「起 zg 进程 + 登记进官方作业注册表 + 挂超时回收」全做完,把可轮询的作业号交回后**立即返回**。建索引可能要下载 embedding 权重、等很久,后台执行免得工具调用一直挂着。
44
- - 不依赖宿主作业工具:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走。插件复用与设置卡**完全相同**的 spawn/登记/占位三步(同一个函数,不是复制品),所以两条入口起的作业在名册、状态投影、轮询端点上完全同形——卡片能看见模型起的索引,反之亦然。
52
+ - 不依赖宿主作业工具:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走。插件复用与设置卡**完全相同**的 spawn/登记/占位三步(同一个函数,不是复制品),所以两条入口起的作业在名册、状态投影、`status` 读面上完全同形——卡片能看见模型起的索引,反之亦然。
45
53
  - 占位与设置卡的重建互斥,且跨入口成立:同根已在跑索引写时,模型侧与卡片侧都只会跟随那一条,不会各起一条 zg 去啃同一份索引。
46
54
  - 官方作业注册表缺席时**根本不起进程**并直接报错:起一条没有环、没有容量、也没人能收的 zg 比不起更糟——它会一直占着同根的写锁,把这棵树的后续索引全堵死。
47
55
  - 落定前该根的语义检索会等它完成再自动重试,期间 grep/rg 不受门禁限制。
@@ -65,16 +73,16 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
65
73
 
66
74
  ### 设置项与检索根
67
75
 
68
- - 命名空间 `zvec-grep` 由宿主**隐式**注册(0.1.7 起 = profile 条目 id,插件侧不再有 `settings.register`);schema 共十四个字段,其中卡上那六枚标 `.volatile()`,内置默认逐字段写在 `.default()` 上。
76
+ - 命名空间 `zvec-grep` 由宿主**隐式**注册(0.1.7 起 = profile 条目 id,插件侧不再有 `settings.register`);schema 共 16 个字段,其中卡上那 6 枚标 `.volatile()`,内置默认逐字段写在 `.default()` 上。
69
77
  - defaultEmbedding=local/qwen3-embedding-0.6b、defaultLimit=10(1-50)、hfEndpoint=国内可达的 HF 兼容镜像基址(可改成别的镜像或留空走官方 HF)。
70
78
  - 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。
79
+ - 另有**非 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
80
  - 远程 embedding 三件套,默认**全关**:`allowRemoteEmbedding=false`、`remoteEmbeddingEndpoint=""`、`remoteEmbeddingApiKeyFrom=""`。
73
81
  - 关着的时候,显式 embedding 引用在**命令构造期**就必须落在本地候选清单里。
74
82
  - 打开后端点与凭据**只经环境变量**下发给 zg 子进程(`ZVEC_GREP_ENDPOINT` / `ZVEC_GREP_API_KEY`),**绝不进 argv**——本包把整条命令当作业 label 回显给卡片,argv 里的密钥会进界面、进日志、进 `ps` 的进程表。
75
83
  - 凭据那项填的是**宿主进程里那个装凭据的环境变量名**(如 `ZVEC_GREP_API_KEY`),不是密钥本身:宿主 subprocess 层会把名字含 KEY/SECRET/TOKEN 的继承变量剔掉,必须由本插件显式转发才到得了 zg;只记名字也让密钥不必落进插件配置文件。
76
84
  - 本插件**不自动传 `--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 即便「用户已批准」照旧被拒。
85
+ - `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
86
  - 优先级:设置里的运行时值 > 组合包层/用户层行的 config > schema 的 `.default()`;行 config 中显式缺省的字段不覆盖默认。读侧是 `config.<field>.get()`(volatile 引用,卡上改完下一个事件即生效);非 volatile 部署值是普通值形态,不经 `.get()`。
79
87
  - root 校验:必须是以 `/` 开头的绝对路径,词典归一折叠空段与 `.`。
80
88
  - 拒绝空串、非字符串、含 NUL、相对路径、越出文件系统根的 `..`,归一后为 `/` 也拒。
@@ -98,19 +106,28 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
98
106
  - `--help`/`--version`/`-V`、`echo "grep x"`、`git commit -m "use rg"` 不算。
99
107
  - 有沙箱执行器时会区分 runner 失败、策略拒绝与 zg 自身失败,并在结果里显式打「可能不完整」标记。
100
108
 
109
+ ### 守护进程(server 模式)
110
+
111
+ - 这一档不是「快一点」的区别。`--mode auto` 的两侧是两种能力面:direct 每发 `zg query` 都要新建再关闭一次引擎、**embedding 模型逐次冷加载**;而索引的增量刷新(watcher)、`refresh=background` 与常驻模型池**只在 server 模式下存在**。上游对 `auto` 只做就绪探测、不会替用户拉起 daemon。
112
+ - 本包**不代为起一个长驻进程**:`zg server on` 会在用户机器上落下 detached 进程与 token 文件,那是该由用户点头的动作,不是插件替部署做的决定。本包做的是把这一档**显式化**,不再让它藏在「检索超时给 5 分钟」和「改动搜不到」这类使用限制背后:
113
+ - 按 TTL(60 秒)缓存 `zg server status --check-ready` 的**退出码**(就绪 0、未就绪非零;读 stdout 文本不行,那是给人看的状态表、不在本包的依赖契约里)。探测失败一律按未就绪收口,**绝不外抛**基础设施故障。
114
+ - 据此收口 `refresh=background`(见工具一节),并在 `zg_status` 的输出尾部与设置卡各回显一行就绪态。探测只由 `roots()` 触发:`rebuild` 与 `status` 不起探测,重建期那条「合成投影」也不起(它本来的契约就是不启子进程)。
115
+ - 设置卡的 `serverReady` 只可能是 `true` / `false`;旧版 host 的应答里根本没有这一位,卡片对「未知」的那一臂**不显示**,而不是把它说成「未就绪」。
116
+ - 想把红利拿到手:在持有终端时执行 `zg server on`(起停与状态另有 `zg server off` / `zg server status`)。本包只读它的就绪态,不拥有它的生命周期。
117
+
101
118
  ### 对外接口
102
119
 
103
- - 三条路由的 handler 第一句都是 `guardTrust(req, res, { servingNonLoopback })`(`shared/lib/trust`),任一判据不过即 `403` + `{ ok:false, error: ... }`。
104
- - 判据次序:Host 权威 → `sec-fetch-site` 白名单 → `origin` 与 Host 逐字比对;两句错误文本是 `"untrusted host authority"` 与 `"cross-origin request rejected"`。
105
- - `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。
107
- - `POST /_dsh/zvec-grep/rebuild?root=...`:闸门 + 头 `x-zvec-grep-csrf` + body <= 4096 字节 + root 命中白名单 + 目录存在,成功回 `{ ok, jobId }`;否则 405/403/400/500。
108
- - `/_dsh/zvec-grep/rebuild-status?jobId=...`:闸门后轮询(卡片每 2 秒一次),回 status/exitCode/root/output(有沙箱时带 sandbox),未知 jobId 回 404 并说明多半是出了本包那条 10 条落定窗口。
120
+ - 重建面是一枚**官方 Typert Remote 命名空间** `zvecGrepRebuild`(`lib/rebuild-shape.ts` 的 `REBUILD_REMOTE_NAMESPACE`),三个方法用程序化方式打标记(`lib/rebuild-remote.ts` 的 `markRemote`),注册在 apply fiber 上。没有 `/_dsh/*` 路由、没有 CSRF token、本包也不再自带 body 上限:认证与 Host / DNS 重绑定 / Origin 判据、请求体上限都由宿主 `/api` 网关承担,本包连 `webServer` 依赖都不再声明。
121
+ - `roots()` → `{ roots, serverReady }`:本 daemon 真实观测到的白名单工作区,加上卡片那一行守护进程就绪态。`zg server status --check-ready` 探测**只在这里发**,与三条工具共用同一份 60 秒 TTL 缓存。`serverReady` 在探测答不出时是 `undefined`,卡片对这一臂什么都不显示,而不是把「不知道」说成「未就绪」。
122
+ - `rebuild({ root })` → `{ ok: true, jobId, reused? }` 或 `{ ok: false, error, status }。判据与 HTTP 版一模一样,因为它们护的是动作本身、与传输方式无关:非 `/` 开头的路径先拒(`assertAbsoluteRoot`),不在观测白名单里的拒,目录已消失的拒,宿主 `jobs` 服务不在场时**一条都不 spawn**(503 那一臂)。同根占位在第一个 `await` 之前取,是唯一的互斥依据,因此第二次点击跟随在跑的那条(`reused: true`),跟不到也只是被拒,不会在同一份索引上再起一条 `zg`。版本门槛与 ignore 文件预检排在命令构造之前;启动失败会交回自己的码并归还占位,那棵树不会被永久标成「重建中」。
123
+ - `status({ jobId })` → `{ status, exitCode, root, output }`(有沙箱时带 `sandbox`)或 `{ ok: false, error, status: 404 | 503 }`。它只认本包侧表里的 id——保留最近 10 条**已落定**记录(`REBUILD_HISTORY_MAX`,在跑的永不淘汰),所以别人的作业(如宿主的 `bash-1`)经这里读不到。三档 404 分别是「窗口过去了」「注册表那一行不再持有它」「身份三元组(kind / label / startedAt)与这条记录不符」;503 那一档是两次启动之间注册表消失。卡片每 2 秒敲一次(`REBUILD_POLL_MS = 2000`)。
124
+ - 拒绝结果里的 `status` 是**保留下来的语义码,不是 HTTP 状态**:应答由网关成框,所以拒绝就是一个普通结果对象,卡片渲染 `error`,那个数字存在是为了让测试钉住是哪条判据拦的。这三个方法都不许把异常抛穿到网关——一次被拒的 Remote 调用对卡片只是一条笼统的失败,会停掉轮询并让还在跑的重建从此看不见。
109
125
  - 另有 systemPrompt 段 `zvec-grep-routing`(order 1550)与 settings 命名空间 `zvec-grep`。
110
- - 白名单只记本 daemon 真实观测到的会话工作区,容量 64(超出按插入序淘汰)。
126
+ - 客户端那一侧(`src/rebuild-reader.ts`)用 `$mount` 挂三条手写 descriptor(`kind: "direct"`、`result: { mode: "src-json" }`,两个入参各带 strict codec),挂载只发生一次,随后按派生键 `remote.zvecGrepRebuild` 取服务。宿主没有 `remote` 服务时根本不构造读面;服务在、命名空间没挂上时读面抛 `… 未提供`,卡片显示 `rebuildUnavailable` 那一行而不是整片空白。
127
+ - 白名单只记本 daemon 真实观测到的会话工作区,容量 64;**命中会触摸**该条(挪到队尾),淘汰先掉已过期的、再按**最久未触摸**依次淘汰,不是按插入序。
111
128
  - 同时能跑几个重建由**宿主注册表**决定(实测默认未拥有桶 10),本包不再自带并发上限;
112
- 满员时 `POST /rebuild` 直接回 500 并带上官方的点名文案,**不会**再杀掉已经在跑的重建。
113
- - `rebuild-status` 的 `jobId` 只在本包侧表里查得到:本包保留最近 10 条**已结束**的记录
129
+ 满员时 `rebuild` 直接交回拒绝结果并带上官方的点名文案,**不会**再杀掉已经在跑的重建。
130
+ - `status` 的 `jobId` 只在本包侧表里查得到:本包保留最近 10 条**已结束**的记录
114
131
  (超出即从注册表 remove ⇒ 404),进行中的记录永不被动。
115
132
 
116
133
  ### 后台作业面(官方 `ctx.jobs`)
@@ -120,16 +137,16 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
120
137
 
121
138
  | 面 | 事实 |
122
139
  | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
123
- | 模型侧能看见了 | 官方 `job_list` / `job_output` / `job_kill` 现在列得出这次重建,退出码与信号名走作业的 `detail`(口径与宿主的 bash 工具同形,实测 `plugins/docs/harness/f3-equiv/probe-jobs.mjs`)。输出走官方 **pull source**(`proc.observed[*].readFrom`)⇒ 环由注册表按它自己的节拍推进,**设置面板关着也照样前进**;官方那条观察者面与 `readOutput()` 互不偷字节(d.ts 原文 "without stealing bytes from `readOutput`")。controller 只在 `start` 那一瞬挂、摘掉即恢复官方拒绝(见跨包纪律) |
124
- | 未拥有 ⇒ 对全部会话可见 | 官方件按 owner 隔离,未拥有作业任何 caller 都能 `list`/`read`/`kill`。这是本波**已知并接受**的暴露面(卡片是会话外的 webServer 生产者,受有作业则要 `dsh-agent` 注册表,实测不可得)。要收回去只有一条路:回滚这次换装。注意 `/_dsh/zvec-grep/rebuild-status` 仍只认本包侧表里的 id,别人的作业(如宿主的 `bash-1`)经这个端点读不到 |
140
+ | 模型侧能看见了 | 官方 `job_list` / `job_output` / `job_kill` 现在列得出这次重建,退出码与信号名走作业的 `detail`(口径与宿主的 bash 工具同形)。输出走官方 **pull source**(`proc.observed[*].readFrom`)⇒ 环由注册表按它自己的节拍推进,**设置面板关着也照样前进**;官方那条观察者面与 `readOutput()` 互不偷字节(d.ts 原文 "without stealing bytes from `readOutput`")。controller 只在 `start` 那一瞬挂、摘掉即恢复官方拒绝(见跨包纪律) |
141
+ | 未拥有 ⇒ 对全部会话可见 | 官方件按 owner 隔离,未拥有作业任何 caller 都能 `list`/`read`/`kill`。这是本波**已知并接受**的暴露面(卡片经 Remote 读面触达注册表,本身在会话之外,而受有作业则要 `dsh-agent` 注册表,实测不可得)。要收回去只有一条路:回滚这次换装。注意 `status` 读面仍只认本包侧表里的 id,别人的作业(如宿主的 `bash-1`)经它读不到 |
125
142
  | 多了两个状态词 | `stopping`(取消已发出、进程还没收完 ⇒ 卡片按「仍在跑」显示)与 `failed`(注册表侧判定失败 ⇒ 给专门文案,不显示成「退出码 null」) |
126
143
 
127
- 不留存的东西也写清楚:输出环按 **UTF-8 字节**留存(实测宿主默认 262144 字节),卡片的 4000 字符尾窗与 `shown/total` 按 **UTF-16 码元**计——两套单位各管各的。因此 `total` 说的是**留存窗内**的码元数(官方那个字节真值在 `view.output.total`,单位不同不混用),而中文输出下这只窗比换装前(按码元留 256 KiB)**小约 1/3**,这是采用官方件的代价。两条丢失标记各说一件事:`已截断` = 环按留存窗裁掉了头部(`view.output.earliest > 0`,看不见了);`缓冲区溢出` = 执行器的读者报 lossy 或干脆抛了(真少了字节,可能有 spill 文件)。超时说明与沙箱事实**不进环**:环的写权归注册表的泵,而它在落定之后丢弃一切写入(实测),所以这两条由端点在投影时合成,永远不会因为"写晚了"而消失。注册表被重载或记录被别人收走时轮询答 **404**(官方 `get`/`readAt` 对未知 id 抛错,而宿主对 handler 抛出的兜法是记一条日志再写一枚没有 body、没有 content-type 的 **400**,只有头已发时才断掉 socket —— installed dsh-host-webserver `lib/index.js:246-256` ⇒ 卡片会进终止态并停轮询,那条还在跑的重建就再也看不见)。
144
+ 不留存的东西也写清楚:输出环按 **UTF-8 字节**留存(实测宿主默认 262144 字节),卡片的 4000 字符尾窗与 `shown/total` 按 **UTF-16 码元**计——两套单位各管各的。因此 `total` 说的是**留存窗内**的码元数(官方那个字节真值在 `view.output.total`,单位不同不混用),而中文输出下这只窗比换装前(按码元留 256 KiB)**小约 1/3**,这是采用官方件的代价。两条丢失标记各说一件事:`已截断` = 环按留存窗裁掉了头部(`view.output.earliest > 0`,看不见了);`缓冲区溢出` = 执行器的读者报 lossy 或干脆抛了(真少了字节,可能有 spill 文件)。超时说明与沙箱事实**不进环**:环的写权归注册表的泵,而它在落定之后丢弃一切写入(实测),所以这两条由 `status` 读面在投影时合成,永远不会因为"写晚了"而消失。注册表被重载或记录被别人收走时 `status` 交回拒绝结果(`status: 404`),而不是让官方的 `unknown job` 异常抛穿到网关——一次被拒的调用对卡片只是一条笼统失败,会停掉轮询并让还在跑的重建从此看不见。
128
145
 
129
146
  ### 数据与隐私
130
147
 
131
148
  - 索引的唯一落盘形状是被检索 root 下的 `.zvec-grep/` 目录,由 zg 写入(read-only 沙箱下写不了它,会明确报索引可能不完整)。
132
- - 重建有两条路:模型侧 `zg_index`(rebuild=true、confirm=true),或设置卡「工作区重建」走上面的 rebuild 路由;删除是 `zg_index` drop=true(拼成 `zg index <root> --drop --yes`)。
149
+ - 重建有两条路:模型侧 `zg_index`(rebuild=true、confirm=true),或设置卡「工作区重建」走上面的 `rebuild` 方法;删除是 `zg_index` drop=true(拼成 `zg index <root> --drop --yes`)。
133
150
  - 本包自身不写任何文件(唯一的 fs 调用是索引探测:existsSync + 读一次清单),也不向宿主数据目录 `$DSH_HOME`(`<dsh 数据目录>`)落数据。
134
151
  - 索引探测不只判「`.zvec-grep/manifest.json` 在不在」:还要**解析清单**并确认它的 `rootPaths` 真的覆盖这个目录。两种实况会被「只判存在」误判成有索引,而实际检索必然失败——文件在但不是一份清单(半截写入/同名占用),以及清单在但根路径指向别处。此时门禁若还按「已建索引」拦着 grep/rg,就等于把检索与门禁双向堵死。
135
152
  - 认的结构只有 `manifestVersion`(**严格等于 1**)与 `rootPaths`(非空数组、每项带非空 `absolutePath`)两处——版本不等时上游读它会直接抛 `MANIFEST.INVALID`,此时这个目录一次检索都做不了,宽松放行只会把用户卡在「门禁拦着、检索又必失败」的死角里。刻意不校验 embedding / policy 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
@@ -146,11 +163,12 @@ dsh plugin --profile web add @jayyuen66/dsh-zvec-grep
146
163
  ### 常见问题
147
164
 
148
165
  - grep/rg 被拒且提示「尚未执行过 zg_search」:这是 search-first 门禁,先 zg_search;配额用尽或过期同理,换个更准的 query/fts 重搜即可续上,不必关插件。
149
- - 检索超时:默认 `--refresh wait` 会同步刷新既有索引,大工作区请用 globs/fileTypes 缩小范围或调小 limit,也可先手写字面检索。
150
- - 重建按钮回 403「root 不在本 daemon 观测到的工作区白名单内」:该目录从未在本 daemon 开过会话;先在该目录起会话,或让模型带 confirm=true 调 zg_index。
166
+ - 检索超时:默认 `--refresh wait` 会同步刷新既有索引,大工作区请用 globs/fileTypes 缩小范围或调小 limit,也可先手写字面检索;想让超时这件事本身变小,就起守护进程(见「守护进程」一节)——直连模式每次都要冷加载 embedding 模型,那才是超时预算被抬到 5 分钟的原因。
167
+ - 重建按钮的拒绝文案是「root 不在本 daemon 观测到的工作区白名单内」:该目录从未在本 daemon 开过会话;先在该目录起会话,或让模型带 confirm=true 调 zg_index。
151
168
  - 卡片显示重建失败而 zg 看着像跑完了:成功判据是 completed 且 exit 0——exit 127(zg 没装)也落在 completed,看输出尾部原因。
152
169
  - 从未建索引的 root:zg_search 明确报错而不是静默建索引;建索引只在用户明确要求时由 zg_index 做。
153
170
  - 换了 embedding 却搜不到语义结果:切换 embedding 必须 rebuild=true 重建后才生效。
171
+ - zg 失败只回显一句没有 `Code:` 的文案:上游在不带 `--debug` 时会把两类失败(权重下载失败、索引文件失败)塌成一句话,本包那套按码归因正好在这条链上失效。所以这种失败的回显尾部会补一句「可加 `--debug` 复跑」的指引——本包**不默认带** `--debug`:它会明显拉长输出,而这三条工具的回显有界(stdout 400000 字节)是给模型读的。已有 `Code:` 行的失败不补这一句。
154
172
 
155
173
  ### 开发
156
174