@jayyuen66/dsh-zvec-grep 0.1.8 → 0.1.10

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
@@ -2,6 +2,7 @@
2
2
  import Schema from "@deepseek-ai/schemastery";
3
3
  import { accessSync, constants, existsSync, readFileSync, statSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
+ import { scopeOf } from "@deepseek-ai/dsh-scope";
5
6
  import { isRecord } from "@jayyuen66/dsh-plugin-shared/lib/record";
6
7
  import { errorText } from "@jayyuen66/dsh-plugin-shared/lib/errors";
7
8
  import { LOCALE_SETTINGS_NAMESPACE, messagesFor, resolveLocalePreference } from "@jayyuen66/dsh-plugin-shared/lib/locale";
@@ -18,16 +19,7 @@ const DEFAULT_EMBEDDING = "local/qwen3-embedding-0.6b";
18
19
  * 而不是静默产出一个不在联合里的字符串。
19
20
  */
20
21
  const TRANSFORMERS_JS_BACKEND = "transformers-js";
21
- /**
22
- * 本地候选清单,按后端分三档(体积/语言口径,实测 zg v0.2.1):
23
- * - llama-cpp:qwen3-embedding-0.6b 约 640MB(本包默认)、
24
- * embeddinggemma-300m 约 300MB(英文)——两档都要原生件,Metal 加速由 zg 侧 device=auto 试;
25
- * - model2vec:potion-code-16m-v2 约 32MB(代码专用、最轻最快)、potion-multilingual-128m
26
- * (多语言轻量)、potion-retrieval-32m(通用检索)——纯 JS worker,零原生依赖;
27
- * - transformers-js:其余 ONNX 小模型,384 维那批是英文/多语言轻量档,768 维那批里
28
- * jina 面向代码、gte/nomic 面向 8192 长文。
29
- */
30
- const LOCAL_EMBEDDINGS = [
22
+ const LOCAL_EMBEDDINGS = Object.freeze([
31
23
  {
32
24
  reference: "local/qwen3-embedding-0.6b",
33
25
  backend: "llama-cpp",
@@ -83,14 +75,15 @@ const LOCAL_EMBEDDINGS = [
83
75
  backend: TRANSFORMERS_JS_BACKEND,
84
76
  dimension: 768
85
77
  }
86
- ];
78
+ ].map((entry) => Object.freeze(entry)));
87
79
  function isLocalEmbedding(reference) {
88
- return LOCAL_EMBEDDINGS.some((entry) => entry.reference === reference);
80
+ const normalized = reference.trim();
81
+ return LOCAL_EMBEDDINGS.some((entry) => entry.reference === normalized);
89
82
  }
90
83
  // lib/messages.ts
91
84
  /** 中文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义、同一份判据)。 */
92
85
  const ABSOLUTE_ROOT_HINT_ZH = "工作区绝对路径(可选:缺省=当前会话工作区;显式传入时须在本会话可操作范围内——会话工作区本身、其上级或下级、或本会话已登记过的工作区)";
93
- /** 英文侧「绝对路径 + 可操作范围」那句共用文案(检索/索引两个 root 参数同义)。 */
86
+ /** 英文侧「绝对路径 + 可操作范围」那句共用文案(三个 root 参数同义)。 */
94
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)";
95
88
  const MESSAGES = {
96
89
  zh: {
@@ -250,7 +243,7 @@ const MESSAGES = {
250
243
  gateReason: "[zvec-grep] 工作区检索门禁({state}):当前工作区已建 zg 索引({indexRoot}/{indexDir}),直接 grep/rg 字面检索经常漏检。请先调用 zg_search(语义/混合检索,覆盖面与相关性更好;把当前检索目标作为 query/fts),每次成功的 zg_search 解锁 {budget} 次 grep/rg({windowMin} 分钟内有效),用于精确字面/正则补充。"
251
244
  },
252
245
  en: {
253
- 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.",
246
+ 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.",
254
247
  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.",
255
248
  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.",
256
249
  rootSearchDescription: ABSOLUTE_ROOT_HINT,
@@ -417,7 +410,7 @@ const MESSAGES = {
417
410
  */
418
411
  function fill(template, params) {
419
412
  return template.replaceAll(/\{(?<key>\w+)\}/gu, (_all, key) => {
420
- const value = params[key];
413
+ const value = Object.hasOwn(params, key) ? params[key] : void 0;
421
414
  return value === void 0 ? "" : String(value);
422
415
  });
423
416
  }
@@ -473,10 +466,10 @@ function stringList(value, name, messages, maxItems = MAX_FILTER_ITEMS, maxChars
473
466
  const trimmed = assertTextLen(item.trim(), name, messages, maxChars);
474
467
  if (trimmed.length > 0) out.push(trimmed);
475
468
  }
476
- if (value.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
469
+ if (out.length > maxItems) throw new TypeError(fill(messages.tooManyItems, {
477
470
  name,
478
471
  maxItems,
479
- actual: value.length
472
+ actual: out.length
480
473
  }));
481
474
  return out;
482
475
  }
@@ -737,15 +730,15 @@ function pushQueryArgs(parts, args, messages) {
737
730
  routeCount += 1;
738
731
  }
739
732
  for (const query of queryList(args.queries, "queries", messages)) {
740
- parts.push("--hybrid", shq(query));
733
+ parts.push(`--hybrid=${shq(query)}`);
741
734
  routeCount += 1;
742
735
  }
743
736
  for (const query of queryList(args.fts, "fts", messages)) {
744
- parts.push("--fts", shq(query));
737
+ parts.push(`--fts=${shq(query)}`);
745
738
  routeCount += 1;
746
739
  }
747
740
  for (const query of queryList(args.vector, "vector", messages)) {
748
- parts.push("--vector", shq(query));
741
+ parts.push(`--vector=${shq(query)}`);
749
742
  routeCount += 1;
750
743
  }
751
744
  if (routeCount > 32) throw new Error(fill(messages.tooManyQueryRoutes, {
@@ -789,8 +782,8 @@ function buildIndexedCommand(args, root, messages, mode, backgroundSupport) {
789
782
  if (routeCount === 0) throw new Error(messages.searchNeedsQuery);
790
783
  if (boolOf(args.fuse, "fuse", messages)) parts.push("--fuse");
791
784
  const refresh = refreshOf(args.refresh, messages);
785
+ if (refresh === "background" && mode === "direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
792
786
  if (refresh === "background" && backgroundSupport === "daemon-down") throw new Error(fill(messages.refreshBackgroundNeedsServer, { root }));
793
- if (refresh === "background" && backgroundSupport === "mode-direct") throw new Error(fill(messages.refreshBackgroundPinnedDirect, { root }));
794
787
  parts.push("--limit", String(resolveLimit(args.limit, messages)), "--preview", previewOf(args.preview, messages), "--refresh", refresh);
795
788
  pushSearchGlobs(parts, args, messages);
796
789
  if (boolOf(args.preferSymbol, "preferSymbol", messages)) parts.push("--prefer-symbol");
@@ -960,7 +953,7 @@ function pushIndexResetPathsFlag(parts, args, messages) {
960
953
  function indexEmbedding(args, defaultEmbedding, messages, allowRemote) {
961
954
  const given = optionalText(args.embedding, "embedding", messages, MAX_FILTER_CHARS);
962
955
  if (given.length === 0) return defaultEmbedding;
963
- if (isLocalEmbedding(given) || allowRemote) return given;
956
+ if (isLocalEmbedding(given) || allowRemote) return given.trim();
964
957
  throw new Error(fill(messages.embeddingNotAllowed, {
965
958
  reference: given,
966
959
  choices: LOCAL_EMBEDDINGS.map((entry) => entry.reference).join(" | ")
@@ -1049,6 +1042,8 @@ function buildStatusCommand(args, messages, mode = DEFAULT_CLIENT_MODE) {
1049
1042
  return assembled(parts, root, messages);
1050
1043
  }
1051
1044
  // lib/search-predicates.ts
1045
+ /** 根目录末尾斜杠。 */
1046
+ const TRAILING_SLASHES$1 = /\/+$/u;
1052
1047
  const GREP_COMMAND_NAMES = /* @__PURE__ */ new Set([
1053
1048
  "grep",
1054
1049
  "egrep",
@@ -1077,62 +1072,193 @@ const SEARCH_PREFIX_WORDS = /* @__PURE__ */ new Set([
1077
1072
  "parallel"
1078
1073
  ]);
1079
1074
  /**
1080
- * 包装命令里「带一个取值」的选项:其后那一个 token 是它的值,不是被执行的命令
1081
- * (`sudo -u root grep`、`nice -n 10 rg`、`timeout -s 9 5 rg`)。
1075
+ * 包装命令里「带一个取值」的选项,按包装命令分表(键 = 包装命令的 basename)。
1076
+ * 其后那一个 token 是它的值,不是被执行的命令(`sudo -u root grep`、`nice -n 10 rg`、
1077
+ * `timeout -s 9 5 rg`)。
1082
1078
  *
1083
- * 跨包装命令共用一张表:这些短选项在 git/xargs/env/sudo/time/nice/timeout 里
1084
- * 语义一致,逐个包装登记一份只会让「加了新包装却忘了登记」多一处可能。
1079
+ * **必须分表**:同一枚短选项在不同包装下语义不同——`nice -n 10`、`xargs -n 5` 的 `-n`
1080
+ * 吃取值,而 `sudo -n`(non-interactive)、`time -p`(POSIX 输出)、`git -p`(--paginate)、
1081
+ * `xargs -r/-t/-p` 都不吃。共用一张表会把紧随其后的真命令当成取值吞掉,命令位链断开,
1082
+ * 于是 `sudo -n grep foo`、`time -p grep x`、`find … | xargs -r grep TODO` 全部判成
1083
+ * 「不是检索」——漏判的方向就是门禁放行。
1084
+ * 未登记的包装(nohup 没有取值旗标)落空表,无需登记。
1085
1085
  */
1086
- const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Set([
1087
- "-a",
1088
- "-c",
1086
+ const VALUE_TAKING_FLAGS = /* @__PURE__ */ new Map([
1087
+ ["git", /* @__PURE__ */ new Set([
1088
+ "-c",
1089
+ "-C",
1090
+ "--git-dir",
1091
+ "--work-tree",
1092
+ "--namespace",
1093
+ "--super-prefix",
1094
+ "--config-env"
1095
+ ])],
1096
+ ["xargs", /* @__PURE__ */ new Set([
1097
+ "-a",
1098
+ "-d",
1099
+ "-E",
1100
+ "-I",
1101
+ "-L",
1102
+ "-n",
1103
+ "-P",
1104
+ "-s",
1105
+ "--arg-file",
1106
+ "--delimiter",
1107
+ "--eof",
1108
+ "--max-args",
1109
+ "--max-chars",
1110
+ "--max-lines",
1111
+ "--max-procs",
1112
+ "--process-slot-var",
1113
+ "--replace"
1114
+ ])],
1115
+ ["env", /* @__PURE__ */ new Set([
1116
+ "-u",
1117
+ "-C",
1118
+ "-S",
1119
+ "--unset",
1120
+ "--chdir",
1121
+ "--split-string"
1122
+ ])],
1123
+ ["sudo", /* @__PURE__ */ new Set([
1124
+ "-u",
1125
+ "-g",
1126
+ "-C",
1127
+ "-D",
1128
+ "-h",
1129
+ "-p",
1130
+ "-r",
1131
+ "-t",
1132
+ "-T",
1133
+ "-U",
1134
+ "-R",
1135
+ "--user",
1136
+ "--group",
1137
+ "--close-from",
1138
+ "--chdir",
1139
+ "--host",
1140
+ "--prompt",
1141
+ "--role",
1142
+ "--type",
1143
+ "--command-timeout",
1144
+ "--other-user",
1145
+ "--chroot"
1146
+ ])],
1147
+ ["time", /* @__PURE__ */ new Set([
1148
+ "-f",
1149
+ "-o",
1150
+ "--format",
1151
+ "--output"
1152
+ ])],
1153
+ ["timeout", /* @__PURE__ */ new Set([
1154
+ "-s",
1155
+ "-k",
1156
+ "--signal",
1157
+ "--kill-after"
1158
+ ])],
1159
+ ["nice", /* @__PURE__ */ new Set(["-n", "--adjustment"])],
1160
+ ["parallel", /* @__PURE__ */ new Set([
1161
+ "-j",
1162
+ "-S",
1163
+ "-n",
1164
+ "--jobs",
1165
+ "--sshlogin",
1166
+ "--sshloginfile",
1167
+ "--joblog",
1168
+ "--results",
1169
+ "--tmpdir",
1170
+ "--delay",
1171
+ "--max-args"
1172
+ ])]
1173
+ ]);
1174
+ /**
1175
+ * grep/rg 自己的「带一个取值」选项:其后那个 token 是模式(`-e foo`)、glob(`-g *.ts`)、
1176
+ * 编码名(`-E utf-8`)……不是检索目标。判「目标是否在根外」时要跳过它——否则
1177
+ * `grep -f /tmp/patterns .`、`rg --glob /tmp/x foo .` 里的取值会被当成根外证据,
1178
+ * 门禁直接放行(实测过的绕过形态)。
1179
+ * 取 grep 与 rg 的并集:多跳一枚在本函数里只可能导致「少认一个目标」,方向是**多拦**,
1180
+ * 不构成放行。
1181
+ */
1182
+ const SEARCH_VALUE_FLAGS = /* @__PURE__ */ new Set([
1183
+ "-e",
1184
+ "-f",
1185
+ "-g",
1186
+ "-m",
1187
+ "-A",
1188
+ "-B",
1089
1189
  "-C",
1090
1190
  "-d",
1191
+ "-D",
1091
1192
  "-E",
1092
- "-f",
1093
- "-g",
1094
- "-I",
1095
- "-k",
1096
- "-L",
1097
- "-n",
1098
- "-o",
1099
- "-p",
1100
- "-P",
1193
+ "-j",
1194
+ "-M",
1101
1195
  "-r",
1102
- "-s",
1103
1196
  "-t",
1104
1197
  "-T",
1105
- "-u",
1106
- "-U",
1107
- "--adjustment",
1108
- "--group",
1109
- "--kill-after",
1110
- "--signal",
1111
- "--user"
1198
+ "--regexp",
1199
+ "--file",
1200
+ "--glob",
1201
+ "--iglob",
1202
+ "--type",
1203
+ "--type-not",
1204
+ "--max-count",
1205
+ "--after-context",
1206
+ "--before-context",
1207
+ "--context",
1208
+ "--directories",
1209
+ "--devices",
1210
+ "--encoding",
1211
+ "--threads",
1212
+ "--max-columns",
1213
+ "--max-depth",
1214
+ "--max-filesize",
1215
+ "--replace",
1216
+ "--sort",
1217
+ "--sortr",
1218
+ "--include",
1219
+ "--exclude",
1220
+ "--exclude-from",
1221
+ "--exclude-dir",
1222
+ "--include-dir",
1223
+ "--label",
1224
+ "--pre",
1225
+ "--pre-glob",
1226
+ "--ignore-file"
1112
1227
  ]);
1113
1228
  /** 命令前的壳层赋值(`VAR=1 grep x` 里的 `VAR=1`):它自己不是命令,其后仍是命令位。 */
1114
- const SHELL_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
1229
+ const SHELL_ASSIGNMENT = /^[A-Za-z_]\w*=/u;
1115
1230
  /** 包装命令的裸数值参数(`timeout 5 rg` 的 `5`):也不是被执行的命令。 */
1116
1231
  const BARE_NUMBER = /^\d+$/u;
1117
- /** 结束一个 token、但**不**开启新命令位的字符(空白、右括号、重定向)。 */
1232
+ /** 结束一个 token、但**不**开启新命令位的字符(空白)。 */
1118
1233
  const TOKEN_BREAK_CHARS = /* @__PURE__ */ new Set([
1119
1234
  " ",
1120
1235
  " ",
1121
1236
  "\v",
1122
- "\f",
1123
- ")",
1124
- "<",
1125
- ">"
1237
+ "\f"
1126
1238
  ]);
1127
- /** 结束一个 token 并让紧随其后的 token 处于命令位(控制符 / 换行 / 反引号 / 组)。 */
1239
+ /** 结束一个 token 并让紧随其后的 token 处于命令位(控制符 / 换行 / 反引号)。 */
1128
1240
  const COMMAND_BREAK_CHARS = /* @__PURE__ */ new Set([
1129
1241
  "|",
1130
1242
  ";",
1131
1243
  "&",
1132
- "(",
1133
1244
  "\n",
1134
1245
  "\r",
1135
- "`",
1246
+ "`"
1247
+ ]);
1248
+ /**
1249
+ * 重定向符:其后那一个 token 是 I/O 目标(`> /tmp/out`、`< /tmp/in`),不是检索操作数。
1250
+ * 判「目标是否在根外」时必须跳过它——否则 `grep foo src > /tmp/out` 会凭一个输出文件
1251
+ * 被判成「检索根外目标」而放行。
1252
+ */
1253
+ const REDIRECT_CHARS = /* @__PURE__ */ new Set(["<", ">"]);
1254
+ /**
1255
+ * 组字符:只有在**独立成词**(buffer 为空)时才是分隔——`(subshell)`、`{ group; }`
1256
+ * 之后是新的命令位。词中的它们属参数展开 / 命令替换(`${DIR}/src`、`$(pwd)/src`),
1257
+ * 必须并进当前 token:切成独立伪 token 会让 `/src` 这类片段被当成绝对路径证据而放行。
1258
+ */
1259
+ const GROUP_CHARS = /* @__PURE__ */ new Set([
1260
+ "(",
1261
+ ")",
1136
1262
  "{",
1137
1263
  "}"
1138
1264
  ]);
@@ -1155,12 +1281,111 @@ function indexAfterComment(command, from) {
1155
1281
  return nextLine === -1 ? command.length : nextLine - 1;
1156
1282
  }
1157
1283
  /**
1284
+ * 控制符(`|` `;` `&` 换行 反引号)之后:新命令位开始,并记下「下一段是否吃上一段的 stdout」。
1285
+ *
1286
+ * 只有单个 `|` 把上一段的 stdout 接进下一段的 stdin;`;`、`&&`、`||` 之后的命令不是
1287
+ * (`||` 的后半段恰恰是「前半段没产出时才跑」的那条,输入不是 stdout)。`||` 由两个竖线
1288
+ * 字符分别进来,前一枚与后一枚都必须判成「不是管道」。
1289
+ */
1290
+ function markCommandBreak(command, index, char, state) {
1291
+ state.atCommand = true;
1292
+ const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
1293
+ state.pipedNext = char === "|" && !neighbourIsPipe;
1294
+ }
1295
+ /**
1296
+ * 独立成词的组字符才分隔(`(subshell)` / `{ group; }`):`(` 与 `{` 之后是新命令位;
1297
+ * 词中的它们是展开的一部分(`${DIR}/src`、`$(pwd)/src`),并进当前 token。
1298
+ */
1299
+ function consumeGroupChar(char, state) {
1300
+ if (state.buffer.length > 0) state.buffer += char;
1301
+ else if (char === "(" || char === "{") state.atCommand = true;
1302
+ }
1303
+ /** 引号外、词首的 `#` 起为注释(整段跳到行尾)。 */
1304
+ function isCommentStart(char, state) {
1305
+ return state.quote === "" && char === "#" && state.buffer.length === 0;
1306
+ }
1307
+ /**
1308
+ * 词中开/闭引号(grep'rg')合并进同一 token:混淆写法照拦。
1309
+ * 走到这里的 char 只可能是「空」或「与 quote 同种」(异种引号在更上面的分支已被当作
1310
+ * 字面量吃进 buffer),故一个三元即覆盖开/闭两种情形。
1311
+ */
1312
+ function toggleQuote(char, quote) {
1313
+ return quote === char ? "" : char;
1314
+ }
1315
+ /** 包装命令的旗标、裸数值、壳层赋值:都不是被执行的命令,也不结束命令位链。 */
1316
+ function isWrapperNoiseText(isCommand, text) {
1317
+ return isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text));
1318
+ }
1319
+ /**
1320
+ * 明确的路径形状:绝对路径、含 `/` 的相对路径、裸 `.` 与 `..`(模式词与文件名不算)。
1321
+ * `.` 与 `..` 都算:`grep foo .` 检索的就是当前工作区。
1322
+ */
1323
+ function isPathShape(text) {
1324
+ return text.startsWith("/") || text.includes("/") || text === "." || text === "..";
1325
+ }
1326
+ /**
1327
+ * token 的命令名(basename,小写)。
1328
+ * 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
1329
+ * (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
1330
+ * 永远走不到的分支。
1331
+ */
1332
+ function baseName(text) {
1333
+ return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
1334
+ }
1335
+ /**
1336
+ * 把一枚 token 推进命令位链(纯函数:不改入参,返回下一状态与「这枚是不是命令」)。
1337
+ *
1338
+ * 单独成函数不为复用,只为把这条含 3 层嵌套的判定链从循环里挪出来——循环里只剩
1339
+ * 「推进一步、命中就记下标」两件事。
1340
+ */
1341
+ function advanceCommandChain(token, state) {
1342
+ const { text } = token;
1343
+ const consumingValue = state.pendingValue;
1344
+ const next = {
1345
+ ...state,
1346
+ pendingValue: false
1347
+ };
1348
+ if (consumingValue) next.afterPrefix = true;
1349
+ else if (token.atCommand) {
1350
+ next.wrapper = "";
1351
+ next.afterPrefix = false;
1352
+ }
1353
+ const isCommand = token.atCommand || next.afterPrefix || next.wrapper !== "";
1354
+ const takesValue = isCommand && VALUE_TAKING_FLAGS.get(next.wrapper)?.has(text) === true;
1355
+ if (consumingValue && !token.atCommand) return {
1356
+ state: next,
1357
+ command: false
1358
+ };
1359
+ if (takesValue) {
1360
+ next.pendingValue = true;
1361
+ return {
1362
+ state: next,
1363
+ command: false
1364
+ };
1365
+ }
1366
+ if (isWrapperNoiseText(isCommand, text)) {
1367
+ next.afterPrefix = true;
1368
+ return {
1369
+ state: next,
1370
+ command: false
1371
+ };
1372
+ }
1373
+ if (isCommand) next.wrapper = SEARCH_PREFIX_WORDS.has(baseName(text)) ? baseName(text) : "";
1374
+ next.afterPrefix = false;
1375
+ return {
1376
+ state: next,
1377
+ command: isCommand
1378
+ };
1379
+ }
1380
+ /**
1158
1381
  * 手写 shell 切词(只为「找出命令位上的命令名」服务,不做完整求值):
1159
1382
  * - 单/双引号与反斜杠转义**内部**的字符不参与分隔 → `echo "grep x"`、
1160
1383
  * `printf 'grep'`、`git commit -m "use rg"` 里的字面量不再被当成命令
1161
1384
  * (旧实现把引号当分隔符,故这三种全被判为检索 → 过度拦截);
1162
1385
  * - 引号外、词首的 `#` 起为注释,整段跳到行尾;
1163
- * - 控制符(`|` `;` `&` `(` 换行 反引号 `{` `}`)之后的 token 记为命令位。
1386
+ * - 控制符(`|` `;` `&` 换行 反引号)与**独立成词**的 `(` / `{` 之后的 token 记为
1387
+ * 命令位;词中的组字符属参数展开 / 命令替换(`${DIR}/src`、`$(pwd)/src`),并进当前 token;
1388
+ * - 重定向符(`<` `>`)之后的那一个 token 标记为 `redirect`:它是 I/O 落点,不是检索操作数。
1164
1389
  * 双引号内保留字面内容(含空格),故 `"/usr/bin/rg foo"` 是一个非命令位 token。
1165
1390
  */
1166
1391
  function tokenizeShell(command) {
@@ -1169,6 +1394,7 @@ function tokenizeShell(command) {
1169
1394
  buffer: "",
1170
1395
  atCommand: true,
1171
1396
  pipedNext: false,
1397
+ redirectNext: false,
1172
1398
  quote: ""
1173
1399
  };
1174
1400
  const flush = () => {
@@ -1176,11 +1402,13 @@ function tokenizeShell(command) {
1176
1402
  tokens.push({
1177
1403
  text: state.buffer,
1178
1404
  atCommand: state.atCommand,
1179
- piped: state.pipedNext
1405
+ piped: state.pipedNext,
1406
+ redirect: state.redirectNext
1180
1407
  });
1181
1408
  state.buffer = "";
1182
1409
  state.atCommand = false;
1183
1410
  state.pipedNext = false;
1411
+ state.redirectNext = false;
1184
1412
  }
1185
1413
  };
1186
1414
  let index = 0;
@@ -1191,14 +1419,16 @@ function tokenizeShell(command) {
1191
1419
  state.buffer += char;
1192
1420
  escaped = false;
1193
1421
  } else if (isQuotedLiteral(char, state.quote)) state.buffer += char;
1194
- else if (state.quote === "" && char === "#" && state.buffer.length === 0) index = indexAfterComment(command, index);
1422
+ else if (isCommentStart(char, state)) index = indexAfterComment(command, index);
1195
1423
  else if (char === "\\") escaped = true;
1196
- else if (QUOTE_CHARS.has(char)) state.quote = state.quote === char ? "" : char;
1424
+ else if (QUOTE_CHARS.has(char)) state.quote = toggleQuote(char, state.quote);
1197
1425
  else if (COMMAND_BREAK_CHARS.has(char)) {
1198
1426
  flush();
1199
- state.atCommand = true;
1200
- const neighbourIsPipe = command.slice(index + 1, index + 2) === "|" || command.slice(index - 1, index) === "|";
1201
- state.pipedNext = char === "|" && !neighbourIsPipe;
1427
+ markCommandBreak(command, index, char, state);
1428
+ } else if (GROUP_CHARS.has(char)) consumeGroupChar(char, state);
1429
+ else if (REDIRECT_CHARS.has(char)) {
1430
+ flush();
1431
+ state.redirectNext = true;
1202
1432
  } else if (TOKEN_BREAK_CHARS.has(char)) flush();
1203
1433
  else state.buffer += char;
1204
1434
  index += 1;
@@ -1207,15 +1437,6 @@ function tokenizeShell(command) {
1207
1437
  return tokens;
1208
1438
  }
1209
1439
  /**
1210
- * token 的命令名(basename,小写)。
1211
- * 两个调用点都只喂命令位 token,而命令位判据已经把 `-` 开头的选项排除了
1212
- * (见 `commandPositionIndexes`),所以这里不再重复判一次前缀:那会是一条
1213
- * 永远走不到的分支。
1214
- */
1215
- function baseName(text) {
1216
- return text.slice(text.lastIndexOf("/") + 1).toLowerCase();
1217
- }
1218
- /**
1219
1440
  * 挑出处在「被执行位置」的 token:串首 / 控制符之后 / 包装命令(git、xargs、
1220
1441
  * env…)之后那个真正的实参。
1221
1442
  *
@@ -1226,20 +1447,15 @@ function baseName(text) {
1226
1447
  */
1227
1448
  function commandPositionIndexes(tokens) {
1228
1449
  const out = [];
1229
- let afterPrefix = false;
1230
- let pendingValue = false;
1450
+ let chain = {
1451
+ wrapper: "",
1452
+ pendingValue: false,
1453
+ afterPrefix: false
1454
+ };
1231
1455
  for (const [index, token] of tokens.entries()) {
1232
- const { text } = token;
1233
- const isCommand = token.atCommand || afterPrefix;
1234
- if (pendingValue) {
1235
- pendingValue = false;
1236
- afterPrefix = true;
1237
- } else if (isCommand && VALUE_TAKING_FLAGS.has(text)) pendingValue = true;
1238
- else if (isCommand && (text.startsWith("-") || BARE_NUMBER.test(text) || SHELL_ASSIGNMENT.test(text))) afterPrefix = true;
1239
- else {
1240
- if (isCommand) out.push(index);
1241
- afterPrefix = isCommand && SEARCH_PREFIX_WORDS.has(baseName(text));
1242
- }
1456
+ const step = advanceCommandChain(token, chain);
1457
+ chain = step.state;
1458
+ if (step.command) out.push(index);
1243
1459
  }
1244
1460
  return out;
1245
1461
  }
@@ -1250,7 +1466,7 @@ function commandPositionIndexes(tokens) {
1250
1466
  function hasPathOperand(tokens, from) {
1251
1467
  for (const token of tokens.slice(from + 1)) {
1252
1468
  if (token.atCommand) break;
1253
- if (!token.text.startsWith("-") && (token.text.startsWith("/") || token.text.includes("/") || token.text === "." || token.text === "..")) return true;
1469
+ if (!token.redirect && !token.text.startsWith("-") && isPathShape(token.text)) return true;
1254
1470
  }
1255
1471
  return false;
1256
1472
  }
@@ -1273,7 +1489,8 @@ function hasPathOperand(tokens, from) {
1273
1489
  * - --help/--version/-V 豁免按整条命令判断(`rg a --version && grep b c`
1274
1490
  * 复合命令会漏拦 grep);
1275
1491
  * - shell 关键字(`for … ; do grep`、`if … ; then rg`)不是控制符,其后的
1276
- * grep 不在命令位;`VAR=1 grep x` 同理。
1492
+ * grep 不在命令位。壳层赋值(`VAR=1 grep x`)**不**属此列:commandPositionIndexes
1493
+ * 把 `VAR=1` 当「跳过但不断链」处理。
1277
1494
  */
1278
1495
  function isGrepRgCommand(command) {
1279
1496
  const tokens = tokenizeShell(command);
@@ -1293,7 +1510,7 @@ function isGrepRgCommand(command) {
1293
1510
  * 失败形态是 fail-fast 而不是静默漂移。要真正支持 Windows,得连上面那三处判据一起改。
1294
1511
  */
1295
1512
  function normalizeRoot(root) {
1296
- const trimmed = root.replace(/\/+$/u, "");
1513
+ const trimmed = root.replace(TRAILING_SLASHES$1, "");
1297
1514
  return trimmed.length > 0 ? trimmed : "/";
1298
1515
  }
1299
1516
  /**
@@ -1334,9 +1551,18 @@ function pathInsideRoot(target, root, messages) {
1334
1551
  */
1335
1552
  function hasExternalTarget(root, command, messages) {
1336
1553
  const base = normalizeRoot(root);
1337
- for (const token of tokenizeShell(command)) {
1554
+ const tokens = tokenizeShell(command);
1555
+ const commandIndexes = new Set(commandPositionIndexes(tokens));
1556
+ /** 上一枚是检索侧的取值旗标:这一枚是它的值(模式 / glob / 编码名…),不是目标。 */
1557
+ let pendingValue = false;
1558
+ for (const [index, token] of tokens.entries()) {
1338
1559
  const { text } = token;
1339
- if (!text.startsWith("-") && (text.startsWith("/") || text.includes("/") || text === "..") && !pathInsideRoot(text, base, messages)) return true;
1560
+ const consumedValue = pendingValue;
1561
+ pendingValue = false;
1562
+ if (!(commandIndexes.has(index) || consumedValue || token.redirect)) {
1563
+ if (text.startsWith("-")) pendingValue = SEARCH_VALUE_FLAGS.has(text);
1564
+ else if (isPathShape(text) && !pathInsideRoot(text, base, messages)) return true;
1565
+ }
1340
1566
  }
1341
1567
  return false;
1342
1568
  }
@@ -1390,6 +1616,19 @@ const ZG_TOOL_NAMES = /* @__PURE__ */ new Set([
1390
1616
  function isZgToolName(name) {
1391
1617
  return typeof name === "string" && ZG_TOOL_NAMES.has(name);
1392
1618
  }
1619
+ /** search-first 门禁要求先调用的工具名(与注册表里的名字同源)。 */
1620
+ const ZG_SEARCH_NAME = "zg_search";
1621
+ /**
1622
+ * `zg_search` 在本步骤是否可执行。宿主不交步骤准入(rc 线)时按既有的「可执行」处理:
1623
+ * 没有准入信息就不该凭空放行。有准入时按该 Agent 的作用域查视图——受限子代理的
1624
+ * 拒绝与条件工具的未准入都在这里显形,门禁不再强迫模型去调一个本步骤调不动的工具。
1625
+ */
1626
+ function searchAdmitted(execution) {
1627
+ const { toolSet } = execution;
1628
+ if (toolSet === void 0) return true;
1629
+ const scope = execution.agent?.ctx === void 0 ? void 0 : scopeOf(execution.agent.ctx);
1630
+ return toolSet.view(scope).has(ZG_SEARCH_NAME);
1631
+ }
1393
1632
  /** 会话工作区(官方 Agent.session.header.cwd;值按 unknown 读,理由见 SessionFace)。 */
1394
1633
  function sessionHeaderCwd$1(execution) {
1395
1634
  const raw = execution.agent?.session?.header?.cwd;
@@ -1529,29 +1768,35 @@ function nativeTargetInsideRoot(cwd, indexRoot, target, messages) {
1529
1768
  }
1530
1769
  return pathInsideRoot(absolute, indexRoot, messages);
1531
1770
  }
1532
- function buildSearchFirstReason(cwd, scope, deps, messages) {
1533
- const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
1771
+ /** 索引根已定且这棵树的范围判定要走门禁时的那句拒绝理由;交回 undefined 即放行。 */
1772
+ function gateReasonAt(indexRoot, cwd, scope, deps, messages) {
1773
+ const inScope = scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages);
1534
1774
  let reason;
1535
- if (indexRoot !== void 0 && (scope.kind === "shell" ? !hasExternalTarget(indexRoot, scope.command, messages) : nativeTargetInsideRoot(cwd, indexRoot, scope.target, messages))) {
1536
- const rebuilding = deps.rebuildBypass?.(indexRoot) === true;
1537
- const unlock = rebuilding ? void 0 : deps.lookupUnlock(indexRoot);
1538
- if (rebuilding) {} else if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
1539
- else {
1540
- let state;
1541
- if (unlock === void 0) state = messages.gateNeverSearched;
1542
- else if (unlock.grepsLeft <= 0) state = messages.gateQuotaExhausted;
1543
- else state = messages.gateUnlockExpired;
1544
- reason = fill(messages.gateReason, {
1545
- state,
1546
- indexRoot,
1547
- indexDir: INDEX_DIR_NAME,
1548
- budget: deps.grepBudget,
1549
- windowMin: deps.windowMin
1550
- });
1775
+ if (inScope) {
1776
+ if (!(deps.rebuildBypass?.(indexRoot) === true)) {
1777
+ const unlock = deps.lookupUnlock(indexRoot);
1778
+ if (unlock !== void 0 && unlockActive(unlock, deps.now())) deps.consumeGrep(unlock);
1779
+ else {
1780
+ let state;
1781
+ if (unlock === void 0) state = messages.gateNeverSearched;
1782
+ else if (unlock.grepsLeft <= 0) state = messages.gateQuotaExhausted;
1783
+ else state = messages.gateUnlockExpired;
1784
+ reason = fill(messages.gateReason, {
1785
+ state,
1786
+ indexRoot,
1787
+ indexDir: INDEX_DIR_NAME,
1788
+ budget: deps.grepBudget,
1789
+ windowMin: deps.windowMin
1790
+ });
1791
+ }
1551
1792
  }
1552
1793
  }
1553
1794
  return reason;
1554
1795
  }
1796
+ function buildSearchFirstReason(cwd, scope, deps, messages) {
1797
+ const indexRoot = findIndexRoot(cwd, deps.indexProbe, deps.findIndexDepth);
1798
+ return indexRoot === void 0 ? void 0 : gateReasonAt(indexRoot, cwd, scope, deps, messages);
1799
+ }
1555
1800
  /**
1556
1801
  * shell 面(bash/pwsh)的一次检索裁决:命令串里真出现 grep/rg 才交给门禁,
1557
1802
  * 否则放行。`command` 非字符串(模型产出的是 unknown)按空串处理,与旧实现同形。
@@ -1586,12 +1831,18 @@ function searchFirstGuard(execution, deps, messages) {
1586
1831
  const args = isRecord(execution.arguments) ? execution.arguments : {};
1587
1832
  const cwd = sessionHeaderCwd$1(execution);
1588
1833
  let reason;
1589
- if (deps.enabled && cwd !== void 0) {
1834
+ if (deps.enabled && cwd !== void 0 && searchAdmitted(execution)) {
1590
1835
  if (name === "bash" || name === "pwsh") reason = shellSearchProblem(args, cwd, deps, messages);
1591
1836
  else if (name === "grep") reason = nativeGrepProblem(args, cwd, deps, messages);
1592
1837
  }
1593
1838
  return reason;
1594
1839
  }
1840
+ // lib/rebuild-state.ts
1841
+ /** 「某条占位已落定」这条承诺的收口:只交回结论,把 promise 本身留在注册表内部。 */
1842
+ async function settledOutcome(target) {
1843
+ await target.settled;
1844
+ return "settled";
1845
+ }
1595
1846
  /**
1596
1847
  * 表超过阈值就报警一次(不删任何条目)。
1597
1848
  *
@@ -1626,23 +1877,25 @@ function createRebuildRegistry(options = {}) {
1626
1877
  const maxTracked = options.maxTracked ?? 32;
1627
1878
  const entries = /* @__PURE__ */ new Map();
1628
1879
  let crowded = false;
1629
- const release = (root) => {
1630
- const entry = entries.get(root);
1631
- if (entry === void 0) return false;
1632
- entries.delete(root);
1880
+ const release = (root, claimed) => {
1881
+ const key = normalizeRoot(root);
1882
+ const entry = entries.get(key);
1883
+ if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
1884
+ entries.delete(key);
1633
1885
  entry.settle();
1634
1886
  if (entries.size <= maxTracked) crowded = false;
1635
1887
  return true;
1636
1888
  };
1637
1889
  return {
1638
1890
  claim(root, origin, startedAt) {
1639
- if (entries.has(root)) return null;
1891
+ const key = normalizeRoot(root);
1892
+ if (entries.has(key)) return null;
1640
1893
  const { promise: settled, resolve } = Promise.withResolvers();
1641
1894
  const settle = () => {
1642
1895
  resolve(void 0);
1643
1896
  };
1644
1897
  const entry = {
1645
- root,
1898
+ root: key,
1646
1899
  origin,
1647
1900
  startedAt: startedAt ?? now(),
1648
1901
  phase: "starting",
@@ -1650,28 +1903,26 @@ function createRebuildRegistry(options = {}) {
1650
1903
  settled,
1651
1904
  settle
1652
1905
  };
1653
- entries.set(root, entry);
1906
+ entries.set(key, entry);
1654
1907
  crowded = warnIfCrowded(entries, maxTracked, crowded);
1655
1908
  return entry;
1656
1909
  },
1657
- attach(root, jobId) {
1658
- const entry = entries.get(root);
1659
- if (entry === void 0) return;
1910
+ attach(root, jobId, claimed) {
1911
+ const entry = entries.get(normalizeRoot(root));
1912
+ if (entry === void 0 || claimed !== void 0 && claimed !== entry) return false;
1660
1913
  entry.jobId = jobId;
1661
1914
  entry.phase = "running";
1915
+ return true;
1662
1916
  },
1663
1917
  release,
1664
1918
  active(root) {
1665
- return entries.get(root);
1919
+ return entries.get(normalizeRoot(root));
1666
1920
  },
1667
1921
  covering(root, messages) {
1668
- return coveringOf(entries, root, messages);
1669
- },
1670
- hasPollable(root) {
1671
- return entries.get(root)?.jobId !== void 0;
1922
+ return coveringOf(entries, normalizeRoot(root), messages);
1672
1923
  },
1673
1924
  async wait(root, messages, timeoutMs, signal) {
1674
- const entry = coveringOf(entries, root, messages);
1925
+ const entry = coveringOf(entries, normalizeRoot(root), messages);
1675
1926
  if (entry === void 0) return "settled";
1676
1927
  if (signal?.aborted === true) return "aborted";
1677
1928
  const { promise, resolve } = Promise.withResolvers();
@@ -1682,12 +1933,14 @@ function createRebuildRegistry(options = {}) {
1682
1933
  resolve("aborted");
1683
1934
  };
1684
1935
  signal?.addEventListener("abort", onAbort, { once: true });
1685
- const settledOutcome = async () => {
1686
- await entry.settled;
1687
- return "settled";
1936
+ const waitCovering = async (target) => {
1937
+ const outcome = await Promise.race([settledOutcome(target), promise]);
1938
+ if (outcome !== "settled") return outcome;
1939
+ const next = coveringOf(entries, root, messages);
1940
+ return next === void 0 ? "settled" : waitCovering(next);
1688
1941
  };
1689
1942
  try {
1690
- return await Promise.race([settledOutcome(), promise]);
1943
+ return await waitCovering(entry);
1691
1944
  } finally {
1692
1945
  clearTimeout(timer);
1693
1946
  signal?.removeEventListener("abort", onAbort);
@@ -1700,6 +1953,10 @@ function createRebuildRegistry(options = {}) {
1700
1953
  }
1701
1954
  /** 索引重建与其它占用者分开:等与不等是两回事。 */
1702
1955
  const REBUILD_OPERATION = "index.rebuild";
1956
+ /** 明细块的表头行(`Details:`)。 */
1957
+ const DETAILS_HEADER = /^\s*Details:\s*$/u;
1958
+ /** 行首空白:明细键值行以缩进起始,零缩进内容属于下一段。 */
1959
+ const INDENTED_LINE = /^\s/u;
1703
1960
  /**
1704
1961
  * zg 明细块的键值行。三个细节都来自「明细行是缩进的」这一实测形状:
1705
1962
  * - 缩进**必填**(`\s+`):明细块之后任何含冒号的非空行(第二个错误块的 `Error:` /
@@ -1708,7 +1965,7 @@ const REBUILD_OPERATION = "index.rebuild";
1708
1965
  * 还能被认出来(值是否被消费由查表侧决定),不至于整块收集在此中断;
1709
1966
  * - 值必须以非空白开头:把只含空白的行当成有效值没有意义。
1710
1967
  */
1711
- const DETAIL_LINE = /^(?:\s+)(?<key>[A-Za-z][\w-]*):\s*(?<value>\S.*?)\s*$/u;
1968
+ const DETAIL_LINE = /^\s+(?<key>[A-Za-z][\w-]*):\s*(?<value>\S.*)$/u;
1712
1969
  /** 错误码行的**定位**形状(只认行首,不核内容)。 */
1713
1970
  const CODE_LINE_PREFIX = /^\s*Code:/u;
1714
1971
  /** 错误码行的**取值**形状:`Code:` 之后是单一 token。 */
@@ -1724,19 +1981,43 @@ function zgErrorCode(stderr) {
1724
1981
  return firstCodeLine === void 0 ? void 0 : CODE_LINE.exec(firstCodeLine)?.groups?.["code"];
1725
1982
  }
1726
1983
  /**
1984
+ * 在第一个错误块的码行之后找明细表头。明细必须属于第一个错误块:码行之后遇到下一条
1985
+ * 无缩进内容(第二个块的 Error:/Code: 或散文)就说明这一块没有明细,不能顺延去捡后面
1986
+ * 块的键值。找不到返回 -1。
1987
+ */
1988
+ function detailsStartAfter(lines, codeIndex) {
1989
+ const rest = lines.slice(codeIndex + 1);
1990
+ for (const [offset, line] of rest.entries()) {
1991
+ if (DETAILS_HEADER.test(line)) return codeIndex + 1 + offset;
1992
+ if (line.trim().length > 0 && !INDENTED_LINE.test(line)) return -1;
1993
+ }
1994
+ return -1;
1995
+ }
1996
+ /**
1727
1997
  * 明细块的键值表。`Details:` 之后的缩进行才是明细,标题与错误码行不参与。
1728
1998
  * 重复键取首次出现(zg 不会重复输出同一个键,重复即形状异常,不覆盖)。
1729
1999
  * 明细块遇到非键值行即终止:其后多半是尾部截断的散文,继续收只会捡到假键值。
2000
+ * 导出只为把「没有 Code 行时不捡明细」这一支钉进单测;生产侧只经
2001
+ * `classifyConcurrentFailure` 调用(那里已先确认有码)。
1730
2002
  */
2003
+ /** 明细块的协议键:查表侧只许从这里取值,键名改名不会漏改一条。 */
2004
+ const DETAIL_KEY = {
2005
+ ownerOperation: "ownerOperation",
2006
+ ownerPid: "ownerPid",
2007
+ lock: "lock",
2008
+ pid: "pid"
2009
+ };
1731
2010
  function zgErrorDetails(stderr) {
1732
2011
  const details = /* @__PURE__ */ new Map();
1733
2012
  const lines = stderr.split("\n");
1734
- const start = lines.findIndex((line) => /^\s*Details:\s*$/u.test(line));
2013
+ const codeIndex = lines.findIndex((line) => CODE_LINE_PREFIX.test(line));
2014
+ if (codeIndex === -1) return details;
2015
+ const start = detailsStartAfter(lines, codeIndex);
1735
2016
  if (start === -1) return details;
1736
2017
  for (const line of lines.slice(start + 1)) {
1737
2018
  const matched = DETAIL_LINE.exec(line);
1738
2019
  const key = matched?.groups?.["key"];
1739
- const value = matched?.groups?.["value"];
2020
+ const value = matched?.groups?.["value"]?.trimEnd();
1740
2021
  if (key !== void 0 && value !== void 0) {
1741
2022
  if (!details.has(key)) details.set(key, value);
1742
2023
  } else if (line.trim().length > 0) break;
@@ -1753,17 +2034,17 @@ function classifyConcurrentFailure(stderr) {
1753
2034
  const code = zgErrorCode(stderr);
1754
2035
  if (code === void 0) return null;
1755
2036
  const details = zgErrorDetails(stderr);
1756
- const ownerOperation = details.get("ownerOperation");
2037
+ const ownerOperation = details.get(DETAIL_KEY.ownerOperation);
1757
2038
  if (code === "ZVEC_GREP.ENGINE.LOCK.BUSY") return {
1758
2039
  kind: "lock-busy",
1759
2040
  ownerOperation,
1760
- ownerPid: details.get("ownerPid"),
1761
- lockPath: details.get("lock"),
2041
+ ownerPid: details.get(DETAIL_KEY.ownerPid),
2042
+ lockPath: details.get(DETAIL_KEY.lock),
1762
2043
  rebuild: ownerOperation === REBUILD_OPERATION
1763
2044
  };
1764
2045
  if (code === "ZVEC_GREP.ENGINE.DAEMON_LEASE_ACTIVE") return {
1765
2046
  kind: "daemon-lease",
1766
- pid: details.get("pid")
2047
+ pid: details.get(DETAIL_KEY.pid)
1767
2048
  };
1768
2049
  return null;
1769
2050
  }
@@ -1777,8 +2058,12 @@ const MINIMUM = {
1777
2058
  minor: 2,
1778
2059
  patch: 2
1779
2060
  };
2061
+ /** 版本号的字面形态(回显用:门槛文案要让用户看得见自己装的是哪个版本)。 */
2062
+ function formatZgVersion(version) {
2063
+ return `${version.major}.${version.minor}.${version.patch}`;
2064
+ }
1780
2065
  /** 本包按之书写的 zg 语义版本(字面形态,给文案回显)。低于它一律在命令构造前拒绝。 */
1781
- const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
2066
+ const MINIMUM_ZG_VERSION = formatZgVersion(MINIMUM);
1782
2067
  /**
1783
2068
  * 形状:整串就是一个三段数字版本,`v` 前缀可有可无,可带前后的空白与换行。
1784
2069
  * 分量至多 9 位数字:`Number()` 对超长数字串会丢精度乃至得到 Infinity,畸形输入
@@ -1789,8 +2074,8 @@ const MINIMUM_ZG_VERSION = `${MINIMUM.major}.${MINIMUM.minor}.${MINIMUM.patch}`;
1789
2074
  const VERSION_SHAPE = /^\s*v?(?<major>\d{1,9})\.(?<minor>\d{1,9})\.(?<patch>\d{1,9})\s*$/u;
1790
2075
  /**
1791
2076
  * 不是版本号时用的哨兵:版本分量恒非负,故负数只可能来自「没解析出来」。
1792
- * 三个函数都收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
1793
- * consistent-return 判成两种返回形态),故用哨兵而不是提前 return。
2077
+ * `parseZgVersion` 收敛成**单一 return**(`return a` 与 `return undefined` 混排会被本仓的
2078
+ * consistent-return 判成两种返回形态),故用哨兵而不是提前 return;其它函数不受此约束。
1794
2079
  */
1795
2080
  const UNPARSED = -1;
1796
2081
  /** 取一段具名捕获组;组不存在时给哨兵。 */
@@ -1810,10 +2095,6 @@ function parseZgVersion(stdout) {
1810
2095
  patch
1811
2096
  };
1812
2097
  }
1813
- /** 版本号的字面形态(回显用:门槛文案要让用户看得见自己装的是哪个版本)。 */
1814
- function formatZgVersion(version) {
1815
- return `${version.major}.${version.minor}.${version.patch}`;
1816
- }
1817
2098
  /** actual 是否 >= minimum:逐段比数值(不是比字符串,否则 `0.10.0 < 0.9.0`)。 */
1818
2099
  function versionAtLeast(actual, minimum) {
1819
2100
  if (actual.major !== minimum.major) return actual.major > minimum.major;
@@ -1839,7 +2120,8 @@ const UNUSABLE_FILE_CODES = /* @__PURE__ */ new Set([
1839
2120
  "ENOENT",
1840
2121
  "EACCES",
1841
2122
  "EISDIR",
1842
- "ENOTDIR"
2123
+ "ENOTDIR",
2124
+ "ENAMETOOLONG"
1843
2125
  ]);
1844
2126
  /** node:fs 的失败一律是带 string code 的 Error 实例;形状不合(非对象、无 code、码非串)
1845
2127
  * 一律按环境故障处理。导出只为把非 Error 形状的判别面钉进单测(真 fs 抛不出这些)。 */
@@ -1891,9 +2173,10 @@ function assertIgnoreFilesExist(args, root, messages) {
1891
2173
  * 会产出「enforcement=」这类残缺后缀——缺席与空白同归「不交代」。
1892
2174
  */
1893
2175
  function sandboxFacts(info, messages) {
1894
- const enforcement = info.enforcement === void 0 || info.enforcement.length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
2176
+ const enforcement = info.enforcement === void 0 || info.enforcement.trim().length === 0 ? "" : fill(messages.sandboxEnforcement, { value: info.enforcement });
2177
+ const mode = typeof info.mode === "string" && info.mode.trim().length > 0 ? info.mode.trim() : "unknown";
1895
2178
  return fill(messages.sandboxFacts, {
1896
- mode: info.mode,
2179
+ mode,
1897
2180
  enforcement
1898
2181
  });
1899
2182
  }
@@ -1928,6 +2211,8 @@ function procSandboxNote(proc, messages) {
1928
2211
  /** 宿主服务键 = 客户端线上命名空间(两侧共用的唯一来源)。 */
1929
2212
  const REBUILD_REMOTE_NAMESPACE = "zvecGrepRebuild";
1930
2213
  // lib/zg-config.ts
2214
+ /** 端点末尾斜杠。 */
2215
+ const TRAILING_SLASHES = /\/+$/u;
1931
2216
  /** http(s) 且带 host 的基地址才算端点:`http://`、`/` 这类值不是可用的镜像基地址。 */
1932
2217
  function isUsableBaseUrl(value) {
1933
2218
  try {
@@ -1943,14 +2228,13 @@ function isUsableBaseUrl(value) {
1943
2228
  * 规范化(剥尾斜杠)之后还要再验一次:`/`、`///` 会被剥成空串,`http://` 这类没有
1944
2229
  * host 的值也不是基地址——发一个空的或畸形的 HF_ENDPOINT 只会把失败推迟到
1945
2230
  * node-llama-cpp 的下载期,定位成本远高于这里的一次静默省略。 */
2231
+ function normalizedEndpoint(value) {
2232
+ const normalized = typeof value === "string" ? value.trim().replace(TRAILING_SLASHES, "") : "";
2233
+ return normalized.length > 0 && isUsableBaseUrl(normalized) ? normalized : void 0;
2234
+ }
1946
2235
  function hfEndpointEnv(config) {
1947
- const endpoint = config.hfEndpoint.get();
1948
- let env;
1949
- if (typeof endpoint === "string") {
1950
- const normalized = endpoint.trim().replace(/\/+$/u, "");
1951
- if (normalized.length > 0 && isUsableBaseUrl(normalized)) env = { HF_ENDPOINT: normalized };
1952
- }
1953
- return env;
2236
+ const endpoint = normalizedEndpoint(config.hfEndpoint.get());
2237
+ return endpoint === void 0 ? void 0 : { HF_ENDPOINT: endpoint };
1954
2238
  }
1955
2239
  /**
1956
2240
  * 部署值里的可选字符串:空串/空白/非字符串一律归一成 undefined(=「没配」)。
@@ -1975,7 +2259,7 @@ function allowRemoteEmbedding(config) {
1975
2259
  * 任意变量(含与 zg 无关的敏感值)转发给子进程;`__proto__` / `constructor` 这类键还会
1976
2260
  * 让 `process.env[name]` 读到对象而不是字符串。不匹配的名字按「没配」处理。
1977
2261
  */
1978
- const ENV_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*$/u;
2262
+ const ENV_NAME_SHAPE = /^[A-Za-z_]\w*$/u;
1979
2263
  /**
1980
2264
  * zg 子进程的环境变量:HF 镜像 + (仅在部署开放远程 embedding 时的)远程端点与凭据。
1981
2265
  *
@@ -1996,7 +2280,7 @@ const ENV_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_]*$/u;
1996
2280
  function zgEnv(config) {
1997
2281
  const env = { ...hfEndpointEnv(config) };
1998
2282
  if (allowRemoteEmbedding(config)) {
1999
- const endpoint = trimmedConfigString(config.remoteEmbeddingEndpoint);
2283
+ const endpoint = normalizedEndpoint(config.remoteEmbeddingEndpoint);
2000
2284
  if (endpoint !== void 0) env["ZVEC_GREP_ENDPOINT"] = endpoint;
2001
2285
  const keyName = trimmedConfigString(config.remoteEmbeddingApiKeyFrom);
2002
2286
  const key = keyName !== void 0 && ENV_NAME_SHAPE.test(keyName) ? process.env[keyName] : void 0;
@@ -2007,7 +2291,7 @@ function zgEnv(config) {
2007
2291
  }
2008
2292
  function readDefaultEmbedding(config) {
2009
2293
  const raw = config.defaultEmbedding.get();
2010
- if (typeof raw === "string" && isLocalEmbedding(raw)) return raw;
2294
+ if (typeof raw === "string" && isLocalEmbedding(raw)) return raw.trim();
2011
2295
  return DEFAULT_EMBEDDING;
2012
2296
  }
2013
2297
  /**
@@ -2148,12 +2432,14 @@ function killProc(proc) {
2148
2432
  * @returns {void}
2149
2433
  */
2150
2434
  function pruneRebuildHistory(jobs, records) {
2151
- const settled = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status));
2152
- for (const job of settled.slice(0, Math.max(settled.length - 9, 0))) {
2435
+ const ordered = jobs.list().filter((job) => job.kind === REBUILD_JOB_KIND).filter((job) => !isLiveStatus(job.status)).toSorted((left, right) => left.startedAt - right.startedAt);
2436
+ for (const job of ordered.slice(0, Math.max(ordered.length - 9, 0))) {
2153
2437
  jobs.remove(job.id);
2154
2438
  records.delete(job.id);
2155
2439
  }
2156
2440
  }
2441
+ /** 远端容量上限的括号形态。 */
2442
+ const CAPACITY_LIMIT = /\(limit: (?<limit>\d+)\)/u;
2157
2443
  /**
2158
2444
  * 从官方容量闸的错误文本里取出上限(实测原文:`background job limit reached for this
2159
2445
  * owner (limit: 10)`)。认不出来 ⇒ undefined,调用方退回通用的启动失败文案。
@@ -2161,7 +2447,7 @@ function pruneRebuildHistory(jobs, records) {
2161
2447
  * 人话的那一条——用户此时要做的是去 job_list 里收掉不需要的作业,而不是读一句英文。
2162
2448
  */
2163
2449
  function capacityLimitOf(error) {
2164
- return /\(limit: (?<limit>\d+)\)/u.exec(errorText(error))?.groups?.["limit"];
2450
+ return CAPACITY_LIMIT.exec(errorText(error))?.groups?.["limit"];
2165
2451
  }
2166
2452
  /**
2167
2453
  * 「工作区重建」的四道前置校验:绝对路径 + 归一化、本 daemon 观测过的白名单、
@@ -2250,13 +2536,11 @@ function startUnderController(jobs, spec) {
2250
2536
  /**
2251
2537
  * 交给注册表的作业规格:输出源 + `run` 的两枚钩子(cancel / done)与那枚 kill 定时器。
2252
2538
  * 单独成一段是因为它只在 `start` 的那一拍被同步调用一次,与「登记进侧表」是两件事。
2253
- * @param routes 本次注册的共享依赖(config 现读超时、host 挂 timer、jobsOf 现读注册表)
2254
- * @param proc 已经起来的 zg 进程
2255
- * @param state 这条重建的状态盒(与侧表记录共用)
2256
- * @param command 实际执行的命令行(作业 label,模型在 job_list 里看见的那句)
2539
+ * @param options 一次启动所需的全部输入:共享依赖、已起的进程、状态盒、命令、根与 claim 凭据
2257
2540
  * @returns 官方 JobSpec:kind / label / output / run
2258
2541
  */
2259
- function rebuildJobSpec(routes, proc, state, command, root) {
2542
+ function rebuildJobSpec(options) {
2543
+ const { routes, proc, state, command, root, claimed } = options;
2260
2544
  const { config, host, jobsOf, messages } = routes;
2261
2545
  return {
2262
2546
  kind: REBUILD_JOB_KIND,
@@ -2277,13 +2561,17 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2277
2561
  if (proc.status !== "running") return;
2278
2562
  const live = liveJob();
2279
2563
  if (live !== null && live.status !== "running") return;
2280
- const minutes = Math.round(config.indexTimeoutMs / 6e4);
2564
+ const minutes = Math.max(1, Math.ceil(config.indexTimeoutMs / 6e4));
2281
2565
  state.timeoutNote = fill(messages().rebuildTimeout, { minutes });
2282
2566
  if (live === null) {
2283
2567
  killProc(proc);
2284
2568
  return;
2285
2569
  }
2286
- live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2570
+ try {
2571
+ live.jobs.kill(handle.id, void 0, fill(messages().jobReasonTimeout, { minutes }));
2572
+ } catch {
2573
+ killProc(proc);
2574
+ }
2287
2575
  }, config.indexTimeoutMs);
2288
2576
  return {
2289
2577
  cancel: () => {
@@ -2295,7 +2583,7 @@ function rebuildJobSpec(routes, proc, state, command, root) {
2295
2583
  return jobOutcomeOf(proc);
2296
2584
  } finally {
2297
2585
  cancelKillTimer();
2298
- routes.rebuilds.release(root);
2586
+ routes.rebuilds.release(root, claimed);
2299
2587
  }
2300
2588
  })()
2301
2589
  };
@@ -2356,9 +2644,11 @@ async function spawnIndexWrite(routes, started, indexArgs, embedding) {
2356
2644
  * @param root 已过前置校验的工作区(写进侧表供卡片回显)
2357
2645
  * @param started 本次请求语言的文案表
2358
2646
  * @param spawned spawnIndexWrite 交回的进程与命令
2647
+ * @param claimed claim 拿到的那枚占位(重建/后台路径必有):收尾释放按它校验代次,
2648
+ * 条目已被同根新 claim 顶替时那份迟到的释放不许删掉新条目
2359
2649
  * @returns 宿主签发的 `{ jobId }`;失败为 `{ error, status }`
2360
2650
  */
2361
- function attachIndexWrite(routes, root, started, spawned) {
2651
+ function attachIndexWrite(routes, root, started, spawned, claimed) {
2362
2652
  const { jobsOf, records } = routes;
2363
2653
  const { proc, command } = spawned;
2364
2654
  const starting = jobsOf();
@@ -2389,7 +2679,14 @@ function attachIndexWrite(routes, root, started, spawned) {
2389
2679
  };
2390
2680
  let jobId;
2391
2681
  try {
2392
- jobId = startUnderController(starting, rebuildJobSpec(routes, proc, state, command, root));
2682
+ jobId = startUnderController(starting, rebuildJobSpec({
2683
+ routes,
2684
+ proc,
2685
+ state,
2686
+ command,
2687
+ root,
2688
+ claimed
2689
+ }));
2393
2690
  state.identity = identityOf(starting.get(jobId));
2394
2691
  records.set(jobId, {
2395
2692
  proc,
@@ -2447,7 +2744,10 @@ var ZvecRebuildService = class extends TypertRemoteService {
2447
2744
  }
2448
2745
  /** 引导读面:白名单里的工作区 + 守护进程就绪态(都是本插件自己的数据)。 */
2449
2746
  async roots() {
2450
- const serverReady = await this.deps.serverGate.ready();
2747
+ let serverReady = false;
2748
+ try {
2749
+ serverReady = await this.deps.serverGate.ready();
2750
+ } catch {}
2451
2751
  return {
2452
2752
  roots: this.deps.ledger.list(),
2453
2753
  serverReady
@@ -2476,7 +2776,8 @@ var ZvecRebuildService = class extends TypertRemoteService {
2476
2776
  error: started.endpointJobsUnavailable,
2477
2777
  status: 503
2478
2778
  };
2479
- if (this.deps.rebuilds.claim(root, "card") === null) {
2779
+ const claimed = this.deps.rebuilds.claim(root, "card");
2780
+ if (claimed === null) {
2480
2781
  const following = followRunningRebuild(jobs, this.deps.records, root);
2481
2782
  return following === void 0 ? {
2482
2783
  ok: false,
@@ -2495,23 +2796,23 @@ var ZvecRebuildService = class extends TypertRemoteService {
2495
2796
  rebuild: true
2496
2797
  }, embedding);
2497
2798
  if ("error" in spawned) {
2498
- this.deps.rebuilds.release(root);
2799
+ this.deps.rebuilds.release(root, claimed);
2499
2800
  return {
2500
2801
  ok: false,
2501
2802
  error: spawned.error,
2502
2803
  status: spawned.status
2503
2804
  };
2504
2805
  }
2505
- const attached = attachIndexWrite(this.deps, root, started, spawned);
2806
+ const attached = attachIndexWrite(this.deps, root, started, spawned, claimed);
2506
2807
  if ("error" in attached) {
2507
- this.deps.rebuilds.release(root);
2808
+ this.deps.rebuilds.release(root, claimed);
2508
2809
  return {
2509
2810
  ok: false,
2510
2811
  error: attached.error,
2511
2812
  status: attached.status
2512
2813
  };
2513
2814
  }
2514
- this.deps.rebuilds.attach(root, attached.jobId);
2815
+ this.deps.rebuilds.attach(root, attached.jobId, claimed);
2515
2816
  return {
2516
2817
  ok: true,
2517
2818
  jobId: attached.jobId
@@ -2607,6 +2908,8 @@ function installRebuildRemote(ctx, deps) {
2607
2908
  return true;
2608
2909
  }
2609
2910
  // host.ts
2911
+ /** 纯数字计数行。 */
2912
+ const DIGITS_ONLY = /^\d+$/u;
2610
2913
  const SEARCH_TIMEOUT_MS = 3e5;
2611
2914
  const STATUS_TIMEOUT_MS = 6e4;
2612
2915
  const INDEX_TIMEOUT_MS = 6e5;
@@ -2936,7 +3239,7 @@ const HITS_LINE_PREFIX = "hits: ";
2936
3239
  const HIT_LINE_PREFIX = /^#\d+(?:\s+\[[^\]]*\])?\s+matchedBy=\S+\s+(?:score=-?\d+(?:\.\d+)?\s+)?(?<location>\S.*)$/u;
2937
3240
  function hitSummary(stdoutText, limit, truncated, messages) {
2938
3241
  const lines = stdoutText.split("\n");
2939
- const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => /^\d+$/u.test(digits)).map((digits) => Math.trunc(Number(digits)));
3242
+ const perGroup = lines.filter((line) => line.startsWith(HITS_LINE_PREFIX)).map((line) => line.slice(6)).filter((digits) => DIGITS_ONLY.test(digits)).map((digits) => Math.trunc(Number(digits)));
2940
3243
  if (perGroup.length === 0) return null;
2941
3244
  const locations = /* @__PURE__ */ new Set();
2942
3245
  for (const line of lines) {
@@ -3061,9 +3364,17 @@ function readUnlockWindowMin(config) {
3061
3364
  function readEnforceSearchFirst(config) {
3062
3365
  return config.enforceSearchFirst.get() ?? true;
3063
3366
  }
3064
- /** 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。 */
3065
- function comparablePath(root) {
3066
- return root.startsWith("/private/") ? root.slice(8) : root;
3367
+ /**
3368
+ * 归一路径的跨平台可比形式:剥掉 macOS 的 `/private` 解析前缀(`/tmp` ⇄ `/private/tmp`)。
3369
+ *
3370
+ * 剥除**只在 macOS 上成立**:darwin 的 `/private` 是 `/tmp` 等目录的 realpath 前缀,
3371
+ * 两种拼写指同一目录;Linux 上 `/private/xxx` 是一个与 `/xxx` 无关的真实目录,无差别
3372
+ * 剥除会把两棵不同的树判成同一棵(manifest 覆盖判据随之错配)。Windows 不在本包支持面。
3373
+ *
3374
+ * `platform` 供测试注入:分支覆盖不依赖测试机自己的操作系统。导出只为可测。
3375
+ */
3376
+ function comparablePath(root, platform = process.platform) {
3377
+ return platform === "darwin" && root.startsWith("/private/") ? root.slice(8) : root;
3067
3378
  }
3068
3379
  /** 认的清单版本:与上游 v0.2.2 的 `export const CURRENT_MANIFEST_VERSION = 1` 同值。 */
3069
3380
  const SUPPORTED_MANIFEST_VERSION = 1;
@@ -3699,7 +4010,7 @@ function indexToolParameters(registered) {
3699
4010
  * @param messages 本次 execute 现取的文案表
3700
4011
  * @returns 交给官方 output schema 的 `{ text }`
3701
4012
  */
3702
- async function startBackgroundIndex(runtime, root, indexArgs, messages) {
4013
+ async function startBackgroundIndex(runtime, root, indexArgs, messages, claimed) {
3703
4014
  const routes = {
3704
4015
  host: runtime.host,
3705
4016
  config: runtime.config,
@@ -3710,20 +4021,20 @@ async function startBackgroundIndex(runtime, root, indexArgs, messages) {
3710
4021
  versionGate: runtime.versionGate
3711
4022
  };
3712
4023
  if (runtime.jobsOf() === void 0) {
3713
- runtime.rebuilds.release(root);
4024
+ runtime.rebuilds.release(root, claimed);
3714
4025
  throw new Error(messages.endpointJobsUnavailable);
3715
4026
  }
3716
4027
  const spawned = await spawnIndexWrite(routes, messages, indexArgs, readDefaultEmbedding(runtime.config));
3717
4028
  if ("error" in spawned) {
3718
- runtime.rebuilds.release(root);
4029
+ runtime.rebuilds.release(root, claimed);
3719
4030
  throw new Error(spawned.error);
3720
4031
  }
3721
- const attached = attachIndexWrite(routes, root, messages, spawned);
4032
+ const attached = attachIndexWrite(routes, root, messages, spawned, claimed);
3722
4033
  if ("error" in attached) {
3723
- runtime.rebuilds.release(root);
4034
+ runtime.rebuilds.release(root, claimed);
3724
4035
  throw new Error(attached.error);
3725
4036
  }
3726
- runtime.rebuilds.attach(root, attached.jobId);
4037
+ runtime.rebuilds.attach(root, attached.jobId, claimed);
3727
4038
  return { text: fill(messages.indexBackgroundStarted, {
3728
4039
  root,
3729
4040
  jobId: attached.jobId,
@@ -3742,8 +4053,13 @@ async function runIndexTool(runtime, args, exec, messages) {
3742
4053
  const rewriting = boolOf(args["rebuild"], "rebuild", messages) || background;
3743
4054
  boolOf(args["confirm"], "confirm", messages);
3744
4055
  await runtime.versionGate.ensure(messages);
3745
- if (rewriting && rebuilds.claim(root, "tool") === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
3746
- if (background) return startBackgroundIndex(runtime, root, indexArgs, messages);
4056
+ let foregroundClaim;
4057
+ if (rewriting) {
4058
+ const claimed = rebuilds.claim(root, "tool");
4059
+ if (claimed === null) return { text: fill(messages.indexRebuildInFlight, { root }) };
4060
+ if (background) return startBackgroundIndex(runtime, root, indexArgs, messages, claimed);
4061
+ foregroundClaim = claimed;
4062
+ }
3747
4063
  try {
3748
4064
  assertIgnoreFilesExist(indexArgs, root, messages);
3749
4065
  const { command, workdir } = buildIndexCommand(indexArgs, readDefaultEmbedding(config), messages, readClientMode(config, messages), allowRemoteEmbedding(config));
@@ -3754,7 +4070,7 @@ async function runIndexTool(runtime, args, exec, messages) {
3754
4070
  messages
3755
4071
  }) };
3756
4072
  } finally {
3757
- if (rewriting) rebuilds.release(root);
4073
+ if (foregroundClaim !== void 0) rebuilds.release(root, foregroundClaim);
3758
4074
  }
3759
4075
  }
3760
4076
  /** 注册 zg_index:建/重建/删索引。 */
@@ -3802,6 +4118,7 @@ async function runStatusTool(runtime, args, exec, messages) {
3802
4118
  },
3803
4119
  ...checkReady ? { resolveFailure: (failure, result) => {
3804
4120
  if (result.timedOut || result.aborted || result.sandbox?.denied === true) return null;
4121
+ if (classifyConcurrentFailure(result.stderr.text) !== null) return null;
3805
4122
  const report = result.stdout.text.trim();
3806
4123
  return report.length > 0 ? `${report}\n${fill(messages.statusNotReady, {
3807
4124
  root,
@@ -3977,4 +4294,4 @@ var host_default = {
3977
4294
  Config: configSchema,
3978
4295
  apply
3979
4296
  };
3980
- export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };
4297
+ export { configSchema as Config, INDEX_PROBE_CACHE_MAX, INDEX_PROBE_TTL_MS, comparablePath, createIndexProbeCache, createRootLedger, createUnlockLedger, host_default as default, hitSummary, signalStderr };