@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/host.js CHANGED
@@ -2,13 +2,11 @@
2
2
  import Schema from "@deepseek-ai/schemastery";
3
3
  import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
- import { randomUUID } from "node:crypto";
6
- import { guardBody, queryParam, sendJson } from "@jayyuen66/dsh-plugin-shared/lib/http";
7
- import { guardTrust, isNonLoopbackBindHost } from "@jayyuen66/dsh-plugin-shared/lib/trust";
8
5
  import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
9
6
  import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
10
7
  import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from "@jayyuen66/dsh-plugin-shared/lib/locale";
11
8
  import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
9
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
12
10
  import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
13
11
  //#region lib/embedding-catalog.ts
14
12
  /** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
@@ -109,7 +107,7 @@ const MESSAGES = {
109
107
  fuseDescription: "融合所有组为单一排名",
110
108
  limitDescription: "每组最大条数 1-50,默认 10",
111
109
  previewDescription: "每条命中带的源码片段大小:none 只给锚点行、short 给锚点加一段有界上下文、full 给整段源码。默认 short",
112
- refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。注意 background 只在守护进程模式下成立,直连模式下 zg 会降级成 off 并在 stderr 提示",
110
+ refreshDescription: "检索前如何刷新索引:wait 等刷新到最新(默认)、off 不刷新、background 交给守护进程后台刷新。background 只在守护进程就绪时可用:没有守护进程时这一档在命令构造前就被拒绝(直连模式下 zg 只会静默关掉刷新并留一行 stderr warning,那等于把「没刷新」说成「后台在刷」),要它请先在终端执行 `zg server on`",
113
111
  globsDescription: "路径 glob(如 src/**),单个字符串或数组",
114
112
  globsIndexDescription: "路径 glob",
115
113
  insensitiveGlobsDescription: "大小写不敏感 glob",
@@ -164,7 +162,7 @@ const MESSAGES = {
164
162
  rebuildWaitTimeout: "等待 {root} 的重建完成超时(约 {seconds} 秒),重建可能仍在进行;请稍后重试。本次不会发放 grep/rg 配额——重建期间索引不可读,先等它结束。",
165
163
  rebuildWaitAborted: "等待 {root} 的重建完成时被中止。",
166
164
  statusRebuilding: "{root} 正在重建中(作业 {jobId})。重建期间索引不可读,检索会自动等待它完成后重试。如需查看实时输出,请在设置卡的工作区重建面板里观察。此刻即使问「索引是否就绪」也是否定的答案——重建落定后再问。",
167
- statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail}",
165
+ statusNotReady: "[zvec-grep] {root} 的索引**未就绪**(上面是 zg 的完整就绪报告)。这不是执行失败,而是 checkReady=true 要的那个结论:{detail} 若刷新反复失败(报告里出现 `read only mode` 一类写入被拒的措辞),那是该索引自身的状态问题,重建即可恢复:zg_index(root=\"…\", confirm=true, rebuild=true)。",
168
166
  checkReadyDescription: "就绪判定:就绪报告照常给出,另行判定索引是否 ready 并在结论里明说。未就绪不是执行失败,报告仍会返回",
169
167
  traceDescription: "排障用:每条命中附一行检索轨迹,说明它被哪几路召回、在各组里名次如何,并给出分值。输出会明显变长;穷举检索(rg)模式不支持该参数",
170
168
  indexBackgroundStarted: "已在后台为 {root} 启动索引(作业 {jobId}),命令:{command}。索引落定前该根的语义检索会等它完成再重试,grep/rg 在这段时间不受门禁限制。用 zg_status 查就绪与否;本次调用不发放 grep/rg 配额",
@@ -181,6 +179,7 @@ const MESSAGES = {
181
179
  genericFailure: "zg 执行失败(exit={exit}){detail}",
182
180
  detailPrefix: " 详情:{detail}",
183
181
  detailColon: ":{detail}",
182
+ noErrorCodeHint: "(这条失败没有 zg 的结构化 `Code:` 行,本包无法按码归因。上游不带 `--debug` 时会把部分失败塌成一句无码文本;要拿到可归因的完整输出,请让持有终端的用户把同一条命令加上 `--debug` 复跑一次)",
184
183
  outputTruncated: "[zvec-grep] 注意:输出超过 {maxBytes} 字节上限,已截断,仅保留尾部{spill}。如需完整结果请缩小检索范围(更精确的 query / 更小的 limit / 更窄的 root)。",
185
184
  spillNote: "(完整输出已落盘:{path})",
186
185
  sandboxWarning: "[zvec-grep] 警告:{denied}——下面的结果可能缺少被拒读写的文件,别把它当成全工作区的完整检索结论。",
@@ -202,7 +201,6 @@ const MESSAGES = {
202
201
  endpointRootGone: "root 目录已不存在:{root}",
203
202
  endpointStartFailed: "启动重建失败:{reason}",
204
203
  endpointJobsUnavailable: "后台重建不可用:宿主未提供 ctx.jobs(@deepseek-ai/dsh-jobs-local 未装载),本插件不再自带任务注册表",
205
- endpointRegistryReplaced: "后台作业服务已被替换(新注册表重新从同一个 id 开始签发作业),本次重建已放弃并终止:请重载 zvec-grep 插件后再发起,否则旧面板会跟着另一棵树的作业走",
206
204
  endpointJobsAtCapacity: "后台作业已满(宿主上限 {limit} 条,进行中与正在收尾的都计数),本次重建未启动:请先在模型侧用 job_kill 收掉不再需要的作业,再重新发起重建",
207
205
  unknownJobId: "unknown jobId(这条重建记录已移出历史窗口:本插件只保留最近 {maxJobs} 条已结束的重建,超限时最老的已结束记录先被移除;进行中的重建不会被顶掉,但并发满员时新的启动请求会被直接拒绝。请重新发起重建)",
208
206
  jobOutputView: "\n[zvec-grep](仅显示尾部 {shown} 字符,共 {total} 字符)",
@@ -213,6 +211,10 @@ const MESSAGES = {
213
211
  clientModeInvalid: "zg 传输模式非法:{received}(合法取值:{allowed})",
214
212
  previewInvalid: "预览档位非法:{received}(合法取值:{allowed})",
215
213
  refreshInvalid: "刷新策略非法:{received}(合法取值:{allowed})",
214
+ refreshBackgroundNeedsServer: "{root} 没有可用的 zg 守护进程,`refresh=background` 因此被拒绝——它只在守护进程模式下成立。缺了守护进程时这次调用要的是 background,而上游只会往 stderr 打一行 warning 就把**刷新整个关掉**,所以这里不再替它把「没刷新」说成「后台在刷」。两条出路:按默认 refresh=wait(检索前同步刷到最新,直连模式可用),或在持有终端时先执行 `zg server on` 再来要后台刷新——后者还会顺带带来索引增量刷新与常驻的模型池。",
215
+ refreshBackgroundPinnedDirect: "{root} 这次检索把 `refresh=background` 拒绝了:本 daemon 的传输模式被部署钉死在 direct(行 config 的 `clientMode: direct`),而后台刷新只在 server 模式下存在。这一档**不是**起一个守护进程能解决的——出路是把行 config 的 clientMode 改回 auto 或 server,或按缺省的 refresh=wait 检索。",
216
+ serverReadyNote: "[zvec-grep] 守护进程:就绪(检索可走 server 模式:索引增量刷新、embedding 模型池常驻)",
217
+ serverUnavailableNote: "[zvec-grep] 守护进程:未就绪。检索因此按直连模式逐次冷加载 embedding 模型(大工作区会更慢,且 refresh=background 不可用);需要增量索引与常驻模型池时,请在持有终端执行 `zg server on`",
216
218
  symbolTypeInvalid: "符号类型非法:{received}(合法取值:{allowed},只接受小写)",
217
219
  rootEscapesFs: "root 含越界的 .. 段:{path}",
218
220
  rootMustBeString: "root 必须是字符串(收到 {received})",
@@ -220,6 +222,7 @@ const MESSAGES = {
220
222
  rootMustBeAbsolute: "root 必须是绝对路径(以 / 开头):{path}",
221
223
  rootIsFsRoot: "root 不能是文件系统根目录 /",
222
224
  rootRequiredWithFallback: "root 必填,且为工作区绝对路径(可省略:缺省为当前会话工作区)",
225
+ limitInvalid: "limit 必须是非负整数(省略则用默认值)",
223
226
  mustBeStringArray: "{name} 必须是字符串数组",
224
227
  tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
225
228
  nonStringItem: "{name} 含非字符串项({received})",
@@ -257,7 +260,7 @@ const MESSAGES = {
257
260
  fuseDescription: "Fuse all groups into a single ranking",
258
261
  limitDescription: "Max hits per group, 1-50, default 10",
259
262
  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",
263
+ 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
264
  globsDescription: "Path globs (e.g. src/**), a single string or an array",
262
265
  globsIndexDescription: "Path globs",
263
266
  insensitiveGlobsDescription: "Case-insensitive globs",
@@ -312,7 +315,7 @@ const MESSAGES = {
312
315
  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
316
  rebuildWaitAborted: "aborted while waiting for the rebuild of {root} to finish",
314
317
  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}",
318
+ 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
319
  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
320
  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
321
  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 +332,7 @@ const MESSAGES = {
329
332
  genericFailure: "zg failed (exit={exit}){detail}",
330
333
  detailPrefix: " details: {detail}",
331
334
  detailColon: ": {detail}",
335
+ 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
336
  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
337
  spillNote: " (full output spilled to {path})",
334
338
  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.",
@@ -350,7 +354,6 @@ const MESSAGES = {
350
354
  endpointRootGone: "root directory no longer exists: {root}",
351
355
  endpointStartFailed: "failed to start the rebuild: {reason}",
352
356
  endpointJobsUnavailable: "background rebuild unavailable: the host provides no ctx.jobs (dsh-jobs-local is not loaded); this plugin no longer ships its own job registry",
353
- endpointRegistryReplaced: "the background job service was replaced (a fresh registry restarts id numbering), so this rebuild was abandoned and its process terminated: reload the zvec-grep plugin before retrying, otherwise a stale panel would follow a different workspace's job",
354
357
  endpointJobsAtCapacity: "background jobs are at the host's limit ({limit} slots; running and stopping both count), so this rebuild never started: stop what you no longer need with job_kill, then start the rebuild again",
355
358
  unknownJobId: "unknown jobId (this rebuild record left the history window: the plugin keeps the most recent {maxJobs} finished rebuilds and drops the oldest settled one first; running rebuilds are never displaced, but a start request is refused outright once the concurrent limit is reached. Start the rebuild again)",
356
359
  jobOutputView: "\n[zvec-grep] (showing only the last {shown} of {total} characters)",
@@ -361,6 +364,10 @@ const MESSAGES = {
361
364
  clientModeInvalid: "invalid zg client mode: {received} (allowed: {allowed})",
362
365
  previewInvalid: "invalid preview mode: {received} (allowed: {allowed})",
363
366
  refreshInvalid: "invalid refresh policy: {received} (allowed: {allowed})",
367
+ 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.",
368
+ 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.",
369
+ serverReadyNote: "[zvec-grep] daemon: ready (searches can use server mode: incremental index refresh, resident embedding model pool)",
370
+ 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
371
  symbolTypeInvalid: "invalid symbol type: {received} (allowed: {allowed}; lowercase only)",
365
372
  rootEscapesFs: "root contains a .. segment that escapes the filesystem root: {path}",
366
373
  rootMustBeString: "root must be a string (received {received})",
@@ -368,6 +375,7 @@ const MESSAGES = {
368
375
  rootMustBeAbsolute: "root must be an absolute path (starting with /): {path}",
369
376
  rootIsFsRoot: "root must not be the filesystem root /",
370
377
  rootRequiredWithFallback: "root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)",
378
+ limitInvalid: "limit must be a non-negative integer (omit it to use the default)",
371
379
  mustBeStringArray: "{name} must be an array of strings",
372
380
  tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
373
381
  nonStringItem: "{name} contains a non-string item ({received})",
@@ -578,6 +586,16 @@ function refreshOf(value, messages) {
578
586
  }));
579
587
  return value;
580
588
  }
589
+ /**
590
+ * 这次调用**是不是显式要后台刷新**。宿主用它决定要不要探一发守护进程:缺省走 `wait`,
591
+ * 为一档没人要的取值多起一次进程是白给的开销。
592
+ *
593
+ * 这里只做字面量比较、不校验取值:非法的 `refresh`(如 `"Background"`)由 `refreshOf`
594
+ * 在构造期拒,两处判据不重复,也不会出现「先探了进程再报错」那种顺序依赖。
595
+ */
596
+ function requestsBackgroundRefresh(value) {
597
+ return value === "background";
598
+ }
581
599
  /** 合法符号类型名单,外供工具参数面的 JSON Schema `enum`,与取值器同一份来源。 */
582
600
  const SYMBOL_TYPE_NAMES = Object.keys({
583
601
  module: "module",
@@ -662,11 +680,11 @@ function resolveRoot(value, fallback, messages) {
662
680
  if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
663
681
  throw new Error(messages.rootRequiredWithFallback);
664
682
  }
665
- /** limit 钳制:非整数回默认,越界钳到 [LIMIT_MIN, LIMIT_MAX]。 */
666
- function clampLimit(value, fallback = 10) {
683
+ /** limit 钳制:省略(undefined/null)回默认;给了但不是非负整数即抛;越界钳到 [LIMIT_MIN, LIMIT_MAX]。 */
684
+ function clampLimit(value, messages, fallback = 10) {
667
685
  if (value === void 0 || value === null) return fallback;
668
686
  const num = typeof value === "number" ? value : Number(value);
669
- if (!Number.isSafeInteger(num)) return fallback;
687
+ if (!Number.isSafeInteger(num) || num < 0) throw new Error(messages.limitInvalid);
670
688
  return Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, num));
671
689
  }
672
690
  /** 检索类数组(queries/fts/vector)取值:条数与单条长度都放宽到 query 档。 */
@@ -745,12 +763,15 @@ function pushSearchGlobs(parts, args, messages) {
745
763
  function singleText(args, messages) {
746
764
  return optionalText(args.query, "query", messages, MAX_QUERY_CHARS);
747
765
  }
748
- function buildIndexedCommand(args, root, messages, mode) {
766
+ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
749
767
  const parts = ["zg", "query"];
750
768
  const { routeCount, dashGuard } = pushQueryArgs(parts, args, messages);
751
769
  if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
752
770
  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));
771
+ const refresh = refreshOf(args.refresh, messages);
772
+ if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
773
+ if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
774
+ parts.push("--limit", String(clampLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
754
775
  pushSearchGlobs(parts, args, messages);
755
776
  if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
756
777
  if (boolOf(args.trace, "trace", messages)) parts.push("--trace");
@@ -795,7 +816,7 @@ function buildExhaustiveCommand(args, root, messages, mode) {
795
816
  if (pattern.length === 0) throw new Error(messages.exhaustiveNeedsPattern);
796
817
  if (pattern.startsWith("-")) parts.push("-e", shq(pattern));
797
818
  else parts.push(shq(pattern));
798
- parts.push("--limit", String(clampLimit(args.limit)));
819
+ parts.push("--limit", String(clampLimit(args.limit, messages)));
799
820
  pushPathFilters(parts, args, messages);
800
821
  pushTimeFilters(parts, args, messages);
801
822
  parts.push(deviceFlag(args.device, messages), modeFlag(mode));
@@ -808,10 +829,14 @@ function buildExhaustiveCommand(args, root, messages, mode) {
808
829
  * `exhaustive` 走 zg 的穷举词法通道(`--rg`):不需要索引,是「工作区尚无索引」时的
809
830
  * 首选路径。选哪条路由由**宿主**判(它才有索引探测能力),本纯函数只按判据构造——
810
831
  * 判据见 host.ts 的 pickExhaustive。
832
+ *
833
+ * `backgroundSupport` 是宿主算得的「后台刷新能不能用」,只有索引通道用得上(穷举通道本就
834
+ * 不接受 refresh)。缺省按**不可用**处理:拿不到判据时把 background 拒掉是安全的一侧,而把
835
+ * 「没算出来」当成「可用」放行等于把一句假话发给模型。
811
836
  */
812
- function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false) {
837
+ function buildSearchCommand(args, messages, mode = DEFAULT_CLIENT_MODE, exhaustive = false, backgroundSupport = "daemon-down") {
813
838
  const root = assertAbsoluteRoot(args.root, messages);
814
- return exhaustive ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode);
839
+ return exhaustive ? buildExhaustiveCommand(args, root, messages, mode) : buildIndexedCommand(args, root, messages, mode, backgroundSupport);
815
840
  }
816
841
  /** 非负/正整数字符串化;非数值类型或非整数报错(`true` 不算 1)。 */
817
842
  function intFlag(value, name, messages, min) {
@@ -850,10 +875,12 @@ function pushIndexBoolFlags(parts, flags) {
850
875
  * type-not → 密钥排除 → ignore-file)。
851
876
  *
852
877
  * 密钥排除走 --iglob 而非 --glob,两个原因都是实测得来的:
853
- * - 扩展名大小写:真正会被索引的密钥库格式里,`.p12` / `.pfx` / `.keystore` 都存在
854
- * 混合大小写变体(`secret.P12`、`secret.PfX`、`secret.KEYSTORE` 皆实测入索引)。
878
+ * - 扩展名大小写:`.pem` / `.p12` / `.pfx` / `.keystore` 都**确实会被索引**(真 zg 0.2.2 实测:
879
+ * 一份只有 `secret.pem` / `secret.P12` / `a.ts` 的工作区,`zg index` 回执就是
880
+ * `3 scanned, 3 added`,随后 `zg query MARKERPEMLINE` 交回 `#1 matchedBy=fts+vector secret.pem:1-2`),
881
+ * 且都存在混合大小写变体(`secret.P12` / `secret.PfX` / `secret.KEYSTORE` 同样入索引)。
855
882
  * --glob 的 `!*.p12` 匹配不到 `secret.P12`,--iglob 走大小写不敏感匹配才能全部排除。
856
- * (`.pem` 不在此列:它本就不在 zg 的可索引类型里,不下发任何规则也不会进索引。)
883
+ * 判据钉在 test/e2e/zg-cli.test.ts 的「密钥排除真的在挡东西」那一组。
857
884
  * - 规则次序:引擎把全部 --glob 规则排在全部 --iglob 规则之前有序求值。密钥规则若
858
885
  * 用 --glob,用户一条宽泛的正向 --iglob(如 `**`)会在其后求值并把无扩展名的
859
886
  * `id_rsa*` 救回索引(实测「被索引」);用 --iglob 且排在本函数最后(用户 iglob
@@ -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) {
@@ -1656,91 +1711,45 @@ function tooOldZgVersion(stdout) {
1656
1711
  return parsed === void 0 || versionAtLeast(parsed, MINIMUM) ? void 0 : parsed;
1657
1712
  }
1658
1713
  //#endregion
1659
- //#region host.ts
1660
- const SEARCH_TIMEOUT_MS = 3e5;
1661
- const STATUS_TIMEOUT_MS = 6e4;
1662
- const INDEX_TIMEOUT_MS = 6e5;
1663
- const STDOUT_MAX_BYTES = 4e5;
1664
- /** 检索等待同根重建落定的上限(ms)。部署值:大型工作区的重建可能跑很久,
1665
- * 但也不该让一次检索无限期挂着。 */
1666
- const REBUILD_WAIT_MS = 12e4;
1667
- const REBUILD_PATH = "/_dsh/zvec-grep/rebuild";
1668
- const REBUILD_STATUS_PATH = "/_dsh/zvec-grep/rebuild-status";
1669
- /** 卡片取「可选工作区 + CSRF token」的引导端点(GET,只回本插件自己的数据)。 */
1670
- const REBUILD_ROOTS_PATH = "/_dsh/zvec-grep/rebuild-roots";
1671
- /** 动作端点的 CSRF 头名(值是每次 apply 重新生成的随机 token)。 */
1672
- const REBUILD_CSRF_HEADER = "x-zvec-grep-csrf";
1673
- /** rebuild 端点没有业务请求体,但必须把它读完(keep-alive 残留字节的协议正确性)。 */
1674
- const REBUILD_BODY_MAX_BYTES = 4096;
1675
- /** 工作区白名单容量:超过按最近使用淘汰最冷的一条(常驻进程内存有界)。 */
1676
- const MAX_LEDGER_ROOTS = 64;
1677
- /**
1678
- * 白名单条目的有效期:多久没被提到就当它不再活跃。一天足够覆盖「今天开过的会话」,
1679
- * 又不会让一个月前随手开过的一个目录一直占着名额。
1680
- */
1681
- const LEDGER_TTL_MS = 864e5;
1682
- /** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
1683
- const STDERR_NOTE_CHARS = 400;
1684
- /** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
1685
- * 也会放过「是个对象但没注册方法」的错注入。 */
1686
- function hasMethod(value, name, keys) {
1687
- const member = value[name];
1688
- return isRecord(member) && keys.every((key) => typeof member[key] === "function");
1689
- }
1714
+ //#region lib/index-preflight.ts
1690
1715
  /**
1691
- * host 是否为本插件所需服务面:五个注入面都必须是**带相应方法的对象**,
1692
- * 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
1693
- * 才 `undefined is not a function` 更早、更可诊断。
1716
+ * `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
1694
1717
  *
1695
- * settings 只探 `describe`:0.1.7 起那是本包唯一**直接调**的 settings 方法
1696
- * (跨命名空间读 locale)。`configure` 经 `ctx.inject` 的子上下文才拿到,
1697
- * `mutate` 本包 host 侧根本不用(写是卡片经 settingsScope 走 client 面)——
1698
- * 探它们等于断言一条没有测试撑着的能力。
1699
- */
1700
- function isZvecGrepHost(value) {
1701
- if (!isRecord(value)) return false;
1702
- return hasMethod(value, "settings", ["describe"]) && hasMethod(value, "shell", ["resolve", "execute"]) && hasMethod(value, "tools", ["register", "guard"]) && hasMethod(value, "systemPrompt", ["section"]) && hasMethod(value, "timer", ["timeout"]) && typeof value["get"] === "function";
1703
- }
1704
- /** 当前会话工作区(root 缺省回退源);非字符串视为缺(读取面见 lib/routing.ts 的 SessionFace)。 */
1705
- function sessionHeaderCwd(exec) {
1706
- const raw = exec.agent?.session?.header?.cwd;
1707
- return typeof raw === "string" && raw.length > 0 ? raw : void 0;
1708
- }
1709
- /**
1710
- * JSON.stringify 在本包**拥有的声明**上把返回宽成 `string | undefined`:lib 的签名恒为
1711
- * `string`,但 ECMA-262 规定入参是 undefined / 函数 / 符号时它返回 undefined(下面
1712
- * textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
1713
- * 会被 TS 的收窄按声明面判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
1718
+ * 判据「读得了 + 是文件」合成**一次** try(accessSync 在前):`statSync().isFile()` 对 mode 000
1719
+ * 的文件照样返回 true(stat 只要父目录可搜索、不要文件本身可读),故先 `accessSync(R_OK)` 补上
1720
+ * "当前进程真能 open 来读"这半段——它与 zg 的读权限同 uid 同源(root 下两者都放行、非 root 下
1721
+ * 两者都拒);再用 `isFile()` 挡掉目录。**不拆成「不存在」与「读不了」两条独立分支**:可读性那
1722
+ * 一档在 windows(chmod 只翻只读位,属主仍读得了)与 root(绕过 DAC)下根本造不出来,拆成独立
1723
+ * 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
1724
+ * 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
1725
+ *
1726
+ * drop 那一臂整段跳过:`--drop` 的命令只有 `zg index <root> --drop --yes`,ignoreFiles 被
1727
+ * buildIndexCommand 静默丢掉、根本不进 zg(见 lib/cli.ts 的 drop 分支),预检它没有意义,还会
1728
+ * 拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。判 drop 用与构造器**同一个**
1729
+ * `boolOf`,两处口径不会漂。
1730
+ * @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
1731
+ * @param root 已归一的工作区根(相对路径按它解析)
1732
+ * @param messages 文案表
1733
+ * @returns {void}
1734
+ * @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项)
1714
1735
  */
1715
- function stringifyJson(value) {
1716
- return JSON.stringify(value, null, 2);
1717
- }
1718
- function textBlock(value) {
1719
- const { text: textValue } = isRecord(value) ? value : {};
1720
- if (typeof textValue === "string") return [{
1721
- type: "text",
1722
- text: textValue
1723
- }];
1724
- let text;
1725
- try {
1726
- text = stringifyJson(value) ?? String(value);
1727
- } catch {
1736
+ function assertIgnoreFilesExist(args, root, messages) {
1737
+ if (boolOf(args.drop, "drop", messages)) return;
1738
+ for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
1739
+ const target = entry.startsWith("/") ? entry : `${root}/${entry}`;
1740
+ let usable = false;
1728
1741
  try {
1729
- text = String(value);
1730
- } catch {
1731
- text = "[unrenderable value]";
1732
- }
1742
+ accessSync(target, constants.R_OK);
1743
+ usable = statSync(target).isFile();
1744
+ } catch {}
1745
+ if (!usable) throw new Error(fill(messages.ignoreFileMissing, {
1746
+ path: entry,
1747
+ root
1748
+ }));
1733
1749
  }
1734
- return [{
1735
- type: "text",
1736
- text
1737
- }];
1738
1750
  }
1739
- const TEXT_OUTPUT_SCHEMA = {
1740
- type: "object",
1741
- additionalProperties: false,
1742
- properties: { text: { type: "string" } }
1743
- };
1751
+ //#endregion
1752
+ //#region lib/sandbox-note.ts
1744
1753
  /** 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。 */
1745
1754
  function sandboxFacts(info, messages) {
1746
1755
  const enforcement = info.enforcement === void 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
@@ -1749,116 +1758,28 @@ function sandboxFacts(info, messages) {
1749
1758
  enforcement
1750
1759
  });
1751
1760
  }
1752
- /**
1753
- * 沙箱侧的**硬**失败:命令根本没跑起来。
1754
- * runnerFailed 与 exitCode 无关——runner 在命令执行前就挂了,exit 码是 runner 的,
1755
- * 拿来判「zg 未安装」是把沙箱故障误报成用户缺二进制。
1756
- */
1757
- function sandboxFailure(result, messages) {
1758
- const info = result.sandbox;
1759
- if (info?.runnerFailed !== true) return null;
1760
- return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
1761
- }
1762
1761
  /** 沙箱策略拒绝的可读说明(拒绝 ≠ 崩溃:既用于失败消息,也用于成功但残缺的结果)。 */
1763
1762
  function deniedNote(info, messages) {
1764
1763
  return fill(messages.sandboxDenied, { facts: sandboxFacts(info, messages) });
1765
1764
  }
1766
- /** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
1767
- * 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
1768
- * 尾切点会留下孤立**低**代理(`truncateStart` 丢掉它);对调两个函数同样不留孤立代理,
1769
- * 只是头尾内容掉头 ⇒ 测试里另有一组哨兵断言钉住归属。 */
1770
- function failureDetail(result, messages) {
1771
- const raw = result.stderr.text.length > 0 ? result.stderr.text : result.stdout.text;
1772
- if (raw.length <= 800) return raw;
1773
- const half = 400;
1774
- return fill(messages.detailMiddle, {
1775
- head: truncateEnd(raw, half),
1776
- tail: truncateStart(raw, half)
1777
- });
1778
- }
1779
- /** 有详情才带前缀拼接(不同句式各有前缀),空详情绝不留孤儿标点。 */
1780
- function withDetail(detail, prefix) {
1781
- return detail.length > 0 ? fill(prefix, { detail }) : "";
1782
- }
1783
- function shellFailure(result, messages) {
1784
- const runnerFailure = sandboxFailure(result, messages);
1785
- if (runnerFailure !== null) return runnerFailure;
1786
- if (result.timedOut) return messages.timeoutFailure;
1787
- if (result.aborted) return messages.abortedFailure;
1788
- if (result.exitCode === 0) return null;
1789
- const detail = failureDetail(result, messages);
1790
- const { sandbox } = result;
1791
- if (sandbox?.denied === true) return fill(messages.deniedFailure, {
1792
- exit: result.exitCode,
1793
- denied: deniedNote(sandbox, messages),
1794
- detail: withDetail(detail, messages.detailPrefix)
1795
- });
1796
- if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
1797
- return fill(messages.genericFailure, {
1798
- exit: result.exitCode,
1799
- detail: withDetail(detail, messages.detailColon)
1800
- });
1801
- }
1802
- /**
1803
- * 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
1804
- *
1805
- * zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行落盘,实测原文:`Scanning files...` /
1806
- * `Preparing local/potion-code-16m-v2` / `Indexing complete`)。这些行每次建索引都在,写进
1807
- * 工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:降级提示、锁冲突、
1808
- * 沙箱事实,以及任何本包**不认识**的新增告警。
1809
- *
1810
- * 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
1811
- * 新提示就会静默吞掉,那正是最不该发生的失败模式。
1812
- *
1813
- * 进度行词表逐条对着上游的进度格式化函数核过(含下载与就绪两档):
1814
- * Scanning files… / Indexing files… / Indexing complete / Preparing <model> /
1815
- * Downloading <model> · … / Model ready: <model>
1816
- * 其中 `Indexing complete` 用**整行相等**匹配,不能用前缀——`Indexing completed with 3 failed
1817
- * files`(部分文件失败的信号,必须留着)字面上就以它开头。
1818
- */
1819
- const STDERR_PROGRESS_LINES = /* @__PURE__ */ new Set(["Scanning files...", "Indexing complete"]);
1820
- /** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
1821
- function isStderrProgressLine(line) {
1822
- const trimmed = line.trim();
1823
- if (STDERR_PROGRESS_LINES.has(trimmed)) return true;
1824
- return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
1825
- }
1826
- /** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
1827
- function signalStderr(text) {
1828
- return text.split("\n").filter((line) => line.trim().length > 0 && !isStderrProgressLine(line)).join("\n");
1829
- }
1830
1765
  /**
1831
- * 成功(exit 0)执行的结果体检:把「其实不完整」的三类事实显式打标,避免模型
1832
- * 把残缺输出当完整证据用。
1833
- * 1. stdout 超上限被截尾(可能已落 spill);
1834
- * 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
1835
- * 3. **stderr 去噪之后仍非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为
1836
- * 纯词法兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
1837
- * 结果」的检索当语义检索的完整结果。这里回显尾部一段。整段都是索引进度时一句都不加。
1766
+ * 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
1767
+ * dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
1768
+ * 与「zg 根本没跑起来」分开。
1838
1769
  */
1839
- function successNotes(result, messages, stdoutMaxBytes) {
1840
- const notes = [];
1841
- if (result.stdout.truncated) {
1842
- const spill = result.stdout.spillPath === void 0 ? "" : fill(messages.spillNote, { path: result.stdout.spillPath });
1843
- notes.push(fill(messages.outputTruncated, {
1844
- maxBytes: stdoutMaxBytes,
1845
- spill
1846
- }));
1847
- }
1848
- const { sandbox } = result;
1849
- if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
1850
- const { stderr } = result;
1851
- const signal = signalStderr(stderr.text);
1852
- if (signal.length > 0) {
1853
- const tail = truncateStart(signal, STDERR_NOTE_CHARS);
1854
- const truncatedMark = stderr.truncated ? "[…]" : "";
1855
- notes.push(fill(messages.stderrNote, {
1856
- marked: truncatedMark,
1857
- tail
1858
- }));
1859
- }
1860
- return notes;
1770
+ function procSandboxNote(proc, messages) {
1771
+ const info = proc.sandbox;
1772
+ if (info === void 0) return null;
1773
+ if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
1774
+ if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
1775
+ return null;
1861
1776
  }
1777
+ //#endregion
1778
+ //#region lib/rebuild-shape.ts
1779
+ /** 宿主服务键 = 客户端线上命名空间(两侧共用的唯一来源)。 */
1780
+ const REBUILD_REMOTE_NAMESPACE = "zvecGrepRebuild";
1781
+ //#endregion
1782
+ //#region lib/zg-config.ts
1862
1783
  /** 各环境读一个 HF 镜像/代理基地址的优先级:显式入参 > 设置。
1863
1784
  * `typeof` 判断是 host 侧兜底:值域正常时 schema 的 `.default()` 已保证是字符串,
1864
1785
  * 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。 */
@@ -1892,14 +1813,13 @@ function allowRemoteEmbedding(config) {
1892
1813
  * **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
1893
1814
  * - 本包把整条命令当官方作业的 `JobSpec.label` 回显给卡片,argv 里的密钥会进界面、
1894
1815
  * 进日志、进 `ps` 的进程列表;
1895
- * - 上游自己就优先读环境变量(zvec-grep v0.2.2 `src/engine/config.ts`:
1896
- * `nonEmptyEnvironmentValue(environment.ZVEC_GREP_ENDPOINT)`、
1897
- * `environmentApiKey()` 依次试 `ZVEC_GREP_API_KEY` / `DASHSCOPE_API_KEY` / `QWEN_API_KEY`),
1816
+ * - 上游自己就优先读环境变量(zvec-grep v0.2.2 `src/engine/config.ts` 的
1817
+ * `nonEmptyEnvironmentValue(environment.ZVEC_GREP_ENDPOINT)` / `environmentApiKey()`),
1898
1818
  * 走 env 既是它的正路,也省掉一条 argv 泄露面。
1899
1819
  *
1900
1820
  * **凭据为什么是「宿主进程里某个环境变量的名字」而不是值本身**:官方 subprocess 层会把
1901
1821
  * 名字命中 `/KEY|PASSWORD|SECRET|TOKEN/i` 的变量从子进程环境里**剔掉**
1902
- * (`packages/subprocess/subprocess/src/index.ts` 的 `scrubbedParentEnv`),所以光靠在
1822
+ * (packages/subprocess/subprocess/src/index.ts 的 `scrubbedParentEnv`),所以光靠在
1903
1823
  * 宿主进程里 export 一个 `ZVEC_GREP_API_KEY` 是到不了 zg 的——必须由本插件显式转发。
1904
1824
  * 于是配置里只记**名字**、值现读现转:密钥不必落进插件配置文件,也不进 argv、不进日志。
1905
1825
  * 两项都只在 allowRemoteEmbedding 打开时才读:默认部署下这段代码根本不执行。
@@ -1915,1143 +1835,1320 @@ function zgEnv(config) {
1915
1835
  }
1916
1836
  return Object.keys(env).length > 0 ? env : void 0;
1917
1837
  }
1918
- /** 版本探测结果的缓存时长:够长到一次会话里基本只探一次,够短到用户中途升级 zg 也算数。 */
1919
- const ZG_VERSION_TTL_MS = 6e5;
1920
- /** 探测自身的超时:`zg --version` 是纯打印,给它检索超时是浪费,也让它卡住主流程。 */
1921
- const ZG_VERSION_PROBE_TIMEOUT_MS = 1e4;
1922
- /** 门槛文案:回显实际版本与门槛值,并给出唯一的出路(升级 zvec-grep)。 */
1923
- function tooOldZgError(actual, messages) {
1924
- return new Error(fill(messages.zgVersionTooOld, {
1925
- actual: formatZgVersion(actual),
1926
- minimum: MINIMUM_ZG_VERSION
1927
- }));
1838
+ function readDefaultEmbedding(config) {
1839
+ const raw = config.defaultEmbedding.get();
1840
+ if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
1841
+ return DEFAULT_EMBEDDING;
1928
1842
  }
1929
1843
  /**
1930
- * 跑一次 `zg --version`,只把 stdout 交回来(undefined = 探测不出来:非零退出、
1931
- * 读不懂的形状,或 spawn/执行器层面的任何失败)。**失败绝不外抛**:这道门槛的职责
1932
- * 只有一个——把「确知太老」拦下来,拿「没读懂」去拦用户是在制造新故障。
1844
+ * zg 传输模式:域内取值由 schema 保证,这里只处理「字段缺省」与宿主退化时交回的非域值。
1845
+ * 读一次即传给检索、索引、状态与后台重建四条命令路径——混用模式会在守护进程持有索引
1846
+ * 租约时让写侧直接失败,故四条路径必须同源。
1933
1847
  */
1934
- async function probeZgVersion(host, config) {
1935
- let stdout;
1936
- try {
1937
- const env = zgEnv(config);
1938
- const spec = host.shell.resolve({
1939
- command: "zg --version",
1940
- workdir: tmpdir(),
1941
- timeoutMs: ZG_VERSION_PROBE_TIMEOUT_MS,
1942
- stdoutMaxBytes: config.stdoutMaxBytes,
1943
- ...env ? { env } : {}
1944
- });
1945
- const result = await (await host.shell.execute(spec)).result();
1946
- stdout = result.exitCode === 0 ? result.stdout.text : void 0;
1947
- } catch {
1948
- stdout = void 0;
1949
- }
1950
- return stdout === void 0 ? void 0 : tooOldZgVersion(stdout);
1848
+ function readClientMode(config, messages) {
1849
+ return clientModeOf(config.clientMode, messages);
1951
1850
  }
1851
+ //#endregion
1852
+ //#region lib/rebuild-remote.ts
1853
+ /** 本包作业的 kind(宿主据此发出的 id 形如 `zvec-grep-rebuild-<hex>`)。 */
1854
+ const REBUILD_JOB_KIND = "zvec-grep-rebuild";
1952
1855
  /**
1953
- * 建这道门槛。缓存挂在闭包里(随 apply 生死),TTL 到期或探测失败后重探一次。
1954
- *
1955
- * workdir 取系统临时目录而不是会话 cwd:这是一次与工作区无关的纯打印探测,
1956
- * 不该因为某个会话的工作区不存在而失败,也不该顺手触发 root 授权那一套。
1856
+ * 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
1857
+ * 正好 `MAX` 条在册(文案与卡片拒绝提示都按这个数说)。同时能跑几个不在这里——那是
1858
+ * 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
1859
+ * 自行回收落定记录("A settled record stays listed until its owner's disposal, service
1860
+ * disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
1861
+ * 裁剪是本包的责任。
1957
1862
  */
1958
- function createZgVersionGate(host, config) {
1959
- let cachedAt = 0;
1960
- let cachedTooOld;
1961
- return { async ensure(messages) {
1962
- const now = Date.now();
1963
- if (now - cachedAt < ZG_VERSION_TTL_MS) {
1964
- if (cachedTooOld !== void 0) throw tooOldZgError(cachedTooOld, messages);
1965
- return;
1966
- }
1967
- const probe = await probeZgVersion(host, config);
1968
- cachedAt = now;
1969
- cachedTooOld = probe;
1970
- if (probe !== void 0) throw tooOldZgError(probe, messages);
1971
- } };
1863
+ const REBUILD_HISTORY_MAX = 10;
1864
+ /** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
1865
+ const JOB_OUT_VIEW_CHARS = 4e3;
1866
+ /** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
1867
+ function identityOf(view) {
1868
+ return {
1869
+ kind: view.kind,
1870
+ label: view.label,
1871
+ startedAt: view.startedAt
1872
+ };
1873
+ }
1874
+ /** 两段身份证是否同一回事(三段全同才算)。 */
1875
+ function sameIdentity(left, right) {
1876
+ return left.kind === right.kind && left.label === right.label && left.startedAt === right.startedAt;
1972
1877
  }
1973
1878
  /**
1974
- * zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
1975
- * 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
1976
- * 在 fts 组排第 4、在 vector 组排第 1),直接求和会把同一处位置重复计入。
1977
- * - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
1978
- * - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
1979
- * 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
1980
- * 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
1981
- * 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
1982
- * 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
1983
- * 不数就不谎称。
1879
+ * 身份证尚未盖章时的占位出生时刻。
1984
1880
  *
1985
- * zg 的输出**不提供**任何截断信号,故命中数正好等于 --limit 只能作为观察陈述,不能
1986
- * 断言发生了截断(`hitCapped` 因此不含断言措辞)。
1881
+ * `startedAt` 由官方签发(`Date.now()`,永不为 0),而 kind/label 在 `start` 之前就已
1882
+ * 已知——那正是本包递给官方的那份规格。于是"start 的同步块里就跑到了 `run()`"那一档读取
1883
+ * 比对时必然落到"对不上":那一刻还没有可比的出生时刻,不该把同 id 的另一条作业当成自己的收走。
1987
1884
  */
1988
- /** zg 每个查询组的计数行前缀(实测输出形状:`hits: 3`,源码行都带行号前缀)。 */
1989
- const HITS_LINE_PREFIX = "hits: ";
1885
+ const UNSIGNED_STARTED_AT = 0;
1990
1886
  /**
1991
- * zg 命中条目头行的形状:`#<名次> [选择理由] matchedBy=<来源> [score=<分>] <相对路径>:<行号范围>`。
1992
- * 捕获组即身份键。
1993
- *
1994
- * 两段可选装饰都不能进键,各有实测依据(`--trace` 开启时出现,见 formatScore 与
1995
- * agentRankedItemHeader):
1996
- * - `score=`:**同一处位置在两个组里分值可以不同**(实测 `src/beta.ts:1-2` 在 fts 组
1997
- * 是 0.0164、在 vector 组是 0.0161)。带分值入键等于让每次命中都成"新位置",去重
1998
- * 直接失效、位置数虚高一倍。分值形态是 `Number.isInteger ? String : toFixed(4)`,
1999
- * 故整数与四位小数都要收;只认纯数字,路径若真以 `score=1.txt` 开头则不会被误剥
2000
- * (`score=1` 后面跟的是 `.` 不是空白,整段不匹配)。
2001
- * - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
2002
- * 就匹配不上,那条命中会被当成不存在。
1887
+ * 名册里那条 id 是不是**我们**的那条作业。
2003
1888
  *
2004
- * preview 的源码行都带 `<行号>\t` 前缀、markdown 标题行是 `heading:`、追踪行是 `trace:`,
2005
- * 都撞不上这一形状。匹配来源逐组变化(fts / vector / fts+vector),故 `\S+` 只消费来源。
1889
+ * 只比 id 不够:id 是从请求里读进来的,名册里同 id 的那条完全可能是另一条作业(另一棵树、
1890
+ * 另一条命令),旧卡片跟上去就是串台。三段身份都由官方签发。
2006
1891
  */
2007
- const HIT_LINE_PREFIX = /^#\d+(?:\s+\[[^\]]*\])?\s+matchedBy=\S+\s+(?:score=-?\d+(?:\.\d+)?\s+)?(?<location>\S.*)$/u;
2008
- function hitSummary(stdoutText, limit, truncated, messages) {
2009
- const lines = stdoutText.split("\n");
2010
- const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => /^\d+$/u.test(digits)).map((digits) => Math.trunc(Number(digits)));
2011
- if (perGroup.length === 0) return null;
2012
- const locations = /* @__PURE__ */ new Set();
2013
- for (const line of lines) {
2014
- const location = HIT_LINE_PREFIX.exec(line)?.groups?.["location"];
2015
- if (location !== void 0) locations.add(location);
2016
- }
2017
- const grouped = perGroup.reduce((sum, count) => sum + count, 0);
2018
- const capped = perGroup.some((count) => count >= limit);
2019
- return fill(messages.hitSummary, {
2020
- groups: perGroup.length,
2021
- grouped,
2022
- dedup: locations.size === 0 ? "" : fill(messages.hitDedup, { unique: locations.size }),
2023
- limit,
2024
- capped: capped ? messages.hitCapped : "",
2025
- truncated: truncated ? messages.hitTruncated : ""
2026
- });
1892
+ function sameJob(state, view) {
1893
+ return sameIdentity(state.identity, identityOf(view));
2027
1894
  }
2028
1895
  /**
2029
- * 被「本插件正在重建」挡住的失败:文案照常是人话,但额外带上结构化结论,
2030
- * 让检索路径能判断「等它落定后重试一次」而不是无脑失败。
2031
- * 只有占锁方自报重建才带这个类型——把「别的进程占锁」也当成可等的重建,
2032
- * 会在一把永远不会由本插件放开的锁上无界挂起。
1896
+ * 本包作业的输出面:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
1897
+ * 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核后按实测定下的:
1898
+ * - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
1899
+ * types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
1900
+ * 消费式游标互不干扰;
1901
+ * - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
1902
+ * 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
1903
+ * @param proc 后台进程句柄
1904
+ * @param state 这条重建的状态盒(见 {@link RebuildState})
1905
+ * @returns 交给 JobSpec.output 的两条源
2033
1906
  */
2034
- var RebuildLockBusyError = class extends Error {
2035
- constructor(message) {
2036
- super(message);
2037
- this.name = "RebuildLockBusyError";
2038
- }
2039
- };
2040
- async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
2041
- const spec = host.shell.resolve({
2042
- command,
2043
- workdir,
2044
- timeoutMs,
2045
- stdoutMaxBytes: opts.stdoutMaxBytes,
2046
- signal: opts.signal,
2047
- ...opts.env ? { env: opts.env } : {}
1907
+ function rebuildSources(proc, state) {
1908
+ return ["stdout", "stderr"].map((channel) => {
1909
+ let failed = false;
1910
+ return {
1911
+ channel,
1912
+ read: (fromByte) => {
1913
+ if (failed) return {
1914
+ text: "",
1915
+ nextOffset: fromByte,
1916
+ lossy: true
1917
+ };
1918
+ try {
1919
+ const read = proc.observed[channel].readFrom(fromByte);
1920
+ if (read.lossy) state.lost = true;
1921
+ return read;
1922
+ } catch {
1923
+ state.lost = true;
1924
+ failed = true;
1925
+ return {
1926
+ text: "",
1927
+ nextOffset: fromByte,
1928
+ lossy: true
1929
+ };
1930
+ }
1931
+ }
1932
+ };
2048
1933
  });
2049
- const result = await (await host.shell.execute(spec)).result();
2050
- const failure = shellFailure(result, opts.messages);
2051
- if (failure !== null) {
2052
- const resolved = opts.resolveFailure?.(failure, result) ?? null;
2053
- if (resolved !== null) return resolved;
2054
- const concurrent = classifyConcurrentFailure(result.stderr.text);
2055
- throw concurrent?.kind === "lock-busy" && concurrent.rebuild ? new RebuildLockBusyError(failure) : new Error(failure);
1934
+ }
1935
+ /** 官方件对未知/已淘汰 id 抛错;本包的判据要的是"有没有",不是异常(无 ⇒ null)。 */
1936
+ function jobView(jobs, id) {
1937
+ try {
1938
+ return jobs.get(id);
1939
+ } catch {
1940
+ return null;
2056
1941
  }
2057
- const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
2058
- const { text } = result.stdout;
2059
- const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
2060
- const extras = summary === null ? notes : [...notes, summary];
2061
- return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
2062
1942
  }
2063
- /** 等待期间被取消时的出路(与 zg 自身被中止区分开:这里等的是重建,不是命令)。 */
2064
- function messagesAbortedWaiting(root, messages) {
2065
- return fill(messages.rebuildWaitAborted, { root });
1943
+ /** 一次成对读数:状态投影 + 留存窗内容;注册表已无此 id ⇒ null。 */
1944
+ function readRebuildOutput(jobs, id) {
1945
+ try {
1946
+ return {
1947
+ view: jobs.get(id),
1948
+ retained: jobs.readAt(id, 0)
1949
+ };
1950
+ } catch {
1951
+ return null;
1952
+ }
2066
1953
  }
2067
- /** 等待重建落定超时:给出可行动出路,并说明不会因此发放 grep/rg 配额。 */
2068
- function messagesWaitExpired(root, maxWaitMs, messages) {
2069
- return fill(messages.rebuildWaitTimeout, {
2070
- root,
2071
- seconds: Math.round(maxWaitMs / 1e3)
2072
- });
1954
+ /** 官方 JobStatus 里"仍在跑"的两枚:`stopping` 是取消已发出、进程还没收完。 */
1955
+ function isLiveStatus(status) {
1956
+ return status === "running" || status === "stopping";
2073
1957
  }
2074
1958
  /**
2075
- * 前台执行 + **一次**重建等待重试。
2076
- *
2077
- * 重建持有该根的写锁时,检索会立刻以「索引不可用」失败(zg 的锁是纯 fail-fast,不等)。
2078
- * 直接把失败回给模型,等于在重建窗口内把该根的检索通道整个关掉——而门禁又要求先成功
2079
- * 检索才放行 grep/rg,于是模型连退路都没有。这里改为:确认占锁方确实是本插件的重建,
2080
- * 就等它落定后重跑一次;只等一次,不做轮询式长等,避免把一次检索拖成分钟级。
1959
+ * 收掉子进程,**忽略抛错**:进程可能已自然退出或已被系统回收,此时 kill 失败不是本包的失败。
1960
+ * 调用点都在清理臂(卸载、被拒、超时)上,那里没有可行动的下一步;把异常抛出去只会让清理链
1961
+ * 半途而废,留下更难的现场。
2081
1962
  */
2082
- async function runForeground(host, command, workdir, timeoutMs, opts) {
2083
- const base = {
2084
- signal: opts.signal,
2085
- env: opts.env,
2086
- stdoutMaxBytes: opts.stdoutMaxBytes,
2087
- messages: opts.messages,
2088
- summaryLimit: opts.summaryLimit,
2089
- resolveFailure: opts.resolveFailure
2090
- };
2091
- const wait = opts.rebuildWait;
2092
- if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
1963
+ function killProc(proc) {
2093
1964
  try {
2094
- return await runForegroundOnce(host, command, workdir, timeoutMs, base);
2095
- } catch (error) {
2096
- const entry = wait.rebuilds.covering(wait.root, opts.messages);
2097
- if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
2098
- const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
2099
- if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
2100
- throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
2101
- }
1965
+ proc.kill();
1966
+ } catch {}
2102
1967
  }
2103
1968
  /**
2104
- * root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
2105
- * ENOENT 失败——那与「bash 没装」「zg 没装」在同一句 stderr 里无法区分,
2106
- * 模型据此给出的建议会把用户带偏。提前一次 existsSync 换明确归因。
1969
+ * 历史窗口有界:按注册表的**可见集合**淘汰本 kind 最老的已落定记录。
1970
+ *
1971
+ * 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
1972
+ * 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
1973
+ * 同一口径。判据的时点是**新作业落定之后**,不是剪完那一刻——只看后者会把这条判反。
1974
+ * 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务。
1975
+ * 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
1976
+ * `list()` 而不是 `records`。
1977
+ * @param jobs 官方注册表
1978
+ * @param records 本包侧表(被淘汰记录同步删掉)
1979
+ * @returns {void}
2107
1980
  */
2108
- function assertRootExists(root, messages) {
2109
- if (!existsSync(root)) throw new Error(fill(messages.rootMissing, { root }));
2110
- return root;
2111
- }
2112
- function readDefaultEmbedding(config) {
2113
- const raw = config.defaultEmbedding.get();
2114
- if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
2115
- return DEFAULT_EMBEDDING;
1981
+ function pruneRebuildHistory(jobs, records) {
1982
+ const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
1983
+ for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
1984
+ jobs.remove(job.id);
1985
+ records.delete(job.id);
1986
+ }
2116
1987
  }
2117
1988
  /**
2118
- * 默认每组结果数:值域 1-50 由 Config schema(隐式命名空间与行 config 共用)保证,
2119
- * 这里只处理「字段缺省」。真正兜住越界的是 cli.clampLimit(命令构造边界)。
1989
+ * 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
1990
+ * owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
1991
+ * 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
1992
+ * 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
2120
1993
  */
2121
- function readDefaultLimit(config) {
2122
- return config.defaultLimit.get() ?? 10;
2123
- }
2124
- /** search-first 解锁配额:每次成功 zg_search 发放的 grep/rg 次数(值域 1-20 由 schema 保证)。 */
2125
- function readGrepBudget(config) {
2126
- return config.grepBudgetPerSearch.get() ?? 3;
1994
+ function capacityLimitOf(error) {
1995
+ return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
2127
1996
  }
2128
1997
  /**
2129
- * zg 传输模式:域内取值由 schema 保证,这里只处理「字段缺省」与宿主退化时交回的非域值。
2130
- * 读一次即传给检索、索引、状态与后台重建四条命令路径——混用模式会在守护进程持有索引
2131
- * 租约时让写侧直接失败,故四条路径必须同源。
1998
+ * 「工作区重建」的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
1999
+ * 目录此刻仍存在。不过就交回可直接显示的文案(错误文本全走双语字典)。
2000
+ *
2001
+ * 白名单是**动作**的闸门:没有它,任何拿得到这条读面的一方都能用任意绝对路径去
2002
+ * `zg index --rebuild`——读遍那棵树、写 `.zvec-grep/`,还可能把其中的非隐藏敏感文件
2003
+ * 灌进向量库并回显到上下文。
2004
+ * @param raw 请求里带来的 root(未经类型校验)
2005
+ * @param ledger 观测到的工作区白名单
2006
+ * @param started 本次请求语言的文案表
2007
+ * @returns 归一化后可用的绝对路径;不合格时 `{ error }`
2132
2008
  */
2133
- function readClientMode(config, messages) {
2134
- return clientModeOf(config.clientMode, messages);
2135
- }
2136
- /** search-first 解锁时效(分钟,值域 1-240 由 schema 保证)。 */
2137
- function readUnlockWindowMin(config) {
2138
- return config.unlockWindowMin.get() ?? 10;
2139
- }
2140
- /** search-first 门禁开关:**fail-closed**。schema 默认已是 true,引用仍交回 undefined
2141
- * (条目没被投影 / 宿主退化)时按「门禁开着」处理——宁可多拦一次 grep,也不能把
2142
- * 「读不到设置」静默当成「用户关了门禁」。 */
2143
- function readEnforceSearchFirst(config) {
2144
- return config.enforceSearchFirst.get() ?? true;
2009
+ function acceptableRoot(raw, ledger, started) {
2010
+ let root;
2011
+ try {
2012
+ root = assertAbsoluteRoot(raw, started);
2013
+ } catch (error) {
2014
+ return { error: {
2015
+ value: fill(started.endpointRootInvalid, { reason: errorText(error) }),
2016
+ status: 400
2017
+ } };
2018
+ }
2019
+ if (!ledger.has(root)) return { error: {
2020
+ value: fill(started.endpointRootUntracked, { root }),
2021
+ status: 403
2022
+ } };
2023
+ if (!existsSync(root)) return { error: {
2024
+ value: fill(started.endpointRootGone, { root }),
2025
+ status: 400
2026
+ } };
2027
+ return { root };
2145
2028
  }
2146
- /** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
2147
- function comparablePath(root) {
2148
- return root.startsWith("/private/") ? root.slice(8) : root;
2029
+ /**
2030
+ * 这个 root 上有没有**仍在跑**的本包重建?有 ⇒ 返回那枚作业 id 让新面板跟随。
2031
+ *
2032
+ * 判据是三条一起:"侧表里有这条" + "名册里同 id 的那条确实是我们那条(比出生时刻)" +
2033
+ * "状态还在跑/正在收"。第二条不能省:jobs 被重载之后 id 会重名,只查侧表就把一张新面板
2034
+ * 领到别人的作业上。
2035
+ * @param jobs 调用方已确认在场的注册表(缺席那一支在重建方法更早答过)
2036
+ * @param records 本包侧表
2037
+ * @param root 已归一化的工作区
2038
+ * @returns 跟进的那枚作业 id;没有可跟的就是 undefined
2039
+ */
2040
+ function followRunningRebuild(jobs, records, root) {
2041
+ return [...records.values()].find((record) => {
2042
+ if (record.root !== root) return false;
2043
+ const view = jobView(jobs, record.id);
2044
+ return view !== null && sameJob(record.state, view) && isLiveStatus(view.status);
2045
+ })?.id;
2149
2046
  }
2150
- /** 认的清单版本:与上游 `CURRENT_MANIFEST_VERSION` 同值([v0.2.2] src/engine/manifest.ts:8)。 */
2151
- const SUPPORTED_MANIFEST_VERSION = 1;
2152
2047
  /**
2153
- * 索引清单是否**真的**覆盖这个工作区。
2048
+ * 把「起一条 zg 失败」的原因翻成卡片文案。
2154
2049
  *
2155
- * 只判「文件在不在」是不够的,两种实况都会把它判成有索引而实际检索必然失败:
2156
- * - 文件在,但内容不是一份清单(半截写入、被别的东西占了同名文件)——解析失败即不算。
2157
- * - 清单在,但索引的根路径不覆盖这个目录(例如指向另一个盘符/被改写过的路径)——此时
2158
- * 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
2159
- * - 清单的版本不是当前认的那一版——上游读它会直接抛 MANIFEST.INVALID(要求
2160
- * `manifestVersion` 严格等于 `CURRENT_MANIFEST_VERSION`),此时本目录**一次检索都做不了**,
2161
- * 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
2050
+ * **本函数不杀进程**:杀由 `attachIndexWrite` 负责——它才是真正握着那条进程句柄、
2051
+ * 且知道作业有没有登记成功的地方(preflight 在 controller/容量/入参上拒掉作业时,spawn
2052
+ * 已经发生,不杀就会留下一条没登记、谁也停不掉的 zg)。这里只管文案。
2162
2053
  *
2163
- * 认的结构只有真正用到的两处(实测上游的 workspace manifest 形状):
2164
- * `manifestVersion` 严格等于 1,`rootPaths` 是非空数组且每项带一个非空 `absolutePath`。
2165
- * 刻意不校验 embedding / policy 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
2054
+ * 满员那一档单独翻文案:它是本包唯一会把宿主英文原话插进卡片的错误,又最该翻成人话
2055
+ * (用户要做的是去 job_list 收作业,不是读一句英文)。
2056
+ */
2057
+ function startupFailureText(error, started) {
2058
+ const capacity = capacityLimitOf(error);
2059
+ return capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity });
2060
+ }
2061
+ /**
2062
+ * 在 controller 闸门下起一条未拥有作业。
2166
2063
  *
2167
- * 覆盖判据是「归一后相等」。实测 macOS 上清单里写的是**未解析**路径(`/tmp/x`)而
2168
- * `path` 字段才是解析过的(`/private/tmp/x`),会话 cwd 通常也是未解析那一支;但调用方
2169
- * 完全可能交来解析过的形式,故两边都再剥一次 `/private` 前缀再比。
2064
+ * 官方件在"没有 controller 服务这个 owner"时直接拒绝 `start`(实测),而未拥有
2065
+ * 作业只被 global 层服务;web 面上宿主自己的 `tool-jobs` 被移进了各 preset realm
2066
+ * (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs 在宿主平面 disabled),
2067
+ * 所以本包必须自带一枚从无作用域上下文 attach 的 controller。但**只在 start 这一瞬挂**:
2068
+ * 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
2069
+ * 读,作业的后续(read/kill/落定)都不依赖它。留一枚常驻 token 等于在"宿主故意没装 job
2070
+ * 工具"的组成里替全宿主开着那道闸门——官方契约写的是"生产者不能起一台 owner 收不掉、
2071
+ * 停不掉的作业",常驻就是把它反过来做。
2170
2072
  */
2171
- function manifestCoversRoot(manifestPath, dir) {
2172
- let parsed;
2073
+ function startUnderController(jobs, spec) {
2074
+ const detach = jobs.attachController("zvec-grep: rebuild");
2173
2075
  try {
2174
- parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
2175
- } catch {
2176
- return false;
2076
+ return jobs.start(spec);
2077
+ } finally {
2078
+ detach();
2177
2079
  }
2178
- if (!isRecord(parsed) || !("manifestVersion" in parsed) || parsed["manifestVersion"] !== SUPPORTED_MANIFEST_VERSION) return false;
2179
- const { rootPaths } = parsed;
2180
- if (!Array.isArray(rootPaths) || rootPaths.length === 0) return false;
2181
- const target = comparablePath(normalizeRoot(dir));
2182
- return rootPaths.some((entry) => isRecord(entry) && typeof entry["absolutePath"] === "string" && entry["absolutePath"].length > 0 && comparablePath(normalizeRoot(entry["absolutePath"])) === target);
2183
- }
2184
- /** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
2185
- * 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
2186
- * home** 征用(`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
2187
- * 只判目录存在的话,一个从没建过索引的工作区会因祖先目录撞名而被当成「已建索引」——
2188
- * 门禁随即在没有任何索引可搜的情况下拦下 grep/rg,而 zg_search 也答不出任何东西。
2189
- * manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
2190
- * 才说明这个工作区真的建过索引。 */
2191
- function indexProbeOf(dir) {
2192
- const base = `${dir}/${INDEX_DIR_NAME}`;
2193
- if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
2194
- return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
2195
- }
2196
- /** 工具入参的 root:显式值 > 会话工作区,再过存在性预检(一处三工具共用)。 */
2197
- 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;
2206
- }
2207
- function define(host, spec) {
2208
- const { parameters } = spec;
2209
- const required = Array.isArray(parameters["required"]) ? parameters["required"].filter((item) => typeof item === "string") : [];
2210
- host.tools.register({
2211
- name: spec.name,
2212
- description: spec.description,
2213
- parameters,
2214
- output: {
2215
- schema: TEXT_OUTPUT_SCHEMA,
2216
- render: (_args, value) => textBlock(value)
2217
- },
2218
- execute: async (rawArgs, exec) => {
2219
- const messages = spec.messages();
2220
- if (!isRecord(rawArgs)) throw new Error(fill(messages.argsMustBeObject, {
2221
- name: spec.name,
2222
- received: rawArgs === null ? "null" : typeof rawArgs
2223
- }));
2224
- const missing = required.filter((fieldName) => rawArgs[fieldName] === void 0);
2225
- if (missing.length > 0) throw new Error(fill(messages.missingRequiredArgs, {
2226
- name: spec.name,
2227
- fields: missing.join(", ")
2228
- }));
2229
- return await spec.run(rawArgs, exec, messages);
2230
- }
2231
- });
2232
2080
  }
2233
- /** 隐式命名空间与 loader 行 config 共用同一 schema(单源,防漂移)。
2234
- * 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
2235
- * 外部仍以 `Config` 名导入(export as),公开 API 不变。
2236
- *
2237
- * 0.1.7 迁移要点(两处都是静默失效,写错不报错):
2238
- * - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
2239
- * (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
2240
- * (settings/src/index.ts 里 `volatileForm(schema)` 空判即 `return []` 的那一处)、写入抛
2241
- * `has no volatile fields`(同文件的那句 throw)。
2242
- * - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
2243
- * 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
2244
- * 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
2245
- * 六个 volatile 字段全是本卡的可编辑项,一个都不该漏;四个非 volatile 部署值
2246
- * (超时三项 + stdout 上限)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
2247
- const configSchema = Schema.object({
2248
- defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
2249
- defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
2250
- hfEndpoint: Schema.string().default("https://modelscope.cn/models").volatile(),
2251
- enforceSearchFirst: Schema.boolean().default(true).volatile(),
2252
- grepBudgetPerSearch: Schema.natural().min(1).max(20).default(3).volatile(),
2253
- unlockWindowMin: Schema.natural().min(1).max(240).default(10).volatile(),
2254
- searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
2255
- statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
2256
- indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
2257
- stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES),
2258
- clientMode: Schema.union([
2259
- "auto",
2260
- "direct",
2261
- "server"
2262
- ]).default(DEFAULT_CLIENT_MODE),
2263
- rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
2264
- allowRemoteEmbedding: Schema.boolean().default(false),
2265
- remoteEmbeddingEndpoint: Schema.string().default(""),
2266
- remoteEmbeddingApiKeyFrom: Schema.string().default(""),
2267
- requireApprovalForExplicitRoot: Schema.boolean().default(false)
2268
- });
2269
- /** 官方注册表里本包作业的 kind;宿主据此发出的 id 形如 `zvec-grep-rebuild-N`。 */
2270
- const REBUILD_JOB_KIND = "zvec-grep-rebuild";
2271
2081
  /**
2272
- * 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
2273
- * 正好 `MAX` 条在册(文案与卡片 404 提示都按这个数说)。同时能跑几个不在这里——那是
2274
- * 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
2275
- * 自行回收落定记录("A settled record stays listed until its owner's disposal, service
2276
- * disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
2277
- * 裁剪是本包的责任。注意它只管历史窗口:**同时能跑几个**由注册表的容量说了算
2278
- * (实测默认 10,且超限是**拒绝**,不是替我们杀在跑的任务)。
2082
+ * 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
2083
+ * 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
2084
+ * @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
2085
+ * @param proc 已经起来的 zg 进程
2086
+ * @param state 这条重建的状态盒(与侧表记录共用)
2087
+ * @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
2088
+ * @returns 官方 JobSpec:kind / label / output / run
2279
2089
  */
2280
- const REBUILD_HISTORY_MAX = 10;
2281
- /** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
2282
- const JOB_OUT_VIEW_CHARS = 4e3;
2283
- /** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
2284
- function identityOf(view) {
2090
+ function rebuildJobSpec(routes, proc, state, command, root) {
2091
+ const { config, host, jobsOf, messages } = routes;
2285
2092
  return {
2286
- kind: view.kind,
2287
- label: view.label,
2288
- startedAt: view.startedAt
2093
+ kind: REBUILD_JOB_KIND,
2094
+ label: command,
2095
+ output: rebuildSources(proc, state),
2096
+ run: (handle) => {
2097
+ const liveJob = () => {
2098
+ const live = jobsOf();
2099
+ if (live === void 0) return null;
2100
+ const view = jobView(live, handle.id);
2101
+ if (view === null || !sameJob(state, view)) return null;
2102
+ return {
2103
+ jobs: live,
2104
+ status: view.status
2105
+ };
2106
+ };
2107
+ const cancelKillTimer = host.timer.timeout(() => {
2108
+ if (proc.status !== "running") return;
2109
+ const live = liveJob();
2110
+ if (live !== null && live.status !== "running") return;
2111
+ const minutes = Math.round(config.indexTimeoutMs / 6e4);
2112
+ state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
2113
+ if (live === null) {
2114
+ killProc(proc);
2115
+ return;
2116
+ }
2117
+ live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2118
+ }, config.indexTimeoutMs);
2119
+ return {
2120
+ cancel: () => {
2121
+ killProc(proc);
2122
+ },
2123
+ done: (async () => {
2124
+ await proc.done;
2125
+ cancelKillTimer();
2126
+ try {
2127
+ return jobOutcomeOf(proc);
2128
+ } finally {
2129
+ routes.rebuilds.release(root);
2130
+ }
2131
+ })()
2132
+ };
2133
+ }
2289
2134
  };
2290
2135
  }
2291
- /** 两段身份证是否同一回事(三段全同才算)。 */
2292
- function sameIdentity(left, right) {
2293
- return left.kind === right.kind && left.label === right.label && left.startedAt === right.startedAt;
2294
- }
2295
2136
  /**
2296
- * 身份证尚未盖章时的占位出生时刻。
2137
+ * 起一条 `zg index`:命令构造 + resolve + execute 三步。
2297
2138
  *
2298
- * `startedAt` 由官方签发(`Date.now()`,永不为 0),而 kind/label 在 `start` 之前就已
2299
- * 已知——那正是本包递给官方的那份规格。于是"start 的同步块里就跑到了 `run()`"那一档读取
2300
- * (官方 `start` 会同步跑第一拍)比对时必然落到"对不上":那一刻还没有可比的出生时刻,
2301
- * 不该把同 id 的另一条作业当成自己的收走。
2302
- */
2303
- const UNSIGNED_STARTED_AT = 0;
2304
- /**
2305
- * 名册里那条 id 是不是**我们**的那条作业。
2139
+ * 远程重建与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
2140
+ * 在名册、状态投影、轮询读面上完全同形。命令形态由 `indexArgs` 决定,故它也服务普通建索引。
2141
+ *
2142
+ * 版本门槛排在命令构造**之前**:确知装的是太老的 zg 时,在这一行就给出可照做的指引,
2143
+ * 而不是起一条命令形态对不上的 zg 再让人对着结果猜。注意这个顺序也保证了「门槛失败」
2144
+ * 发生在任何进程存在之前,调用方那条 `release` 出口足以收干净。
2306
2145
  *
2307
- * 只比 id 不够:计数器是注册表的实例字段(实测两枚实例对同一 kind 都从 1 开始),换一枚
2308
- * 实例就重名;那时同 id 指向的是另一条作业(另一棵树/另一条命令),旧卡片跟上去就是串台。
2309
- * @param state 这条记录的状态盒
2310
- * @param view 名册里同 id 的那条投影
2311
- * @returns 同一条作业
2146
+ * 任一步抛错即就地翻成 `{ error, status }`;**本函数不释放占位**,那由调用方做(它才持有 root)。
2147
+ * @param routes 本次注册的共享依赖(现读 config / host / jobsOf)
2148
+ * @param started 本次请求语言的文案表
2149
+ * @param indexArgs 已归一 root 的索引入参
2150
+ * @param embedding 设置里的默认 embedding(`indexArgs.embedding` 为空时用它)
2151
+ * @returns 起来的进程与它跑的命令;失败为 `{ error, status }`
2312
2152
  */
2313
- function sameJob(state, view) {
2314
- return sameIdentity(state.identity, identityOf(view));
2315
- }
2316
- /** 终止重建进程:kill 异常忽略(进程可能已自然退出/已被回收)。 */
2317
- function killProc(proc) {
2153
+ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
2154
+ const { config, host } = routes;
2155
+ let spawned;
2318
2156
  try {
2319
- proc.kill();
2320
- } catch {}
2157
+ await routes.versionGate.ensure(started);
2158
+ assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started), started);
2159
+ const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
2160
+ const env = zgEnv(config);
2161
+ const spec = host.shell.resolve({
2162
+ command: built.command,
2163
+ workdir: built.workdir,
2164
+ onExpiry: "none",
2165
+ stdoutMaxBytes: config.stdoutMaxBytes,
2166
+ ...env ? { env } : {}
2167
+ });
2168
+ spawned = {
2169
+ proc: await host.shell.execute(spec),
2170
+ command: built.command
2171
+ };
2172
+ } catch (error) {
2173
+ return {
2174
+ error: fill(started.endpointStartFailed, { reason: errorText(error) }),
2175
+ status: 500
2176
+ };
2177
+ }
2178
+ return spawned;
2321
2179
  }
2322
2180
  /**
2323
- * 本包作业的输出面:官方 pull source,stdout/stderr 各一只游标,外加一层"读失败不许
2324
- * 拖垮泵"的兜。选 pull 而不是生产者 push(`JobHandle.append`)是复核
2325
- * 后按实测定下的:
2326
- * - `proc.observed[*].readFrom` 是**非消费**的独立观察者面(installed dsh-shell
2327
- * types.d.ts:"without stealing bytes from `readOutput`"),与本包前台用的
2328
- * 消费式游标互不干扰——此前本仓写的"官方泵会与 readOutput 争同一份游标"是错的;
2329
- * - 泵按注册表自己的节拍跑(实测默认 150ms,落定前再排最后一次)⇒ **卡片关着环也前进**,
2330
- * 模型侧 job_output 随时看得见进度;push 形态把可见性绑在了轮询上。
2331
- * @param proc 后台进程句柄
2332
- * @param state 这条重建的状态盒(见 {@link RebuildState})
2333
- * @returns 交给 JobSpec.output 的两条源
2181
+ * 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
2182
+ *
2183
+ * 三种失败(注册表换人 / 同名不同命 / start 抛错)都**先把那条进程杀掉**再交回错误:
2184
+ * 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
2185
+ * 同样地,本函数不释放占位——那件事由调用方做。
2186
+ * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
2187
+ * @param root 已过前置校验的工作区(写进侧表供卡片回显)
2188
+ * @param started 本次请求语言的文案表
2189
+ * @param spawned spawnIndexWrite 交回的进程与命令
2190
+ * @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
2334
2191
  */
2335
- function rebuildSources(proc, state) {
2336
- return ["stdout", "stderr"].map((channel) => {
2337
- let failed = false;
2192
+ function attachIndexWrite(routes, root, started, spawned) {
2193
+ const { jobsOf, records } = routes;
2194
+ const { proc, command } = spawned;
2195
+ const starting = jobsOf();
2196
+ if (starting === void 0) {
2197
+ killProc(proc);
2338
2198
  return {
2339
- channel,
2340
- read: (fromByte) => {
2341
- if (failed) return {
2342
- text: "",
2343
- nextOffset: fromByte,
2344
- lossy: true
2345
- };
2346
- try {
2347
- const read = proc.observed[channel].readFrom(fromByte);
2348
- if (read.lossy) state.lost = true;
2349
- return read;
2350
- } catch {
2351
- state.lost = true;
2352
- failed = true;
2353
- return {
2354
- text: "",
2355
- nextOffset: fromByte,
2356
- lossy: true
2357
- };
2358
- }
2359
- }
2199
+ error: started.endpointJobsUnavailable,
2200
+ status: 503
2360
2201
  };
2361
- });
2362
- }
2363
- /** 官方件对未知/已淘汰 id 抛错;本包的判据要的是"有没有",不是异常(无 ⇒ null)。 */
2364
- function jobView(jobs, id) {
2365
- try {
2366
- return jobs.get(id);
2367
- } catch {
2368
- return null;
2369
2202
  }
2370
- }
2371
- /** 轮询端点的一次成对读数:状态投影 + 留存窗内容;注册表已无此 id ⇒ undefined。 */
2372
- function readRebuildOutput(jobs, id) {
2203
+ pruneRebuildHistory(starting, records);
2204
+ const state = {
2205
+ identity: {
2206
+ kind: REBUILD_JOB_KIND,
2207
+ label: command,
2208
+ startedAt: UNSIGNED_STARTED_AT
2209
+ },
2210
+ lost: false,
2211
+ timeoutNote: null
2212
+ };
2213
+ let jobId;
2373
2214
  try {
2215
+ jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
2216
+ state.identity = identityOf(starting.get(jobId));
2217
+ records.set(jobId, {
2218
+ proc,
2219
+ root,
2220
+ id: jobId,
2221
+ state
2222
+ });
2223
+ } catch (error) {
2224
+ killProc(proc);
2374
2225
  return {
2375
- view: jobs.get(id),
2376
- retained: jobs.readAt(id, 0)
2226
+ error: startupFailureText(error, started),
2227
+ status: 500
2377
2228
  };
2378
- } catch {
2379
- return null;
2380
2229
  }
2381
- }
2382
- /** 官方 JobStatus 里"仍在跑"的两枚:`stopping` 是取消已发出、进程还没收完。 */
2383
- function isLiveStatus(status) {
2384
- return status === "running" || status === "stopping";
2230
+ return { jobId };
2385
2231
  }
2386
2232
  /**
2387
- * 历史窗口有界:按注册表的**可见集合**淘汰本 kind 最老的已落定记录。
2388
- *
2389
- * 剪到**只剩 `MAX-1` 条**才是对的:这一剪发生在 start 之前,紧接着就有一条新作业进来,
2390
- * 它落定之后名册里正好是最近 `MAX` 条已落定记录 ⇒ 与卡片文案「只保留最近 10 条已结束的重建」
2391
- * 同一口径。剪到 `MAX` 条会让册子在任何时刻都有 `MAX+1` 条已结束记录(实测 11 条),
2392
- * 最初把这条判反了(只看剪完那一刻的 9 条),后来回退。
2393
- * 在跑的一条不动——官方件对超额的答法是拒绝 start(实测),不是替我们杀任务,
2394
- * 这里跟着杀等于把"用户的重建被静默终止"重新发明一遍。
2395
- * 侧表里没有的 id(上一次 apply 卸载后残留的记录)同样要能清掉,所以遍历的是
2396
- * `list()` 而不是 `records`。
2397
- * @param jobs 官方注册表
2398
- * @param records 本包侧表(被淘汰记录同步删掉)
2233
+ * 卸载效应的收口:把侧表里的进程与在册作业收干净。
2234
+ * @param deps 本次注册的共享依赖(jobsOf 现读、侧表引用、文案现取)
2399
2235
  * @returns {void}
2400
2236
  */
2401
- function pruneRebuildHistory(jobs, records) {
2402
- const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
2403
- for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
2404
- jobs.remove(job.id);
2405
- records.delete(job.id);
2237
+ function releaseRebuildRecords(deps) {
2238
+ const { jobsOf, messages, records } = deps;
2239
+ const unloadReason = messages().jobReasonUnload;
2240
+ const jobs = jobsOf();
2241
+ if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
2242
+ else for (const record of records.values()) {
2243
+ const view = jobView(jobs, record.id);
2244
+ if (view === null || !sameJob(record.state, view)) killProc(record.proc);
2245
+ else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
2246
+ else jobs.remove(record.id);
2406
2247
  }
2248
+ records.clear();
2407
2249
  }
2408
2250
  /**
2409
- * 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
2410
- * owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
2411
- * 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
2412
- * 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
2413
- */
2414
- function capacityLimitOf(error) {
2415
- return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
2416
- }
2417
- /**
2418
- * 「工作区重建」动作端点的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
2419
- * 目录此刻仍存在。不过就把错误就地答完并返回 undefined(错误文本全走双语字典)。
2251
+ * 设置卡片「工作区重建」的读面(引导 / 启动 / 轮询三个方法)。
2420
2252
  *
2421
- * 这四道是**动作**端点的闸门:webServer 可被绑到本机网卡的具体地址,没有白名单的话任何能连上
2422
- * 服务面的一方都能拿任意绝对路径去 `zg index --rebuild`——读遍那棵树、写 `.zvec-grep/`,
2423
- * 还可能把其中的非隐藏敏感文件灌进向量库并回显到上下文。
2424
- * @param req 请求对象
2425
- * @param res 响应对象(不过时由本函数就地应答)
2426
- * @param ledger 观测到的工作区白名单
2427
- * @param started 本次请求语言的文案表
2428
- * @returns 归一化后可用的绝对路径;不合格时 null(那时本函数已经答过)
2253
+ * ⚠ 服务在**构造时**注册(cordis `Service` 的契约:`ctx.reflect.provide`,随所属 fiber
2254
+ * 卸载自动撤),所以调用方拿实例没有任何用处——装入口 `installRebuildRemote` 说明了这一点。
2255
+ *
2256
+ * ⚠ `jobsOf` 必须每次用时现读,不在闭包里钉住一枚实例。`ctx.get` 是无 inject 语义的存储
2257
+ * 读(官方 reflect.d.ts:"or `undefined` when not (yet) provided",实测读一次就只那一次)——
2258
+ * 在 apply 里读会把两种正常事件变成永久故障:服务比本插件晚到位 ⇒ 启动从此一直回答不可用
2259
+ * (还指着用户去装一个其实装好了的包);服务被重载 ⇒ 从此往一枚已销毁的实例里起作业。
2260
+ * 本包也不把 `jobs` 列进 `inject` 名单:那会让缺席的整条 client 入口都不激活,而缺席只该让
2261
+ * 「启动/轮询」这一档不可用。
2429
2262
  */
2430
- function acceptableRebuildRoot(req, res, ledger, started) {
2431
- let root;
2432
- try {
2433
- root = assertAbsoluteRoot(queryParam(req, "root"), started);
2434
- } catch (error) {
2435
- sendJson(res, 400, {
2436
- ok: false,
2437
- error: fill(started.endpointRootInvalid, { reason: errorText(error) })
2438
- });
2439
- return null;
2263
+ var ZvecRebuildService = class extends TypertRemoteService {
2264
+ deps;
2265
+ constructor(ctx, deps) {
2266
+ super(ctx, REBUILD_REMOTE_NAMESPACE);
2267
+ this.deps = deps;
2268
+ }
2269
+ /** 引导读面:白名单里的工作区 + 守护进程就绪态(都是本插件自己的数据)。 */
2270
+ async roots() {
2271
+ const serverReady = await this.deps.serverGate.ready();
2272
+ return {
2273
+ roots: this.deps.ledger.list(),
2274
+ serverReady
2275
+ };
2440
2276
  }
2441
- if (!ledger.has(root)) {
2442
- sendJson(res, 403, {
2277
+ /**
2278
+ * 起一条重建(或跟随同根已在跑的那条)。
2279
+ *
2280
+ * 占位是**互斥的唯一依据**,必须落在第一个 await 之前。先「查在不在跑」再占位,
2281
+ * 两次并发点击会同时通过那次查询、各自 spawn——两个进程在同一份索引上互相啃,
2282
+ * 后一条被 zg 的写锁直接顶掉并报成「启动失败」。改成「先占位、抢不到就跟随」,
2283
+ * 这条竞态就没有窗口了。
2284
+ */
2285
+ async rebuild(request) {
2286
+ const started = this.deps.messages();
2287
+ const accepted = acceptableRoot(isRecord(request) ? request.root : void 0, this.deps.ledger, started);
2288
+ if ("error" in accepted) return {
2443
2289
  ok: false,
2444
- error: fill(started.endpointRootUntracked, { root })
2445
- });
2446
- return null;
2290
+ error: accepted.error.value,
2291
+ status: accepted.error.status
2292
+ };
2293
+ const { root } = accepted;
2294
+ const jobs = this.deps.jobsOf();
2295
+ if (jobs === void 0) return {
2296
+ ok: false,
2297
+ error: started.endpointJobsUnavailable,
2298
+ status: 503
2299
+ };
2300
+ if (this.deps.rebuilds.claim(root, "card") === null) {
2301
+ const following = followRunningRebuild(jobs, this.deps.records, root);
2302
+ return following === void 0 ? {
2303
+ ok: false,
2304
+ error: started.endpointRebuildInFlight,
2305
+ status: 409
2306
+ } : {
2307
+ ok: true,
2308
+ jobId: following,
2309
+ reused: true
2310
+ };
2311
+ }
2312
+ const embedding = readDefaultEmbedding(this.deps.config);
2313
+ const spawned = await spawnIndexWrite(this.deps, started, {
2314
+ root,
2315
+ embedding,
2316
+ rebuild: true
2317
+ }, embedding);
2318
+ if ("error" in spawned) {
2319
+ this.deps.rebuilds.release(root);
2320
+ return {
2321
+ ok: false,
2322
+ error: spawned.error,
2323
+ status: spawned.status
2324
+ };
2325
+ }
2326
+ const attached = attachIndexWrite(this.deps, root, started, spawned);
2327
+ if ("error" in attached) {
2328
+ this.deps.rebuilds.release(root);
2329
+ return {
2330
+ ok: false,
2331
+ error: attached.error,
2332
+ status: attached.status
2333
+ };
2334
+ }
2335
+ this.deps.rebuilds.attach(root, attached.jobId);
2336
+ return {
2337
+ ok: true,
2338
+ jobId: attached.jobId
2339
+ };
2447
2340
  }
2448
- if (!existsSync(root)) {
2449
- sendJson(res, 400, {
2341
+ /**
2342
+ * 轮询读面:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。
2343
+ *
2344
+ * 侧表就是这条投影的授权边界:官方 id 是可预测的 `<kind>-<hex>`(宿主 bash 工具的
2345
+ * `bash-1` 同样猜得到),而它不在本包表里 ⇒ 一律拒绝,绝不代读别人的作业。
2346
+ */
2347
+ status(request) {
2348
+ const marks = this.deps.messages();
2349
+ const raw = isRecord(request) ? request.jobId : void 0;
2350
+ const record = typeof raw === "string" && raw.length > 0 ? this.deps.records.get(raw) : void 0;
2351
+ if (record === void 0) return {
2450
2352
  ok: false,
2451
- error: fill(started.endpointRootGone, { root })
2452
- });
2453
- return null;
2353
+ error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2354
+ status: 404
2355
+ };
2356
+ const jobs = this.deps.jobsOf();
2357
+ if (jobs === void 0) return {
2358
+ ok: false,
2359
+ error: marks.endpointJobsUnavailable,
2360
+ status: 503
2361
+ };
2362
+ const output = readRebuildOutput(jobs, record.id);
2363
+ if (output === null) return {
2364
+ ok: false,
2365
+ error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2366
+ status: 404
2367
+ };
2368
+ if (!sameJob(record.state, output.view)) return {
2369
+ ok: false,
2370
+ error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2371
+ status: 404
2372
+ };
2373
+ const { view, retained } = output;
2374
+ const text = retained.chunks.map((chunk) => chunk.text).join("");
2375
+ const shown = truncateStart(text, JOB_OUT_VIEW_CHARS);
2376
+ const viewMark = text.length > JOB_OUT_VIEW_CHARS ? fill(marks.jobOutputView, {
2377
+ shown: JOB_OUT_VIEW_CHARS,
2378
+ total: text.length
2379
+ }) : "";
2380
+ return {
2381
+ ok: true,
2382
+ status: view.status,
2383
+ exitCode: record.proc.exitCode,
2384
+ root: record.root,
2385
+ ...record.proc.sandbox === void 0 ? {} : { sandbox: record.proc.sandbox },
2386
+ output: (view.output.earliest > 0 ? marks.jobOutputTruncated : "") + (record.state.lost ? marks.jobOutputLost : "") + (record.state.timeoutNote ?? "") + (procSandboxNote(record.proc, marks) ?? "") + viewMark + shown
2387
+ };
2454
2388
  }
2455
- return root;
2389
+ };
2390
+ /**
2391
+ * 标准装饰器的**程序化调用**:`@Remote` 的全部作用就是往类原型写一枚描述符,而标准装饰器
2392
+ * 语法需要一条 tsc 降级管线(本仓的测试/构建解析器都不降级它)。这里直接按 TC39 的
2393
+ * `ClassMethodDecoratorContext` 形状调同一个 decorator 函数,把标记落到真正的原型上,
2394
+ * 于是源码里不再需要装饰器语法,构建与测试都不必再挂那枚预转换插件。
2395
+ */
2396
+ function markRemote(prototype, methodName) {
2397
+ const context = {
2398
+ kind: "method",
2399
+ name: methodName,
2400
+ static: false,
2401
+ private: false,
2402
+ addInitializer: (initializer) => {
2403
+ Reflect.apply(initializer, Object.create(prototype), []);
2404
+ }
2405
+ };
2406
+ const decorate = Remote(methodName);
2407
+ Reflect.apply(decorate, void 0, [Reflect.get(prototype, methodName), context]);
2456
2408
  }
2409
+ markRemote(ZvecRebuildService.prototype, "roots");
2410
+ markRemote(ZvecRebuildService.prototype, "rebuild");
2411
+ markRemote(ZvecRebuildService.prototype, "status");
2457
2412
  /**
2458
- * 这个 root 上有没有**仍在跑**的本包重建?有 ⇒ 返回那枚作业 id 让新面板跟随。
2459
2413
  *
2460
- * 判据是三条一起:"侧表里有这条" + "名册里同 id 的那条确实是我们那条(比出生时刻)" +
2461
- * "状态还在跑/正在收"。第二条不能省:jobs 被重载之后 id 会重名,只查侧表就把一张新面板
2462
- * 领到别人的作业上。
2463
- * 就地答完(200 + 复用旗标)并返回 true ⇒ 调用方直接 return;否则返回 false 继续起进程。
2464
- * @param jobs 调用方已确认在场的注册表(缺席那一支在启动端点更早就答过 503)
2465
- * @param records 本包侧表
2466
- * @param res 响应对象
2467
- * @param root 已归一化的工作区
2468
- * @returns 是否已把这张面板领到在跑的那条上(领到了就地答完 200)
2414
+ * 为什么是一枚函数而不是让调用方直接 `new`:这枚 `new` 的**全部意义在构造期的注册副作用**
2415
+ * 上——实例由 cordis 的 fiber 持有(`Service` 基类把 `reflect.provide` 的 disposer 挂给
2416
+ * fiber),调用方拿到它没有任何用处。卸载效应也在这里登记:侧表里的进程与在册作业必须
2417
+ * 随本插件一起收干净。
2418
+ *
2419
+ * @param ctx - 宿主上下文
2420
+ * @param deps - 重建读面的全部依赖(见 ZvecRebuildDeps)
2469
2421
  */
2470
- function followRunningRebuild(jobs, records, res, root) {
2471
- const following = [...records.values()].find((record) => {
2472
- if (record.root !== root) return false;
2473
- const view = jobView(jobs, record.id);
2474
- return view !== null && sameJob(record.state, view) && isLiveStatus(view.status);
2475
- });
2476
- if (following === void 0) return false;
2477
- sendJson(res, 200, {
2478
- ok: true,
2479
- jobId: following.id,
2480
- reused: true
2481
- });
2422
+ function installRebuildRemote(ctx, deps) {
2423
+ if (!isRecord(ctx) || !isRecord(ctx.reflect) || typeof ctx.reflect.provide !== "function") return false;
2424
+ new ZvecRebuildService(ctx, deps);
2425
+ ctx.effect(() => () => {
2426
+ releaseRebuildRecords(deps);
2427
+ }, "zvec-grep: rebuild records");
2482
2428
  return true;
2483
2429
  }
2430
+ //#endregion
2431
+ //#region host.ts
2432
+ const SEARCH_TIMEOUT_MS = 3e5;
2433
+ const STATUS_TIMEOUT_MS = 6e4;
2434
+ const INDEX_TIMEOUT_MS = 6e5;
2435
+ const STDOUT_MAX_BYTES = 4e5;
2436
+ /** 检索等待同根重建落定的上限(ms)。部署值:大型工作区的重建可能跑很久,
2437
+ * 但也不该让一次检索无限期挂着。 */
2438
+ const REBUILD_WAIT_MS = 12e4;
2439
+ /** 工作区白名单容量:超过按最近使用淘汰最冷的一条(常驻进程内存有界)。 */
2440
+ const MAX_LEDGER_ROOTS = 64;
2484
2441
  /**
2485
- * 把「起一条 zg 失败」的原因翻成卡片文案。
2486
- *
2487
- * **本函数不再杀进程**:杀现在由 `attachIndexWrite` 负责——它才是真正握着那条进程句柄、
2488
- * 且知道作业有没有登记成功的地方(preflight 在 controller/容量/入参上拒掉作业时,spawn
2489
- * 已经发生,不杀就会留下一条没登记、谁也停不掉的 zg)。这里只管文案。
2490
- *
2491
- * 满员那一档单独翻文案:它是本包唯一会把宿主英文原话插进卡片的错误,又最该翻成人话
2492
- * (用户要做的是去 job_list 收作业,不是读一句英文)。
2493
- * @param error 官方件(或本包 starter)抛出的原因
2494
- * @param started 本次请求语言的文案表
2495
- * @returns 可直接进响应体的错误文案
2442
+ * 白名单条目的有效期:多久没被提到就当它不再活跃。一天足够覆盖「今天开过的会话」,
2443
+ * 又不会让一个月前随手开过的一个目录一直占着名额。
2496
2444
  */
2497
- function startupFailureText(error, started) {
2498
- const capacity = capacityLimitOf(error);
2499
- return capacity === void 0 ? fill(started.endpointStartFailed, { reason: errorText(error) }) : fill(started.endpointJobsAtCapacity, { limit: capacity });
2445
+ const LEDGER_TTL_MS = 864e5;
2446
+ /** 成功执行里回显 stderr 的尾部长度(降级提示常就在这一行)。 */
2447
+ const STDERR_NOTE_CHARS = 400;
2448
+ /** 具名方法在位(typeof 函数)——只看 `typeof x === "object"` 会放过 null、
2449
+ * 也会放过「是个对象但没注册方法」的错注入。 */
2450
+ function hasMethod(value, name, keys) {
2451
+ const member = value[name];
2452
+ return isRecord(member) && keys.every((key) => typeof member[key] === "function");
2500
2453
  }
2501
2454
  /**
2502
- * 在 controller 闸门下起一条未拥有作业。
2455
+ * host 是否为本插件所需服务面:五个注入面都必须是**带相应方法的对象**,
2456
+ * 且 `get` 可调用。守卫失败即 apply 抛错(fail-fast),比运行到某次工具调用
2457
+ * 才 `undefined is not a function` 更早、更可诊断。
2503
2458
  *
2504
- * 官方件在"没有 controller 服务这个 owner"时直接拒绝 `start`(实测台架第 1 条),而未拥有
2505
- * 作业只被 global 层服务;web 面上宿主自己的 `tool-jobs` 被移进了各 preset realm
2506
- * (packages/bundle/web-app/cordis.patch.yml 把 tool-jobs 在宿主平面 disabled),
2507
- * 所以本包必须自带一枚从无作用域上下文 attach 的 controller。但**只在 start 这一瞬挂**:
2508
- * 实测挂上即放行、摘掉即恢复拒绝、可反复,而 global 层的 controller 只被 `servesOwner`
2509
- * 读(installed dsh-jobs-local 全文只有那一处消费),作业的后续(read/kill/落定)都不
2510
- * 依赖它。留一枚常驻 token 等于在"宿主故意没装 job 工具"的组成里替全宿主开着那道闸门——
2511
- * 官方契约写的是"生产者不能起一台 owner 收不掉、停不掉的作业",常驻就是把它反过来做。
2459
+ * settings 只探 `describe`:0.1.7 起那是本包唯一**直接调**的 settings 方法
2460
+ * (跨命名空间读 locale)。`configure` 经 `ctx.inject` 的子上下文才拿到,
2461
+ * `mutate` 本包 host 侧根本不用(写是卡片经 settingsScope 走 client 面)——
2462
+ * 探它们等于断言一条没有测试撑着的能力。
2512
2463
  */
2513
- function startUnderController(jobs, spec) {
2514
- const detach = jobs.attachController("zvec-grep: rebuild");
2515
- try {
2516
- return jobs.start(spec);
2517
- } finally {
2518
- detach();
2519
- }
2464
+ function isZvecGrepHost(value) {
2465
+ if (!isRecord(value)) return false;
2466
+ return hasMethod(value, "settings", ["describe"]) && hasMethod(value, "shell", ["resolve", "execute"]) && hasMethod(value, "tools", ["register", "guard"]) && hasMethod(value, "systemPrompt", ["section"]) && hasMethod(value, "timer", ["timeout"]) && typeof value["get"] === "function";
2467
+ }
2468
+ /** 当前会话工作区(root 缺省回退源);非字符串视为缺(读取面见 lib/routing.ts 的 SessionFace)。 */
2469
+ function sessionHeaderCwd(exec) {
2470
+ const raw = exec.agent?.session?.header?.cwd;
2471
+ return typeof raw === "string" && raw.length > 0 ? raw : void 0;
2520
2472
  }
2521
2473
  /**
2522
- * 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
2523
- * dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
2524
- * 与「zg 根本没跑起来」分开。
2474
+ * JSON.stringify 在本包**拥有的声明**上把返回宽成 `string | undefined`:lib 的签名恒为
2475
+ * `string`,但 ECMA-262 规定入参是 undefined / 函数 / 符号时它返回 undefined(下面
2476
+ * textBlock 的用例就直喂 undefined)。宽化只能落在这里——调用点里 `JSON.stringify(...) ?? x`
2477
+ * 会被 TS 的收窄按声明面判成冗余守卫,而删掉那道具象兜底会把 `{ text: undefined }` 交给官方。
2525
2478
  */
2526
- function procSandboxNote(proc, messages) {
2527
- const info = proc.sandbox;
2528
- if (info === void 0) return null;
2529
- if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
2530
- if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
2531
- return null;
2479
+ function stringifyJson(value) {
2480
+ return JSON.stringify(value, null, 2);
2532
2481
  }
2533
- /** 白名单键:归一化后的绝对路径;非法 root(相对/越界/NUL)归 undefined。 */
2534
- function ledgerKey(root, messages) {
2535
- let key;
2482
+ function textBlock(value) {
2483
+ const { text: textValue } = isRecord(value) ? value : {};
2484
+ if (typeof textValue === "string") return [{
2485
+ type: "text",
2486
+ text: textValue
2487
+ }];
2488
+ let text;
2536
2489
  try {
2537
- key = assertAbsoluteRoot(root, messages);
2490
+ text = stringifyJson(value) ?? String(value);
2538
2491
  } catch {
2539
- key = void 0;
2492
+ try {
2493
+ text = String(value);
2494
+ } catch {
2495
+ text = "[unrenderable value]";
2496
+ }
2540
2497
  }
2541
- return key;
2498
+ return [{
2499
+ type: "text",
2500
+ text
2501
+ }];
2542
2502
  }
2503
+ const TEXT_OUTPUT_SCHEMA = {
2504
+ type: "object",
2505
+ additionalProperties: false,
2506
+ properties: { text: { type: "string" } }
2507
+ };
2543
2508
  /**
2544
- * 淘汰一张常驻表:先按**有效期**丢过期项,再按**最近使用**丢最老项到不超过上限。
2545
- *
2546
- * 为什么不是纯插入序(原 `trimMapTo`):`Map` 的插入序在 `delete` 后重排,故「插入序淘汰」
2547
- * 实际是「最早插入且此后没被重新插入的先走」——一张每轮都被 `set` 命中的表(解锁额度就是,
2548
- * 每次成功检索都重置同一批键)永远淘汰不掉真正冷掉的项,而一条很久没被碰过的键会一直占位。
2549
- * 改成:命中即触摸(`delete` + `set` 把键挪到队尾),淘汰从队首取。这样「最久没用过」
2550
- * 才有确定含义。
2551
- *
2552
- * 有效期同样必要:一个只在半小时前出现过一次的工作区,到明天早就不该还占着白名单名额。
2553
- * 两者都保留,故上界(内存有界)与语义(冷掉的先走)同时成立。
2554
- *
2555
- * @param map 目标表(就地改)
2556
- * @param max 条数上限
2557
- * @param expiresAt 取某条目的过期时刻;无则视为永不过期
2558
- * @param now 当前时刻(epoch ms)
2509
+ * 沙箱侧的**硬**失败:命令根本没跑起来。
2510
+ * runnerFailed 与 exitCode 无关——runner 在命令执行前就挂了,exit 码是 runner 的,
2511
+ * 拿来判「zg 未安装」是把沙箱故障误报成用户缺二进制。
2559
2512
  */
2560
- function evictAged(map, max, expiresAt, now) {
2561
- for (const [key, value] of map) {
2562
- const expiry = expiresAt(value);
2563
- if (expiry !== void 0 && expiry <= now) map.delete(key);
2564
- }
2565
- for (const key of map.keys()) {
2566
- if (map.size <= max) break;
2567
- map.delete(key);
2568
- }
2513
+ function sandboxFailure(result, messages) {
2514
+ const info = result.sandbox;
2515
+ if (info?.runnerFailed !== true) return null;
2516
+ return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
2569
2517
  }
2570
- /** 命中即触摸:把键挪到队尾,使「最近使用」在插入序上成立。 */
2571
- function touch(map, key, value) {
2572
- map.delete(key);
2573
- map.set(key, value);
2518
+ /** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
2519
+ * 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
2520
+ * 尾切点会留下孤立**低**代理(`truncateStart` 丢掉它);对调两个函数同样不留孤立代理,
2521
+ * 只是头尾内容掉头 ⇒ 测试里另有一组哨兵断言钉住归属。 */
2522
+ function failureDetail(result, messages) {
2523
+ const raw = result.stderr.text.length > 0 ? result.stderr.text : result.stdout.text;
2524
+ if (raw.length <= 800) return raw;
2525
+ const half = 400;
2526
+ return fill(messages.detailMiddle, {
2527
+ head: truncateEnd(raw, half),
2528
+ tail: truncateStart(raw, half)
2529
+ });
2530
+ }
2531
+ /** 有详情才带前缀拼接(不同句式各有前缀),空详情绝不留孤儿标点。 */
2532
+ function withDetail(detail, prefix) {
2533
+ return detail.length > 0 ? fill(prefix, { detail }) : "";
2574
2534
  }
2575
- /** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
2576
- const INDEX_PROBE_TTL_MS = 6e4;
2577
- /** 探测缓存容量(条):guard 一次调用至多探 9 层祖先,32 条覆盖多工作区来回切换。 */
2578
- const INDEX_PROBE_CACHE_MAX = 32;
2579
2535
  /**
2580
- * zg 索引库存在性探测的**按目录缓存**(P2:guard 每次工具调用里 findIndexRoot 最多
2581
- * 向上探 9 层 existsSync,同一工作区的连续调用命中的是同一串祖先目录;zg_search 的
2582
- * 解锁路径也要再走一遍同样的上溯)。
2583
- *
2584
- * 失效策略选**进程内 TTL(60s)**而不是会话内不过期:正向条目(有索引)在「索引目录
2585
- * 运行期不会消失」的假设下永不陈旧,TTL 对它只是内存有界的双保险;真正需要 TTL 的是
2586
- * **负向**条目——zg_index 是运行期动作,新索引落地后若永不过期,门禁要到进程重启才
2587
- * 看得见它。60s 的负向陈旧只是「索引出现前的既有行为」(grep 不被拦)的短暂延续,
2588
- * 方向安全,且与「建索引后立刻去搜」的真实节奏相比可忽略。
2589
- *
2590
- * 缓存是**纯性能优化**:只替 existsSync 的答案,不改 findIndexRoot 的走法——root 不
2591
- * 存在(probe 恒 false)、走满 maxDepth、上溯到 / 等失败路径在相同探测结果下与原实现
2592
- * 逐分支一致。命中即触摸(delete+set 挪到队尾),配合 trimMapTo 的插入序淘汰 ⇒ LRU。
2536
+ * zg 的结构化失败在 stderr 上以一行 `Code: <CODE>` 交出错误码(上游 `src/cli/errors.ts`),
2537
+ * 本包所有按码归因的判据都读那一行。**缺了这一行**就意味着这次失败没有可机读的码,而上游
2538
+ * 恰好有两类塌法会长这样:不带 `--debug` 时 `MODEL2VEC_DOWNLOAD_FAILED` 与
2539
+ * `INDEXING.FILES_FAILED` 被折成一句无码文案(首次下载 embedding 权重正落在这一档)。
2540
+ * 这里据此补一条可行动的出路,而不是让模型对着「exit=1 + 一句话」猜。
2593
2541
  *
2594
- * @param probe 目录探测(生产注入 indexProbeOf;测试注入计数桩)
2595
- * @param now 时钟注入(默认 Date.now;测试用它推进过 TTL)
2596
- * @param ttlMs 条目存活时长(默认 {@link INDEX_PROBE_TTL_MS})
2597
- * @param max 容量上限(默认 {@link INDEX_PROBE_CACHE_MAX})
2598
- * @returns 与 probe 同签名的缓存化探测函数
2542
+ * 空 detail 不补:什么都没打出来时谈不上「上游把原因塌成了一句」,那条指引只会占住回显预算。
2543
+ * 已有 `Code:` 行时也不补:那时归因本就够了。
2599
2544
  */
2600
- function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS, max = 32) {
2601
- const cache = /* @__PURE__ */ new Map();
2602
- return (dir) => {
2603
- const at = now();
2604
- const hit = cache.get(dir);
2605
- if (hit !== void 0 && at - hit.probedAt < ttlMs) {
2606
- touch(cache, dir, hit);
2607
- return hit.result;
2608
- }
2609
- const result = probe(dir);
2610
- cache.delete(dir);
2611
- cache.set(dir, {
2612
- result,
2613
- probedAt: at
2614
- });
2615
- evictAged(cache, max, (entry) => entry.probedAt + ttlMs, at);
2616
- return result;
2617
- };
2545
+ const STRUCTURED_ERROR_CODE = /^\s*Code:/imu;
2546
+ function noCodeHint(detail, messages) {
2547
+ return detail.length === 0 || STRUCTURED_ERROR_CODE.test(detail) ? "" : `\n${messages.noErrorCodeHint}`;
2548
+ }
2549
+ function shellFailure(result, messages) {
2550
+ const runnerFailure = sandboxFailure(result, messages);
2551
+ if (runnerFailure !== null) return runnerFailure;
2552
+ if (result.timedOut) return messages.timeoutFailure;
2553
+ if (result.aborted) return messages.abortedFailure;
2554
+ if (result.exitCode === 0) return null;
2555
+ const detail = failureDetail(result, messages);
2556
+ const { sandbox } = result;
2557
+ if (sandbox?.denied === true) return fill(messages.deniedFailure, {
2558
+ exit: result.exitCode,
2559
+ denied: deniedNote(sandbox, messages),
2560
+ detail: withDetail(detail, messages.detailPrefix)
2561
+ });
2562
+ if (result.exitCode === 127) return fill(messages.notInstalledFailure, { detail: withDetail(detail, messages.detailPrefix) });
2563
+ return `${fill(messages.genericFailure, {
2564
+ exit: result.exitCode,
2565
+ detail: withDetail(detail, messages.detailColon)
2566
+ })}${noCodeHint(detail, messages)}`;
2618
2567
  }
2619
2568
  /**
2620
- * 工作区白名单:只认本 daemon 真实观测过的会话工作区(重建端点与 root 授权共用)。
2569
+ * 成功执行的 stderr 里哪些是「进度噪声」、哪些必须交回。
2621
2570
  *
2622
- * 条目记的是**最后一次被提到**的时刻,不是第一次:白名单的用途是「这棵树刚被用过」,
2623
- * 一直热着的键理应活得比冷键久。故 `has` 命中即触摸,淘汰先按有效期、再按最近使用。
2624
- * 有效期是固定的 `LEDGER_TTL_MS`(一天),与解锁时效那个部署值无关——后者只有 1–240 分钟
2625
- * 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
2626
- * 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
2571
+ * zg 在**成功**时也往 stderr 写索引进度(非 TTY 下逐行落盘,实测原文:`Scanning files...` /
2572
+ * `Preparing local/potion-code-16m-v2` / `Indexing complete`)。这些行每次建索引都在,写进
2573
+ * 工具回执只是让模型对着同一堆噪声反复读;真正需要它看见的是另一类:降级提示、锁冲突、
2574
+ * 沙箱事实,以及任何本包**不认识**的新增告警。
2575
+ *
2576
+ * 所以判据是「只丢认得的进度行,其余全留」,而不是「只留认得的告警」——后者一旦 zg 出了
2577
+ * 新提示就会静默吞掉,那正是最不该发生的失败模式。
2578
+ *
2579
+ * 进度行词表逐条对着上游的进度格式化函数核过(含下载与就绪两档):
2580
+ * Scanning files… / Indexing files… / Indexing complete / Preparing <model> /
2581
+ * Downloading <model> · … / Model ready: <model>
2582
+ * 其中 `Indexing complete` 用**整行相等**匹配,不能用前缀——`Indexing completed with 3 failed
2583
+ * files`(部分文件失败的信号,必须留着)字面上就以它开头。
2627
2584
  */
2628
- function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS) {
2629
- const seen = /* @__PURE__ */ new Map();
2630
- return {
2631
- add(root) {
2632
- const key = ledgerKey(root, messages);
2633
- if (key === void 0) return;
2634
- touch(seen, key, now());
2635
- evictAged(seen, max, (seenAt) => seenAt + ttlMs, now());
2636
- },
2637
- has(root) {
2638
- const key = ledgerKey(root, messages);
2639
- if (key === void 0) return false;
2640
- const seenAt = seen.get(key);
2641
- if (seenAt === void 0 || now() - seenAt >= ttlMs) return false;
2642
- touch(seen, key, seenAt);
2643
- return true;
2644
- },
2645
- list() {
2646
- return [...seen.keys()];
2647
- }
2648
- };
2585
+ const STDERR_PROGRESS_LINES = /* @__PURE__ */ new Set(["Scanning files...", "Indexing complete"]);
2586
+ /** 该行是否只是进度噪声。`warning` / `Error` / `zvec-grep` 一律不判为噪声。 */
2587
+ function isStderrProgressLine(line) {
2588
+ const trimmed = line.trim();
2589
+ if (STDERR_PROGRESS_LINES.has(trimmed)) return true;
2590
+ return trimmed.startsWith("Indexing files") || trimmed.startsWith("Preparing ") || trimmed.startsWith("Downloading ") || trimmed.startsWith("Model ready: ");
2649
2591
  }
2650
- /** 引导端点:交回本次 apply 生成的 CSRF token 与白名单里观测到的工作区。 */
2651
- function handleRebuildRoots(routes, req, res) {
2652
- const { csrf, ledger, servingNonLoopback } = routes;
2653
- if (!guardTrust(req, res, { servingNonLoopback })) return;
2654
- if (req.method !== "GET" && req.method !== "HEAD") {
2655
- res.setHeader("Allow", "GET");
2656
- sendJson(res, 405, {
2657
- ok: false,
2658
- error: "GET only"
2659
- });
2660
- return;
2661
- }
2662
- sendJson(res, 200, {
2663
- ok: true,
2664
- csrf,
2665
- roots: ledger.list()
2666
- });
2592
+ /** 剥掉进度行,留下真正要交回的 stderr(可能为空串)。 */
2593
+ function signalStderr(text) {
2594
+ return text.split("\n").filter((line) => line.trim().length > 0 && !isStderrProgressLine(line)).join("\n");
2667
2595
  }
2668
2596
  /**
2669
- * 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
2670
- * 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
2671
- * @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
2672
- * @param proc 已经起来的 zg 进程
2673
- * @param state 这条重建的状态盒(与侧表记录共用)
2674
- * @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
2675
- * @returns 官方 JobSpec:kind / label / output / run
2597
+ * 成功(exit 0)执行的结果体检:把「其实不完整」的三类事实显式打标,避免模型
2598
+ * 把残缺输出当完整证据用。
2599
+ * 1. stdout 超上限被截尾(可能已落 spill);
2600
+ * 2. 沙箱在执行中拒绝过一次文件操作(zg 仍可 exit 0,但结果少了被拒的部分);
2601
+ * 3. **stderr 去噪之后仍非空**:zg 的降级提示(例如 embedding 模型拉不到 → 退化为
2602
+ * 纯词法兜底、跳过 --refresh)只写在 stderr,旧实现整个丢掉 → 用户把「只有词法
2603
+ * 结果」的检索当语义检索的完整结果。这里回显尾部一段。整段都是索引进度时一句都不加。
2676
2604
  */
2677
- function rebuildJobSpec(routes, proc, state, command, root) {
2678
- const { config, host, jobsOf, messages } = routes;
2679
- return {
2680
- kind: REBUILD_JOB_KIND,
2681
- label: command,
2682
- output: rebuildSources(proc, state),
2683
- run: (handle) => {
2684
- const liveJob = () => {
2685
- const live = jobsOf();
2686
- if (live === void 0) return null;
2687
- const view = jobView(live, handle.id);
2688
- if (view === null || !sameJob(state, view)) return null;
2689
- return {
2690
- jobs: live,
2691
- status: view.status
2692
- };
2693
- };
2694
- const cancelKillTimer = host.timer.timeout(() => {
2695
- if (proc.status !== "running") return;
2696
- const live = liveJob();
2697
- if (live !== null && live.status !== "running") return;
2698
- const minutes = Math.round(config.indexTimeoutMs / 6e4);
2699
- state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
2700
- if (live === null) {
2701
- killProc(proc);
2702
- return;
2703
- }
2704
- live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2705
- }, config.indexTimeoutMs);
2706
- return {
2707
- cancel: () => {
2708
- killProc(proc);
2709
- },
2710
- done: (async () => {
2711
- await proc.done;
2712
- cancelKillTimer();
2713
- try {
2714
- return jobOutcomeOf(proc);
2715
- } finally {
2716
- routes.rebuilds.release(root);
2717
- }
2718
- })()
2719
- };
2605
+ function successNotes(result, messages, stdoutMaxBytes) {
2606
+ const notes = [];
2607
+ if (result.stdout.truncated) {
2608
+ const spill = result.stdout.spillPath === void 0 ? "" : fill(messages.spillNote, { path: result.stdout.spillPath });
2609
+ notes.push(fill(messages.outputTruncated, {
2610
+ maxBytes: stdoutMaxBytes,
2611
+ spill
2612
+ }));
2613
+ }
2614
+ const { sandbox } = result;
2615
+ if (sandbox?.denied === true) notes.push(fill(messages.sandboxWarning, { denied: deniedNote(sandbox, messages) }));
2616
+ const { stderr } = result;
2617
+ const signal = signalStderr(stderr.text);
2618
+ if (signal.length > 0) {
2619
+ const tail = truncateStart(signal, STDERR_NOTE_CHARS);
2620
+ const truncatedMark = stderr.truncated ? "[…]" : "";
2621
+ notes.push(fill(messages.stderrNote, {
2622
+ marked: truncatedMark,
2623
+ tail
2624
+ }));
2625
+ }
2626
+ return notes;
2627
+ }
2628
+ /** 版本探测结果的缓存时长:够长到一次会话里基本只探一次,够短到用户中途升级 zg 也算数。 */
2629
+ const ZG_VERSION_TTL_MS = 6e5;
2630
+ /** 探测自身的超时:`zg --version` 是纯打印,给它检索超时是浪费,也让它卡住主流程。 */
2631
+ const ZG_VERSION_PROBE_TIMEOUT_MS = 1e4;
2632
+ /** 门槛文案:回显实际版本与门槛值,并给出唯一的出路(升级 zvec-grep)。 */
2633
+ function tooOldZgError(actual, messages) {
2634
+ return new Error(fill(messages.zgVersionTooOld, {
2635
+ actual: formatZgVersion(actual),
2636
+ minimum: MINIMUM_ZG_VERSION
2637
+ }));
2638
+ }
2639
+ /**
2640
+ * 跑一次 `zg --version`,只把 stdout 交回来(undefined = 探测不出来:非零退出、
2641
+ * 读不懂的形状,或 spawn/执行器层面的任何失败)。**失败绝不外抛**:这道门槛的职责
2642
+ * 只有一个——把「确知太老」拦下来,拿「没读懂」去拦用户是在制造新故障。
2643
+ */
2644
+ async function probeZgVersion(host, config) {
2645
+ let stdout;
2646
+ try {
2647
+ const env = zgEnv(config);
2648
+ const spec = host.shell.resolve({
2649
+ command: "zg --version",
2650
+ workdir: tmpdir(),
2651
+ timeoutMs: ZG_VERSION_PROBE_TIMEOUT_MS,
2652
+ stdoutMaxBytes: config.stdoutMaxBytes,
2653
+ ...env ? { env } : {}
2654
+ });
2655
+ const result = await (await host.shell.execute(spec)).result();
2656
+ stdout = result.exitCode === 0 ? result.stdout.text : void 0;
2657
+ } catch {
2658
+ stdout = void 0;
2659
+ }
2660
+ return stdout === void 0 ? void 0 : tooOldZgVersion(stdout);
2661
+ }
2662
+ /**
2663
+ * 建这道门槛。缓存挂在闭包里(随 apply 生死),TTL 到期或探测失败后重探一次。
2664
+ *
2665
+ * workdir 取系统临时目录而不是会话 cwd:这是一次与工作区无关的纯打印探测,
2666
+ * 不该因为某个会话的工作区不存在而失败,也不该顺手触发 root 授权那一套。
2667
+ */
2668
+ function createZgVersionGate(host, config) {
2669
+ let cachedAt = 0;
2670
+ let cachedTooOld;
2671
+ return { async ensure(messages) {
2672
+ const now = Date.now();
2673
+ if (now - cachedAt < ZG_VERSION_TTL_MS) {
2674
+ if (cachedTooOld !== void 0) throw tooOldZgError(cachedTooOld, messages);
2675
+ return;
2720
2676
  }
2721
- };
2677
+ const probe = await probeZgVersion(host, config);
2678
+ cachedAt = now;
2679
+ cachedTooOld = probe;
2680
+ if (probe !== void 0) throw tooOldZgError(probe, messages);
2681
+ } };
2682
+ }
2683
+ /** 就绪态缓存时长:daemon 可被随时 `zg server on/off` 起停,比版本探测勤得多。 */
2684
+ const SERVER_READY_TTL_MS = 6e4;
2685
+ /** 探测自身超时:`zg server status` 是纯读,不该借检索超时。 */
2686
+ const SERVER_READY_PROBE_TIMEOUT_MS = 1e4;
2687
+ /** 就绪探测命令行:`--check-ready` 把「就绪与否」 expressed 成退出码。 */
2688
+ const SERVER_READY_COMMAND = "zg server status --check-ready";
2689
+ /** 探一次守护进程就绪态:退出码 0 = 就绪。任何异常与非零退出都算未就绪。 */
2690
+ async function probeServerReady(host, config) {
2691
+ try {
2692
+ const env = zgEnv(config);
2693
+ const spec = host.shell.resolve({
2694
+ command: SERVER_READY_COMMAND,
2695
+ workdir: tmpdir(),
2696
+ timeoutMs: SERVER_READY_PROBE_TIMEOUT_MS,
2697
+ stdoutMaxBytes: config.stdoutMaxBytes,
2698
+ ...env ? { env } : {}
2699
+ });
2700
+ return (await (await host.shell.execute(spec)).result()).exitCode === 0;
2701
+ } catch {
2702
+ return false;
2703
+ }
2722
2704
  }
2723
2705
  /**
2724
- * `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
2706
+ * 建这道门槛。缓存挂闭包(随 apply 生死),TTL 到期后重探。
2707
+ *
2708
+ * **并发不合并**:两条检索同时撞上 TTL 边界会各探一次,多起一发纯读进程而已——
2709
+ * 换来的是没有「在途 Promise 该不该共享」这层状态可测(与版本门槛同一口径)。
2710
+ */
2711
+ function createZgServerGate(host, config) {
2712
+ let cachedAt = 0;
2713
+ let cachedReady = false;
2714
+ let probed = false;
2715
+ return { async ready() {
2716
+ const now = Date.now();
2717
+ if (probed && now - cachedAt < SERVER_READY_TTL_MS) return cachedReady;
2718
+ cachedReady = await probeServerReady(host, config);
2719
+ cachedAt = now;
2720
+ probed = true;
2721
+ return cachedReady;
2722
+ } };
2723
+ }
2724
+ /**
2725
+ * zg query 输出的命中摘要。口径分两栏,因为**分组计数之和不是命中总数**:同一处代码
2726
+ * 会被多个查询组各命中一次(名次与 `matchedBy` 逐组变化,实测同一 `src/beta.ts:1-3`
2727
+ * 在 fts 组排第 4、在 vector 组排第 1),直接求和会把同一处位置重复计入。
2728
+ * - 分组计数合计:各组 `hits:` 之和,反映 zg 实际跑了多少路。
2729
+ * - 去重后不同位置:按 `相对路径:行号范围` 这一稳定身份键去重——名次、匹配来源、
2730
+ * 分数都逐组变化,不能入键——反映模型真正看到几处不同代码。
2731
+ * 身份键取条目头行里 `matchedBy=` 之后的**整段原样**文本,不去拆行号范围:路径本身
2732
+ * 可以含空格与冒号(实测 `deep/a/b/c d/we:ird file.ts:1-2`),任何拆解都会引入误判,
2733
+ * 而原样文本已经恰好就是「相对路径 + 行号范围」。一条位置都数不出时整段去重口径省略,
2734
+ * 不数就不谎称。
2725
2735
  *
2726
- * 为什么必须预检(全部实测,见 test/e2e/zg-cli.test.ts):真 zg 遇到读不成的 ignore 文件
2727
- * **不是**按"没有这条规则"继续,而是整次索引失败(`ZVEC_GREP.ENGINE.INDEXING.WORKSPACE_FAILED`,
2728
- * 原因是 ENOENT / EACCES / EISDIR),并且那个坏路径会**写进工作区索引的状态**——此后这条树上的
2729
- * `zg index` 与 `zg status` 都报同一个错,`--reset-paths` 清不掉,只有 `zg_index drop`(整棵
2730
- * 索引删掉重来)能救。一个拼错的文件名、一个存在但读不了的文件(mode 000 / 他人属主,用绝对路径
2731
- * 还够得着系统文件)、或一个目录,就把用户的工作区索引弄坏,属于必须在起进程之前拦下的那一类。
2736
+ * zg 的输出**不提供**任何截断信号,故命中数正好等于 --limit 只能作为观察陈述,不能
2737
+ * 断言发生了截断(`hitCapped` 因此不含断言措辞)。
2738
+ */
2739
+ /** zg 每个查询组的计数行前缀(实测输出形状:`hits: 3`,源码行都带行号前缀)。 */
2740
+ const HITS_LINE_PREFIX = "hits: ";
2741
+ /**
2742
+ * zg 命中条目头行的形状:`#<名次> [选择理由] matchedBy=<来源> [score=<分>] <相对路径>:<行号范围>`。
2743
+ * 捕获组即身份键。
2732
2744
  *
2733
- * 判据「读得了 + 是文件」合成**一次** try(accessSync 在前):`statSync().isFile()` 对 mode 000
2734
- * 的文件照样返回 true(stat 只要父目录可搜索、不要文件本身可读),故先 `accessSync(R_OK)` 补上
2735
- * "当前进程真能 open 来读"这半段——它与 zg 的读权限同 uid 同源(root 下两者都放行、非 root 下
2736
- * 两者都拒);再用 `isFile()` 挡掉目录。**不拆成「不存在」与「读不了」两条独立分支**:可读性那
2737
- * 一档在 windows(chmod 只翻只读位,属主仍读得了)与 root(绕过 DAC)下根本造不出来,拆成独立
2738
- * 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
2739
- * 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
2745
+ * 两段可选装饰都不能进键,各有实测依据(`--trace` 开启时出现,见 formatScore 与
2746
+ * agentRankedItemHeader):
2747
+ * - `score=`:**同一处位置在两个组里分值可以不同**(实测 `src/beta.ts:1-2` 在 fts 组
2748
+ * 是 0.0164、在 vector 组是 0.0161)。带分值入键等于让每次命中都成"新位置",去重
2749
+ * 直接失效、位置数虚高一倍。分值形态是 `Number.isInteger ? String : toFixed(4)`,
2750
+ * 故整数与四位小数都要收;只认纯数字,路径若真以 `score=1.txt` 开头则不会被误剥
2751
+ * (`score=1` 后面跟的是 `.` 不是空白,整段不匹配)。
2752
+ * - `[global_fill]` / `[group_coverage: x]`:排在名次与 `matchedBy=` 之间,漏了它整行
2753
+ * 就匹配不上,那条命中会被当成不存在。
2740
2754
  *
2741
- * drop 那一臂整段跳过:`--drop` 的命令只有 `zg index <root> --drop --yes`,ignoreFiles 被
2742
- * buildIndexCommand 静默丢掉、根本不进 zg(见 lib/cli.ts 的 drop 分支),预检它没有意义,还会
2743
- * 拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。判 drop 用与构造器**同一个**
2744
- * `boolOf`,两处口径不会漂。
2745
- * @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
2746
- * @param root 已归一的工作区根(相对路径按它解析)
2747
- * @param messages 文案表
2748
- * @returns {void}
2749
- * @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项)
2755
+ * preview 的源码行都带 `<行号>\t` 前缀、markdown 标题行是 `heading:`、追踪行是 `trace:`,
2756
+ * 都撞不上这一形状。匹配来源逐组变化(fts / vector / fts+vector),故 `\S+` 只消费来源。
2750
2757
  */
2751
- function assertIgnoreFilesExist(args, root, messages) {
2752
- if (boolOf(args.drop, "drop", messages)) return;
2753
- for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
2754
- const target = entry.startsWith("/") ? entry : `${root}/${entry}`;
2755
- let usable = false;
2756
- try {
2757
- accessSync(target, constants.R_OK);
2758
- usable = statSync(target).isFile();
2759
- } catch {}
2760
- if (!usable) throw new Error(fill(messages.ignoreFileMissing, {
2761
- path: entry,
2762
- root
2763
- }));
2758
+ const HIT_LINE_PREFIX = /^#\d+(?:\s+\[[^\]]*\])?\s+matchedBy=\S+\s+(?:score=-?\d+(?:\.\d+)?\s+)?(?<location>\S.*)$/u;
2759
+ function hitSummary(stdoutText, limit, truncated, messages) {
2760
+ const lines = stdoutText.split("\n");
2761
+ const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => /^\d+$/u.test(digits)).map((digits) => Math.trunc(Number(digits)));
2762
+ if (perGroup.length === 0) return null;
2763
+ const locations = /* @__PURE__ */ new Set();
2764
+ for (const line of lines) {
2765
+ const location = HIT_LINE_PREFIX.exec(line)?.groups?.["location"];
2766
+ if (location !== void 0) locations.add(location);
2764
2767
  }
2768
+ const grouped = perGroup.reduce((sum, count) => sum + count, 0);
2769
+ const capped = perGroup.some((count) => count >= limit);
2770
+ return fill(messages.hitSummary, {
2771
+ groups: perGroup.length,
2772
+ grouped,
2773
+ dedup: locations.size === 0 ? "" : fill(messages.hitDedup, { unique: locations.size }),
2774
+ limit,
2775
+ capped: capped ? messages.hitCapped : "",
2776
+ truncated: truncated ? messages.hitTruncated : ""
2777
+ });
2765
2778
  }
2766
2779
  /**
2767
- * 起一条 `zg index`:命令构造 + resolve + execute 三步。
2780
+ * 被「本插件正在重建」挡住的失败:文案照常是人话,但额外带上结构化结论,
2781
+ * 让检索路径能判断「等它落定后重试一次」而不是无脑失败。
2782
+ * 只有占锁方自报重建才带这个类型——把「别的进程占锁」也当成可等的重建,
2783
+ * 会在一把永远不会由本插件放开的锁上无界挂起。
2784
+ */
2785
+ var RebuildLockBusyError = class extends Error {
2786
+ constructor(message) {
2787
+ super(message);
2788
+ this.name = "RebuildLockBusyError";
2789
+ }
2790
+ };
2791
+ async function runForegroundOnce(host, command, workdir, timeoutMs, opts) {
2792
+ const spec = host.shell.resolve({
2793
+ command,
2794
+ workdir,
2795
+ timeoutMs,
2796
+ stdoutMaxBytes: opts.stdoutMaxBytes,
2797
+ signal: opts.signal,
2798
+ ...opts.env ? { env: opts.env } : {}
2799
+ });
2800
+ const result = await (await host.shell.execute(spec)).result();
2801
+ const failure = shellFailure(result, opts.messages);
2802
+ if (failure !== null) {
2803
+ const resolved = opts.resolveFailure?.(failure, result) ?? null;
2804
+ if (resolved !== null) return resolved;
2805
+ const concurrent = classifyConcurrentFailure(result.stderr.text);
2806
+ throw concurrent?.kind === "lock-busy" && concurrent.rebuild ? new RebuildLockBusyError(failure) : new Error(failure);
2807
+ }
2808
+ const notes = successNotes(result, opts.messages, opts.stdoutMaxBytes);
2809
+ const { text } = result.stdout;
2810
+ const summary = opts.summaryLimit === void 0 ? null : hitSummary(text, opts.summaryLimit, result.stdout.truncated, opts.messages);
2811
+ const extras = summary === null ? notes : [...notes, summary];
2812
+ return extras.length > 0 ? `${text}\n${extras.join("\n")}` : text;
2813
+ }
2814
+ /** 等待期间被取消时的出路(与 zg 自身被中止区分开:这里等的是重建,不是命令)。 */
2815
+ function messagesAbortedWaiting(root, messages) {
2816
+ return fill(messages.rebuildWaitAborted, { root });
2817
+ }
2818
+ /** 等待重建落定超时:给出可行动出路,并说明不会因此发放 grep/rg 配额。 */
2819
+ function messagesWaitExpired(root, maxWaitMs, messages) {
2820
+ return fill(messages.rebuildWaitTimeout, {
2821
+ root,
2822
+ seconds: Math.round(maxWaitMs / 1e3)
2823
+ });
2824
+ }
2825
+ /**
2826
+ * 前台执行 + **一次**重建等待重试。
2768
2827
  *
2769
- * 设置卡重建端点与模型侧后台索引**共用**这一个函数(不是复制品),所以两条入口起的作业
2770
- * 在名册、状态投影、轮询端点上完全同形。命令形态由 `indexArgs` 决定,故它也服务普通建索引。
2828
+ * 重建持有该根的写锁时,检索会立刻以「索引不可用」失败(zg 的锁是纯 fail-fast,不等)。
2829
+ * 直接把失败回给模型,等于在重建窗口内把该根的检索通道整个关掉——而门禁又要求先成功
2830
+ * 检索才放行 grep/rg,于是模型连退路都没有。这里改为:确认占锁方确实是本插件的重建,
2831
+ * 就等它落定后重跑一次;只等一次,不做轮询式长等,避免把一次检索拖成分钟级。
2832
+ */
2833
+ async function runForeground(host, command, workdir, timeoutMs, opts) {
2834
+ const base = {
2835
+ signal: opts.signal,
2836
+ env: opts.env,
2837
+ stdoutMaxBytes: opts.stdoutMaxBytes,
2838
+ messages: opts.messages,
2839
+ summaryLimit: opts.summaryLimit,
2840
+ resolveFailure: opts.resolveFailure
2841
+ };
2842
+ const wait = opts.rebuildWait;
2843
+ if (wait === void 0) return runForegroundOnce(host, command, workdir, timeoutMs, base);
2844
+ try {
2845
+ return await runForegroundOnce(host, command, workdir, timeoutMs, base);
2846
+ } catch (error) {
2847
+ const entry = wait.rebuilds.covering(wait.root, opts.messages);
2848
+ if (!(error instanceof RebuildLockBusyError) || entry === void 0) throw error;
2849
+ const outcome = await wait.rebuilds.wait(wait.root, opts.messages, wait.maxWaitMs, opts.signal);
2850
+ if (outcome === "settled") return runForegroundOnce(host, command, workdir, timeoutMs, base);
2851
+ throw new Error(outcome === "aborted" ? messagesAbortedWaiting(entry.root, opts.messages) : messagesWaitExpired(entry.root, wait.maxWaitMs, opts.messages), { cause: error });
2852
+ }
2853
+ }
2854
+ /**
2855
+ * root 的存在性预检(item:不验存在)。zg 的 cwd 不存在时,spawn 直接以
2856
+ * ENOENT 失败——那与「bash 没装」「zg 没装」在同一句 stderr 里无法区分,
2857
+ * 模型据此给出的建议会把用户带偏。提前一次 existsSync 换明确归因。
2858
+ */
2859
+ function assertRootExists(root, messages) {
2860
+ if (!existsSync(root)) throw new Error(fill(messages.rootMissing, { root }));
2861
+ return root;
2862
+ }
2863
+ /**
2864
+ * 默认每组结果数:值域 1-50 由 Config schema(隐式命名空间与行 config 共用)保证,
2865
+ * 这里只处理「字段缺省」。真正兜住越界的是 cli.clampLimit(命令构造边界)。
2866
+ */
2867
+ function readDefaultLimit(config) {
2868
+ return config.defaultLimit.get() ?? 10;
2869
+ }
2870
+ /** search-first 解锁配额:每次成功 zg_search 发放的 grep/rg 次数(值域 1-20 由 schema 保证)。 */
2871
+ function readGrepBudget(config) {
2872
+ return config.grepBudgetPerSearch.get() ?? 3;
2873
+ }
2874
+ /** search-first 解锁时效(分钟,值域 1-240 由 schema 保证)。 */
2875
+ function readUnlockWindowMin(config) {
2876
+ return config.unlockWindowMin.get() ?? 10;
2877
+ }
2878
+ /** search-first 门禁开关:**fail-closed**。schema 默认已是 true,引用仍交回 undefined
2879
+ * (条目没被投影 / 宿主退化)时按「门禁开着」处理——宁可多拦一次 grep,也不能把
2880
+ * 「读不到设置」静默当成「用户关了门禁」。 */
2881
+ function readEnforceSearchFirst(config) {
2882
+ return config.enforceSearchFirst.get() ?? true;
2883
+ }
2884
+ /** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
2885
+ function comparablePath(root) {
2886
+ return root.startsWith("/private/") ? root.slice(8) : root;
2887
+ }
2888
+ /** 认的清单版本:与上游 v0.2.2 的 `export const CURRENT_MANIFEST_VERSION = 1` 同值。 */
2889
+ const SUPPORTED_MANIFEST_VERSION = 1;
2890
+ /**
2891
+ * 索引清单是否**真的**覆盖这个工作区。
2771
2892
  *
2772
- * 版本门槛排在命令构造**之前**:确知装的是太老的 zg 时,在这一行就给出可照做的指引,
2773
- * 而不是起一条命令形态对不上的 zg 再让人对着结果猜。注意这个顺序也保证了「门槛失败」
2774
- * 发生在任何进程存在之前,调用方那条 `release` 出口足以收干净。
2893
+ * 只判「文件在不在」是不够的,两种实况都会把它判成有索引而实际检索必然失败:
2894
+ * - 文件在,但内容不是一份清单(半截写入、被别的东西占了同名文件)——解析失败即不算。
2895
+ * - 清单在,但索引的根路径不覆盖这个目录(例如指向另一个盘符/被改写过的路径)——此时
2896
+ * 在这个目录里检索会报「索引不可用」,而门禁却按「已建索引」拦着 grep/rg。
2897
+ * - 清单的版本不是当前认的那一版——上游读它会直接抛 MANIFEST.INVALID(要求
2898
+ * `manifestVersion` 严格等于 `CURRENT_MANIFEST_VERSION`),此时本目录**一次检索都做不了**,
2899
+ * 却会被「是个数字」这种宽松判据放进门禁。故这里同样取严格相等。
2775
2900
  *
2776
- * 任一步抛错即就地翻成 `{ error, status }`;**本函数不写响应、不释放占位**,两件事都由
2777
- * 调用方做(它们才持有 root 与响应对象)。
2778
- * @param routes 本次注册的共享依赖(现读 config / host / jobsOf)
2779
- * @param started 本次请求语言的文案表
2780
- * @param indexArgs 已归一 root 的索引入参
2781
- * @param embedding 设置里的默认 embedding(`indexArgs.embedding` 为空时用它)
2782
- * @returns 起来的进程与它跑的命令;失败为 `{ error, status }`
2901
+ * 认的结构只有真正用到的两处(实测上游的 workspace manifest 形状):
2902
+ * `manifestVersion` 严格等于 1,`rootPaths` 是非空数组且每项带一个非空 `absolutePath`。
2903
+ * 刻意不校验 embedding / policy 等字段——那些变了索引照样能用,判成「无索引」反而是错的。
2904
+ *
2905
+ * 覆盖判据是「归一后相等」。实测 macOS 上清单里写的是**未解析**路径(`/tmp/x`)而
2906
+ * `path` 字段才是解析过的(`/private/tmp/x`),会话 cwd 通常也是未解析那一支;但调用方
2907
+ * 完全可能交来解析过的形式,故两边都再剥一次 `/private` 前缀再比。
2783
2908
  */
2784
- async function spawnIndexWrite(routes, started, indexArgs, embedding) {
2785
- const { config, host } = routes;
2786
- let spawned;
2909
+ function manifestCoversRoot(manifestPath, dir) {
2910
+ let parsed;
2787
2911
  try {
2788
- await routes.versionGate.ensure(started);
2789
- assertIgnoreFilesExist(indexArgs, assertAbsoluteRoot(indexArgs.root, started), started);
2790
- const built = buildIndexCommand(indexArgs, embedding, started, readClientMode(config, started), allowRemoteEmbedding(config));
2791
- const env = zgEnv(config);
2792
- const spec = host.shell.resolve({
2793
- command: built.command,
2794
- workdir: built.workdir,
2795
- onExpiry: "none",
2796
- stdoutMaxBytes: config.stdoutMaxBytes,
2797
- ...env ? { env } : {}
2798
- });
2799
- spawned = {
2800
- proc: await host.shell.execute(spec),
2801
- command: built.command
2802
- };
2912
+ parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
2913
+ } catch {
2914
+ return false;
2915
+ }
2916
+ if (!isRecord(parsed) || !("manifestVersion" in parsed) || parsed["manifestVersion"] !== SUPPORTED_MANIFEST_VERSION) return false;
2917
+ const { rootPaths } = parsed;
2918
+ if (!Array.isArray(rootPaths) || rootPaths.length === 0) return false;
2919
+ const target = comparablePath(normalizeRoot(dir));
2920
+ return rootPaths.some((entry) => isRecord(entry) && typeof entry["absolutePath"] === "string" && entry["absolutePath"].length > 0 && comparablePath(normalizeRoot(entry["absolutePath"])) === target);
2921
+ }
2922
+ /** zg 索引库存在性探测(search-first 门禁与 zg_search 登记共用)。
2923
+ * 必须连 workspace manifest 一起看:`<dir>/.zvec-grep/` 这个名字被 zg 自己的**全局
2924
+ * home** 征用(`ZVEC_GREP_HOME ?? ~/.zvec-grep`,装的是 config.json / locks / models),
2925
+ * 只判目录存在的话,一个从没建过索引的工作区会因祖先目录撞名而被当成「已建索引」——
2926
+ * 门禁随即在没有任何索引可搜的情况下拦下 grep/rg,而 zg_search 也答不出任何东西。
2927
+ * manifest 是上游写索引时落的那一份(`writeWorkspaceManifest`),只有它在场,
2928
+ * 才说明这个工作区真的建过索引。 */
2929
+ function indexProbeOf(dir) {
2930
+ const base = `${dir}/${INDEX_DIR_NAME}`;
2931
+ if (!existsSync(base) || !existsSync(`${base}/manifest.json`)) return false;
2932
+ return manifestCoversRoot(`${base}/${WORKSPACE_MANIFEST_FILE}`, dir);
2933
+ }
2934
+ /** root 判据的单一来源:显式值 > 会话工作区 → 存在性 → 授权(已观测 / 同一棵树)。 */
2935
+ function judgeRoot(rawRoot, cwd, messages, ledger) {
2936
+ let resolved;
2937
+ try {
2938
+ resolved = assertRootExists(resolveRoot(rawRoot, cwd, messages), messages);
2803
2939
  } catch (error) {
2804
2940
  return {
2805
- error: fill(started.endpointStartFailed, { reason: errorText(error) }),
2806
- status: 500
2941
+ allowed: false,
2942
+ reason: errorText(error)
2807
2943
  };
2808
2944
  }
2809
- return spawned;
2945
+ if (cwd !== void 0 && normalizeRoot(resolved) === normalizeRoot(cwd) || ledger.has(resolved)) return {
2946
+ allowed: true,
2947
+ root: resolved,
2948
+ question: void 0
2949
+ };
2950
+ if (cwd !== void 0 && pathsRelated(resolved, cwd, messages)) return {
2951
+ allowed: true,
2952
+ root: resolved,
2953
+ question: {
2954
+ root: resolved,
2955
+ cwd
2956
+ }
2957
+ };
2958
+ return {
2959
+ allowed: false,
2960
+ reason: fill(messages.rootNotAuthorized, {
2961
+ root: resolved,
2962
+ cwd: cwd ?? messages.rootNoSession
2963
+ })
2964
+ };
2965
+ }
2966
+ /** 工具入参的 root:过 root 判据,放行后登记进白名单(一处三工具共用)。 */
2967
+ function rootOf(args, exec, messages, ledger) {
2968
+ const decision = judgeRoot(args["root"], sessionHeaderCwd(exec), messages, ledger);
2969
+ if (!decision.allowed) throw new Error(decision.reason);
2970
+ ledger.add(decision.root);
2971
+ return decision.root;
2972
+ }
2973
+ function define(host, spec) {
2974
+ const { parameters } = spec;
2975
+ const required = Array.isArray(parameters["required"]) ? parameters["required"].filter((item) => typeof item === "string") : [];
2976
+ host.tools.register({
2977
+ name: spec.name,
2978
+ description: spec.description,
2979
+ parameters,
2980
+ output: {
2981
+ schema: TEXT_OUTPUT_SCHEMA,
2982
+ render: (_args, value) => textBlock(value)
2983
+ },
2984
+ execute: async (rawArgs, exec) => {
2985
+ const messages = spec.messages();
2986
+ if (!isRecord(rawArgs)) throw new Error(fill(messages.argsMustBeObject, {
2987
+ name: spec.name,
2988
+ received: rawArgs === null ? "null" : typeof rawArgs
2989
+ }));
2990
+ const missing = required.filter((fieldName) => rawArgs[fieldName] === void 0);
2991
+ if (missing.length > 0) throw new Error(fill(messages.missingRequiredArgs, {
2992
+ name: spec.name,
2993
+ fields: missing.join(", ")
2994
+ }));
2995
+ return await spec.run(rawArgs, exec, messages);
2996
+ }
2997
+ });
2998
+ }
2999
+ /** 隐式命名空间与 loader 行 config 共用同一 schema(单源,防漂移)。
3000
+ * 值名退避为 configSchema:避免与同名 interface Config 触发 no-redeclare;
3001
+ * 外部仍以 `Config` 名导入(export as),公开 API 不变。
3002
+ *
3003
+ * 0.1.7 迁移要点(两处都是静默失效,写错不报错):
3004
+ * - `.volatile()` 决定字段是否进设置表单。宿主 `describe()` 只投影 volatile 字段
3005
+ * (packages/settings/settings/src/schema.ts 的 volatileForm),全漏标则整条被跳过
3006
+ * (settings/src/index.ts 里 `volatileForm(schema)` 空判即 `return []` 的那一处)、写入抛
3007
+ * `has no volatile fields`(同文件的那句 throw)。
3008
+ * - `settings.register(ns, schema, { base })` 的「底座」层已被宿主移除:内置默认逐字段
3009
+ * 落成下面的 `.default()`(原 BUILTIN_BASE 原样搬来,单一来源),cordis 装载期按同一
3010
+ * 份 schema 校验行 config 并填默认,再把 volatile 字段包成引用交给 apply。
3011
+ * 六个 volatile 字段全是本卡的可编辑项,一个都不该漏;四个非 volatile 部署值
3012
+ * (超时三项 + stdout 上限)只走行 config,标 volatile 反而会把它们变成设置卡项。 */
3013
+ const configSchema = Schema.object({
3014
+ defaultEmbedding: Schema.string().default(DEFAULT_EMBEDDING).volatile(),
3015
+ defaultLimit: Schema.natural().min(1).max(50).default(10).volatile(),
3016
+ hfEndpoint: Schema.string().default("https://modelscope.cn/models").volatile(),
3017
+ enforceSearchFirst: Schema.boolean().default(true).volatile(),
3018
+ grepBudgetPerSearch: Schema.natural().min(1).max(20).default(3).volatile(),
3019
+ unlockWindowMin: Schema.natural().min(1).max(240).default(10).volatile(),
3020
+ searchTimeoutMs: Schema.natural().min(1).default(SEARCH_TIMEOUT_MS),
3021
+ statusTimeoutMs: Schema.natural().min(1).default(STATUS_TIMEOUT_MS),
3022
+ indexTimeoutMs: Schema.natural().min(1).default(INDEX_TIMEOUT_MS),
3023
+ stdoutMaxBytes: Schema.natural().min(1).default(STDOUT_MAX_BYTES),
3024
+ clientMode: Schema.union([
3025
+ "auto",
3026
+ "direct",
3027
+ "server"
3028
+ ]).default(DEFAULT_CLIENT_MODE),
3029
+ rebuildWaitMs: Schema.natural().min(1).default(REBUILD_WAIT_MS),
3030
+ allowRemoteEmbedding: Schema.boolean().default(false),
3031
+ remoteEmbeddingEndpoint: Schema.string().default(""),
3032
+ remoteEmbeddingApiKeyFrom: Schema.string().default(""),
3033
+ requireApprovalForExplicitRoot: Schema.boolean().default(false)
3034
+ });
3035
+ /** 白名单键:归一化后的绝对路径;非法 root(相对/越界/NUL)归 undefined。 */
3036
+ function ledgerKey(root, messages) {
3037
+ let key;
3038
+ try {
3039
+ key = assertAbsoluteRoot(root, messages);
3040
+ } catch {
3041
+ key = void 0;
3042
+ }
3043
+ return key;
2810
3044
  }
2811
3045
  /**
2812
- * 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
3046
+ * 淘汰一张常驻表:先按**有效期**丢过期项,再按**最近使用**丢最老项到不超过上限。
2813
3047
  *
2814
- * 三种失败(注册表换人 / 同名不同命 / start 抛错)都**先把那条进程杀掉**再交回错误:
2815
- * 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
2816
- * 同样地,本函数不写响应、不释放占位——那两件事由调用方做。
2817
- * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
2818
- * @param root 已过前置校验的工作区(写进侧表供卡片回显)
2819
- * @param started 本次请求语言的文案表
2820
- * @param spawned spawnIndexWrite 交回的进程与命令
2821
- * @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
3048
+ * 为什么不是纯插入序(原 `trimMapTo`):`Map` 的插入序在 `delete` 后重排,故「插入序淘汰」
3049
+ * 实际是「最早插入且此后没被重新插入的先走」——一张每轮都被 `set` 命中的表(解锁额度就是,
3050
+ * 每次成功检索都重置同一批键)永远淘汰不掉真正冷掉的项,而一条很久没被碰过的键会一直占位。
3051
+ * 改成:命中即触摸(`delete` + `set` 把键挪到队尾),淘汰从队首取。这样「最久没用过」
3052
+ * 才有确定含义。
3053
+ *
3054
+ * 有效期同样必要:一个只在半小时前出现过一次的工作区,到明天早就不该还占着白名单名额。
3055
+ * 两者都保留,故上界(内存有界)与语义(冷掉的先走)同时成立。
3056
+ *
3057
+ * @param map 目标表(就地改)
3058
+ * @param max 条数上限
3059
+ * @param expiresAt 取某条目的过期时刻;无则视为永不过期
3060
+ * @param now 当前时刻(epoch ms)
2822
3061
  */
2823
- function attachIndexWrite(routes, root, started, spawned) {
2824
- const { jobsOf, records } = routes;
2825
- const { proc, command } = spawned;
2826
- const starting = jobsOf();
2827
- if (starting === void 0) {
2828
- killProc(proc);
2829
- return {
2830
- error: started.endpointJobsUnavailable,
2831
- status: 503
2832
- };
3062
+ function evictAged(map, max, expiresAt, now) {
3063
+ for (const [key, value] of map) {
3064
+ const expiry = expiresAt(value);
3065
+ if (expiry !== void 0 && expiry <= now) map.delete(key);
2833
3066
  }
2834
- pruneRebuildHistory(starting, records);
2835
- const state = {
2836
- identity: {
2837
- kind: REBUILD_JOB_KIND,
2838
- label: command,
2839
- startedAt: UNSIGNED_STARTED_AT
2840
- },
2841
- lost: false,
2842
- timeoutNote: null
2843
- };
2844
- let jobId;
2845
- try {
2846
- jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
2847
- state.identity = identityOf(starting.get(jobId));
2848
- const clashed = records.get(jobId);
2849
- if (clashed !== void 0 && !sameIdentity(clashed.state.identity, state.identity)) {
2850
- killProc(proc);
2851
- return {
2852
- error: started.endpointRegistryReplaced,
2853
- status: 503
2854
- };
2855
- }
2856
- records.set(jobId, {
2857
- proc,
2858
- root,
2859
- id: jobId,
2860
- state
2861
- });
2862
- } catch (error) {
2863
- killProc(proc);
2864
- return {
2865
- error: startupFailureText(error, started),
2866
- status: 500
2867
- };
3067
+ for (const key of map.keys()) {
3068
+ if (map.size <= max) break;
3069
+ map.delete(key);
2868
3070
  }
2869
- return { jobId };
2870
3071
  }
2871
- /** 启动端点:四道前置校验(同源 / CSRF / 白名单 / 目录存在)后复用或起一条重建。 */
2872
- async function handleRebuildStart(routes, req, res) {
2873
- const { csrf, jobsOf, ledger, messages, records, servingNonLoopback } = routes;
2874
- if (!guardTrust(req, res, { servingNonLoopback })) return;
2875
- if (req.method !== "POST") {
2876
- res.setHeader("Allow", "POST");
2877
- sendJson(res, 405, {
2878
- ok: false,
2879
- error: "POST only"
2880
- });
2881
- return;
2882
- }
2883
- if (await guardBody(req, res, {
2884
- maxBytes: REBUILD_BODY_MAX_BYTES,
2885
- csrf: {
2886
- token: csrf,
2887
- headerName: REBUILD_CSRF_HEADER
2888
- }
2889
- }) === null) return;
2890
- const started = messages();
2891
- const root = acceptableRebuildRoot(req, res, ledger, started);
2892
- if (root === null) return;
2893
- const jobs = jobsOf();
2894
- if (jobs === void 0) {
2895
- sendJson(res, 503, {
2896
- ok: false,
2897
- error: started.endpointJobsUnavailable
2898
- });
2899
- return;
2900
- }
2901
- if (routes.rebuilds.claim(root, "card") === null) {
2902
- if (!followRunningRebuild(jobs, records, res, root)) sendJson(res, 409, {
2903
- ok: false,
2904
- error: started.endpointRebuildInFlight
2905
- });
2906
- return;
2907
- }
2908
- const embedding = readDefaultEmbedding(routes.config);
2909
- const spawned = await spawnIndexWrite(routes, started, {
2910
- root,
2911
- embedding,
2912
- rebuild: true
2913
- }, embedding);
2914
- if ("error" in spawned) {
2915
- routes.rebuilds.release(root);
2916
- sendJson(res, spawned.status, {
2917
- ok: false,
2918
- error: spawned.error
2919
- });
2920
- return;
2921
- }
2922
- const attached = attachIndexWrite(routes, root, started, spawned);
2923
- if ("error" in attached) {
2924
- routes.rebuilds.release(root);
2925
- sendJson(res, attached.status, {
2926
- ok: false,
2927
- error: attached.error
2928
- });
2929
- return;
2930
- }
2931
- routes.rebuilds.attach(root, attached.jobId);
2932
- sendJson(res, 200, {
2933
- ok: true,
2934
- jobId: attached.jobId
2935
- });
3072
+ /** 命中即触摸:把键挪到队尾,使「最近使用」在插入序上成立。 */
3073
+ function touch(map, key, value) {
3074
+ map.delete(key);
3075
+ map.set(key, value);
2936
3076
  }
2937
- /** 轮询端点:官方状态投影 + 退出码/沙箱事实 + 打标后的输出尾窗(卡片每 2s 敲一次)。 */
2938
- function handleRebuildStatus(routes, req, res) {
2939
- const { jobsOf, messages, records, servingNonLoopback } = routes;
2940
- if (!guardTrust(req, res, { servingNonLoopback })) return;
2941
- const jobId = queryParam(req, "jobId");
2942
- const record = jobId === null || jobId === "" ? void 0 : records.get(jobId);
2943
- if (record === void 0) {
2944
- sendJson(res, 404, {
2945
- ok: false,
2946
- error: fill(messages().unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
2947
- });
2948
- return;
2949
- }
2950
- const marks = messages();
2951
- const jobs = jobsOf();
2952
- if (jobs === void 0) {
2953
- sendJson(res, 503, {
2954
- ok: false,
2955
- error: marks.endpointJobsUnavailable
2956
- });
2957
- return;
2958
- }
2959
- const output = readRebuildOutput(jobs, record.id);
2960
- if (output === null) {
2961
- sendJson(res, 404, {
2962
- ok: false,
2963
- error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
2964
- });
2965
- return;
2966
- }
2967
- if (!sameJob(record.state, output.view)) {
2968
- sendJson(res, 404, {
2969
- ok: false,
2970
- error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX })
3077
+ /** 探测缓存的 TTL(ms):负向条目(当时无索引)的陈旧上界,选型论证见下。 */
3078
+ const INDEX_PROBE_TTL_MS = 6e4;
3079
+ /** 探测缓存容量(条):guard 一次调用至多探 9 层祖先,32 条覆盖多工作区来回切换。 */
3080
+ const INDEX_PROBE_CACHE_MAX = 32;
3081
+ /**
3082
+ * zg 索引库存在性探测的**按目录缓存**(P2:guard 每次工具调用里 findIndexRoot 最多
3083
+ * 向上探 9 层 existsSync,同一工作区的连续调用命中的是同一串祖先目录;zg_search 的
3084
+ * 解锁路径也要再走一遍同样的上溯)。
3085
+ *
3086
+ * 失效策略选**进程内 TTL(60s)**而不是会话内不过期:正向条目(有索引)在「索引目录
3087
+ * 运行期不会消失」的假设下永不陈旧,TTL 对它只是内存有界的双保险;真正需要 TTL 的是
3088
+ * **负向**条目——zg_index 是运行期动作,新索引落地后若永不过期,门禁要到进程重启才
3089
+ * 看得见它。60s 的负向陈旧只是「索引出现前的既有行为」(grep 不被拦)的短暂延续,
3090
+ * 方向安全,且与「建索引后立刻去搜」的真实节奏相比可忽略。
3091
+ *
3092
+ * 缓存是**纯性能优化**:只替 existsSync 的答案,不改 findIndexRoot 的走法——root 不
3093
+ * 存在(probe 恒 false)、走满 maxDepth、上溯到 / 等失败路径在相同探测结果下与原实现
3094
+ * 逐分支一致。命中即触摸(delete+set 挪到队尾),配合 trimMapTo 的插入序淘汰 ⇒ LRU。
3095
+ *
3096
+ * @param probe 目录探测(生产注入 indexProbeOf;测试注入计数桩)
3097
+ * @param now 时钟注入(默认 Date.now;测试用它推进过 TTL)
3098
+ * @param ttlMs 条目存活时长(默认 {@link INDEX_PROBE_TTL_MS})
3099
+ * @param max 容量上限(默认 {@link INDEX_PROBE_CACHE_MAX})
3100
+ * @returns 与 probe 同签名的缓存化探测函数
3101
+ */
3102
+ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS, max = 32) {
3103
+ const cache = /* @__PURE__ */ new Map();
3104
+ return (dir) => {
3105
+ const at = now();
3106
+ const hit = cache.get(dir);
3107
+ if (hit !== void 0 && at - hit.probedAt < ttlMs) {
3108
+ touch(cache, dir, hit);
3109
+ return hit.result;
3110
+ }
3111
+ const result = probe(dir);
3112
+ cache.delete(dir);
3113
+ cache.set(dir, {
3114
+ result,
3115
+ probedAt: at
2971
3116
  });
2972
- return;
2973
- }
2974
- const { view, retained } = output;
2975
- const text = retained.chunks.map((chunk) => chunk.text).join("");
2976
- const shown = truncateStart(text, JOB_OUT_VIEW_CHARS);
2977
- const viewMark = text.length > JOB_OUT_VIEW_CHARS ? fill(marks.jobOutputView, {
2978
- shown: JOB_OUT_VIEW_CHARS,
2979
- total: text.length
2980
- }) : "";
2981
- sendJson(res, 200, {
2982
- ok: true,
2983
- status: view.status,
2984
- exitCode: record.proc.exitCode,
2985
- root: record.root,
2986
- ...record.proc.sandbox === void 0 ? {} : { sandbox: record.proc.sandbox },
2987
- output: (view.output.earliest > 0 ? marks.jobOutputTruncated : "") + (record.state.lost ? marks.jobOutputLost : "") + (record.state.timeoutNote ?? "") + (procSandboxNote(record.proc, marks) ?? "") + viewMark + shown
2988
- });
3117
+ evictAged(cache, max, (entry) => entry.probedAt + ttlMs, at);
3118
+ return result;
3119
+ };
2989
3120
  }
2990
3121
  /**
2991
- * 卸载效应的收口:三条路由已由调用方摘掉,这里把侧表里的进程与在册作业收干净。
2992
- * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用、文案现取)
2993
- * @returns {void}
3122
+ * 工作区白名单:只认本 daemon 真实观测过的会话工作区(重建与 root 授权共用)。
3123
+ *
3124
+ * 条目记的是**最后一次被提到**的时刻,不是第一次:白名单的用途是「这棵树刚被用过」,
3125
+ * 一直热着的键理应活得比冷键久。故 `has` 命中即触摸,淘汰先按有效期、再按最近使用。
3126
+ * 有效期是固定的 `LEDGER_TTL_MS`(一天),与解锁时效那个部署值无关——后者只有 1–240 分钟
3127
+ * 的取值域,量级差两个数量级,拿来当「这棵树多久算还在用」会短到让跨天的会话反复重新登记。
3128
+ * 上界与有效期两道都留着:上界保证常驻内存有界,有效期保证冷键不长期占位。
2994
3129
  */
2995
- function releaseRebuildRecords(routes) {
2996
- const { jobsOf, messages, records } = routes;
2997
- const unloadReason = messages().jobReasonUnload;
2998
- const jobs = jobsOf();
2999
- if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
3000
- else for (const record of records.values()) {
3001
- const view = jobView(jobs, record.id);
3002
- if (view === null || !sameJob(record.state, view)) killProc(record.proc);
3003
- else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
3004
- else jobs.remove(record.id);
3005
- }
3006
- records.clear();
3007
- }
3008
- /** 设置卡片的「工作区重建」端点组(引导 / 启动 / 轮询)。按语义拆离 apply 主体。 */
3009
- function registerRebuildEndpoints(deps) {
3010
- const { ctx, host, config, csrf, ledger, messages, rebuilds, versionGate } = deps;
3011
- const webServer = host.get("webServer");
3012
- if (!webServer) return;
3013
- const servingNonLoopback = isNonLoopbackBindHost(webServer.host);
3014
- const { jobsOf } = deps;
3015
- const { records } = deps;
3016
- const routes = {
3017
- host,
3018
- config,
3019
- csrf,
3020
- ledger,
3021
- messages,
3022
- jobsOf,
3023
- records,
3024
- rebuilds,
3025
- versionGate,
3026
- servingNonLoopback
3027
- };
3028
- const disposeRoots = webServer.register({
3029
- kind: "exact",
3030
- path: REBUILD_ROOTS_PATH,
3031
- handler: (req, res) => {
3032
- handleRebuildRoots(routes, req, res);
3033
- }
3034
- });
3035
- const disposeRebuild = webServer.register({
3036
- kind: "exact",
3037
- path: REBUILD_PATH,
3038
- handler: async (req, res) => {
3039
- await handleRebuildStart(routes, req, res);
3040
- }
3041
- });
3042
- const disposeStatus = webServer.register({
3043
- kind: "exact",
3044
- path: REBUILD_STATUS_PATH,
3045
- handler: (req, res) => {
3046
- handleRebuildStatus(routes, req, res);
3130
+ function createRootLedger(messages, max = MAX_LEDGER_ROOTS, now = Date.now, ttlMs = LEDGER_TTL_MS) {
3131
+ const seen = /* @__PURE__ */ new Map();
3132
+ return {
3133
+ add(root) {
3134
+ const key = ledgerKey(root, messages);
3135
+ if (key === void 0) return;
3136
+ touch(seen, key, now());
3137
+ evictAged(seen, max, (seenAt) => seenAt + ttlMs, now());
3138
+ },
3139
+ has(root) {
3140
+ const key = ledgerKey(root, messages);
3141
+ if (key === void 0) return false;
3142
+ const seenAt = seen.get(key);
3143
+ if (seenAt === void 0 || now() - seenAt >= ttlMs) return false;
3144
+ touch(seen, key, seenAt);
3145
+ return true;
3146
+ },
3147
+ list() {
3148
+ const at = now();
3149
+ return [...seen].filter(([, seenAt]) => at - seenAt < ttlMs).map(([root]) => root);
3047
3150
  }
3048
- });
3049
- ctx.effect(() => () => {
3050
- disposeRoots();
3051
- disposeRebuild();
3052
- disposeStatus();
3053
- releaseRebuildRecords(routes);
3054
- }, "zvec-grep: rebuild endpoints");
3151
+ };
3055
3152
  }
3056
3153
  /**
3057
3154
  * 页面策略声明:本包自带设置卡片,别让宿主再生成一份自动表单页。
@@ -3072,7 +3169,7 @@ function configureSettingsPage(host) {
3072
3169
  }
3073
3170
  /**
3074
3171
  * 文案语言随官方 locale 偏好走的读取器:用户在「设置 → 常规」里改语言后,下一次工具回显、
3075
- * guard 拒绝与端点应答就是新文案(不重启、不加本包自己的 locale 设置项)。
3172
+ * guard 拒绝与重建应答就是新文案(不重启、不加本包自己的 locale 设置项)。
3076
3173
  * 跨命名空间读在 0.1.7 只有 describe() 一条路:挑出 ns === 'locale' 那条的 value
3077
3174
  * (未装 client-locale / 该条目未被投影 → undefined → 中文默认)。
3078
3175
  * @param host 已通过服务面守卫的宿主上下文
@@ -3081,7 +3178,7 @@ function configureSettingsPage(host) {
3081
3178
  function createLocaleMessages(host) {
3082
3179
  return () => messagesFor(MESSAGES, resolveLocalePreference(host.settings.describe().find((row) => row.ns === LOCALE_SETTINGS_NAMESPACE)?.value));
3083
3180
  }
3084
- /** 观测到的工作区:既给重建端点当白名单,也让卡片能列出可重建的 root。 */
3181
+ /** 观测到的工作区:既给重建当白名单,也让卡片能列出可重建的 root。 */
3085
3182
  function trackObservedRoot(ledger, exec) {
3086
3183
  const cwd = sessionHeaderCwd(exec);
3087
3184
  if (cwd !== void 0) ledger.add(cwd);
@@ -3264,6 +3361,22 @@ function pickExhaustive(value, hasIndex) {
3264
3361
  return !hasIndex;
3265
3362
  }
3266
3363
  /**
3364
+ * 这次检索能不能用 `refresh=background`(取值语义见 lib/cli.ts 的 BackgroundSupport)。
3365
+ *
3366
+ * 要同时看两件事:**传输模式有没有被部署钉死在 direct**,以及**守护进程是否就绪**。
3367
+ * 钉死 direct 时后者根本无从生效,此时还叫用户去 `zg server on` 是指错方向;而守护进程
3368
+ * 缺席时叫他去起一个是有效的。两档各有各的文案,但判据只有这一处。
3369
+ *
3370
+ * 没人要这一档时交回 `daemon-down`——构造器只在 `refresh` 真的是 background 时才读它,
3371
+ * 于是「不为没人要的档位起一发探测」与「拿不到判据时保守拒绝」两头同时成立,不必再引入
3372
+ * 第三种「不适用」状态。探测结果与 zg_status 的回显、设置卡的引导读面共用同一份 TTL 缓存。
3373
+ */
3374
+ async function backgroundSupportFor(runtime, rawRefresh, mode, exhaustive) {
3375
+ if (exhaustive || !requestsBackgroundRefresh(rawRefresh)) return "daemon-down";
3376
+ if (mode === "direct") return "mode-direct";
3377
+ return await runtime.serverGate.ready() ? "available" : "daemon-down";
3378
+ }
3379
+ /**
3267
3380
  * zg_search 的执行体:登记工作区 → 选通道 → 构造命令 → 前台执行 → 索引通道成功才发配额。
3268
3381
  * @param runtime apply 的运行时依赖(config 现读、解锁表与探测缓存共用)
3269
3382
  * @param args 官方 deep-frozen 后的工具入参
@@ -3285,13 +3398,14 @@ async function runSearchTool(runtime, args, exec, messages) {
3285
3398
  limit: args["limit"] ?? readDefaultLimit(config)
3286
3399
  };
3287
3400
  await runtime.versionGate.ensure(messages);
3288
- const { command, workdir } = buildSearchCommand(searchArgs, messages, readClientMode(config, messages), exhaustive);
3401
+ const mode = readClientMode(config, messages);
3402
+ const { command, workdir } = buildSearchCommand(searchArgs, messages, mode, exhaustive, await backgroundSupportFor(runtime, args["refresh"], mode, exhaustive));
3289
3403
  const raw = await runForeground(host, command, workdir, config.searchTimeoutMs, {
3290
3404
  signal: exec.signal,
3291
3405
  env: zgEnv(config),
3292
3406
  stdoutMaxBytes: config.stdoutMaxBytes,
3293
3407
  messages,
3294
- summaryLimit: clampLimit(searchArgs.limit),
3408
+ summaryLimit: clampLimit(searchArgs.limit, messages),
3295
3409
  rebuildWait: {
3296
3410
  root: resolvedRoot,
3297
3411
  rebuilds: runtime.rebuilds,
@@ -3392,7 +3506,7 @@ function indexToolParameters(registered) {
3392
3506
  * 为什么不要求模型自己去起作业:宿主作业工具在 web 平面已停用,模型侧那条路根本不可走;
3393
3507
  * 插件自己复用与设置卡**完全相同**的 spawn/登记/占位三步(`spawnIndexWrite` 与
3394
3508
  * `attachIndexWrite` 是同两个函数,不是复制品),所以两条入口起的作业在名册、状态投影、
3395
- * 轮询端点上完全同形——卡片能看见模型起的重建,反之亦然。
3509
+ * 轮询读面上完全同形——卡片能看见模型起的重建,反之亦然。
3396
3510
  *
3397
3511
  * 占位在 `runIndexTool` 里、且落在第一个 await 之前就抢好了;本函数只管把已占的位接上作业号。
3398
3512
  * 三条失败出口(注册表缺席 / spawn 失败 / attach 失败)都**交还占位**再抛或答复。
@@ -3406,14 +3520,11 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages) {
3406
3520
  const routes = {
3407
3521
  host: runtime.host,
3408
3522
  config: runtime.config,
3409
- csrf: "",
3410
- ledger: runtime.ledger,
3411
3523
  messages: runtime.messages,
3412
3524
  jobsOf: runtime.jobsOf,
3413
3525
  records: runtime.records,
3414
3526
  rebuilds: runtime.rebuilds,
3415
- versionGate: runtime.versionGate,
3416
- servingNonLoopback: false
3527
+ versionGate: runtime.versionGate
3417
3528
  };
3418
3529
  if (runtime.jobsOf() === void 0) {
3419
3530
  runtime.rebuilds.release(root);
@@ -3462,23 +3573,6 @@ async function runIndexTool(runtime, args, exec, messages) {
3462
3573
  if (rewriting) rebuilds.release(root);
3463
3574
  }
3464
3575
  }
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
3576
  /** 注册 zg_index:建/重建/删索引。 */
3483
3577
  function registerIndexTool(runtime, registered) {
3484
3578
  define(runtime.host, {
@@ -3512,7 +3606,7 @@ async function runStatusTool(runtime, args, exec, messages) {
3512
3606
  root,
3513
3607
  checkReady
3514
3608
  }, messages, readClientMode(config, messages));
3515
- return { text: await runForeground(host, command, workdir, config.statusTimeoutMs, {
3609
+ return { text: `${await runForeground(host, command, workdir, config.statusTimeoutMs, {
3516
3610
  signal: exec.signal,
3517
3611
  env: zgEnv(config),
3518
3612
  stdoutMaxBytes: config.stdoutMaxBytes,
@@ -3529,9 +3623,8 @@ async function runStatusTool(runtime, args, exec, messages) {
3529
3623
  detail: failure
3530
3624
  })}` : null;
3531
3625
  } } : {}
3532
- }) };
3626
+ })}\n${await runtime.serverGate.ready() ? messages.serverReadyNote : messages.serverUnavailableNote}` };
3533
3627
  }
3534
- /** 注册 zg_status:索引状态。 */
3535
3628
  function registerStatusTool(runtime, registered) {
3536
3629
  define(runtime.host, {
3537
3630
  name: "zg_status",
@@ -3578,28 +3671,23 @@ function registerRoutingSection(host, registered) {
3578
3671
  * 于是 name/arguments/signal/agent 的键名与值域都由宿主声明负责——两个谓词收到的
3579
3672
  * 是本包加宽后的读取投影(lib/routing.ts),加宽即容错,收窄校验留在谓词内部。
3580
3673
  */
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
3674
  /** 该不该为这次调用问一句;不该问就交回 undefined(调用方转交 next())。 */
3591
3675
  function explicitRootAsk(execution, ledger, messages) {
3592
3676
  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 : {
3677
+ let question;
3678
+ if (typeof raw === "string" && raw.trim().length > 0) {
3679
+ const decision = judgeRoot(raw, sessionHeaderCwd(execution), messages, ledger);
3680
+ question = decision.allowed ? decision.question : void 0;
3681
+ }
3682
+ return question === void 0 ? void 0 : {
3595
3683
  kind: "ask",
3596
3684
  reason: fill(messages.rootApprovalReason, {
3597
- root: raw,
3598
- cwd: cwd ?? messages.rootNoSession
3685
+ root: question.root,
3686
+ cwd: question.cwd
3599
3687
  }),
3600
3688
  displayReason: {
3601
- en: fill(MESSAGES.en.rootApprovalPrompt, { root: raw }),
3602
- zh: fill(MESSAGES.zh.rootApprovalPrompt, { root: raw })
3689
+ en: fill(MESSAGES.en.rootApprovalPrompt, { root: question.root }),
3690
+ zh: fill(MESSAGES.zh.rootApprovalPrompt, { root: question.root })
3603
3691
  }
3604
3692
  };
3605
3693
  }
@@ -3612,11 +3700,14 @@ function explicitRootAsk(execution, ledger, messages) {
3612
3700
  * 用户点「允许一次」才放行;approval 服务缺席、或策略是 `never`(danger-full-access 预设 /
3613
3701
  * 委派子代理)时,宿主把 ask **确定性降级成拒绝**(core/tools 的 serviceAsk)。
3614
3702
  *
3615
- * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且那个 root 既不是本会话工作区、
3616
- * 也不在本包已登记的根集合里。也就是 rootOf() 走「互为祖先/后代」那条放行路径时——
3617
- * 会话开在 /repo/pkg 而模型要去检索 /repo,用户最该被问一句的就是这种。
3703
+ * 问的是哪一类调用:三个 zg 工具里,**显式给了 root**、且这次调用要靠 rootOf() 的
3704
+ * 「与会话工作区互为祖先/后代」那一条才放行——会话开在 /repo/pkg 而模型要去检索 /repo,
3705
+ * 用户最该被问一句的就是这种。判据与 rootOf **同源于 judgeRoot**,因此两类调用不再被误问:
3706
+ * - 注定被拒的(越界、目录不存在、解析不了、没有会话工作区可作参照):一次确认都换不来放行,
3707
+ * 弹窗只是让用户为一个无法兑现的承诺点按钮;
3708
+ * - 无需授权的(root 就是会话工作区本身、或这台 daemon 已观测过):本来就是用户自己开的路径。
3618
3709
  *
3619
- * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 不存在/越界照样被拒。
3710
+ * 这道闸**只加不减**:`rootOf` 的授权判据一字未改,root 越界照样被拒。
3620
3711
  * 用户批准只对本次调用生效,不会把那个 root 写进白名单(那是 rootOf 成功后的事)。
3621
3712
  */
3622
3713
  function registerRootApproval(runtime) {
@@ -3649,53 +3740,22 @@ function registerToolGuards(runtime) {
3649
3740
  }, messages);
3650
3741
  });
3651
3742
  }
3652
- /**
3653
- * 设置卡片的「工作区重建」端点组(引导 + 后台进程 + 轮询状态)。
3654
- *
3655
- * ⚠ 这三条路由的归属方必须对 webServer **建立依赖**,不能在 apply 里读一次就算完:
3656
- * `ctx.get` 是无 inject 语义的存储读(官方 reflect.d.ts 明写 "or `undefined`
3657
- * when not (yet) provided"),而真实宿主上 webServer 比本条目晚到位——隔离 DSH_HOME
3658
- * 实测 apply 当场读到 undefined、+1.3s 才交得出实例。旧写法的结果是三条路由在任何
3659
- * web profile 上都不注册,卡片的「工作区重建」永远 404。子 fiber 只在依赖到位时激活、
3660
- * 依赖换实例时先卸后装(registry.d.ts),故效应挂在**子上下文**上即得「后到即注册、
3661
- * 重启即重注册」。不写进插件级 inject:那会让没有 webServer 的宿主(TUI)连三个工具
3662
- * 一并失活。
3663
- * @param runtime apply 的运行时依赖(host / config / 白名单 / 文案读取器)
3664
- * @param csrf 本次 apply 生成的 CSRF token
3665
- * @returns {void}
3666
- */
3667
- function registerRebuildRoutes(runtime, csrf) {
3668
- const { config, host, ledger, messages, rebuilds, versionGate } = runtime;
3669
- host.inject(["webServer"], (child) => {
3670
- registerRebuildEndpoints({
3671
- ctx: child,
3672
- host,
3673
- config,
3674
- csrf,
3675
- ledger,
3676
- messages,
3677
- rebuilds,
3678
- jobsOf: runtime.jobsOf,
3679
- records: runtime.records,
3680
- versionGate
3681
- });
3682
- });
3683
- }
3684
3743
  function apply(ctx, config) {
3685
3744
  if (!isZvecGrepHost(ctx)) throw new Error("[zvec-grep] required services (settings/shell/tools/systemPrompt/timer/get) missing");
3686
3745
  const host = ctx;
3687
3746
  configureSettingsPage(host);
3688
3747
  const localeMessages = createLocaleMessages(host);
3689
- const csrf = randomUUID();
3748
+ const ledger = createRootLedger(localeMessages());
3690
3749
  const runtime = {
3691
3750
  host,
3692
3751
  config,
3693
3752
  messages: localeMessages,
3694
- ledger: createRootLedger(localeMessages()),
3753
+ ledger,
3695
3754
  unlocks: createUnlockLedger(config),
3696
3755
  indexProbe: createIndexProbeCache(indexProbeOf),
3697
3756
  rebuilds: createRebuildRegistry(),
3698
3757
  versionGate: createZgVersionGate(host, config),
3758
+ serverGate: createZgServerGate(host, config),
3699
3759
  jobsOf: () => host.get("jobs"),
3700
3760
  records: /* @__PURE__ */ new Map(),
3701
3761
  sessionParent: (id) => {
@@ -3709,7 +3769,17 @@ function apply(ctx, config) {
3709
3769
  registerRoutingSection(host, registered);
3710
3770
  registerToolGuards(runtime);
3711
3771
  registerRootApproval(runtime);
3712
- registerRebuildRoutes(runtime, csrf);
3772
+ installRebuildRemote(host, {
3773
+ host,
3774
+ config,
3775
+ messages: localeMessages,
3776
+ jobsOf: runtime.jobsOf,
3777
+ records: runtime.records,
3778
+ rebuilds: runtime.rebuilds,
3779
+ versionGate: runtime.versionGate,
3780
+ ledger,
3781
+ serverGate: runtime.serverGate
3782
+ });
3713
3783
  }
3714
3784
  var host_default = {
3715
3785
  inject: [