@jayyuen66/dsh-zvec-grep 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host.js CHANGED
@@ -8,7 +8,8 @@ import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from
8
8
  import { truncateEnd, truncateStart } from "@jayyuen66/dsh-plugin-shared/lib/text";
9
9
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
10
10
  import { jobOutcomeOf } from "@jayyuen66/dsh-plugin-shared/lib/job-outcome";
11
- //#region lib/embedding-catalog.ts
11
+ import path from "node:path";
12
+ // lib/embedding-catalog.ts
12
13
  /** 默认模型:本地最强(1024 维 / 8192 上下文 / 中英通用),约 640MB 一次性下载。 */
13
14
  const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
14
15
  /**
@@ -86,15 +87,14 @@ const LOCAL_EMBEDDINGS = [
86
87
  function isLocalEmbedding(reference) {
87
88
  return LOCAL_EMBEDDINGS.some((entry) => entry.reference === reference);
88
89
  }
89
- //#endregion
90
- //#region lib/messages.ts
90
+ // lib/messages.ts
91
91
  /** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
92
92
  const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
93
93
  /** 英文侧「绝对路径 + 可操作范围」那句共用文案(检索/索引两个 root 参数同义)。 */
94
94
  const ABSOLUTE_ROOT_HINT = "Absolute workspace path (optional: default = current session workspace; when passed explicitly it must stay inside this session's operable scope — the workspace itself, its parents or children, or a workspace this session already registered)";
95
95
  const MESSAGES = {
96
96
  zh: {
97
- searchToolDescription: "对已建索引的工作区做语义/混合检索(BM25+向量+RRF),用于精确查找无法回答的问题:架构、调用链、依赖、生命周期、数据流/控制流、设计意图、跨文件对比与综合。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内(会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区)。检索会自动同步既有索引的新鲜度(--refresh wait),因此改完代码无需先手动 zg_index 也能搜到新内容;但从未建索引的 root 仍会明确报错,不会静默建索引。每个命中都带**有界源码片段**(--preview short:锚点行 + 少量上下文),足够时视为已读证据,需要更多上下文再 read。精确字面/正则/文件名/报错串查找请用原生 grep/glob。大型工作区请用 globs/fileTypes 缩小范围,否则可能超时。至少提供 query/queries/fts/vector 之一。已建索引的工作区 grep/rg 受 search-first 门禁约束:每次成功的 zg_search 会为当前会话解锁 grepBudgetPerSearch 次 grep/rg(unlockWindowMin 分钟内有效),配额用尽或过期后需换一个更准确的 query/fts 重新检索。",
97
+ searchToolDescription: "对已建索引的工作区做语义/混合检索(BM25+向量+RRF),用于精确查找无法回答的问题:架构、调用链、依赖、生命周期、数据流/控制流、设计意图、跨文件对比与综合。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内(会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区)。检索会自动同步既有索引的新鲜度(--refresh wait),因此改完代码无需先手动 zg_index 也能搜到新内容;从未建索引的 root 也不会被静默建索引:调用会改走穷举词法检索,并在结果里显式声明这一点。每个命中都带**有界源码片段**(--preview short:锚点行 + 少量上下文),足够时视为已读证据,需要更多上下文再 read。精确字面/正则/文件名/报错串查找请用原生 grep/glob。大型工作区请用 globs/fileTypes 缩小范围,否则可能超时。至少提供 query/queries/fts/vector 之一。已建索引的工作区 grep/rg 受 search-first 门禁约束:每次成功的 zg_search 会为当前会话解锁 grepBudgetPerSearch 次 grep/rg(unlockWindowMin 分钟内有效),配额用尽或过期后需换一个更准确的 query/fts 重新检索。",
98
98
  indexToolDescription: "为工作区 root 创建/增量更新/重建/删除持久检索索引(建后 zg_search 才可用)。仅在用户明确要求建/重建/删索引时调用,且 confirm 必须为 true;绝不静默建索引。root 缺省为当前会话工作区;显式传入时必须落在本会话可操作范围内——会话工作区本身、它的上级或下级目录,或本会话已登记过的工作区;其余绝对路径一律拒绝(一个合法绝对路径不构成授权)。embedding 默认用设置里的 defaultEmbedding,也可显式指定,但**只接受本地候选清单内的模型**(远程 embedding 会把工作区内容送到外部端点,须由用户在部署配置里显式开放,模型侧无法开启);切换 embedding 需 rebuild=true 才重新生效。删除传 drop=true。要清掉这个根继承来的文件选择设置传 resetPaths=true。",
99
99
  statusToolDescription: "查询工作区 root 的索引状态(是否已建、文件数、freshness、活动任务)。用于索引缺失/失败/取消后的诊断或显式进度监控;普通搜索前不要调用。",
100
100
  rootSearchDescription: ABSOLUTE_ROOT_HINT_ZH,
@@ -125,7 +125,7 @@ const MESSAGES = {
125
125
  rebuildDescription: "重建已有索引(切换 embedding 时必须为 true)",
126
126
  dropDescription: "删除索引(与其它索引选项互斥)",
127
127
  ignoreFilesDescription: "额外的 ignore 文件路径(如 .gitignore 之外的排除清单),透传 zg --ignore-file",
128
- excludeSecretsDescription: "是否排除私钥/密钥库格式(*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*),默认 true。本插件的排除规则排在用户正向 glob 之后,用户规则覆盖不掉它——所以这一位是「要不要索引私钥」的唯一开关:置 false 会把这批文件灌进向量库,此后检索可以把它们回显到上下文。只有用户明确要求索引密钥夹具时才给 false",
128
+ excludeSecretsDescription: "是否排除私钥/密钥库格式(*.pem/*.key/*.p12/*.pfx/*.keystore/*.jks/*.ppk/id_rsa*),默认 true。本插件的排除规则排在用户正向 glob 之后,用户规则覆盖不掉它——所以这一位是「要不要索引私钥」的唯一开关:置 false 会把这批文件灌进向量库,此后检索可以把它们回显到上下文。只有用户明确要求索引密钥夹具时才给 false",
129
129
  hiddenDescription: "包含隐藏文件(默认不含,隐藏密钥文件因此已被排除)",
130
130
  noIgnoreDescription: "不读 ignore 文件",
131
131
  maxDepthDescription: "最大目录深度",
@@ -226,14 +226,15 @@ const MESSAGES = {
226
226
  mustBeStringArray: "{name} 必须是字符串数组",
227
227
  tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
228
228
  nonStringItem: "{name} 含非字符串项({received})",
229
- commandTooLong: "zg 命令总长 {length} 超过 {maxChars} 字符上限,请缩小检索范围",
229
+ commandTooLong: "zg 命令总长 {length} 字节,超过 {maxBytes} 字节上限,请缩小检索范围",
230
230
  tooManyQueryRoutes: "检索路由合计 {count} 组,超过 {max} 组上限",
231
231
  searchNeedsQuery: "zg_search 需要 query/queries/fts/vector 至少其一",
232
232
  exhaustiveNeedsPattern: "穷举检索(rg=true)需要一个 query 作为匹配模式",
233
233
  exhaustiveConflicts: "穷举检索(rg=true)与下列索引侧参数互斥:{names}。穷举是纯词法匹配,不支持这些参数;把它们去掉,或先建索引(zg_index)再用索引检索",
234
234
  embeddingNotAllowed: "embedding 引用 {reference} 不在本地候选清单内,而本部署未开放远程 embedding。远程 embedding 会把工作区内容送到外部端点,必须由用户在部署配置里显式开放(allowRemoteEmbedding),本插件不接受模型侧开启。可选本地模型:{choices}。若用户确已自行配好远程凭据(zg config provider set / zg auth grant <root> --capability embedding --scope workspace),请在插件部署配置里打开对应开关后重试。",
235
235
  dropWithResetPaths: "drop 与 resetPaths 互斥:--drop 整条命令只有删除索引一件事,resetPaths 无处安放(上游 zg 也拒这一对)。要清继承的文件选择设置,请不要传 drop。",
236
- ignoreFileMissing: "ignoreFiles 里的 {path} 在 {root} 下不是一份「存在且当前进程可读的文件」(不存在、是目录、或有文件但读不了都算)。上游 zg 遇到读不成的忽略文件不会按「没有这条规则」继续,而是整次索引失败(ENOENT / EISDIR / EACCES),并把这条坏路径写进工作区索引状态——此后这条树上的 zg index / zg status 都会报同一个错,--reset-paths 也清不掉,只有 zg_index drop 能救。请给一个真实存在、当前用户可读的忽略文件路径。",
236
+ dropWithIndexArgs: "drop 与这些索引侧参数互斥:{names}。--drop 整条命令只有删除索引一件事,它们不会被使用(静默收下只会让人以为过滤/重建生效了);请去掉这些参数后重发删除。",
237
+ ignoreFileMissing: "ignoreFiles 里的 {path} 不是一份「存在且当前进程可读的文件」(不存在、是目录、或有文件但读不了都算)。上游 zg 遇到读不成的忽略文件不会按「没有这条规则」继续,而是整次索引失败(ENOENT / EISDIR / EACCES),并把这条坏路径写进工作区索引状态——此后这条树上的 zg index / zg status 都会报同一个错,--reset-paths 也清不掉,只有 zg_index drop 能救。请给一个真实存在、当前用户可读的忽略文件路径。",
237
238
  exhaustiveFallbackNote: "[zvec-grep] 该工作区(含向上各级)尚无 zg 索引,已自动改用穷举词法检索(rg 模式)。结果是逐行字面匹配,不是语义相关度排序;需要语义检索请先 zg_index 建索引。",
238
239
  rgDescription: "穷举词法检索(对应 zg query --rg):不需要索引,逐行字面匹配。留空则在工作区无索引时自动改用它、有索引时照常走索引检索。显式 false 可要求只用索引检索(无索引即报错)。它不支持 preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries,且不发放 grep/rg 配额",
239
240
  intWithReceived: "{name} 必须是 >= {min} 的整数(收到 {received})",
@@ -247,8 +248,8 @@ const MESSAGES = {
247
248
  gateReason: "[zvec-grep] 工作区检索门禁({state}):当前工作区已建 zg 索引({indexRoot}/{indexDir}),直接 grep/rg 字面检索经常漏检。请先调用 zg_search(语义/混合检索,覆盖面与相关性更好;把当前检索目标作为 query/fts),每次成功的 zg_search 解锁 {budget} 次 grep/rg({windowMin} 分钟内有效),用于精确字面/正则补充。"
248
249
  },
249
250
  en: {
250
- searchToolDescription: "Semantic/hybrid search (BM25 + vector + RRF) over an indexed workspace, for questions exact lookup cannot answer: architecture, call chains, dependencies, lifecycles, data/control flow, design intent, cross-file comparison and synthesis. root defaults to the current session workspace; you may also name another already-indexed absolute path. Search refreshes the existing index automatically (--refresh wait), so code edited moments ago is searchable without re-running zg_index; a root that was never indexed still fails loudly rather than silently building an index. Every hit carries a **bounded source snippet** (--preview short: anchor line plus a little context) — treat it as read evidence when enough, otherwise read for more context. Use the native grep/glob for exact literal/regex/filename/error-string lookups. Narrow large workspaces with globs/fileTypes or the search may time out. Provide at least one of query/queries/fts/vector. In indexed workspaces grep/rg is gated by search-first: each successful zg_search unlocks grepBudgetPerSearch grep/rg calls for the current session (valid for unlockWindowMin minutes); once the quota is spent or expired, re-search with a more precise query/fts.",
251
- indexToolDescription: "Create / incrementally update / rebuild / delete the persistent search index for workspace root (zg_search only works after that). Call it only when the user explicitly asks to build/rebuild/drop the index, and confirm must be true; never index silently. root defaults to the current session workspace; another absolute path may be named explicitly (a target the user confirmed). embedding defaults to the configured defaultEmbedding and may be set explicitly, but **only models in the local catalog are accepted** (remote embedding sends workspace content to an external endpoint and must be enabled explicitly by the user in the deployment config — the model side cannot turn it on); switching embedding only takes effect with rebuild=true. Pass drop=true to delete. Pass resetPaths=true to clear the file-selection settings this root inherited.",
251
+ searchToolDescription: "Semantic/hybrid search (BM25 + vector + RRF) over an indexed workspace, for questions exact lookup cannot answer: architecture, call chains, dependencies, lifecycles, data/control flow, design intent, cross-file comparison and synthesis. root defaults to the current session workspace; you may also name another already-indexed absolute path. Search refreshes the existing index automatically (--refresh wait), so code edited moments ago is searchable without re-running zg_index; a root that was never indexed is not indexed silently either: the call switches to exhaustive literal search and says so in the result. Every hit carries a **bounded source snippet** (--preview short: anchor line plus a little context) — treat it as read evidence when enough, otherwise read for more context. Use the native grep/glob for exact literal/regex/filename/error-string lookups. Narrow large workspaces with globs/fileTypes or the search may time out. Provide at least one of query/queries/fts/vector. In indexed workspaces grep/rg is gated by search-first: each successful zg_search unlocks grepBudgetPerSearch grep/rg calls for the current session (valid for unlockWindowMin minutes); once the quota is spent or expired, re-search with a more precise query/fts.",
252
+ indexToolDescription: "Create / incrementally update / rebuild / delete the persistent search index for workspace root (zg_search only works after that). Call it only when the user explicitly asks to build/rebuild/drop the index, and confirm must be true; never index silently. root defaults to the current session workspace; another absolute path is allowed only when this session can already reach it — a workspace or a parent/child of one this session has opened, or one this session already registered — and anything else is refused (a path merely existing is not an authorization). embedding defaults to the configured defaultEmbedding and may be set explicitly, but **only models in the local catalog are accepted** (remote embedding sends workspace content to an external endpoint and must be enabled explicitly by the user in the deployment config — the model side cannot turn it on); switching embedding only takes effect with rebuild=true. Pass drop=true to delete. Pass resetPaths=true to clear the file-selection settings this root inherited.",
252
253
  statusToolDescription: "Query the index status of workspace root (indexed or not, file count, freshness, running jobs). Use it to diagnose a missing/failed/cancelled index or to watch progress explicitly; do not call it before a normal search.",
253
254
  rootSearchDescription: ABSOLUTE_ROOT_HINT,
254
255
  rootIndexDescription: ABSOLUTE_ROOT_HINT,
@@ -278,7 +279,7 @@ const MESSAGES = {
278
279
  rebuildDescription: "Rebuild the existing index (must be true when switching embedding)",
279
280
  dropDescription: "Delete the index (mutually exclusive with the other index options)",
280
281
  ignoreFilesDescription: "Extra ignore-file paths (exclusion lists beyond .gitignore), passed through as zg --ignore-file",
281
- excludeSecretsDescription: "Whether to exclude private-key/keystore formats (*.pem/*.key/*.p12/*.pfx/*.keystore/id_rsa*), default true. These exclusion rules are evaluated after user include globs, so no user glob can bring the files back: this flag is the only switch for indexing private keys, and false feeds them into the vector store, from where search can echo them back into context. Set false only when the user explicitly asks to index key fixtures",
282
+ excludeSecretsDescription: "Whether to exclude private-key/keystore formats (*.pem/*.key/*.p12/*.pfx/*.keystore/*.jks/*.ppk/id_rsa*), default true. These exclusion rules are evaluated after user include globs, so no user glob can bring the files back: this flag is the only switch for indexing private keys, and false feeds them into the vector store, from where search can echo them back into context. Set false only when the user explicitly asks to index key fixtures",
282
283
  hiddenDescription: "Include hidden files (excluded by default, which also drops hidden key files)",
283
284
  noIgnoreDescription: "Do not read ignore files",
284
285
  maxDepthDescription: "Maximum directory depth",
@@ -379,14 +380,15 @@ const MESSAGES = {
379
380
  mustBeStringArray: "{name} must be an array of strings",
380
381
  tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
381
382
  nonStringItem: "{name} contains a non-string item ({received})",
382
- commandTooLong: "the zg command is {length} characters, over the {maxChars} character limit — narrow the search",
383
+ commandTooLong: "the zg command is {length} bytes, over the {maxBytes} byte limit — narrow the search",
383
384
  tooManyQueryRoutes: "{count} query routes in total, over the limit of {max}",
384
385
  searchNeedsQuery: "zg_search needs at least one of query/queries/fts/vector",
385
386
  exhaustiveNeedsPattern: "exhaustive search (rg=true) needs a query to use as the pattern",
386
387
  exhaustiveConflicts: "exhaustive search (rg=true) conflicts with these indexed-search parameters: {names}. Exhaustive search is pure lexical matching and does not support them; drop them, or build an index first (zg_index) and search the index",
387
388
  embeddingNotAllowed: "embedding reference {reference} is not in the local catalog, and this deployment has not enabled remote embedding. Remote embedding sends workspace content to an external endpoint and must be turned on explicitly by the user in the deployment config (allowRemoteEmbedding); this plugin never lets the model side enable it. Local choices: {choices}. If the user has already set up remote credentials themselves (zg config provider set / zg auth grant <root> --capability embedding --scope workspace), enable the matching deployment setting and retry.",
388
389
  dropWithResetPaths: "drop conflicts with resetPaths: --drop does nothing but delete the index, so resetPaths has nowhere to go (upstream zg rejects the pair too). To clear inherited file-selection settings, do not pass drop.",
389
- ignoreFileMissing: "{path} under {root} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). Upstream zg does not treat a failed ignore-file read as \"no such rule\": the whole indexing run fails (ENOENT / EISDIR / EACCES) and the bad path is written into the workspace index state, after which every zg index / zg status on that tree reports the same error — even --reset-paths cannot clear it, only zg_index drop can. Give a path that really exists and that the current user can read.",
390
+ dropWithIndexArgs: "drop conflicts with these index-side parameters: {names}. --drop does nothing but delete the index, so they would never be used (accepting them silently only suggests the filters/rebuild took effect); remove them and resend the drop.",
391
+ ignoreFileMissing: "{path} is not an existing file the current process can read (missing, a directory, or present-but-unreadable all count). Upstream zg does not treat a failed ignore-file read as \"no such rule\": the whole indexing run fails (ENOENT / EISDIR / EACCES) and the bad path is written into the workspace index state, after which every zg index / zg status on that tree reports the same error — even --reset-paths cannot clear it, only zg_index drop can. Give a path that really exists and that the current user can read.",
390
392
  exhaustiveFallbackNote: "[zvec-grep] This workspace (and every directory above it) has no zg index, so the search fell back to exhaustive lexical matching (rg mode). Results are literal line matches, not ranked by semantic relevance; run zg_index first if you need semantic search.",
391
393
  rgDescription: "Exhaustive lexical search (zg query --rg): needs no index, matches literal text line by line. Leave it unset to fall back to it automatically when the workspace has no index, and to use the index when one exists. An explicit false demands indexed search only (an error when there is no index). It does not support preview / refresh / fuse / symbolTypes / preferSymbol / fts / vector / queries, and it grants no grep/rg quota",
392
394
  intWithReceived: "{name} must be an integer >= {min} (received {received})",
@@ -415,8 +417,7 @@ function fill(template, params) {
415
417
  return value === void 0 ? "" : String(value);
416
418
  });
417
419
  }
418
- //#endregion
419
- //#region lib/argv-guard.ts
420
+ // lib/argv-guard.ts
420
421
  const MAX_COMMAND_BYTES = 64e3;
421
422
  /** 单条 query 文本上限(再长属误用:zg 的语义检索按句切分)。 */
422
423
  const MAX_QUERY_CHARS = 4e3;
@@ -458,11 +459,6 @@ function optionalText(value, name, messages, maxChars) {
458
459
  function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars = MAX_FILTER_CHARS) {
459
460
  if (value === void 0 || value === null) return [];
460
461
  if (!Array.isArray(value)) throw new TypeError(fill(messages.mustBeStringArray, { name }));
461
- if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
462
- name,
463
- maxItems,
464
- actual: value.length
465
- }));
466
462
  const out = [];
467
463
  for (const item of value) {
468
464
  if (typeof item !== "string") throw new TypeError(fill(messages.nonStringItem, {
@@ -473,6 +469,11 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
473
469
  const trimmed = assertTextLen(item.trim(), name, messages, maxChars);
474
470
  if (trimmed.length > 0) out.push(trimmed);
475
471
  }
472
+ if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
473
+ name,
474
+ maxItems,
475
+ actual: value.length
476
+ }));
476
477
  return out;
477
478
  }
478
479
  /**
@@ -510,13 +511,12 @@ const SECRET_EXCLUDE_GLOBS = [
510
511
  "!*.p12",
511
512
  "!*.pfx",
512
513
  "!*.keystore",
514
+ "!*.jks",
515
+ "!*.ppk",
513
516
  "!id_rsa*",
514
517
  "!id_ed25519*"
515
518
  ];
516
- //#endregion
517
- //#region lib/cli.ts
518
- const LIMIT_MIN = 1;
519
- const LIMIT_MAX = 50;
519
+ // lib/cli.ts
520
520
  const CLIENT_MODE_NAMES = Object.keys({
521
521
  auto: "auto",
522
522
  direct: "direct",
@@ -674,8 +674,11 @@ function assertAbsoluteRoot(root, messages) {
674
674
  * root 解析:显式绝对路径优先;缺失/空串回退到 fallback(当前会话工作区,
675
675
  * 调用方从 exec.agent.session.header.cwd 取——官方 dsh-tool-fs-search 同模式)。
676
676
  * ROC 原则:fallback 也走 assertAbsoluteRoot 校验,绝不无条件接受。
677
+ * 显式的**非字符串**值不进 fallback 分支:模型写 `{root: 123}` 时若静默滑到会话工作区,
678
+ * 搜索就在模型没指定的目录上执行并交回一份「合法」结果——类型错必须当场报。
677
679
  */
678
680
  function resolveRoot(value, fallback, messages) {
681
+ if (value !== void 0 && value !== null && typeof value !== "string") throw new TypeError(fill(messages.rootMustBeString, { received: typeof value }));
679
682
  if (typeof value === "string" && value.trim().length > 0) return assertAbsoluteRoot(value.trim(), messages);
680
683
  if (typeof fallback === "string" && fallback.trim().length > 0) return assertAbsoluteRoot(fallback.trim(), messages);
681
684
  throw new Error(messages.rootRequiredWithFallback);
@@ -690,19 +693,21 @@ function clampLimit(value, messages, fallback = 10) {
690
693
  if (value === void 0 || value === null) return fallback;
691
694
  if (typeof value !== "number") throw new TypeError(messages.limitInvalid);
692
695
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(messages.limitInvalid);
693
- return Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, value));
696
+ return Math.min(50, Math.max(1, value));
694
697
  }
695
698
  /** 检索类数组(queries/fts/vector)取值:条数与单条长度都放宽到 query 档。 */
696
699
  function queryList(value, name, messages) {
697
700
  return stringList(value, name, messages, 32, MAX_QUERY_CHARS);
698
701
  }
699
- /** 整条命令的规模闸门:超 MAX_COMMAND_BYTES 即拒(防 E2BIG 与无界内存)。 */
702
+ /** 整条命令的规模闸门:按 UTF-8 字节比 MAX_COMMAND_BYTES(防 E2BIG 与无界内存)。
703
+ * 多字节内容一个码元可占 3~4 字节,按 `String.length`(码元数)比会在中文/emoji 面上
704
+ * 放过 Linux MAX_ARG_STRLEN 的单参数上限——判据必须落在内核真正收到的字节数上。 */
700
705
  function assembled(parts, workdir, messages) {
701
706
  const command = parts.join(" ");
702
- const { length } = command;
707
+ const length = Buffer.byteLength(command, "utf8");
703
708
  if (length > 64e3) throw new Error(fill(messages.commandTooLong, {
704
709
  length,
705
- maxChars: MAX_COMMAND_BYTES
710
+ maxBytes: MAX_COMMAND_BYTES
706
711
  }));
707
712
  return {
708
713
  command,
@@ -952,8 +957,32 @@ function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
952
957
  }));
953
958
  }
954
959
  /**
960
+ * drop 那一臂用不上的索引侧参数(--drop 的命令只有 `index <root> --drop --yes`)。
961
+ * 只在这里点名:出现任何一个,drop 臂整体拒绝而不是静默丢弃——布尔旗标在那之前已按
962
+ * 类型校验过、丢弃无声,其余参数连类型都没校验,两种待遇并存会让
963
+ * `{drop:true, hidden:"yes"}` 报错而 `{drop:true, maxDepth:"3"}` 静默通过。
964
+ */
965
+ const INDEX_ONLY_PARAMS = [
966
+ "rebuild",
967
+ "embedding",
968
+ "globs",
969
+ "insensitiveGlobs",
970
+ "fileTypes",
971
+ "excludedFileTypes",
972
+ "ignoreFiles",
973
+ "hidden",
974
+ "noIgnore",
975
+ "excludeSecrets",
976
+ "maxDepth",
977
+ "maxFileSizeBytes",
978
+ "follow",
979
+ "embeddingConcurrency",
980
+ "device"
981
+ ];
982
+ /**
955
983
  * 构造 zg index 命令。root 是位置参数(转义)。
956
- * - drop=true:`zg index <root> --drop --yes --mode <mode>`(非交互 shell 必须 --yes)。
984
+ * - drop=true:`zg index <root> --drop --yes --mode <mode>`(非交互 shell 必须 --yes);
985
+ * 索引侧参数与 drop 互斥(resetPaths 另有单独互斥文案),出现即点名拒绝。
957
986
  * - 否则:`zg index <root> --embedding <m> [--rebuild] ... --mode <mode>`。
958
987
  * embedding 缺省时由调用方传入 defaultEmbedding(设置里的默认值);显式值过构造期
959
988
  * allowlist(见 indexEmbedding)。
@@ -973,6 +1002,8 @@ function buildIndexCommand(args, defaultEmbedding, messages, mode = DEFAULT_CLIE
973
1002
  const flags = readIndexFlags(args, messages);
974
1003
  if (boolOf(args.drop, "drop", messages)) {
975
1004
  if (boolOf(args.resetPaths, "resetPaths", messages)) throw new Error(messages.dropWithResetPaths);
1005
+ const ignored = INDEX_ONLY_PARAMS.filter((name) => args[name] !== void 0 && args[name] !== null);
1006
+ if (ignored.length > 0) throw new Error(fill(messages.dropWithIndexArgs, { names: ignored.join(" | ") }));
976
1007
  parts.push("--drop", "--yes", modeFlag(mode));
977
1008
  return assembled(parts, root, messages);
978
1009
  }
@@ -1007,8 +1038,7 @@ function buildStatusCommand(args, messages, mode = DEFAULT_CLIENT_MODE) {
1007
1038
  parts.push(modeFlag(mode));
1008
1039
  return assembled(parts, root, messages);
1009
1040
  }
1010
- //#endregion
1011
- //#region lib/search-predicates.ts
1041
+ // lib/search-predicates.ts
1012
1042
  const GREP_COMMAND_NAMES = /* @__PURE__ */ new Set([
1013
1043
  "grep",
1014
1044
  "egrep",
@@ -1036,6 +1066,44 @@ const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
1036
1066
  "nice",
1037
1067
  "parallel"
1038
1068
  ]);
1069
+ /**
1070
+ * 包装命令里「带一个取值」的选项:其后那一个 token 是它的值,不是被执行的命令
1071
+ * (`sudo -u root grep`、`nice -n 10 rg`、`timeout -s 9 5 rg`)。
1072
+ *
1073
+ * 跨包装命令共用一张表:这些短选项在 git/xargs/env/sudo/time/nice/timeout 里
1074
+ * 语义一致,逐个包装登记一份只会让「加了新包装却忘了登记」多一处可能。
1075
+ */
1076
+ const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Set([
1077
+ "-a",
1078
+ "-c",
1079
+ "-C",
1080
+ "-d",
1081
+ "-E",
1082
+ "-f",
1083
+ "-g",
1084
+ "-I",
1085
+ "-k",
1086
+ "-L",
1087
+ "-n",
1088
+ "-o",
1089
+ "-p",
1090
+ "-P",
1091
+ "-r",
1092
+ "-s",
1093
+ "-t",
1094
+ "-T",
1095
+ "-u",
1096
+ "-U",
1097
+ "--adjustment",
1098
+ "--group",
1099
+ "--kill-after",
1100
+ "--signal",
1101
+ "--user"
1102
+ ]);
1103
+ /** 命令前的壳层赋值(`VAR=1 grep x` 里的 `VAR=1`):它自己不是命令,其后仍是命令位。 */
1104
+ const SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
1105
+ /** 包装命令的裸数值参数(`timeout 5 rg` 的 `5`):也不是被执行的命令。 */
1106
+ const BARE_NUMBER = /^\d+$/u;
1039
1107
  /** 结束一个 token、但**不**开启新命令位的字符(空白、右括号、重定向)。 */
1040
1108
  const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
1041
1109
  " ",
@@ -1119,7 +1187,8 @@ function tokenizeShell(command) {
1119
1187
  else if (COMMAND_BREAK_CHARS.has(char)) {
1120
1188
  flush();
1121
1189
  state.atCommand = true;
1122
- state.pipedNext = char === "|";
1190
+ const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
1191
+ state.pipedNext = char === "|" && !neighbourIsPipe;
1123
1192
  } else if (TOKEN_BREAK_CHARS.has(char)) flush();
1124
1193
  else state.buffer += char;
1125
1194
  index += 1;
@@ -1127,22 +1196,40 @@ function tokenizeShell(command) {
1127
1196
  flush();
1128
1197
  return tokens;
1129
1198
  }
1130
- /** token 的命令名(basename,小写);`-*` 选项一律不算命令名(返回空串)。 */
1199
+ /**
1200
+ * token 的命令名(basename,小写)。
1201
+ * 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
1202
+ * (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
1203
+ * 永远走不到的分支。
1204
+ */
1131
1205
  function baseName(text) {
1132
- if (text.startsWith("-")) return "";
1133
1206
  return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
1134
1207
  }
1135
1208
  /**
1136
1209
  * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
1137
- * env…)之后的第一个实参。
1210
+ * env…)之后那个真正的实参。
1211
+ *
1212
+ * 「包装命令之后」不是「紧邻的下一个 token」:包装命令自己的选项(`git --no-pager`、
1213
+ * `xargs -0`)、选项取值(`sudo -u root`)、裸数值(`timeout 5`)、壳层赋值(`VAR=1`)
1214
+ * 都还站在命令位之前。只认「紧邻下一个」时命令位链在这些形态上直接断掉,检索调用
1215
+ * 漏判 —— 而漏判的方向是门禁放行。这几类一律「跳过但不断链」。
1138
1216
  */
1139
1217
  function commandPositionIndexes(tokens) {
1140
1218
  const out = [];
1141
1219
  let afterPrefix = false;
1220
+ let pendingValue = false;
1142
1221
  for (const [index, token] of tokens.entries()) {
1222
+ const { text } = token;
1143
1223
  const isCommand = token.atCommand || afterPrefix;
1144
- if (isCommand) out.push(index);
1145
- afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(token.text));
1224
+ if (pendingValue) {
1225
+ pendingValue = false;
1226
+ afterPrefix = true;
1227
+ } else if (isCommand && VALUE_TAKING_FLAGS.has(text)) pendingValue = true;
1228
+ else if (isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text))) afterPrefix = true;
1229
+ else {
1230
+ if (isCommand) out.push(index);
1231
+ afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(text));
1232
+ }
1146
1233
  }
1147
1234
  return out;
1148
1235
  }
@@ -1187,9 +1274,16 @@ function isGrepRgCommand(command) {
1187
1274
  return !(token.piped && !hasPathOperand(tokens, index));
1188
1275
  });
1189
1276
  }
1190
- /** 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。 */
1191
- function normalizeRoot(path) {
1192
- const trimmed = path.replace(/\/+$/u, "");
1277
+ /**
1278
+ * 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。
1279
+ *
1280
+ * 只认 `/`:本包的根判据(`assertAbsoluteRoot` 只收 `/` 开头的串)、命令 tokenizer 与
1281
+ * `rootPaths` 覆盖判据都按 POSIX 形切分,root 归一化再多认一种分隔符只会让上游认得出、
1282
+ * 下游判不回——README 的 Support surface 一节写明 Windows 主机不在支持面内,
1283
+ * 失败形态是 fail-fast 而不是静默漂移。要真正支持 Windows,得连上面那三处判据一起改。
1284
+ */
1285
+ function normalizeRoot(root) {
1286
+ const trimmed = root.replace(/\/+$/u, "");
1193
1287
  return trimmed.length > 0 ? trimmed : "/";
1194
1288
  }
1195
1289
  /**
@@ -1212,7 +1306,8 @@ function pathInsideRoot(target, root, messages) {
1212
1306
  } catch {
1213
1307
  return false;
1214
1308
  }
1215
- return absolute === base || absolute.startsWith(`${base}/`);
1309
+ const prefix = base.endsWith("/") ? base : `${base}/`;
1310
+ return absolute === base || absolute.startsWith(prefix);
1216
1311
  }
1217
1312
  /**
1218
1313
  * bash/pwsh 命令串中是否存在「索引根之外」的路径证据。
@@ -1256,8 +1351,7 @@ function unlockActive(unlock, now) {
1256
1351
  function pathsRelated(left, right, messages) {
1257
1352
  return pathInsideRoot(left, right, messages) || pathInsideRoot(right, left, messages);
1258
1353
  }
1259
- //#endregion
1260
- //#region lib/routing.ts
1354
+ // lib/routing.ts
1261
1355
  /** 紧跟 TOOL_GREP(1500) 之后、TOOL_JOBS(1600) 之前。 */
1262
1356
  const ROUTING_ORDER = 1550;
1263
1357
  const ROUTING_NAME = "zvec-grep-routing";
@@ -1347,11 +1441,13 @@ const WORKSPACE_MANIFEST_FILE = "manifest.json";
1347
1441
  * 从 startDir 向上找含 zg 索引库的最近祖先(含自身),返回该索引根。
1348
1442
  * 会话工作区可能是索引根的子目录(如索引在仓库根、会话开在子包)——不向上走
1349
1443
  * 会漏拦。probe 注入(宿主用 existsSync),本函数保持纯函数可单测。
1444
+ * 相对路径无从向上判(祖先链不是文件系统事实),按「探测不到」处理:返回 undefined,
1445
+ * 与「上一层没有索引」同形,门禁按无索引放行。
1350
1446
  */
1351
1447
  function findIndexRoot(startDir, probe, maxDepth = 8) {
1352
1448
  let dir = normalizeRoot(startDir);
1353
1449
  let found;
1354
- for (let depth = 0; depth <= maxDepth; depth += 1) {
1450
+ if (startDir.startsWith("/")) for (let depth = 0; depth <= maxDepth; depth += 1) {
1355
1451
  if (probe(dir)) {
1356
1452
  found = dir;
1357
1453
  break;
@@ -1393,7 +1489,13 @@ function rootSessionKeyOf(execution, lookup) {
1393
1489
  let cursor = parent;
1394
1490
  for (let hop = 0; hop < 32; hop += 1) {
1395
1491
  if (lookup === void 0) return cursor;
1396
- const next = lookup(cursor)?.parentSession;
1492
+ let parentView;
1493
+ try {
1494
+ parentView = lookup(cursor);
1495
+ } catch {
1496
+ parentView = void 0;
1497
+ }
1498
+ const next = parentView?.parentSession;
1397
1499
  if (typeof next !== "string" || next.length === 0 || seen.has(next)) return cursor;
1398
1500
  seen.add(next);
1399
1501
  cursor = next;
@@ -1401,26 +1503,26 @@ function rootSessionKeyOf(execution, lookup) {
1401
1503
  return cursor;
1402
1504
  }
1403
1505
  /**
1404
- * search-first 门禁(硬约束):拦截对象为
1405
- * - bash/pwsh:命令串里出现 grep/rg 检索调用(isGrepRgCommand),且目标未被
1406
- * hasExternalTarget 判定为索引根之外;
1407
- * - 原生 grep 工具:检索目标位于会话工作区内(path 出界不属工作区检索,放行)。
1408
- * 会话工作区(含祖先)存在 zg 索引且当前无可用解锁额度(从未 zg_search、配额
1409
- * 用尽或已过期)→ 拒绝并给出可行动出路。解锁额度按「会话 × 索引根」计,
1410
- * 每次成功的 zg_search 重置为 N 次、M 分钟有效——保证语义检索频率与 grep
1411
- * 用量成正比,而不是一次放行终身豁免。
1412
- * 已知近似:bash 自由文本无法可靠区分模式与相对路径 token,hasExternalTarget
1413
- * 只认明确的路径形状,`../` 形态的模式词可能被误判为外部目标而放行(漏拦,
1414
- * 安全方向);混合目标(如 `rg foo /repo/src /tmp/x`)整体放行。
1415
- */
1416
- /**
1417
- * 索引根已定后的门禁裁决:无索引根 / 检索索引根之外 / 有可扣额度 → 放行
1418
- * (undefined);否则返回拦截文案。放行会触发 consumeGrep 副作用。
1506
+ * 原生 grep 面的目标是否落在索引根之内。相对路径先按**会话工作区**解析成绝对路径,
1507
+ * 再按索引根判内外——按索引根直接拼相对段会把 `../other` 拼进索引根内部,方向判反。
1508
+ * `..` 越出文件系统根:目标必然不在索引根之内(判范围不判合法性,同 pathInsideRoot)。
1419
1509
  */
1420
- function buildSearchFirstReason(cwd, command, deps, messages) {
1421
- const indexRoot = findIndexRoot(cwd, deps.indexProbe);
1510
+ function nativeTargetInsideRoot(cwd, indexRoot, target, messages) {
1511
+ if (target === void 0 || target.trim().length === 0) return true;
1512
+ const text = target.trim();
1513
+ const joined = text.startsWith("/") ? text : `${normalizeRoot(cwd)}/${text}`;
1514
+ let absolute;
1515
+ try {
1516
+ absolute = normalizeAbsolutePath(joined, messages);
1517
+ } catch {
1518
+ return false;
1519
+ }
1520
+ return pathInsideRoot(absolute, indexRoot, messages);
1521
+ }
1522
+ function buildSearchFirstReason(cwd, scope, deps, messages) {
1523
+ const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
1422
1524
  let reason;
1423
- if (indexRoot !== void 0 && (command === void 0 || !hasExternalTarget(indexRoot, command, messages))) {
1525
+ if (indexRoot !== void 0 && (scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages))) {
1424
1526
  const rebuilding = deps.rebuildBypass?.(indexRoot) === true;
1425
1527
  const unlock = rebuilding ? void 0 : deps.lookupUnlock(indexRoot);
1426
1528
  if (rebuilding) {} else if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
@@ -1447,14 +1549,20 @@ function buildSearchFirstReason(cwd, command, deps, messages) {
1447
1549
  function shellSearchProblem(args, cwd, deps, messages) {
1448
1550
  const commandRaw = args["command"];
1449
1551
  const command = typeof commandRaw === "string" ? commandRaw : "";
1450
- return isGrepRgCommand(command) ? buildSearchFirstReason(cwd, command, deps, messages) : void 0;
1552
+ return isGrepRgCommand(command) ? buildSearchFirstReason(cwd, {
1553
+ kind: "shell",
1554
+ command
1555
+ }, deps, messages) : void 0;
1451
1556
  }
1452
1557
  /**
1453
- * 原生 grep 工具面的一次检索裁决:`path` 出界 = 不是本工作区的检索 → 放行
1558
+ * 原生 grep 工具面的一次检索裁决:目标在索引根之外 = 不是本工作区的检索 → 放行
1454
1559
  * (与 pathInsideRoot 的「判范围不判合法性」同侧)。无 path 参数按搜整个工作区。
1455
1560
  */
1456
1561
  function nativeGrepProblem(args, cwd, deps, messages) {
1457
- return pathInsideRoot(typeof args["path"] === "string" ? args["path"] : void 0, cwd, messages) ? buildSearchFirstReason(cwd, void 0, deps, messages) : void 0;
1562
+ return buildSearchFirstReason(cwd, {
1563
+ kind: "native",
1564
+ target: typeof args["path"] === "string" ? args["path"] : void 0
1565
+ }, deps, messages);
1458
1566
  }
1459
1567
  /**
1460
1568
  * search-first 门禁入口。
@@ -1475,22 +1583,20 @@ function searchFirstGuard(execution, deps, messages) {
1475
1583
  return reason;
1476
1584
  }
1477
1585
  /**
1478
- * 容量上限:超过就淘汰若干条目,但**绝不淘汰已经交出作业号的那条**。
1586
+ * 表超过阈值就报警一次(不删任何条目)。
1479
1587
  *
1480
- * 为什么:淘汰会把条目从表里删掉并兑现它的 `settled`——对一条真在跑的重建来说,那等于
1481
- * 告诉所有等待者「结束了」,而它的 zg 其实还在写这棵树的索引。表一空,下一条 claim 就会
1482
- * 成功,于是两条 `zg index` 同时啃一份索引,撞上 zg 的写锁直接失败——那正是这个注册表
1483
- * 存在的理由。官方作业注册表本身就把同时在跑的作业数卡在一个很小的量级,所以「全部都是
1484
- * running、淘汰不动」时表短暂超限是无害的,内存依然有界。
1588
+ * 为什么只报不删:见 MAX_TRACKED_REBUILDS 的注释——两个阶段都可能有真在跑的 zg,
1589
+ * 淘汰就是造孤儿。真正该做的是让「有一次 claim 没配对 release」这件事被人看见。
1590
+ * 只在刚越过阈值那一刻报一次(回落之后才重新武装),否则每次 claim 都刷一行。
1591
+ * @param entries 活跃表
1592
+ * @param max 阈值
1593
+ * @param alreadyCrowded 上一次判定为「已越阈值」
1594
+ * @returns 本次是否越阈值(供调用方回写状态)
1485
1595
  */
1486
- function trimToMax(entries, max, keep) {
1487
- for (const [root, entry] of entries) {
1488
- if (entries.size <= max) return;
1489
- if (entry !== keep && entry.jobId === void 0) {
1490
- entries.delete(root);
1491
- entry.settle();
1492
- }
1493
- }
1596
+ function warnIfCrowded(entries, max, alreadyCrowded) {
1597
+ if (entries.size <= max) return false;
1598
+ if (!alreadyCrowded) console.warn(`[zvec-grep] 活跃重建表有 ${String(entries.size)} 条,超过阈值 ${String(max)}:这不是容量淘汰(淘汰会让正在跑的重建失去占位,同根就能起第二条 zg),而是有一次 claim 没配对 release —— 请把这段告警连同调用场景报给维护者。`);
1599
+ return true;
1494
1600
  }
1495
1601
  /**
1496
1602
  * 覆盖给定 root 的那条活跃条目:重建根是 root 的祖先或同一处时命中,多条命中取
@@ -1509,11 +1615,13 @@ function createRebuildRegistry(options = {}) {
1509
1615
  const now = options.now ?? Date.now;
1510
1616
  const maxTracked = options.maxTracked ?? 32;
1511
1617
  const entries = /* @__PURE__ */ new Map();
1618
+ let crowded = false;
1512
1619
  const release = (root) => {
1513
1620
  const entry = entries.get(root);
1514
1621
  if (entry === void 0) return false;
1515
1622
  entries.delete(root);
1516
1623
  entry.settle();
1624
+ if (entries.size <= maxTracked) crowded = false;
1517
1625
  return true;
1518
1626
  };
1519
1627
  return {
@@ -1533,7 +1641,7 @@ function createRebuildRegistry(options = {}) {
1533
1641
  settle
1534
1642
  };
1535
1643
  entries.set(root, entry);
1536
- trimToMax(entries, maxTracked, entry);
1644
+ crowded = warnIfCrowded(entries, maxTracked, crowded);
1537
1645
  return entry;
1538
1646
  },
1539
1647
  attach(root, jobId) {
@@ -1582,16 +1690,28 @@ function createRebuildRegistry(options = {}) {
1582
1690
  }
1583
1691
  /** 索引重建与其它占用者分开:等与不等是两回事。 */
1584
1692
  const REBUILD_OPERATION = "index.rebuild";
1585
- /** zg 明细块的键值行。键与值都命名捕获,避免按下标取。 */
1586
- const DETAIL_LINE = /^\s*(?<key>[A-Za-z][A-Za-z0-9]*):\s*(?<value>.+?)\s*$/u;
1587
- /** 输出里的错误码行。 */
1588
- const CODE_LINE = /^\s*Code:\s*(?<code>\S+)\s*$/mu;
1693
+ /**
1694
+ * zg 明细块的键值行。三个细节都来自「明细行是缩进的」这一实测形状:
1695
+ * - 缩进**必填**(`\s+`):明细块之后任何含冒号的非空行(第二个错误块的 `Error:` /
1696
+ * `Code:`、尾注 `Hint:`)都不该被当成明细键收进表,与已知键同名时会污染判断;
1697
+ * - 键字符集放宽到字母开头 + `[\w-]`:上游若改用 `owner_operation` 这类拼写,行至少
1698
+ * 还能被认出来(值是否被消费由查表侧决定),不至于整块收集在此中断;
1699
+ * - 值必须以非空白开头:把只含空白的行当成有效值没有意义。
1700
+ */
1701
+ const DETAIL_LINE = /^(?:\s+)(?<key>[A-Za-z][\w-]*):\s*(?<value>\S.*?)\s*$/u;
1702
+ /** 错误码行的**定位**形状(只认行首,不核内容)。 */
1703
+ const CODE_LINE_PREFIX = /^\s*Code:/u;
1704
+ /** 错误码行的**取值**形状:`Code:` 之后是单一 token。 */
1705
+ const CODE_LINE = /^\s*Code:\s*(?<code>\S+)\s*$/u;
1589
1706
  /**
1590
1707
  * 抽错误码。没有该行就不是 zg 的结构化失败(旁路返回 null,交给通用失败文案)。
1591
- * 只取第一处:一次失败只应有一个码,取多个说明输出形状已变,宁可不判。
1708
+ * 先定位第一条 `Code:` 行、再核它的内容是否为单一 token:一次失败只应有一个码,
1709
+ * 首处写成 `Code: XXX (detail)` 说明输出形状已变——宁可不判,也不许顺延到后文
1710
+ * 捞一个可能属于别的错误块的码回来。
1592
1711
  */
1593
1712
  function zgErrorCode(stderr) {
1594
- return CODE_LINE.exec(stderr)?.groups?.["code"];
1713
+ const firstCodeLine = stderr.split("\n").find((line) => CODE_LINE_PREFIX.test(line));
1714
+ return firstCodeLine === void 0 ? void 0 : CODE_LINE.exec(firstCodeLine)?.groups?.["code"];
1595
1715
  }
1596
1716
  /**
1597
1717
  * 明细块的键值表。`Details:` 之后的缩进行才是明细,标题与错误码行不参与。
@@ -1637,22 +1757,26 @@ function classifyConcurrentFailure(stderr) {
1637
1757
  };
1638
1758
  return null;
1639
1759
  }
1640
- //#endregion
1641
- //#region lib/zg-version.ts
1642
- /** 本包按之书写的 zg 语义版本。低于它一律在命令构造前拒绝。 */
1643
- const MINIMUM_ZG_VERSION = "0.2.2";
1760
+ // lib/zg-version.ts
1644
1761
  /**
1645
- * 形状:整串就是一个三段数字版本,可带前后的空白与换行。
1646
- * 刻意不接受 `v0.2.2` / `0.2.2-rc.1` / `>=0.2.2` 这类——真出现了就说明输出形态变了,
1647
- * 那属于「读不懂」,归到 undefined 由调用方按「探测不到」处理。
1762
+ * 门槛本体:比较用的对象是唯一事实来源,回显用的字符串由它派生——两处在编译期
1763
+ * 就不可能漂移,改门槛只改这一个字面量。
1648
1764
  */
1649
- const VERSION_SHAPE = /^\s*(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)\s*$/u;
1650
- /** 门槛值本身就是常量,拿它自己当被测对象即可(写成字面量免去一次可失败的解析)。 */
1651
1765
  const MINIMUM = {
1652
1766
  major: 0,
1653
1767
  minor: 2,
1654
1768
  patch: 2
1655
1769
  };
1770
+ /** 本包按之书写的 zg 语义版本(字面形态,给文案回显)。低于它一律在命令构造前拒绝。 */
1771
+ const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
1772
+ /**
1773
+ * 形状:整串就是一个三段数字版本,`v` 前缀可有可无,可带前后的空白与换行。
1774
+ * 分量至多 9 位数字:`Number()` 对超长数字串会丢精度乃至得到 Infinity,畸形输入
1775
+ * 会被当成「版本极大」而放行——把「读不懂」当成「够新」是 fail-open。仍不接受
1776
+ * `0.2.2-rc.1` / `>=0.2.2` / 带标题前缀这类——真出现了就说明输出形态变了,那属于
1777
+ * 「读不懂」,归到 undefined 由调用方按「探测不到」处理。
1778
+ */
1779
+ const VERSION_SHAPE = /^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;
1656
1780
  /**
1657
1781
  * 不是版本号时用的哨兵:版本分量恒非负,故负数只可能来自「没解析出来」。
1658
1782
  * 三个函数都收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
@@ -1695,8 +1819,25 @@ function tooOldZgVersion(stdout) {
1695
1819
  const parsed = parseZgVersion(stdout);
1696
1820
  return parsed === void 0 || versionAtLeast(parsed, MINIMUM) ? void 0 : parsed;
1697
1821
  }
1698
- //#endregion
1699
- //#region lib/index-preflight.ts
1822
+ // lib/index-preflight.ts
1823
+ /**
1824
+ * 预检判「文件不合适」时接受的家庭错误码:其余(fd 耗尽、链接环、IO 错误等环境故障)
1825
+ * 与用户给的路径无关,原样上抛——把 EMFILE 说成「请给一个真实存在的文件」会把排查
1826
+ * 引向错误的方向。
1827
+ */
1828
+ const UNUSABLE_FILE_CODES = /* @__PURE__ */ new Set([
1829
+ "ENOENT",
1830
+ "EACCES",
1831
+ "EISDIR",
1832
+ "ENOTDIR"
1833
+ ]);
1834
+ /** node:fs 的失败一律是带 string code 的 Error 实例;形状不合(非对象、无 code、码非串)
1835
+ * 一律按环境故障处理。导出只为把非 Error 形状的判别面钉进单测(真 fs 抛不出这些)。 */
1836
+ function isUnusableFileCode(error) {
1837
+ if (typeof error !== "object" || error === null || !("code" in error)) return false;
1838
+ const code = error.code;
1839
+ return typeof code === "string" && UNUSABLE_FILE_CODES.has(code);
1840
+ }
1700
1841
  /**
1701
1842
  * `ignoreFiles` 的可用性预检:模型给的第 N 条忽略文件必须是**当前进程读得了的普通文件**。
1702
1843
  *
@@ -1708,70 +1849,97 @@ function tooOldZgVersion(stdout) {
1708
1849
  * 分支会让 CI 的 windows 那格在 100% 覆盖率门禁下无从而钉(本仓不用 coverage-ignore 逃生口)。
1709
1850
  * 合成一句「不是存在且可读的文件」文案,三种成因都准确覆盖,且 catch 由「不存在」这一档跨平台钉住。
1710
1851
  *
1711
- * drop 那一臂整段跳过:`--drop` 的命令只有 `zg index <root> --drop --yes`,ignoreFiles 被
1712
- * buildIndexCommand 静默丢掉、根本不进 zg(见 lib/cli.ts 的 drop 分支),预检它没有意义,还会
1713
- * 拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。判 drop 用与构造器**同一个**
1714
- * `boolOf`,两处口径不会漂。
1852
+ * drop 那一臂整段跳过:drop 的命令不含 ignoreFiles,且构造器对「drop 携带索引侧参数」会
1853
+ * 点名拒绝(见 lib/cli.ts 的 buildIndexCommand)——预检既没有可查的对象,也没有机会跑到;
1854
+ * 若照跑,反而会拿"给一个真实存在的忽略文件"这句误导文案把一次合法的删索引拦下。
1855
+ * 判 drop 用与构造器**同一个** `boolOf`,两处口径不会漂。
1715
1856
  * @param args 索引入参(`ignoreFiles` 单值或数组;`drop` 为真时整段跳过)
1716
1857
  * @param root 已归一的工作区根(相对路径按它解析)
1717
1858
  * @param messages 文案表
1718
1859
  * @returns {void}
1719
- * @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项)
1860
+ * @throws Error 指向第一个不可用的条目(不静默丢弃用户给的那一项);node:fs 的环境类
1861
+ * 故障(非文件形状问题)原样上抛
1720
1862
  */
1721
1863
  function assertIgnoreFilesExist(args, root, messages) {
1722
1864
  if (boolOf(args.drop, "drop", messages)) return;
1723
1865
  for (const entry of singleOrList(args.ignoreFiles, "ignoreFiles", messages)) {
1724
- const target = entry.startsWith("/") ? entry : `${root}/${entry}`;
1866
+ const target = path.isAbsolute(entry) ? entry : path.resolve(root, entry);
1725
1867
  let usable = false;
1726
1868
  try {
1727
1869
  accessSync(target, constants.R_OK);
1728
1870
  usable = statSync(target).isFile();
1729
- } catch {}
1730
- if (!usable) throw new Error(fill(messages.ignoreFileMissing, {
1731
- path: entry,
1732
- root
1733
- }));
1871
+ } catch (error) {
1872
+ if (!isUnusableFileCode(error)) throw error;
1873
+ }
1874
+ if (!usable) throw new Error(fill(messages.ignoreFileMissing, { path: target }));
1734
1875
  }
1735
1876
  }
1736
- //#endregion
1737
- //#region lib/sandbox-note.ts
1738
- /** 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。 */
1877
+ // lib/sandbox-note.ts
1878
+ /**
1879
+ * 沙箱事实的公共后缀(把 mode/enforcement 一并交代清楚,避免只说「被拒」)。
1880
+ * enforcement 只认非空串:经序列化/反序列化的运行态数据可能交回空串,拼进模板
1881
+ * 会产出「enforcement=」这类残缺后缀——缺席与空白同归「不交代」。
1882
+ */
1739
1883
  function sandboxFacts(info, messages) {
1740
- const enforcement = info.enforcement === void 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
1884
+ const enforcement = info.enforcement === void 0 || info.enforcement.length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
1741
1885
  return fill(messages.sandboxFacts, {
1742
1886
  mode: info.mode,
1743
1887
  enforcement
1744
1888
  });
1745
1889
  }
1890
+ /**
1891
+ * 把「事实后缀」填进一条模板的统一入口:本文件与 host.ts 的 runnerFailed 共用,
1892
+ * 新增失败类别时漏掉 `sandboxFacts` 包裹或参数名写错都会在编译期红。
1893
+ */
1894
+ function noteWithFacts(template, info, messages) {
1895
+ return fill(template, { facts: sandboxFacts(info, messages) });
1896
+ }
1746
1897
  /** 沙箱策略拒绝的可读说明(拒绝 ≠ 崩溃:既用于失败消息,也用于成功但残缺的结果)。 */
1747
1898
  function deniedNote(info, messages) {
1748
- return fill(messages.sandboxDenied, { facts: sandboxFacts(info, messages) });
1899
+ return noteWithFacts(messages.sandboxDenied, info, messages);
1749
1900
  }
1750
1901
  /**
1751
1902
  * 后台进程的沙箱事实提示。runner 失败 / 策略拒绝都不许被显示成「完成」:
1752
1903
  * dsh-shell 只在有沙箱的执行器下填 proc.sandbox,读了它才能把「zg 自己失败」
1753
1904
  * 与「zg 根本没跑起来」分开。
1905
+ *
1906
+ * 分支次序是刻意的:runnerFailed 优先于 denied——runner 都没起来时 zg 未被执行,
1907
+ * 策略根本没有可拒绝的动作,denied 那一位在那一档不成立;调整次序会无声改变
1908
+ * 同时携带两位时的归因。
1754
1909
  */
1755
1910
  function procSandboxNote(proc, messages) {
1756
1911
  const info = proc.sandbox;
1757
1912
  if (info === void 0) return null;
1758
- if (info.runnerFailed === true) return fill(messages.rebuildRunnerFailed, { facts: sandboxFacts(info, messages) });
1913
+ if (info.runnerFailed === true) return noteWithFacts(messages.rebuildRunnerFailed, info, messages);
1759
1914
  if (info.denied) return fill(messages.rebuildDenied, { denied: deniedNote(info, messages) });
1760
1915
  return null;
1761
1916
  }
1762
- //#endregion
1763
- //#region lib/rebuild-shape.ts
1917
+ // lib/rebuild-shape.ts
1764
1918
  /** 宿主服务键 = 客户端线上命名空间(两侧共用的唯一来源)。 */
1765
1919
  const REBUILD_REMOTE_NAMESPACE = "zvecGrepRebuild";
1766
- //#endregion
1767
- //#region lib/zg-config.ts
1920
+ // lib/zg-config.ts
1921
+ /** http(s) 且带 host 的基地址才算端点:`http://`、`/` 这类值不是可用的镜像基地址。 */
1922
+ function isUsableBaseUrl(value) {
1923
+ try {
1924
+ const parsed = new URL(value);
1925
+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.hostname !== "";
1926
+ } catch {
1927
+ return false;
1928
+ }
1929
+ }
1768
1930
  /** 各环境读一个 HF 镜像/代理基地址的优先级:显式入参 > 设置。
1769
1931
  * `typeof` 判断是 host 侧兜底:值域正常时 schema 的 `.default()` 已保证是字符串,
1770
- * 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。 */
1932
+ * 引用被交回 undefined(条目未投影/宿主退化)时宁可不带 env,也不发一个空 HF_ENDPOINT。
1933
+ * 规范化(剥尾斜杠)之后还要再验一次:`/`、`///` 会被剥成空串,`http://` 这类没有
1934
+ * host 的值也不是基地址——发一个空的或畸形的 HF_ENDPOINT 只会把失败推迟到
1935
+ * node-llama-cpp 的下载期,定位成本远高于这里的一次静默省略。 */
1771
1936
  function hfEndpointEnv(config) {
1772
1937
  const endpoint = config.hfEndpoint.get();
1773
1938
  let env;
1774
- if (typeof endpoint === "string" && endpoint.trim().length > 0) env = { HF_ENDPOINT: endpoint.trim().replace(/\/+$/u, "") };
1939
+ if (typeof endpoint === "string") {
1940
+ const normalized = endpoint.trim().replace(/\/+$/u, "");
1941
+ if (normalized.length > 0 && isUsableBaseUrl(normalized)) env = { HF_ENDPOINT: normalized };
1942
+ }
1775
1943
  return env;
1776
1944
  }
1777
1945
  /**
@@ -1793,6 +1961,12 @@ function allowRemoteEmbedding(config) {
1793
1961
  return config.allowRemoteEmbedding;
1794
1962
  }
1795
1963
  /**
1964
+ * 远程凭据走的环境变量名形状:常规标识符。名字不受约束等于允许行 config 把宿主进程里
1965
+ * 任意变量(含与 zg 无关的敏感值)转发给子进程;`__proto__` / `constructor` 这类键还会
1966
+ * 让 `process.env[name]` 读到对象而不是字符串。不匹配的名字按「没配」处理。
1967
+ */
1968
+ const ENV_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*$/u;
1969
+ /**
1796
1970
  * zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding 时的)远程端点与凭据。
1797
1971
  *
1798
1972
  * **密钥只走环境变量,绝不进 argv**。两道原因,都是实测/读源码得来的:
@@ -1815,7 +1989,8 @@ function zgEnv(config) {
1815
1989
  const endpoint = trimmedConfigString(config.remoteEmbeddingEndpoint);
1816
1990
  if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
1817
1991
  const keyName = trimmedConfigString(config.remoteEmbeddingApiKeyFrom);
1818
- const secret = (keyName === void 0 ? void 0 : process.env[keyName])?.trim();
1992
+ const key = keyName !== void 0 && ENV_NAME_SHAPE.test(keyName) ? process.env[keyName] : void 0;
1993
+ const secret = typeof key === "string" ? key.trim() : void 0;
1819
1994
  if (secret !== void 0 && secret.length > 0) env["ZVEC_GREP_API_KEY"] = secret;
1820
1995
  }
1821
1996
  return Object.keys(env).length > 0 ? env : void 0;
@@ -1833,8 +2008,7 @@ function readDefaultEmbedding(config) {
1833
2008
  function readClientMode(config, messages) {
1834
2009
  return clientModeOf(config.clientMode, messages);
1835
2010
  }
1836
- //#endregion
1837
- //#region lib/rebuild-remote.ts
2011
+ // lib/rebuild-remote.ts
1838
2012
  /** 本包作业的 kind(宿主据此发出的 id 形如 `zvec-grep-rebuild-<hex>`)。 */
1839
2013
  const REBUILD_JOB_KIND = "zvec-grep-rebuild";
1840
2014
  /**
@@ -2106,11 +2280,11 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2106
2280
  killProc(proc);
2107
2281
  },
2108
2282
  done: (async () => {
2109
- await proc.done;
2110
- cancelKillTimer();
2111
2283
  try {
2284
+ await proc.done;
2112
2285
  return jobOutcomeOf(proc);
2113
2286
  } finally {
2287
+ cancelKillTimer();
2114
2288
  routes.rebuilds.release(root);
2115
2289
  }
2116
2290
  })()
@@ -2185,7 +2359,15 @@ function attachIndexWrite(routes, root, started, spawned) {
2185
2359
  status: 503
2186
2360
  };
2187
2361
  }
2188
- pruneRebuildHistory(starting, records);
2362
+ try {
2363
+ pruneRebuildHistory(starting, records);
2364
+ } catch (error) {
2365
+ killProc(proc);
2366
+ return {
2367
+ error: startupFailureText(error, started),
2368
+ status: 500
2369
+ };
2370
+ }
2189
2371
  const state = {
2190
2372
  identity: {
2191
2373
  kind: REBUILD_JOB_KIND,
@@ -2224,11 +2406,13 @@ function releaseRebuildRecords(deps) {
2224
2406
  const unloadReason = messages().jobReasonUnload;
2225
2407
  const jobs = jobsOf();
2226
2408
  if (jobs === void 0) for (const record of records.values()) killProc(record.proc);
2227
- else for (const record of records.values()) {
2409
+ else for (const record of records.values()) try {
2228
2410
  const view = jobView(jobs, record.id);
2229
2411
  if (view === null || !sameJob(record.state, view)) killProc(record.proc);
2230
2412
  else if (isLiveStatus(view.status)) jobs.kill(record.id, void 0, unloadReason);
2231
2413
  else jobs.remove(record.id);
2414
+ } catch {
2415
+ killProc(record.proc);
2232
2416
  }
2233
2417
  records.clear();
2234
2418
  }
@@ -2412,8 +2596,7 @@ function installRebuildRemote(ctx, deps) {
2412
2596
  }, "zvec-grep: rebuild records");
2413
2597
  return true;
2414
2598
  }
2415
- //#endregion
2416
- //#region host.ts
2599
+ // host.ts
2417
2600
  const SEARCH_TIMEOUT_MS = 3e5;
2418
2601
  const STATUS_TIMEOUT_MS = 6e4;
2419
2602
  const INDEX_TIMEOUT_MS = 6e5;
@@ -2498,7 +2681,7 @@ const TEXT_OUTPUT_SCHEMA = {
2498
2681
  function sandboxFailure(result, messages) {
2499
2682
  const info = result.sandbox;
2500
2683
  if (info?.runnerFailed !== true) return null;
2501
- return fill(messages.runnerFailed, { facts: sandboxFacts(info, messages) });
2684
+ return noteWithFacts(messages.runnerFailed, info, messages);
2502
2685
  }
2503
2686
  /** 错误详情:首尾各留一段(zg/cargo 等错误的最终原因常在尾部)。
2504
2687
  * 两半各用一个函数,因为是两种缺陷:头切点会留下孤立**高**代理(`truncateEnd` 丢掉它),
@@ -3782,5 +3965,4 @@ var host_default = {
3782
3965
  Config: configSchema,
3783
3966
  apply
3784
3967
  };
3785
- //#endregion
3786
3968
  export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };