@jayyuen66/dsh-zvec-grep 0.1.9 → 0.1.11

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
@@ -19,16 +19,7 @@ const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
19
19
  * 而不是静默产出一个不在联合里的字符串。
20
20
  */
21
21
  const TRANSFORMERS_JS_BACKEND = "transformers-js";
22
- /**
23
- * 本地候选清单,按后端分三档(体积/语言口径,实测 zg v0.2.1):
24
- * - llama-cpp:qwen3-embedding-0.6b 约 640MB(本包默认)、
25
- * embeddinggemma-300m 约 300MB(英文)——两档都要原生件,Metal 加速由 zg 侧 device=auto 试;
26
- * - model2vec:potion-code-16m-v2 约 32MB(代码专用、最轻最快)、potion-multilingual-128m
27
- * (多语言轻量)、potion-retrieval-32m(通用检索)——纯 JS worker,零原生依赖;
28
- * - transformers-js:其余 ONNX 小模型,384 维那批是英文/多语言轻量档,768 维那批里
29
- * jina 面向代码、gte/nomic 面向 8192 长文。
30
- */
31
- const LOCAL_EMBEDDINGS = [
22
+ const LOCAL_EMBEDDINGS = Object.freeze([
32
23
  {
33
24
  reference: "local/qwen3-embedding-0.6b",
34
25
  backend: "llama-cpp",
@@ -84,14 +75,15 @@ const LOCAL_EMBEDDINGS = [
84
75
  backend: TRANSFORMERS_JS_BACKEND,
85
76
  dimension: 768
86
77
  }
87
- ];
78
+ ].map((entry) => Object.freeze(entry)));
88
79
  function isLocalEmbedding(reference) {
89
- return LOCAL_EMBEDDINGS.some((entry) => entry.reference === reference);
80
+ const normalized = reference.trim();
81
+ return LOCAL_EMBEDDINGS.some((entry) => entry.reference === normalized);
90
82
  }
91
83
  // lib/messages.ts
92
84
  /** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
93
85
  const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
94
- /** 英文侧「绝对路径 + 可操作范围」那句共用文案(检索/索引两个 root 参数同义)。 */
86
+ /** 英文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义)。 */
95
87
  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)";
96
88
  const MESSAGES = {
97
89
  zh: {
@@ -227,6 +219,7 @@ const MESSAGES = {
227
219
  limitInvalid: "limit 必须是非负整数(省略则用默认值)",
228
220
  limitOutOfRange: "limit 超出允许范围 {min}–{max}(省略则用默认值)",
229
221
  mustBeStringArray: "{name} 必须是字符串数组",
222
+ mustBeStringOrArray: "必须是字符串或字符串数组",
230
223
  tooManyItems: "{name} 最多 {maxItems} 项(实际 {actual})",
231
224
  nonStringItem: "{name} 含非字符串项({received})",
232
225
  commandTooLong: "zg 命令总长 {length} 字节,超过 {maxBytes} 字节上限,请缩小检索范围",
@@ -251,7 +244,7 @@ const MESSAGES = {
251
244
  gateReason: "[zvec-grep] 工作区检索门禁({state}):当前工作区已建 zg 索引({indexRoot}/{indexDir}),直接 grep/rg 字面检索经常漏检。请先调用 zg_search(语义/混合检索,覆盖面与相关性更好;把当前检索目标作为 query/fts),每次成功的 zg_search 解锁 {budget} 次 grep/rg({windowMin} 分钟内有效),用于精确字面/正则补充。"
252
245
  },
253
246
  en: {
254
- 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.",
247
+ 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; an explicit one must fall inside this session's operable range — the session workspace itself, a root the daemon has already observed, or an ancestor/descendant of the session workspace (the result then says which relation was used). A path being absolute, or already indexed, is not authorization by itself. 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.",
255
248
  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.",
256
249
  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.",
257
250
  rootSearchDescription: ABSOLUTE_ROOT_HINT,
@@ -382,6 +375,7 @@ const MESSAGES = {
382
375
  rootRequiredWithFallback: "root is required and must be an absolute workspace path (it may be omitted: defaults to the current session workspace)",
383
376
  limitInvalid: "limit must be a non-negative integer (omit it to use the default)",
384
377
  limitOutOfRange: "limit is out of the allowed range {min}–{max} (omit it to use the default)",
378
+ mustBeStringOrArray: "must be a string or an array of strings",
385
379
  mustBeStringArray: "{name} must be an array of strings",
386
380
  tooManyItems: "{name} allows at most {maxItems} items (actual {actual})",
387
381
  nonStringItem: "{name} contains a non-string item ({received})",
@@ -418,7 +412,7 @@ const MESSAGES = {
418
412
  */
419
413
  function fill(template, params) {
420
414
  return template.replaceAll(/\{(?<key>\w+)\}/gu, (_all, key) => {
421
- const value = params[key];
415
+ const value = Object.hasOwn(params, key) ? params[key] : void 0;
422
416
  return value === void 0 ? "" : String(value);
423
417
  });
424
418
  }
@@ -474,10 +468,10 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
474
468
  const trimmed = assertTextLen(item.trim(), name, messages, maxChars);
475
469
  if (trimmed.length > 0) out.push(trimmed);
476
470
  }
477
- if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
471
+ if (out.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
478
472
  name,
479
473
  maxItems,
480
- actual: value.length
474
+ actual: out.length
481
475
  }));
482
476
  return out;
483
477
  }
@@ -491,6 +485,7 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
491
485
  * 其余类型错误(非字符串、非数组的其它值)仍然照旧报错,不做任何静默降级。
492
486
  */
493
487
  function singleOrList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars = MAX_FILTER_CHARS) {
488
+ if (value !== void 0 && value !== null && typeof value !== "string" && !Array.isArray(value)) throw new TypeError(fill(messages.mustBeStringOrArray, { name }));
494
489
  return stringList(typeof value === "string" ? [value] : value, name, messages, maxItems, maxChars);
495
490
  }
496
491
  /**
@@ -738,15 +733,15 @@ function pushQueryArgs(parts, args, messages) {
738
733
  routeCount += 1;
739
734
  }
740
735
  for (const query of queryList(args.queries, "queries", messages)) {
741
- parts.push("--hybrid", shq(query));
736
+ parts.push(`--hybrid=${shq(query)}`);
742
737
  routeCount += 1;
743
738
  }
744
739
  for (const query of queryList(args.fts, "fts", messages)) {
745
- parts.push("--fts", shq(query));
740
+ parts.push(`--fts=${shq(query)}`);
746
741
  routeCount += 1;
747
742
  }
748
743
  for (const query of queryList(args.vector, "vector", messages)) {
749
- parts.push("--vector", shq(query));
744
+ parts.push(`--vector=${shq(query)}`);
750
745
  routeCount += 1;
751
746
  }
752
747
  if (routeCount > 32) throw new Error(fill(messages.tooManyQueryRoutes, {
@@ -790,8 +785,8 @@ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
790
785
  if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
791
786
  if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
792
787
  const refresh = refreshOf(args.refresh, messages);
788
+ if (refresh === "background" && mode === "direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
793
789
  if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
794
- if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
795
790
  parts.push("--limit", String(resolveLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
796
791
  pushSearchGlobs(parts, args, messages);
797
792
  if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
@@ -961,7 +956,7 @@ function pushIndexResetPathsFlag(parts, args, messages) {
961
956
  function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
962
957
  const given = optionalText(args.embedding, "embedding", messages, MAX_FILTER_CHARS);
963
958
  if (given.length === 0) return defaultEmbedding;
964
- if (isLocalEmbedding(given) || allowRemote) return given;
959
+ if (isLocalEmbedding(given) || allowRemote) return given.trim();
965
960
  throw new Error(fill(messages.embeddingNotAllowed, {
966
961
  reference: given,
967
962
  choices: LOCAL_EMBEDDINGS.map((entry) => entry.reference).join(" | ")
@@ -1068,6 +1063,26 @@ const PROBE_FLAGS = /* @__PURE__ */ new Set([
1068
1063
  * 包装/前缀命令:其首个实参本身就是「被执行的命令」,同样算命令位
1069
1064
  * (`git grep`、`… | xargs grep TODO`、`env rg foo` 都是真检索)。
1070
1065
  */
1066
+ /**
1067
+ * 壳层包装命令:它们 `-c` 后面那一枚参数本身就是「要被执行的命令」,
1068
+ * 不看进去就等于 `bash -c 'grep -r secret /'` 凭一层引号绕过门禁。
1069
+ *
1070
+ * 与 SEARCH_PREFIX_WORDS 分开列:那里的包装是「首个实参是被执行的命令」,
1071
+ * 这里要多走一步——先认 `-c` 这类旗标,再把它后面那枚参数当脚本递归判一次。
1072
+ */
1073
+ const SHELL_WRAPPER_NAMES = /* @__PURE__ */ new Set([
1074
+ "sh",
1075
+ "bash",
1076
+ "zsh",
1077
+ "dash",
1078
+ "ksh",
1079
+ "csh",
1080
+ "fish"
1081
+ ]);
1082
+ /** 壳层旗标里「其后一枚参数是脚本」的那些:`-c`、`-lc`、`-xc`(只认以 c 收尾的短旗标)。 */
1083
+ const SHELL_SCRIPT_FLAG = /^-[^c]*c$/u;
1084
+ /** 递归深度上限:一层脚本里的再一层脚本够了;更深的不判(也不该有)。 */
1085
+ const MAX_SHELL_DEPTH = 2;
1071
1086
  const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
1072
1087
  "git",
1073
1088
  "xargs",
@@ -1080,62 +1095,193 @@ const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
1080
1095
  "parallel"
1081
1096
  ]);
1082
1097
  /**
1083
- * 包装命令里「带一个取值」的选项:其后那一个 token 是它的值,不是被执行的命令
1084
- * (`sudo -u root grep`、`nice -n 10 rg`、`timeout -s 9 5 rg`)。
1098
+ * 包装命令里「带一个取值」的选项,按包装命令分表(键 = 包装命令的 basename)。
1099
+ * 其后那一个 token 是它的值,不是被执行的命令(`sudo -u root grep`、`nice -n 10 rg`、
1100
+ * `timeout -s 9 5 rg`)。
1085
1101
  *
1086
- * 跨包装命令共用一张表:这些短选项在 git/xargs/env/sudo/time/nice/timeout 里
1087
- * 语义一致,逐个包装登记一份只会让「加了新包装却忘了登记」多一处可能。
1102
+ * **必须分表**:同一枚短选项在不同包装下语义不同——`nice -n 10`、`xargs -n 5` 的 `-n`
1103
+ * 吃取值,而 `sudo -n`(non-interactive)、`time -p`(POSIX 输出)、`git -p`(--paginate)、
1104
+ * `xargs -r/-t/-p` 都不吃。共用一张表会把紧随其后的真命令当成取值吞掉,命令位链断开,
1105
+ * 于是 `sudo -n grep foo`、`time -p grep x`、`find … | xargs -r grep TODO` 全部判成
1106
+ * 「不是检索」——漏判的方向就是门禁放行。
1107
+ * 未登记的包装(nohup 没有取值旗标)落空表,无需登记。
1108
+ */
1109
+ const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Map([
1110
+ ["git", /* @__PURE__ */ new Set([
1111
+ "-c",
1112
+ "-C",
1113
+ "--git-dir",
1114
+ "--work-tree",
1115
+ "--namespace",
1116
+ "--super-prefix",
1117
+ "--config-env"
1118
+ ])],
1119
+ ["xargs", /* @__PURE__ */ new Set([
1120
+ "-a",
1121
+ "-d",
1122
+ "-E",
1123
+ "-I",
1124
+ "-L",
1125
+ "-n",
1126
+ "-P",
1127
+ "-s",
1128
+ "--arg-file",
1129
+ "--delimiter",
1130
+ "--eof",
1131
+ "--max-args",
1132
+ "--max-chars",
1133
+ "--max-lines",
1134
+ "--max-procs",
1135
+ "--process-slot-var",
1136
+ "--replace"
1137
+ ])],
1138
+ ["env", /* @__PURE__ */ new Set([
1139
+ "-u",
1140
+ "-C",
1141
+ "-S",
1142
+ "--unset",
1143
+ "--chdir",
1144
+ "--split-string"
1145
+ ])],
1146
+ ["sudo", /* @__PURE__ */ new Set([
1147
+ "-u",
1148
+ "-g",
1149
+ "-C",
1150
+ "-D",
1151
+ "-h",
1152
+ "-p",
1153
+ "-r",
1154
+ "-t",
1155
+ "-T",
1156
+ "-U",
1157
+ "-R",
1158
+ "--user",
1159
+ "--group",
1160
+ "--close-from",
1161
+ "--chdir",
1162
+ "--host",
1163
+ "--prompt",
1164
+ "--role",
1165
+ "--type",
1166
+ "--command-timeout",
1167
+ "--other-user",
1168
+ "--chroot"
1169
+ ])],
1170
+ ["time", /* @__PURE__ */ new Set([
1171
+ "-f",
1172
+ "-o",
1173
+ "--format",
1174
+ "--output"
1175
+ ])],
1176
+ ["timeout", /* @__PURE__ */ new Set([
1177
+ "-s",
1178
+ "-k",
1179
+ "--signal",
1180
+ "--kill-after"
1181
+ ])],
1182
+ ["nice", /* @__PURE__ */ new Set(["-n", "--adjustment"])],
1183
+ ["parallel", /* @__PURE__ */ new Set([
1184
+ "-j",
1185
+ "-S",
1186
+ "-n",
1187
+ "--jobs",
1188
+ "--sshlogin",
1189
+ "--sshloginfile",
1190
+ "--joblog",
1191
+ "--results",
1192
+ "--tmpdir",
1193
+ "--delay",
1194
+ "--max-args"
1195
+ ])]
1196
+ ]);
1197
+ /**
1198
+ * grep/rg 自己的「带一个取值」选项:其后那个 token 是模式(`-e foo`)、glob(`-g *.ts`)、
1199
+ * 编码名(`-E utf-8`)……不是检索目标。判「目标是否在根外」时要跳过它——否则
1200
+ * `grep -f /tmp/patterns .`、`rg --glob /tmp/x foo .` 里的取值会被当成根外证据,
1201
+ * 门禁直接放行(实测过的绕过形态)。
1202
+ * 取 grep 与 rg 的并集:多跳一枚在本函数里只可能导致「少认一个目标」,方向是**多拦**,
1203
+ * 不构成放行。
1088
1204
  */
1089
- const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Set([
1090
- "-a",
1091
- "-c",
1205
+ const SEARCH_VALUE_FLAGS = /* @__PURE__ */ new Set([
1206
+ "-e",
1207
+ "-f",
1208
+ "-g",
1209
+ "-m",
1210
+ "-A",
1211
+ "-B",
1092
1212
  "-C",
1093
1213
  "-d",
1214
+ "-D",
1094
1215
  "-E",
1095
- "-f",
1096
- "-g",
1097
- "-I",
1098
- "-k",
1099
- "-L",
1100
- "-n",
1101
- "-o",
1102
- "-p",
1103
- "-P",
1216
+ "-j",
1217
+ "-M",
1104
1218
  "-r",
1105
- "-s",
1106
1219
  "-t",
1107
1220
  "-T",
1108
- "-u",
1109
- "-U",
1110
- "--adjustment",
1111
- "--group",
1112
- "--kill-after",
1113
- "--signal",
1114
- "--user"
1221
+ "--regexp",
1222
+ "--file",
1223
+ "--glob",
1224
+ "--iglob",
1225
+ "--type",
1226
+ "--type-not",
1227
+ "--max-count",
1228
+ "--after-context",
1229
+ "--before-context",
1230
+ "--context",
1231
+ "--directories",
1232
+ "--devices",
1233
+ "--encoding",
1234
+ "--threads",
1235
+ "--max-columns",
1236
+ "--max-depth",
1237
+ "--max-filesize",
1238
+ "--replace",
1239
+ "--sort",
1240
+ "--sortr",
1241
+ "--include",
1242
+ "--exclude",
1243
+ "--exclude-from",
1244
+ "--exclude-dir",
1245
+ "--include-dir",
1246
+ "--label",
1247
+ "--pre",
1248
+ "--pre-glob",
1249
+ "--ignore-file"
1115
1250
  ]);
1116
1251
  /** 命令前的壳层赋值(`VAR=1 grep x` 里的 `VAR=1`):它自己不是命令,其后仍是命令位。 */
1117
1252
  const SHELL_ASSIGNMENT = /^[A-Za-z_]\w*=/u;
1118
1253
  /** 包装命令的裸数值参数(`timeout 5 rg` 的 `5`):也不是被执行的命令。 */
1119
1254
  const BARE_NUMBER = /^\d+$/u;
1120
- /** 结束一个 token、但**不**开启新命令位的字符(空白、右括号、重定向)。 */
1255
+ /** 结束一个 token、但**不**开启新命令位的字符(空白)。 */
1121
1256
  const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
1122
1257
  " ",
1123
1258
  " ",
1124
1259
  "\v",
1125
- "\f",
1126
- ")",
1127
- "<",
1128
- ">"
1260
+ "\f"
1129
1261
  ]);
1130
- /** 结束一个 token 并让紧随其后的 token 处于命令位(控制符 / 换行 / 反引号 / 组)。 */
1262
+ /** 结束一个 token 并让紧随其后的 token 处于命令位(控制符 / 换行 / 反引号)。 */
1131
1263
  const COMMAND_BREAK_CHARS = /* @__PURE__ */ new Set([
1132
1264
  "|",
1133
1265
  ";",
1134
1266
  "&",
1135
- "(",
1136
1267
  "\n",
1137
1268
  "\r",
1138
- "`",
1269
+ "`"
1270
+ ]);
1271
+ /**
1272
+ * 重定向符:其后那一个 token 是 I/O 目标(`> /tmp/out`、`< /tmp/in`),不是检索操作数。
1273
+ * 判「目标是否在根外」时必须跳过它——否则 `grep foo src > /tmp/out` 会凭一个输出文件
1274
+ * 被判成「检索根外目标」而放行。
1275
+ */
1276
+ const REDIRECT_CHARS = /* @__PURE__ */ new Set(["<", ">"]);
1277
+ /**
1278
+ * 组字符:只有在**独立成词**(buffer 为空)时才是分隔——`(subshell)`、`{ group; }`
1279
+ * 之后是新的命令位。词中的它们属参数展开 / 命令替换(`${DIR}/src`、`$(pwd)/src`),
1280
+ * 必须并进当前 token:切成独立伪 token 会让 `/src` 这类片段被当成绝对路径证据而放行。
1281
+ */
1282
+ const GROUP_CHARS = /* @__PURE__ */ new Set([
1283
+ "(",
1284
+ ")",
1139
1285
  "{",
1140
1286
  "}"
1141
1287
  ]);
@@ -1158,12 +1304,121 @@ function indexAfterComment(command, from) {
1158
1304
  return nextLine === -1 ? command.length : nextLine - 1;
1159
1305
  }
1160
1306
  /**
1307
+ * 控制符(`|` `;` `&` 换行 反引号)之后:新命令位开始,并记下「下一段是否吃上一段的 stdout」。
1308
+ *
1309
+ * 只有单个 `|` 把上一段的 stdout 接进下一段的 stdin;`;`、`&&`、`||` 之后的命令不是
1310
+ * (`||` 的后半段恰恰是「前半段没产出时才跑」的那条,输入不是 stdout)。`||` 由两个竖线
1311
+ * 字符分别进来,前一枚与后一枚都必须判成「不是管道」。
1312
+ */
1313
+ function markCommandBreak(command, index, char, state) {
1314
+ state.atCommand = true;
1315
+ const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
1316
+ state.pipedNext = char === "|" && !neighbourIsPipe;
1317
+ }
1318
+ /**
1319
+ * 独立成词的组字符才分隔(`(subshell)` / `{ group; }`):`(` 与 `{` 之后是新命令位;
1320
+ * 词中的它们是展开的一部分(`${DIR}/src`、`$(pwd)/src`),并进当前 token。
1321
+ */
1322
+ function consumeGroupChar(char, state) {
1323
+ if (state.buffer.length > 0) state.buffer += char;
1324
+ else if (char === "(" || char === "{") state.atCommand = true;
1325
+ }
1326
+ /**
1327
+ * `$(` 是命令替换的开头:`$` 已经是 buffer 的全部(引号外)时,这一对字符不是词内展开。
1328
+ *
1329
+ * 不拆开的话 `$(grep x y)` 只能切出一枚 `$(grep` token——它对不上任何检索命令名,
1330
+ * 门禁就凭一层括号放行(与注释里那几条“实测过的绕过形态”同一类)。`${DIR}/src` 不受影响:
1331
+ * 那里跟在 `$` 后面的是 `{`,仍按词内展开并进当前 token。
1332
+ */
1333
+ function isCommandSubstitutionOpen(char, state) {
1334
+ return char === "(" && state.quote === "" && state.buffer === "$";
1335
+ }
1336
+ /** 引号外、词首的 `#` 起为注释(整段跳到行尾)。 */
1337
+ function isCommentStart(char, state) {
1338
+ return state.quote === "" && char === "#" && state.buffer.length === 0;
1339
+ }
1340
+ /**
1341
+ * 词中开/闭引号(grep'rg')合并进同一 token:混淆写法照拦。
1342
+ * 走到这里的 char 只可能是「空」或「与 quote 同种」(异种引号在更上面的分支已被当作
1343
+ * 字面量吃进 buffer),故一个三元即覆盖开/闭两种情形。
1344
+ */
1345
+ function toggleQuote(char, quote) {
1346
+ return quote === char ? "" : char;
1347
+ }
1348
+ /** 包装命令的旗标、裸数值、壳层赋值:都不是被执行的命令,也不结束命令位链。 */
1349
+ function isWrapperNoiseText(isCommand, text) {
1350
+ return isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text));
1351
+ }
1352
+ /**
1353
+ * 明确的路径形状:绝对路径、含 `/` 的相对路径、裸 `.` 与 `..`(模式词与文件名不算)。
1354
+ * `.` 与 `..` 都算:`grep foo .` 检索的就是当前工作区。
1355
+ */
1356
+ function isPathShape(text) {
1357
+ return text.startsWith("/") || text.includes("/") || text === "." || text === "..";
1358
+ }
1359
+ /**
1360
+ * token 的命令名(basename,小写)。
1361
+ * 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
1362
+ * (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
1363
+ * 永远走不到的分支。
1364
+ */
1365
+ function baseName(text) {
1366
+ return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
1367
+ }
1368
+ /**
1369
+ * 把一枚 token 推进命令位链(纯函数:不改入参,返回下一状态与「这枚是不是命令」)。
1370
+ *
1371
+ * 单独成函数不为复用,只为把这条含 3 层嵌套的判定链从循环里挪出来——循环里只剩
1372
+ * 「推进一步、命中就记下标」两件事。
1373
+ */
1374
+ function advanceCommandChain(token, state) {
1375
+ const { text } = token;
1376
+ const consumingValue = state.pendingValue;
1377
+ const next = {
1378
+ ...state,
1379
+ pendingValue: false
1380
+ };
1381
+ if (consumingValue) next.afterPrefix = true;
1382
+ else if (token.atCommand) {
1383
+ next.wrapper = "";
1384
+ next.afterPrefix = false;
1385
+ }
1386
+ const isCommand = token.atCommand || next.afterPrefix || next.wrapper !== "";
1387
+ const takesValue = isCommand && VALUE_TAKING_FLAGS.get(next.wrapper)?.has(text) === true;
1388
+ if (consumingValue && !token.atCommand) return {
1389
+ state: next,
1390
+ command: false
1391
+ };
1392
+ if (takesValue) {
1393
+ next.pendingValue = true;
1394
+ return {
1395
+ state: next,
1396
+ command: false
1397
+ };
1398
+ }
1399
+ if (isWrapperNoiseText(isCommand, text)) {
1400
+ next.afterPrefix = true;
1401
+ return {
1402
+ state: next,
1403
+ command: false
1404
+ };
1405
+ }
1406
+ if (isCommand) next.wrapper = SEARCH_PREFIX_WORDS.has(baseName(text)) ? baseName(text) : "";
1407
+ next.afterPrefix = false;
1408
+ return {
1409
+ state: next,
1410
+ command: isCommand
1411
+ };
1412
+ }
1413
+ /**
1161
1414
  * 手写 shell 切词(只为「找出命令位上的命令名」服务,不做完整求值):
1162
1415
  * - 单/双引号与反斜杠转义**内部**的字符不参与分隔 → `echo "grep x"`、
1163
1416
  * `printf 'grep'`、`git commit -m "use rg"` 里的字面量不再被当成命令
1164
1417
  * (旧实现把引号当分隔符,故这三种全被判为检索 → 过度拦截);
1165
1418
  * - 引号外、词首的 `#` 起为注释,整段跳到行尾;
1166
- * - 控制符(`|` `;` `&` `(` 换行 反引号 `{` `}`)之后的 token 记为命令位。
1419
+ * - 控制符(`|` `;` `&` 换行 反引号)与**独立成词**的 `(` / `{` 之后的 token 记为
1420
+ * 命令位;词中的组字符属参数展开 / 命令替换(`${DIR}/src`、`$(pwd)/src`),并进当前 token;
1421
+ * - 重定向符(`<` `>`)之后的那一个 token 标记为 `redirect`:它是 I/O 落点,不是检索操作数。
1167
1422
  * 双引号内保留字面内容(含空格),故 `"/usr/bin/rg foo"` 是一个非命令位 token。
1168
1423
  */
1169
1424
  function tokenizeShell(command) {
@@ -1172,6 +1427,7 @@ function tokenizeShell(command) {
1172
1427
  buffer: "",
1173
1428
  atCommand: true,
1174
1429
  pipedNext: false,
1430
+ redirectNext: false,
1175
1431
  quote: ""
1176
1432
  };
1177
1433
  const flush = () => {
@@ -1179,11 +1435,13 @@ function tokenizeShell(command) {
1179
1435
  tokens.push({
1180
1436
  text: state.buffer,
1181
1437
  atCommand: state.atCommand,
1182
- piped: state.pipedNext
1438
+ piped: state.pipedNext,
1439
+ redirect: state.redirectNext
1183
1440
  });
1184
1441
  state.buffer = "";
1185
1442
  state.atCommand = false;
1186
1443
  state.pipedNext = false;
1444
+ state.redirectNext = false;
1187
1445
  }
1188
1446
  };
1189
1447
  let index = 0;
@@ -1194,14 +1452,20 @@ function tokenizeShell(command) {
1194
1452
  state.buffer += char;
1195
1453
  escaped = false;
1196
1454
  } else if (isQuotedLiteral(char, state.quote)) state.buffer += char;
1197
- else if (state.quote === "" && char === "#" && state.buffer.length === 0) index = indexAfterComment(command, index);
1455
+ else if (isCommentStart(char, state)) index = indexAfterComment(command, index);
1198
1456
  else if (char === "\\") escaped = true;
1199
- else if (QUOTE_CHARS.has(char)) state.quote = state.quote === char ? "" : char;
1457
+ else if (QUOTE_CHARS.has(char)) state.quote = toggleQuote(char, state.quote);
1200
1458
  else if (COMMAND_BREAK_CHARS.has(char)) {
1201
1459
  flush();
1202
- state.atCommand = true;
1203
- const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
1204
- state.pipedNext = char === "|" && !neighbourIsPipe;
1460
+ markCommandBreak(command, index, char, state);
1461
+ } else if (isCommandSubstitutionOpen(char, state)) {
1462
+ state.buffer = "";
1463
+ flush();
1464
+ markCommandBreak(command, index, char, state);
1465
+ } else if (GROUP_CHARS.has(char)) consumeGroupChar(char, state);
1466
+ else if (REDIRECT_CHARS.has(char)) {
1467
+ flush();
1468
+ state.redirectNext = true;
1205
1469
  } else if (TOKEN_BREAK_CHARS.has(char)) flush();
1206
1470
  else state.buffer += char;
1207
1471
  index += 1;
@@ -1210,15 +1474,6 @@ function tokenizeShell(command) {
1210
1474
  return tokens;
1211
1475
  }
1212
1476
  /**
1213
- * token 的命令名(basename,小写)。
1214
- * 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
1215
- * (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
1216
- * 永远走不到的分支。
1217
- */
1218
- function baseName(text) {
1219
- return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
1220
- }
1221
- /**
1222
1477
  * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
1223
1478
  * env…)之后那个真正的实参。
1224
1479
  *
@@ -1229,23 +1484,28 @@ function baseName(text) {
1229
1484
  */
1230
1485
  function commandPositionIndexes(tokens) {
1231
1486
  const out = [];
1232
- let afterPrefix = false;
1233
- let pendingValue = false;
1487
+ let chain = {
1488
+ wrapper: "",
1489
+ pendingValue: false,
1490
+ afterPrefix: false
1491
+ };
1234
1492
  for (const [index, token] of tokens.entries()) {
1235
- const { text } = token;
1236
- const isCommand = token.atCommand || afterPrefix;
1237
- if (pendingValue) {
1238
- pendingValue = false;
1239
- afterPrefix = true;
1240
- } else if (isCommand && VALUE_TAKING_FLAGS.has(text)) pendingValue = true;
1241
- else if (isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text))) afterPrefix = true;
1242
- else {
1243
- if (isCommand) out.push(index);
1244
- afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(text));
1245
- }
1493
+ const step = advanceCommandChain(token, chain);
1494
+ chain = step.state;
1495
+ if (step.command) out.push(index);
1246
1496
  }
1247
1497
  return out;
1248
1498
  }
1499
+ /** 取壳层包装那条 `-c` 脚本参数(`bash -c '…'` 里引号内那一整枚 token)。 */
1500
+ function shellScriptArguments(tokens) {
1501
+ const scripts = [];
1502
+ for (const [index, token] of tokens.entries()) {
1503
+ const flag = tokens[index + 1];
1504
+ const script = tokens[index + 2];
1505
+ if (token.atCommand && SHELL_WRAPPER_NAMES.has(baseName(token.text)) && flag !== void 0 && script !== void 0 && SHELL_SCRIPT_FLAG.test(flag.text) && !script.atCommand) scripts.push(script.text);
1506
+ }
1507
+ return scripts;
1508
+ }
1249
1509
  /**
1250
1510
  * 该命令位 token 之后的实参里是否出现路径形状的操作数(旗标不算)。
1251
1511
  * `.` 与 `..` 都算:`grep foo .` 检索的就是当前工作区。
@@ -1253,7 +1513,7 @@ function commandPositionIndexes(tokens) {
1253
1513
  function hasPathOperand(tokens, from) {
1254
1514
  for (const token of tokens.slice(from + 1)) {
1255
1515
  if (token.atCommand) break;
1256
- if (!token.text.startsWith("-") && (token.text.startsWith("/") || token.text.includes("/") || token.text === "." || token.text === "..")) return true;
1516
+ if (!token.redirect && !token.text.startsWith("-") && isPathShape(token.text)) return true;
1257
1517
  }
1258
1518
  return false;
1259
1519
  }
@@ -1276,16 +1536,21 @@ function hasPathOperand(tokens, from) {
1276
1536
  * - --help/--version/-V 豁免按整条命令判断(`rg a --version && grep b c`
1277
1537
  * 复合命令会漏拦 grep);
1278
1538
  * - shell 关键字(`for … ; do grep`、`if … ; then rg`)不是控制符,其后的
1279
- * grep 不在命令位;`VAR=1 grep x` 同理。
1539
+ * grep 不在命令位。壳层赋值(`VAR=1 grep x`)**不**属此列:commandPositionIndexes
1540
+ * 把 `VAR=1` 当「跳过但不断链」处理。
1541
+ * - 嵌套只认壳层包装名单里 `-c` 后面那一段,且最多看进去两层;名单外的前缀
1542
+ * (`watch -n 5 grep`)与 `awk 'BEGIN{system("grep x y")}'` 一类不递归。
1280
1543
  */
1281
- function isGrepRgCommand(command) {
1544
+ function isGrepRgCommand(command, depth = 0) {
1282
1545
  const tokens = tokenizeShell(command);
1283
1546
  if (tokens.some((token) => PROBE_FLAGS.has(token.text))) return false;
1284
- return commandPositionIndexes(tokens).some((index) => {
1547
+ if (commandPositionIndexes(tokens).some((index) => {
1285
1548
  const token = tokens[index];
1286
1549
  if (token === void 0 || !GREP_COMMAND_NAMES.has(baseName(token.text))) return false;
1287
1550
  return !(token.piped && !hasPathOperand(tokens, index));
1288
- });
1551
+ })) return true;
1552
+ if (depth >= MAX_SHELL_DEPTH) return false;
1553
+ return shellScriptArguments(tokens).some((script) => isGrepRgCommand(script, depth + 1));
1289
1554
  }
1290
1555
  /**
1291
1556
  * 去掉尾部斜杠的 root 归一化('/' 自身保持 '/')。
@@ -1337,9 +1602,18 @@ function pathInsideRoot(target, root, messages) {
1337
1602
  */
1338
1603
  function hasExternalTarget(root, command, messages) {
1339
1604
  const base = normalizeRoot(root);
1340
- for (const token of tokenizeShell(command)) {
1605
+ const tokens = tokenizeShell(command);
1606
+ const commandIndexes = new Set(commandPositionIndexes(tokens));
1607
+ /** 上一枚是检索侧的取值旗标:这一枚是它的值(模式 / glob / 编码名…),不是目标。 */
1608
+ let pendingValue = false;
1609
+ for (const [index, token] of tokens.entries()) {
1341
1610
  const { text } = token;
1342
- if (!text.startsWith("-") && (text.startsWith("/") || text.includes("/") || text === "..") && !pathInsideRoot(text, base, messages)) return true;
1611
+ const consumedValue = pendingValue;
1612
+ pendingValue = false;
1613
+ if (!(commandIndexes.has(index) || consumedValue || token.redirect)) {
1614
+ if (text.startsWith("-")) pendingValue = SEARCH_VALUE_FLAGS.has(text);
1615
+ else if (isPathShape(text) && !pathInsideRoot(text, base, messages)) return true;
1616
+ }
1343
1617
  }
1344
1618
  return false;
1345
1619
  }
@@ -1545,30 +1819,44 @@ function nativeTargetInsideRoot(cwd, indexRoot, target, messages) {
1545
1819
  }
1546
1820
  return pathInsideRoot(absolute, indexRoot, messages);
1547
1821
  }
1548
- function buildSearchFirstReason(cwd, scope, deps, messages) {
1549
- const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
1822
+ /** 索引根已定且这棵树的范围判定要走门禁时的那句拒绝理由;交回 undefined 即放行。 */
1823
+ function gateReasonAt(indexRoot, cwd, scope, deps, messages) {
1824
+ const inScope = scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages);
1550
1825
  let reason;
1551
- if (indexRoot !== void 0 && (scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages))) {
1552
- const rebuilding = deps.rebuildBypass?.(indexRoot) === true;
1553
- const unlock = rebuilding ? void 0 : deps.lookupUnlock(indexRoot);
1554
- if (rebuilding) {} else if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
1555
- else {
1556
- let state;
1557
- if (unlock === void 0) state = messages.gateNeverSearched;
1558
- else if (unlock.grepsLeft <= 0) state = messages.gateQuotaExhausted;
1559
- else state = messages.gateUnlockExpired;
1560
- reason = fill(messages.gateReason, {
1561
- state,
1562
- indexRoot,
1563
- indexDir: INDEX_DIR_NAME,
1564
- budget: deps.grepBudget,
1565
- windowMin: deps.windowMin
1566
- });
1826
+ if (inScope) {
1827
+ if (!(deps.rebuildBypass?.(indexRoot) === true)) {
1828
+ const unlock = deps.lookupUnlock(indexRoot);
1829
+ if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
1830
+ else {
1831
+ let state;
1832
+ if (unlock === void 0) state = messages.gateNeverSearched;
1833
+ else if (unlock.grepsLeft <= 0) state = messages.gateQuotaExhausted;
1834
+ else state = messages.gateUnlockExpired;
1835
+ reason = fill(messages.gateReason, {
1836
+ state,
1837
+ indexRoot,
1838
+ indexDir: INDEX_DIR_NAME,
1839
+ budget: deps.grepBudget,
1840
+ windowMin: deps.windowMin
1841
+ });
1842
+ }
1567
1843
  }
1568
1844
  }
1569
1845
  return reason;
1570
1846
  }
1571
1847
  /**
1848
+ * 索引根已定后的门禁裁决:无索引根 / 检索索引根之外 / 有可扣额度 → 放行
1849
+ * (undefined);否则返回拦截文案。放行会触发 consumeGrep 副作用。
1850
+ * 两个拦截面的「之内/之外」都以**索引根**为准(不是会话工作区):会话开在索引根的
1851
+ * 子目录时,`../sibling` 或 `/repo/other` 相对 cwd 出界、相对索引根却在界内——shell 面
1852
+ * 的 hasExternalTarget 本来就按索引根判,原生 grep 面若按 cwd 判,同样的目标会从
1853
+ * 工具面绕过门禁,两个面各说各话。
1854
+ */
1855
+ function buildSearchFirstReason(cwd, scope, deps, messages) {
1856
+ const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
1857
+ return indexRoot === void 0 ? void 0 : gateReasonAt(indexRoot, cwd, scope, deps, messages);
1858
+ }
1859
+ /**
1572
1860
  * shell 面(bash/pwsh)的一次检索裁决:命令串里真出现 grep/rg 才交给门禁,
1573
1861
  * 否则放行。`command` 非字符串(模型产出的是 unknown)按空串处理,与旧实现同形。
1574
1862
  */
@@ -1608,6 +1896,12 @@ function searchFirstGuard(execution, deps, messages) {
1608
1896
  }
1609
1897
  return reason;
1610
1898
  }
1899
+ // lib/rebuild-state.ts
1900
+ /** 「某条占位已落定」这条承诺的收口:只交回结论,把 promise 本身留在注册表内部。 */
1901
+ async function settledOutcome(target) {
1902
+ await target.settled;
1903
+ return "settled";
1904
+ }
1611
1905
  /**
1612
1906
  * 表超过阈值就报警一次(不删任何条目)。
1613
1907
  *
@@ -1642,23 +1936,25 @@ function createRebuildRegistry(options = {}) {
1642
1936
  const maxTracked = options.maxTracked ?? 32;
1643
1937
  const entries = /* @__PURE__ */ new Map();
1644
1938
  let crowded = false;
1645
- const release = (root) => {
1646
- const entry = entries.get(root);
1647
- if (entry === void 0) return false;
1648
- entries.delete(root);
1939
+ const release = (root, claimed) => {
1940
+ const key = normalizeRoot(root);
1941
+ const entry = entries.get(key);
1942
+ if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
1943
+ entries.delete(key);
1649
1944
  entry.settle();
1650
1945
  if (entries.size <= maxTracked) crowded = false;
1651
1946
  return true;
1652
1947
  };
1653
1948
  return {
1654
1949
  claim(root, origin, startedAt) {
1655
- if (entries.has(root)) return null;
1950
+ const key = normalizeRoot(root);
1951
+ if (entries.has(key)) return null;
1656
1952
  const { promise: settled, resolve } = Promise.withResolvers();
1657
1953
  const settle = () => {
1658
1954
  resolve(void 0);
1659
1955
  };
1660
1956
  const entry = {
1661
- root,
1957
+ root: key,
1662
1958
  origin,
1663
1959
  startedAt: startedAt ?? now(),
1664
1960
  phase: "starting",
@@ -1666,28 +1962,26 @@ function createRebuildRegistry(options = {}) {
1666
1962
  settled,
1667
1963
  settle
1668
1964
  };
1669
- entries.set(root, entry);
1965
+ entries.set(key, entry);
1670
1966
  crowded = warnIfCrowded(entries, maxTracked, crowded);
1671
1967
  return entry;
1672
1968
  },
1673
- attach(root, jobId) {
1674
- const entry = entries.get(root);
1675
- if (entry === void 0) return;
1969
+ attach(root, jobId, claimed) {
1970
+ const entry = entries.get(normalizeRoot(root));
1971
+ if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
1676
1972
  entry.jobId = jobId;
1677
1973
  entry.phase = "running";
1974
+ return true;
1678
1975
  },
1679
1976
  release,
1680
1977
  active(root) {
1681
- return entries.get(root);
1978
+ return entries.get(normalizeRoot(root));
1682
1979
  },
1683
1980
  covering(root, messages) {
1684
- return coveringOf(entries, root, messages);
1685
- },
1686
- hasPollable(root) {
1687
- return entries.get(root)?.jobId !== void 0;
1981
+ return coveringOf(entries, normalizeRoot(root), messages);
1688
1982
  },
1689
1983
  async wait(root, messages, timeoutMs, signal) {
1690
- const entry = coveringOf(entries, root, messages);
1984
+ const entry = coveringOf(entries, normalizeRoot(root), messages);
1691
1985
  if (entry === void 0) return "settled";
1692
1986
  if (signal?.aborted === true) return "aborted";
1693
1987
  const { promise, resolve } = Promise.withResolvers();
@@ -1698,12 +1992,14 @@ function createRebuildRegistry(options = {}) {
1698
1992
  resolve("aborted");
1699
1993
  };
1700
1994
  signal?.addEventListener("abort", onAbort, { once: true });
1701
- const settledOutcome = async () => {
1702
- await entry.settled;
1703
- return "settled";
1995
+ const waitCovering = async (target) => {
1996
+ const outcome = await Promise.race([settledOutcome(target), promise]);
1997
+ if (outcome !== "settled") return outcome;
1998
+ const next = coveringOf(entries, root, messages);
1999
+ return next === void 0 ? "settled" : waitCovering(next);
1704
2000
  };
1705
2001
  try {
1706
- return await Promise.race([settledOutcome(), promise]);
2002
+ return await waitCovering(entry);
1707
2003
  } finally {
1708
2004
  clearTimeout(timer);
1709
2005
  signal?.removeEventListener("abort", onAbort);
@@ -1718,6 +2014,8 @@ function createRebuildRegistry(options = {}) {
1718
2014
  const REBUILD_OPERATION = "index.rebuild";
1719
2015
  /** 明细块的表头行(`Details:`)。 */
1720
2016
  const DETAILS_HEADER = /^\s*Details:\s*$/u;
2017
+ /** 行首空白:明细键值行以缩进起始,零缩进内容属于下一段。 */
2018
+ const INDENTED_LINE = /^\s/u;
1721
2019
  /**
1722
2020
  * zg 明细块的键值行。三个细节都来自「明细行是缩进的」这一实测形状:
1723
2021
  * - 缩进**必填**(`\s+`):明细块之后任何含冒号的非空行(第二个错误块的 `Error:` /
@@ -1742,14 +2040,38 @@ function zgErrorCode(stderr) {
1742
2040
  return firstCodeLine === void 0 ? void 0 : CODE_LINE.exec(firstCodeLine)?.groups?.["code"];
1743
2041
  }
1744
2042
  /**
2043
+ * 在第一个错误块的码行之后找明细表头。明细必须属于第一个错误块:码行之后遇到下一条
2044
+ * 无缩进内容(第二个块的 Error:/Code: 或散文)就说明这一块没有明细,不能顺延去捡后面
2045
+ * 块的键值。找不到返回 -1。
2046
+ */
2047
+ function detailsStartAfter(lines, codeIndex) {
2048
+ const rest = lines.slice(codeIndex + 1);
2049
+ for (const [offset, line] of rest.entries()) {
2050
+ if (DETAILS_HEADER.test(line)) return codeIndex + 1 + offset;
2051
+ if (line.trim().length > 0 && !INDENTED_LINE.test(line)) return -1;
2052
+ }
2053
+ return -1;
2054
+ }
2055
+ /**
1745
2056
  * 明细块的键值表。`Details:` 之后的缩进行才是明细,标题与错误码行不参与。
1746
2057
  * 重复键取首次出现(zg 不会重复输出同一个键,重复即形状异常,不覆盖)。
1747
2058
  * 明细块遇到非键值行即终止:其后多半是尾部截断的散文,继续收只会捡到假键值。
2059
+ * 导出只为把「没有 Code 行时不捡明细」这一支钉进单测;生产侧只经
2060
+ * `classifyConcurrentFailure` 调用(那里已先确认有码)。
1748
2061
  */
2062
+ /** 明细块的协议键:查表侧只许从这里取值,键名改名不会漏改一条。 */
2063
+ const DETAIL_KEY = {
2064
+ ownerOperation: "ownerOperation",
2065
+ ownerPid: "ownerPid",
2066
+ lock: "lock",
2067
+ pid: "pid"
2068
+ };
1749
2069
  function zgErrorDetails(stderr) {
1750
2070
  const details = /* @__PURE__ */ new Map();
1751
2071
  const lines = stderr.split("\n");
1752
- const start = lines.findIndex((line) => DETAILS_HEADER.test(line));
2072
+ const codeIndex = lines.findIndex((line) => CODE_LINE_PREFIX.test(line));
2073
+ if (codeIndex === -1) return details;
2074
+ const start = detailsStartAfter(lines, codeIndex);
1753
2075
  if (start === -1) return details;
1754
2076
  for (const line of lines.slice(start + 1)) {
1755
2077
  const matched = DETAIL_LINE.exec(line);
@@ -1771,17 +2093,17 @@ function classifyConcurrentFailure(stderr) {
1771
2093
  const code = zgErrorCode(stderr);
1772
2094
  if (code === void 0) return null;
1773
2095
  const details = zgErrorDetails(stderr);
1774
- const ownerOperation = details.get("ownerOperation");
2096
+ const ownerOperation = details.get(DETAIL_KEY.ownerOperation);
1775
2097
  if (code === "ZVEC_GREP.ENGINE.LOCK.BUSY") return {
1776
2098
  kind: "lock-busy",
1777
2099
  ownerOperation,
1778
- ownerPid: details.get("ownerPid"),
1779
- lockPath: details.get("lock"),
2100
+ ownerPid: details.get(DETAIL_KEY.ownerPid),
2101
+ lockPath: details.get(DETAIL_KEY.lock),
1780
2102
  rebuild: ownerOperation === REBUILD_OPERATION
1781
2103
  };
1782
2104
  if (code === "ZVEC_GREP.ENGINE.DAEMON_LEASE_ACTIVE") return {
1783
2105
  kind: "daemon-lease",
1784
- pid: details.get("pid")
2106
+ pid: details.get(DETAIL_KEY.pid)
1785
2107
  };
1786
2108
  return null;
1787
2109
  }
@@ -1795,8 +2117,12 @@ const MINIMUM = {
1795
2117
  minor: 2,
1796
2118
  patch: 2
1797
2119
  };
2120
+ /** 版本号的字面形态(回显用:门槛文案要让用户看得见自己装的是哪个版本)。 */
2121
+ function formatZgVersion(version) {
2122
+ return `${version.major}.${version.minor}.${version.patch}`;
2123
+ }
1798
2124
  /** 本包按之书写的 zg 语义版本(字面形态,给文案回显)。低于它一律在命令构造前拒绝。 */
1799
- const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
2125
+ const MINIMUM_ZG_VERSION = formatZgVersion(MINIMUM);
1800
2126
  /**
1801
2127
  * 形状:整串就是一个三段数字版本,`v` 前缀可有可无,可带前后的空白与换行。
1802
2128
  * 分量至多 9 位数字:`Number()` 对超长数字串会丢精度乃至得到 Infinity,畸形输入
@@ -1807,8 +2133,8 @@ const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
1807
2133
  const VERSION_SHAPE = /^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;
1808
2134
  /**
1809
2135
  * 不是版本号时用的哨兵:版本分量恒非负,故负数只可能来自「没解析出来」。
1810
- * 三个函数都收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
1811
- * consistent-return 判成两种返回形态),故用哨兵而不是提前 return。
2136
+ * `parseZgVersion` 收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
2137
+ * consistent-return 判成两种返回形态),故用哨兵而不是提前 return;其它函数不受此约束。
1812
2138
  */
1813
2139
  const UNPARSED = -1;
1814
2140
  /** 取一段具名捕获组;组不存在时给哨兵。 */
@@ -1828,10 +2154,6 @@ function parseZgVersion(stdout) {
1828
2154
  patch
1829
2155
  };
1830
2156
  }
1831
- /** 版本号的字面形态(回显用:门槛文案要让用户看得见自己装的是哪个版本)。 */
1832
- function formatZgVersion(version) {
1833
- return `${version.major}.${version.minor}.${version.patch}`;
1834
- }
1835
2157
  /** actual 是否 >= minimum:逐段比数值(不是比字符串,否则 `0.10.0 < 0.9.0`)。 */
1836
2158
  function versionAtLeast(actual, minimum) {
1837
2159
  if (actual.major !== minimum.major) return actual.major > minimum.major;
@@ -1857,7 +2179,8 @@ const UNUSABLE_FILE_CODES = /* @__PURE__ */ new Set([
1857
2179
  "ENOENT",
1858
2180
  "EACCES",
1859
2181
  "EISDIR",
1860
- "ENOTDIR"
2182
+ "ENOTDIR",
2183
+ "ENAMETOOLONG"
1861
2184
  ]);
1862
2185
  /** node:fs 的失败一律是带 string code 的 Error 实例;形状不合(非对象、无 code、码非串)
1863
2186
  * 一律按环境故障处理。导出只为把非 Error 形状的判别面钉进单测(真 fs 抛不出这些)。 */
@@ -1909,9 +2232,10 @@ function assertIgnoreFilesExist(args, root, messages) {
1909
2232
  * 会产出「enforcement=」这类残缺后缀——缺席与空白同归「不交代」。
1910
2233
  */
1911
2234
  function sandboxFacts(info, messages) {
1912
- const enforcement = info.enforcement === void 0 || info.enforcement.length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
2235
+ const enforcement = info.enforcement === void 0 || info.enforcement.trim().length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
2236
+ const mode = typeof info.mode === "string" && info.mode.trim().length > 0 ? info.mode.trim() : "unknown";
1913
2237
  return fill(messages.sandboxFacts, {
1914
- mode: info.mode,
2238
+ mode,
1915
2239
  enforcement
1916
2240
  });
1917
2241
  }
@@ -1963,14 +2287,13 @@ function isUsableBaseUrl(value) {
1963
2287
  * 规范化(剥尾斜杠)之后还要再验一次:`/`、`///` 会被剥成空串,`http://` 这类没有
1964
2288
  * host 的值也不是基地址——发一个空的或畸形的 HF_ENDPOINT 只会把失败推迟到
1965
2289
  * node-llama-cpp 的下载期,定位成本远高于这里的一次静默省略。 */
2290
+ function normalizedEndpoint(value) {
2291
+ const normalized = typeof value === "string" ? value.trim().replace(TRAILING_SLASHES, "") : "";
2292
+ return normalized.length > 0 && isUsableBaseUrl(normalized) ? normalized : void 0;
2293
+ }
1966
2294
  function hfEndpointEnv(config) {
1967
- const endpoint = config.hfEndpoint.get();
1968
- let env;
1969
- if (typeof endpoint === "string") {
1970
- const normalized = endpoint.trim().replace(TRAILING_SLASHES, "");
1971
- if (normalized.length > 0 && isUsableBaseUrl(normalized)) env = { HF_ENDPOINT: normalized };
1972
- }
1973
- return env;
2295
+ const endpoint = normalizedEndpoint(config.hfEndpoint.get());
2296
+ return endpoint === void 0 ? void 0 : { HF_ENDPOINT: endpoint };
1974
2297
  }
1975
2298
  /**
1976
2299
  * 部署值里的可选字符串:空串/空白/非字符串一律归一成 undefined(=「没配」)。
@@ -2016,7 +2339,7 @@ const ENV_NAME_SHAPE = /^[A-Za-z_]\w*$/u;
2016
2339
  function zgEnv(config) {
2017
2340
  const env = { ...hfEndpointEnv(config) };
2018
2341
  if (allowRemoteEmbedding(config)) {
2019
- const endpoint = trimmedConfigString(config.remoteEmbeddingEndpoint);
2342
+ const endpoint = normalizedEndpoint(config.remoteEmbeddingEndpoint);
2020
2343
  if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
2021
2344
  const keyName = trimmedConfigString(config.remoteEmbeddingApiKeyFrom);
2022
2345
  const key = keyName !== void 0 && ENV_NAME_SHAPE.test(keyName) ? process.env[keyName] : void 0;
@@ -2027,7 +2350,7 @@ function zgEnv(config) {
2027
2350
  }
2028
2351
  function readDefaultEmbedding(config) {
2029
2352
  const raw = config.defaultEmbedding.get();
2030
- if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
2353
+ if (typeof raw === "string" && isLocalEmbedding(raw)) return raw.trim();
2031
2354
  return DEFAULT_EMBEDDING;
2032
2355
  }
2033
2356
  /**
@@ -2041,15 +2364,6 @@ function readClientMode(config, messages) {
2041
2364
  // lib/rebuild-remote.ts
2042
2365
  /** 本包作业的 kind(宿主据此发出的 id 形如 `zvec-grep-rebuild-<hex>`)。 */
2043
2366
  const REBUILD_JOB_KIND = "zvec-grep-rebuild";
2044
- /**
2045
- * 本 kind 在注册表里的**已落定**记录上限:每次 start 前先剪到 `MAX-1` 条,新那条落定后
2046
- * 正好 `MAX` 条在册(文案与卡片拒绝提示都按这个数说)。同时能跑几个不在这里——那是
2047
- * 注册表的容量闸(实测未拥有桶 10,满员是**拒绝**新 start,不是淘汰旧的)。官方件**不会**
2048
- * 自行回收落定记录("A settled record stays listed until its owner's disposal, service
2049
- * disposal, or an explicit remove"),而注册表又随宿主活着、不随本插件卸载而死 ⇒ 这条
2050
- * 裁剪是本包的责任。
2051
- */
2052
- const REBUILD_HISTORY_MAX = 10;
2053
2367
  /** 卡片视图的尾部长度(打标文案在 lib/messages.ts,随语言走)。 */
2054
2368
  const JOB_OUT_VIEW_CHARS = 4e3;
2055
2369
  /** 从名册投影推导身份证(官方 `JobView` 的三段稳定事实)。 */
@@ -2168,20 +2482,20 @@ function killProc(proc) {
2168
2482
  * @returns {void}
2169
2483
  */
2170
2484
  function pruneRebuildHistory(jobs, records) {
2171
- const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
2172
- for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
2485
+ const ordered = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status)).toSorted((left, right) => left.startedAt - right.startedAt);
2486
+ for (const job of ordered.slice(0, Math.max(ordered.length - 9, 0))) {
2173
2487
  jobs.remove(job.id);
2174
2488
  records.delete(job.id);
2175
2489
  }
2176
2490
  }
2491
+ /** 远端容量上限的括号形态。 */
2492
+ const CAPACITY_LIMIT = /\(limit: (?<limit>\d+)\)/u;
2177
2493
  /**
2178
2494
  * 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
2179
2495
  * owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
2180
2496
  * 为什么单独认这一条:它是本包唯一会把宿主英文原话插进中文卡片的错误,又恰恰最该翻成
2181
2497
  * 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
2182
2498
  */
2183
- /** 远端容量上限的括号形态。 */
2184
- const CAPACITY_LIMIT = /\(limit: (?<limit>\d+)\)/u;
2185
2499
  function capacityLimitOf(error) {
2186
2500
  return CAPACITY_LIMIT.exec(errorText(error))?.groups?.["limit"];
2187
2501
  }
@@ -2272,13 +2586,11 @@ function startUnderController(jobs, spec) {
2272
2586
  /**
2273
2587
  * 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
2274
2588
  * 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
2275
- * @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
2276
- * @param proc 已经起来的 zg 进程
2277
- * @param state 这条重建的状态盒(与侧表记录共用)
2278
- * @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
2589
+ * @param options 一次启动所需的全部输入:共享依赖、已起的进程、状态盒、命令、根与 claim 凭据
2279
2590
  * @returns 官方 JobSpec:kind / label / output / run
2280
2591
  */
2281
- function rebuildJobSpec(routes, proc, state, command, root) {
2592
+ function rebuildJobSpec(options) {
2593
+ const { routes, proc, state, command, root, claimed } = options;
2282
2594
  const { config, host, jobsOf, messages } = routes;
2283
2595
  return {
2284
2596
  kind: REBUILD_JOB_KIND,
@@ -2299,13 +2611,17 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2299
2611
  if (proc.status !== "running") return;
2300
2612
  const live = liveJob();
2301
2613
  if (live !== null && live.status !== "running") return;
2302
- const minutes = Math.round(config.indexTimeoutMs / 6e4);
2614
+ const minutes = Math.max(1, Math.ceil(config.indexTimeoutMs / 6e4));
2303
2615
  state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
2304
2616
  if (live === null) {
2305
2617
  killProc(proc);
2306
2618
  return;
2307
2619
  }
2308
- live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2620
+ try {
2621
+ live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2622
+ } catch {
2623
+ killProc(proc);
2624
+ }
2309
2625
  }, config.indexTimeoutMs);
2310
2626
  return {
2311
2627
  cancel: () => {
@@ -2317,7 +2633,7 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2317
2633
  return jobOutcomeOf(proc);
2318
2634
  } finally {
2319
2635
  cancelKillTimer();
2320
- routes.rebuilds.release(root);
2636
+ routes.rebuilds.release(root, claimed);
2321
2637
  }
2322
2638
  })()
2323
2639
  };
@@ -2371,16 +2687,21 @@ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
2371
2687
  /**
2372
2688
  * 把起来的那条进程登记进官方注册表与本包侧表,交回宿主签发的 id。
2373
2689
  *
2374
- * 三种失败(注册表换人 / 同名不同命 / start 抛错)都**先把那条进程杀掉**再交回错误:
2690
+ * 两类失败(注册表缺席 / start 或登记抛错)都**先把那条进程杀掉**再交回错误:
2375
2691
  * 此刻作业没进名册,没人能通过 job 工具收它,不杀就是一条孤儿 zg 占着这棵树的写锁。
2692
+ * (没有「同 id 撞车」那一臂:jobId 由宿主签发,见 records.set 前的注释。)
2693
+ * start 之后 get 抛错时同样先杀——但那条作业可能已登记进官方注册表,本包侧表
2694
+ * 看不见它,要等注册表自身的 prune 兜底。
2376
2695
  * 同样地,本函数不释放占位——那件事由调用方做。
2377
2696
  * @param routes 本次注册的共享依赖(jobsOf 现读、侧表引用)
2378
2697
  * @param root 已过前置校验的工作区(写进侧表供卡片回显)
2379
2698
  * @param started 本次请求语言的文案表
2380
2699
  * @param spawned spawnIndexWrite 交回的进程与命令
2700
+ * @param claimed claim 拿到的那枚占位(重建/后台路径必有):收尾释放按它校验代次,
2701
+ * 条目已被同根新 claim 顶替时那份迟到的释放不许删掉新条目
2381
2702
  * @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
2382
2703
  */
2383
- function attachIndexWrite(routes, root, started, spawned) {
2704
+ function attachIndexWrite(routes, root, started, spawned, claimed) {
2384
2705
  const { jobsOf, records } = routes;
2385
2706
  const { proc, command } = spawned;
2386
2707
  const starting = jobsOf();
@@ -2411,7 +2732,14 @@ function attachIndexWrite(routes, root, started, spawned) {
2411
2732
  };
2412
2733
  let jobId;
2413
2734
  try {
2414
- jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
2735
+ jobId = startUnderController(starting, rebuildJobSpec({
2736
+ routes,
2737
+ proc,
2738
+ state,
2739
+ command,
2740
+ root,
2741
+ claimed
2742
+ }));
2415
2743
  state.identity = identityOf(starting.get(jobId));
2416
2744
  records.set(jobId, {
2417
2745
  proc,
@@ -2469,7 +2797,10 @@ var ZvecRebuildService = class extends TypertRemoteService {
2469
2797
  }
2470
2798
  /** 引导读面:白名单里的工作区 + 守护进程就绪态(都是本插件自己的数据)。 */
2471
2799
  async roots() {
2472
- const serverReady = await this.deps.serverGate.ready();
2800
+ let serverReady = false;
2801
+ try {
2802
+ serverReady = await this.deps.serverGate.ready();
2803
+ } catch {}
2473
2804
  return {
2474
2805
  roots: this.deps.ledger.list(),
2475
2806
  serverReady
@@ -2498,7 +2829,8 @@ var ZvecRebuildService = class extends TypertRemoteService {
2498
2829
  error: started.endpointJobsUnavailable,
2499
2830
  status: 503
2500
2831
  };
2501
- if (this.deps.rebuilds.claim(root, "card") === null) {
2832
+ const claimed = this.deps.rebuilds.claim(root, "card");
2833
+ if (claimed === null) {
2502
2834
  const following = followRunningRebuild(jobs, this.deps.records, root);
2503
2835
  return following === void 0 ? {
2504
2836
  ok: false,
@@ -2517,23 +2849,23 @@ var ZvecRebuildService = class extends TypertRemoteService {
2517
2849
  rebuild: true
2518
2850
  }, embedding);
2519
2851
  if ("error" in spawned) {
2520
- this.deps.rebuilds.release(root);
2852
+ this.deps.rebuilds.release(root, claimed);
2521
2853
  return {
2522
2854
  ok: false,
2523
2855
  error: spawned.error,
2524
2856
  status: spawned.status
2525
2857
  };
2526
2858
  }
2527
- const attached = attachIndexWrite(this.deps, root, started, spawned);
2859
+ const attached = attachIndexWrite(this.deps, root, started, spawned, claimed);
2528
2860
  if ("error" in attached) {
2529
- this.deps.rebuilds.release(root);
2861
+ this.deps.rebuilds.release(root, claimed);
2530
2862
  return {
2531
2863
  ok: false,
2532
2864
  error: attached.error,
2533
2865
  status: attached.status
2534
2866
  };
2535
2867
  }
2536
- this.deps.rebuilds.attach(root, attached.jobId);
2868
+ this.deps.rebuilds.attach(root, attached.jobId, claimed);
2537
2869
  return {
2538
2870
  ok: true,
2539
2871
  jobId: attached.jobId
@@ -2551,7 +2883,7 @@ var ZvecRebuildService = class extends TypertRemoteService {
2551
2883
  const record = typeof raw === "string" && raw.length > 0 ? this.deps.records.get(raw) : void 0;
2552
2884
  if (record === void 0) return {
2553
2885
  ok: false,
2554
- error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2886
+ error: fill(marks.unknownJobId, { maxJobs: 10 }),
2555
2887
  status: 404
2556
2888
  };
2557
2889
  const jobs = this.deps.jobsOf();
@@ -2563,12 +2895,12 @@ var ZvecRebuildService = class extends TypertRemoteService {
2563
2895
  const output = readRebuildOutput(jobs, record.id);
2564
2896
  if (output === null) return {
2565
2897
  ok: false,
2566
- error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2898
+ error: fill(marks.unknownJobId, { maxJobs: 10 }),
2567
2899
  status: 404
2568
2900
  };
2569
2901
  if (!sameJob(record.state, output.view)) return {
2570
2902
  ok: false,
2571
- error: fill(marks.unknownJobId, { maxJobs: REBUILD_HISTORY_MAX }),
2903
+ error: fill(marks.unknownJobId, { maxJobs: 10 }),
2572
2904
  status: 404
2573
2905
  };
2574
2906
  const { view, retained } = output;
@@ -3085,9 +3417,17 @@ function readUnlockWindowMin(config) {
3085
3417
  function readEnforceSearchFirst(config) {
3086
3418
  return config.enforceSearchFirst.get() ?? true;
3087
3419
  }
3088
- /** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
3089
- function comparablePath(root) {
3090
- return root.startsWith("/private/") ? root.slice(8) : root;
3420
+ /**
3421
+ * 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。
3422
+ *
3423
+ * 剥除**只在 macOS 上成立**:darwin 的 `/private` 是 `/tmp` 等目录的 realpath 前缀,
3424
+ * 两种拼写指同一目录;Linux 上 `/private/xxx` 是一个与 `/xxx` 无关的真实目录,无差别
3425
+ * 剥除会把两棵不同的树判成同一棵(manifest 覆盖判据随之错配)。Windows 不在本包支持面。
3426
+ *
3427
+ * `platform` 供测试注入:分支覆盖不依赖测试机自己的操作系统。导出只为可测。
3428
+ */
3429
+ function comparablePath(root, platform = process.platform) {
3430
+ return platform === "darwin" && root.startsWith("/private/") ? root.slice(8) : root;
3091
3431
  }
3092
3432
  /** 认的清单版本:与上游 v0.2.2 的 `export const CURRENT_MANIFEST_VERSION = 1` 同值。 */
3093
3433
  const SUPPORTED_MANIFEST_VERSION = 1;
@@ -3305,7 +3645,14 @@ const INDEX_PROBE_CACHE_MAX = 32;
3305
3645
  */
3306
3646
  function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS, max = 32) {
3307
3647
  const cache = /* @__PURE__ */ new Map();
3308
- return (dir) => {
3648
+ /** 显式失效通道:zg_index 的 drop / 重建成功会真删真建 `.zvec-grep/`,缓存的
3649
+ * `result: true` 若只等 TTL 过期,60 秒内门禁仍按「已建索引」拦 grep/rg,
3650
+ * findIndexRoot 也仍走索引通道(实际会以 WORKSPACE_INDEX_NOT_FOUND 失败)——
3651
+ * 模型被卡在既搜不到也 grep 不了的窗口里。 */
3652
+ const invalidate = (dir) => {
3653
+ cache.delete(dir);
3654
+ };
3655
+ const cached = (dir) => {
3309
3656
  const at = now();
3310
3657
  const hit = cache.get(dir);
3311
3658
  if (hit !== void 0 && at - hit.probedAt < ttlMs) {
@@ -3321,6 +3668,8 @@ function createIndexProbeCache(probe, now = Date.now, ttlMs = INDEX_PROBE_TTL_MS
3321
3668
  evictAged(cache, max, (entry) => entry.probedAt + ttlMs, at);
3322
3669
  return result;
3323
3670
  };
3671
+ cached.invalidate = invalidate;
3672
+ return cached;
3324
3673
  }
3325
3674
  /**
3326
3675
  * 工作区白名单:只认本 daemon 真实观测过的会话工作区(重建与 root 授权共用)。
@@ -3723,7 +4072,7 @@ function indexToolParameters(registered) {
3723
4072
  * @param messages 本次 execute 现取的文案表
3724
4073
  * @returns 交给官方 output schema 的 `{ text }`
3725
4074
  */
3726
- async function startBackgroundIndex(runtime, root, indexArgs, messages) {
4075
+ async function startBackgroundIndex(runtime, root, indexArgs, messages, claimed) {
3727
4076
  const routes = {
3728
4077
  host: runtime.host,
3729
4078
  config: runtime.config,
@@ -3734,20 +4083,20 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages) {
3734
4083
  versionGate: runtime.versionGate
3735
4084
  };
3736
4085
  if (runtime.jobsOf() === void 0) {
3737
- runtime.rebuilds.release(root);
4086
+ runtime.rebuilds.release(root, claimed);
3738
4087
  throw new Error(messages.endpointJobsUnavailable);
3739
4088
  }
3740
4089
  const spawned = await spawnIndexWrite(routes, messages, indexArgs, readDefaultEmbedding(runtime.config));
3741
4090
  if ("error" in spawned) {
3742
- runtime.rebuilds.release(root);
4091
+ runtime.rebuilds.release(root, claimed);
3743
4092
  throw new Error(spawned.error);
3744
4093
  }
3745
- const attached = attachIndexWrite(routes, root, messages, spawned);
4094
+ const attached = attachIndexWrite(routes, root, messages, spawned, claimed);
3746
4095
  if ("error" in attached) {
3747
- runtime.rebuilds.release(root);
4096
+ runtime.rebuilds.release(root, claimed);
3748
4097
  throw new Error(attached.error);
3749
4098
  }
3750
- runtime.rebuilds.attach(root, attached.jobId);
4099
+ runtime.rebuilds.attach(root, attached.jobId, claimed);
3751
4100
  return { text: fill(messages.indexBackgroundStarted, {
3752
4101
  root,
3753
4102
  jobId: attached.jobId,
@@ -3766,19 +4115,26 @@ async function runIndexTool(runtime, args, exec, messages) {
3766
4115
  const rewriting = boolOf(args["rebuild"], "rebuild", messages) || background;
3767
4116
  boolOf(args["confirm"], "confirm", messages);
3768
4117
  await runtime.versionGate.ensure(messages);
3769
- if (rewriting && rebuilds.claim(root, "tool") === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
3770
- if (background) return startBackgroundIndex(runtime, root, indexArgs, messages);
4118
+ let foregroundClaim;
4119
+ if (rewriting) {
4120
+ const claimed = rebuilds.claim(root, "tool");
4121
+ if (claimed === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
4122
+ if (background) return startBackgroundIndex(runtime, root, indexArgs, messages, claimed);
4123
+ foregroundClaim = claimed;
4124
+ }
3771
4125
  try {
3772
4126
  assertIgnoreFilesExist(indexArgs, root, messages);
3773
4127
  const { command, workdir } = buildIndexCommand(indexArgs, readDefaultEmbedding(config), messages, readClientMode(config, messages), allowRemoteEmbedding(config));
3774
- return { text: await runForeground(host, command, workdir, config.indexTimeoutMs, {
4128
+ const text = await runForeground(host, command, workdir, config.indexTimeoutMs, {
3775
4129
  signal: exec.signal,
3776
4130
  env: zgEnv(config),
3777
4131
  stdoutMaxBytes: config.stdoutMaxBytes,
3778
4132
  messages
3779
- }) };
4133
+ });
4134
+ runtime.indexProbe.invalidate(root);
4135
+ return { text };
3780
4136
  } finally {
3781
- if (rewriting) rebuilds.release(root);
4137
+ if (foregroundClaim !== void 0) rebuilds.release(root, foregroundClaim);
3782
4138
  }
3783
4139
  }
3784
4140
  /** 注册 zg_index:建/重建/删索引。 */
@@ -3814,7 +4170,7 @@ async function runStatusTool(runtime, args, exec, messages) {
3814
4170
  root,
3815
4171
  checkReady
3816
4172
  }, messages, readClientMode(config, messages));
3817
- return { text: `${await runForeground(host, command, workdir, config.statusTimeoutMs, {
4173
+ const text = await runForeground(host, command, workdir, config.statusTimeoutMs, {
3818
4174
  signal: exec.signal,
3819
4175
  env: zgEnv(config),
3820
4176
  stdoutMaxBytes: config.stdoutMaxBytes,
@@ -3826,13 +4182,19 @@ async function runStatusTool(runtime, args, exec, messages) {
3826
4182
  },
3827
4183
  ...checkReady ? { resolveFailure: (failure, result) => {
3828
4184
  if (result.timedOut || result.aborted || result.sandbox?.denied === true) return null;
4185
+ if (classifyConcurrentFailure(result.stderr.text) !== null) return null;
3829
4186
  const report = result.stdout.text.trim();
3830
4187
  return report.length > 0 ? `${report}\n${fill(messages.statusNotReady, {
3831
4188
  root,
3832
4189
  detail: failure
3833
4190
  })}` : null;
3834
4191
  } } : {}
3835
- })}\n${await runtime.serverGate.ready() ? messages.serverReadyNote : messages.serverUnavailableNote}` };
4192
+ });
4193
+ const mode = readClientMode(config, messages);
4194
+ const ready = await runtime.serverGate.ready();
4195
+ let daemonNote = null;
4196
+ if (mode !== "direct") daemonNote = ready ? messages.serverReadyNote : messages.serverUnavailableNote;
4197
+ return daemonNote === null ? { text } : { text: `${text}\n${daemonNote}` };
3836
4198
  }
3837
4199
  function registerStatusTool(runtime, registered) {
3838
4200
  define(runtime.host, {
@@ -4001,4 +4363,4 @@ var host_default = {
4001
4363
  Config: configSchema,
4002
4364
  apply
4003
4365
  };
4004
- export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };
4366
+ export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, comparablePath, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };