argo-search 2.10.1 → 2.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.en.md +48 -11
  2. package/README.es.md +48 -11
  3. package/README.ja.md +48 -11
  4. package/README.ko.md +47 -10
  5. package/README.md +48 -31
  6. package/SKILL.md +16 -15
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/domain_profiles.json +18 -6
  9. package/backends/engine_concept_vectors.json +3104 -0
  10. package/backends/engine_registry.yaml +38 -13
  11. package/backends/quota_profiles.json +30 -10
  12. package/bin/argo +6 -0
  13. package/config.yaml +98 -31
  14. package/docs/ENGINE_CATALOG.md +11 -8
  15. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  16. package/docs/RELEASE_NOTES_v2.11.2.md +50 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/saucenao.yaml +45 -0
  20. package/package.json +4 -2
  21. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  22. package/packages/dsh-plugin/dsh/index.js +12 -7
  23. package/packages/dsh-plugin/dsh/runner.js +79 -47
  24. package/packages/dsh-plugin/package.json +1 -1
  25. package/packages/dsh-plugin/test/index.test.js +64 -0
  26. package/scripts/argo_engine_registry.py +30 -4
  27. package/scripts/argo_paths.py +7 -1
  28. package/scripts/budget.py +13 -3
  29. package/scripts/build_concept_table.py +612 -0
  30. package/scripts/build_route_labels.py +285 -0
  31. package/scripts/caliber_dedupe.py +66 -0
  32. package/scripts/caliber_isolation.py +4 -2
  33. package/scripts/circuit_breaker.py +25 -3
  34. package/scripts/concept_lookup.py +212 -0
  35. package/scripts/engine_dispatch.py +2 -1
  36. package/scripts/engine_families.py +7 -3
  37. package/scripts/engines.py +34 -9
  38. package/scripts/engines_base.py +17 -2
  39. package/scripts/engines_builders.py +0 -1
  40. package/scripts/engines_builders_intl.py +4 -4
  41. package/scripts/engines_builders_reverse_image.py +783 -0
  42. package/scripts/engines_builders_skill.py +87 -10
  43. package/scripts/engines_builders_tech.py +0 -78
  44. package/scripts/extend_route_labels.py +239 -0
  45. package/scripts/extend_route_labels_by_capability.py +344 -0
  46. package/scripts/extend_route_labels_by_language.py +306 -0
  47. package/scripts/gen_routing_snapshot.py +22 -3
  48. package/scripts/job.py +2 -1
  49. package/scripts/lang_detect.py +12 -3
  50. package/scripts/lint_spec_contracts.py +110 -0
  51. package/scripts/lint_stub_targets.py +130 -0
  52. package/scripts/local_image.py +3 -3
  53. package/scripts/local_seek.py +13 -3
  54. package/scripts/mcp_compact.py +5 -0
  55. package/scripts/mcp_transport.py +1 -1
  56. package/scripts/net_proxy.py +47 -0
  57. package/scripts/numeric_verify.py +330 -0
  58. package/scripts/plan.py +36 -4
  59. package/scripts/pre-commit +21 -13
  60. package/scripts/quota.py +109 -10
  61. package/scripts/rank_signals.py +48 -4
  62. package/scripts/ranking_eval.py +23 -1
  63. package/scripts/regression_p0p1.py +7 -2
  64. package/scripts/route.py +24 -3
  65. package/scripts/route_accuracy_eval.py +191 -0
  66. package/scripts/route_combo.py +32 -1
  67. package/scripts/route_domains.py +242 -5
  68. package/scripts/route_primary.py +101 -0
  69. package/scripts/search.py +14 -12
  70. package/scripts/search_cli.py +89 -7
  71. package/scripts/search_output.py +59 -1
  72. package/scripts/search_pipeline.py +20 -15
  73. package/scripts/snippet_clean.py +60 -0
  74. package/scripts/social_engines/twitter_engine.py +159 -42
  75. package/scripts/social_engines/xiaohongshu_engine.py +36 -1
  76. package/scripts/tfidf_router.py +52 -2
  77. package/scripts/train.py +15 -0
  78. package/scripts/verify_with.py +124 -0
  79. package/sub-skills/local-search/SKILL.md +3 -2
  80. package/sub-skills/local-search/bm25.py +89 -8
  81. package/sub-skills/local-search/config.yaml +12 -0
  82. package/sub-skills/local-search/parse_maps.yaml +8 -0
  83. package/sub-skills/local-search/parsers.py +5 -2
  84. package/sub-skills/local-search/search_v3.py +87 -1
  85. package/sub-skills/local-search/smart_router.py +1 -1
  86. package/sub-skills/local-seek/SKILL.md +6 -5
  87. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  88. package/sub-skills/local-seek/scripts/seek.py +152 -36
  89. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
@@ -169,8 +169,12 @@ def _get_candidate_domain_indices(query: str) -> set[int] | None:
169
169
  return candidates
170
170
 
171
171
 
172
- def _ensure_domain_compiled(domain: dict[str, Any]) -> list[tuple[re.Pattern, re.Pattern | None]]:
173
- """按需编译单个域的触发词与意图正则(扫到哪个域才编译哪个域)。"""
172
+ def _ensure_domain_compiled(domain: dict[str, Any]) -> list[tuple[Any, Any]]:
173
+ """按需编译单个域的触发词与意图正则(扫到哪个域才编译哪个域)。
174
+
175
+ 返回的 matcher 是鸭子类型:`re.Pattern` 或 `_LiteralMatcher`,两者都提供
176
+ `.search(query)`(前者返回 `re.Match`,后者返回 `_LiteralMatch`,均带 `.span()`)。
177
+ """
174
178
  rules = domain.get("_rules")
175
179
  if rules is not None:
176
180
  return rules
@@ -204,9 +208,124 @@ def _compile_domain_patterns(domains: list[dict[str, Any]]) -> list[dict[str, An
204
208
  return compiled
205
209
 
206
210
 
207
- def _try_compile(src: Any) -> re.Pattern | None:
211
+ # 纯字面 alternation 判定:只认「剥掉开头 (?i) 与最外层括号后,由 | 分隔、
212
+ # 每段都是纯字面字符」的 pattern。字符类里出现正则元字符(. * + ? ^ $ \ [ ] ( ) |)
213
+ # 或内联结构一律不认——判定必须保守,判不准就交回 re.compile,宁可少优化。
214
+ _LITERAL_CHAR = re.compile(r"^[\w\u4e00-\u9fff \-/#&:,.'’]+\Z", re.UNICODE)
215
+
216
+
217
+ def _literal_alternatives(src: str) -> tuple[list[str], bool] | None:
218
+ """判定 pattern 是否为纯字面 alternation;是则返回 (词表, 是否忽略大小写)。
219
+
220
+ 等价性:`(?i)(a|b)` 的 `re.search` 与「query 含 a 或 b(忽略大小写)」等价;
221
+ 无 `(?i)` 时与「query 含 a 或 b(区分大小写)」等价。含非 ASCII 拉丁字母
222
+ (é/ß 等)时 `(?i)` 与 `str.lower()` 的 Unicode 规则不完全一致,故退回。
223
+ """
224
+ if not src:
225
+ return None
226
+ s = src
227
+ ignore_case = False
228
+ if s.startswith("(?i)"):
229
+ s = s[4:]
230
+ ignore_case = True
231
+ # `(?i)` 只作用于其后的表达式。若顶层还有 `|` 且不是「整体被一对括号
232
+ # 包裹」,flag 作用域只覆盖第一个分支(如 `(?i)foo|bar` 的 bar 区分
233
+ # 大小写),此时按整体忽略大小写处理会误判 → 退回 re.compile。
234
+ wrapped = (s.startswith("(") and s.endswith(")")
235
+ and s.count("(") == 1 and s.count(")") == 1)
236
+ if not wrapped:
237
+ depth = 0
238
+ for ch in s:
239
+ if ch == "(":
240
+ depth += 1
241
+ elif ch == ")":
242
+ depth -= 1
243
+ elif ch == "|" and depth == 0:
244
+ return None
245
+ # 只剥「整体被一对括号包裹」的情形(顶层无其他内容)
246
+ if s.startswith("(") and s.endswith(")") and s.count("(") == 1 and s.count(")") == 1:
247
+ s = s[1:-1]
248
+ parts: list[str] = []
249
+ depth = 0
250
+ cur: list[str] = []
251
+ for ch in s:
252
+ if ch == "(":
253
+ depth += 1
254
+ elif ch == ")":
255
+ depth -= 1
256
+ if ch == "|" and depth == 0:
257
+ parts.append("".join(cur))
258
+ cur = []
259
+ else:
260
+ cur.append(ch)
261
+ parts.append("".join(cur))
262
+ if not parts:
263
+ return None
264
+ words: list[str] = []
265
+ for p in parts:
266
+ if not p or not _LITERAL_CHAR.match(p):
267
+ return None
268
+ if ignore_case:
269
+ if any(ord(c) > 127 and not ("\u4e00" <= c <= "\u9fff") for c in p):
270
+ return None
271
+ p = p.lower()
272
+ words.append(p)
273
+ return words, ignore_case
274
+
275
+
276
+ class _LiteralMatch:
277
+ """`_LiteralMatcher.search` 的返回值:只提供调用方用到的 `.span()`。"""
278
+
279
+ __slots__ = ("_span",)
280
+
281
+ def __init__(self, span: tuple[int, int]):
282
+ self._span = span
283
+
284
+ def span(self) -> tuple[int, int]:
285
+ return self._span
286
+
287
+
288
+ class _LiteralMatcher:
289
+ """纯字面 alternation 的匹配器:子串查找替代 `re.compile` + `re.search`。
290
+
291
+ 为什么值得(2026-11-04 实测):域规则 326 条 pattern 里 134 条是纯字面
292
+ alternation(如 `(?i)(金十|jin10)`、`(?i)(技术社区|程序员社区)`),它们每次
293
+ 冷进程都要付一次 `re.compile`(326 条全量实测 23.8 ms),而子串查找零编译、
294
+ 更快。判定由 `_literal_alternatives` 保守把关,判不准的一律走原正则路径。
295
+ """
296
+
297
+ __slots__ = ("_words", "_ignore_case")
298
+
299
+ def __init__(self, words: list[str], ignore_case: bool):
300
+ self._words = words
301
+ self._ignore_case = ignore_case
302
+
303
+ def search(self, query: str) -> _LiteralMatch | None:
304
+ hay = query.lower() if self._ignore_case else query
305
+ best: tuple[int, int] | None = None
306
+ for w in self._words:
307
+ pos = hay.find(w)
308
+ if pos < 0:
309
+ continue
310
+ # 与 re 的 leftmost 语义一致:取最早出现;同位置取分支顺序在前者
311
+ if best is None or pos < best[0]:
312
+ best = (pos, pos + len(w))
313
+ return _LiteralMatch(best) if best is not None else None
314
+
315
+
316
+ def _try_compile(src: Any) -> Any:
317
+ """编译域规则:纯字面 alternation 走子串匹配,其余走 `re.compile`。
318
+
319
+ 返回值是鸭子类型(均提供 `.search(query)`,返回值带 `.span()`):
320
+ `_LiteralMatcher` 或 `re.Pattern`。写坏的正则仍返回 None 被丢弃,
321
+ 「编译失败静默丢弃」的既有语义不变(纯字面判定本身保证每段都是字面
322
+ 字符,不可能写坏)。
323
+ """
208
324
  if not isinstance(src, str) or not src:
209
325
  return None
326
+ literal = _literal_alternatives(src)
327
+ if literal is not None:
328
+ return _LiteralMatcher(*literal)
210
329
  try:
211
330
  return re.compile(src)
212
331
  except re.error:
@@ -230,14 +349,76 @@ _UNLESS_MACROS: dict[str, str] = {
230
349
  r"价格|多少钱|商业化|市场预测|行情|股价|龙头股|概念股|"
231
350
  r"market\s+size|market\s+share|sales|revenue|valuation|market\s+forecast|pricing)"
232
351
  ),
352
+ # 比较决策/获奖新闻否决集(2026-10-31 评测基线):「…是什么」尾部触发词在
353
+ # cn_encyclopedia 与 fact_check 两处各自存在,把比较题(「A 和 B 的区别/
354
+ # 优劣/怎么选」)与得主类新闻题整类锁进点查域。共用一份否决词,新增守卫域
355
+ # 时在 config.yaml 引用 @compare_or_award,不要复制粘贴展开后的正则。
356
+ "@compare_or_award": (
357
+ r"(?i)(区别|比较|对比|怎么选|哪个好|优劣|利弊|差异|权衡|\bvs\b|得主|获奖)"
358
+ ),
359
+ # 本地/免 key 镜像通道否决集(2026-11-04):`local_*` 六个域是用户**显式
360
+ # 选择**本地化通道的意图(`references/usage.md`:「local_ 前缀是本地化/免 key
361
+ # 镜像通道」),但它们在 config 里排在末尾(idx 92-97),而域匹配先到先得——
362
+ # 于是「本地搜索」「arxiv api」「wikipedia api」「bing news」「百度」全部被
363
+ # 靠前的 catch-all / academic / code_search / news_realtime 截走,那六个域
364
+ # 永远拿不到主位(实测 6/6 失配)。
365
+ #
366
+ # 修法:加 `_channel_intent_gate`(见文件下方),查询含本宏意图词时把
367
+ # local_* 域提到首位。词表与 local_* 六域的 patterns 对齐。
368
+ #
369
+ # **词表只收「带通道语义的写法」,不收裸平台名**:`github repo`、
370
+ # `stackoverflow`、`npm package` 既是通道意图也是普通技术词,收进来会误伤
371
+ # 「github repo 教程 推荐」(实测被误判 local_code)。裸平台名交给各域
372
+ # 自己的 patterns 处理,通道门只认明确的通道修饰语——即「平台名 + 本地/
373
+ # 镜像/免 key」的组合,或「本地 + 平台名」的组合。
374
+ "@local_channel": (
375
+ r"(?i)(本地搜索|local search|零成本|free search|本地新闻|本地中文|"
376
+ r"本地代码|本地学术|本地参考|本地通用|"
377
+ r"arxiv api|semantic scholar|crossref|pubmed|site:arxiv\.org|"
378
+ r"wikipedia api|wiktionary|wikiquote|nominatim|openstreetmap|"
379
+ r"site:baidu|site:sogou|"
380
+ r"(?:github|gitlab|stackoverflow|npm|pip|cargo)\s+(?:repo|package)(?:\s+(?:本地|镜像|免\s?key|local|mirror))|"
381
+ r"(?:本地|镜像)\s+(?:github|gitlab|stackoverflow|npm|pip|cargo))"
382
+ ),
233
383
  }
234
384
 
235
385
 
236
386
  def _split_pattern_entry(entry: Any) -> tuple[Any, Any]:
237
- """触发词条目的两种形态:字符串,或 `{match, unless}`(unless 支持 @宏名 展开)。"""
387
+ """触发词条目的两种形态:字符串,或 `{match, unless}`(unless 支持 @宏名 展开)。
388
+
389
+ `unless` 可以是:
390
+
391
+ - 字符串正则(原样编译);
392
+ - `@宏名`(整体替换成宏的正则);
393
+ - **列表**:每项是字符串正则或 `@宏名`,展开后用 `|` 拼接成一个正则。
394
+
395
+ 列表形态是 2026-11-04 为「一个触发词要挂多个否决集」加的:academic 的
396
+ 论文条目原有写作技巧否决,又要加本地通道否决,两个都要生效——拼接成
397
+ 一个字符串会让 `(?i)` 的作用域只覆盖前半段(实测宏不展开),而整体
398
+ 替换成宏名又会丢掉原有否决。列表让两类否决各占一项、语义清晰。
399
+ """
238
400
  if isinstance(entry, dict):
239
401
  unless = entry.get("unless")
240
- if isinstance(unless, str) and unless in _UNLESS_MACROS:
402
+ if isinstance(unless, list):
403
+ parts: list[str] = []
404
+ for item in unless:
405
+ if isinstance(item, str) and item in _UNLESS_MACROS:
406
+ parts.append(_UNLESS_MACROS[item])
407
+ elif isinstance(item, str) and item:
408
+ parts.append(item)
409
+ # 拼接前剥掉后续项开头的 `(?i)`:Python 3.11+ 不允许内联 flag
410
+ # 出现在非开头位置(`(?i)a|(?i)b` 编译失败),而宏与正则都自带
411
+ # `(?i)`,剥掉后语义不变(整条仍由第一个 `(?i)` 控制)。
412
+ if parts:
413
+ merged = parts[0]
414
+ for p in parts[1:]:
415
+ if p.startswith("(?i)"):
416
+ p = p[4:]
417
+ merged += "|" + p
418
+ unless = merged
419
+ else:
420
+ unless = None
421
+ elif isinstance(unless, str) and unless in _UNLESS_MACROS:
241
422
  unless = _UNLESS_MACROS[unless]
242
423
  return entry.get("match"), unless
243
424
  return entry, None
@@ -415,6 +596,59 @@ def _intent_gate(hits: list[dict[str, Any]], query: str) -> list[dict[str, Any]]
415
596
  return kept
416
597
 
417
598
 
599
+ # ── 阶段 4:显式通道意图门(2026-11-04)──────────────────────────────────────
600
+ #
601
+ # 与 `_intent_gate` 对称但方向相反:那个是「点查域在主题句下让位」,这个是
602
+ # 「泛化域在显式通道意图下让位」。
603
+ #
604
+ # 为什么需要:`local_*` 六个域是用户**显式选择**本地化/免 key 通道的意图
605
+ # (`references/usage.md`:「local_ 前缀是本地化/免 key 镜像通道」),但它们在
606
+ # config 里排在末尾(idx 92-97),而域匹配先到先得——「本地搜索」「arxiv api」
607
+ # 「wikipedia api」「github repo」「bing news」「百度」全部被靠前的泛化域截走,
608
+ # 那六个域永远拿不到主位(实测 6/6 失配)。
609
+ #
610
+ # 为什么不在每个泛化域上加 unless:那是打地鼠——code_search 有四条 pattern
611
+ # 命中同一个查询,逐个加否决总会漏(实测加到第三条仍失配)。而且新增泛化域
612
+ # 时又会漏。门放在匹配层,一次覆盖所有泛化域。
613
+ #
614
+ # 判据:查询含 `@local_channel` 宏的意图词,且命中列表里有 `local_*` 域时,
615
+ # 把非 local_ 的命中域降级为次域(保留在列表里,不删除——它们仍可能补位)。
616
+
617
+ _CHANNEL_INTENT_RE: re.Pattern | None = None
618
+
619
+
620
+ def _channel_intent_re() -> re.Pattern | None:
621
+ """惰性编译通道意图正则(复用 @local_channel 宏,避免词表两处维护)。"""
622
+ global _CHANNEL_INTENT_RE
623
+ if _CHANNEL_INTENT_RE is None:
624
+ src = _UNLESS_MACROS.get("@local_channel")
625
+ if not src:
626
+ return None
627
+ try:
628
+ _CHANNEL_INTENT_RE = re.compile(src, re.I)
629
+ except re.error:
630
+ return None
631
+ return _CHANNEL_INTENT_RE
632
+
633
+
634
+ def _channel_intent_gate(hits: list[dict[str, Any]], query: str) -> list[dict[str, Any]]:
635
+ """显式通道意图存在时,把 local_* 域提到首位(泛化域降为次域)。
636
+
637
+ 不删除泛化域——它们仍可能在 local 通道不可用时补位(fallback 语义)。
638
+ 只调整顺序:主域是 local_*,泛化域退到次域位置。
639
+ """
640
+ if not hits:
641
+ return hits
642
+ re_ = _channel_intent_re()
643
+ if re_ is None or re_.search(query) is None:
644
+ return hits
645
+ local_hits = [h for h in hits if str(h.get("name", "")).startswith("local_")]
646
+ if not local_hits:
647
+ return hits # 没有 local 域命中:不调整(说明 local 域规则没覆盖)
648
+ others = [h for h in hits if not str(h.get("name", "")).startswith("local_")]
649
+ return local_hits + others
650
+
651
+
418
652
  # ── 对外入口 ──────────────────────────────────────────────────────────────────
419
653
 
420
654
  def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
@@ -469,6 +703,9 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
469
703
 
470
704
  hits = _social_domain_first(hits)
471
705
  hits = _intent_gate(hits, query)
706
+ # 显式通道意图门放在最后:它只重排已命中列表(local_* 提前),不改变
707
+ # 「哪些域命中」这个事实,因此不影响前面的意图门与社交提前逻辑。
708
+ hits = _channel_intent_gate(hits, query)
472
709
  hits = hits[:max_n]
473
710
  return hits if hits else ([catch_all] if catch_all else [])
474
711
 
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env python3
2
+ """route_primary.py — primary 可执行性顺位与域否决查询。
3
+
4
+ ## 为什么单独成模块
5
+
6
+ `route.py` 已压着 1000 行硬限,而这两件事都是**独立的判定**,与路由主干的
7
+ 装配流程无关:
8
+
9
+ 1. `promote_executable_primary`:combo 定稿后把 primary 顺位到第一个
10
+ 「路由与执行都判可用」的引擎;
11
+ 2. `domain_vetoed_engines` / `vetoes_apply`:把域规则的 `unless` 否决
12
+ 事实交给 TF-IDF 注入层。
13
+
14
+ 放在这里,route.py 只留两个调用点。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ from config import get_engines
22
+ from route_combo import is_engine_routable
23
+
24
+
25
+ def promote_executable_primary(combo: list[str], specs: dict | None = None,
26
+ enabled: set[str] | None = None
27
+ ) -> tuple[list[str], str | None]:
28
+ """把 primary 顺位到第一个「路由与执行都判可用」的引擎。
29
+
30
+ 路由准入与执行准入此前不是同一套判据:`is_engine_routable` 查
31
+ enabled/依赖/熔断/配额/死源/语言,而执行层的 `engine_status` 另算
32
+ dep_ready——两者在 2026-11-02 才对齐。即便对齐后仍有一个缺口:
33
+ `is_engine_routable` 默认 check_deps=True,但域装配早期
34
+ (_get_engines_combo 与 policy 截断)不看依赖,于是 xiaohongshu 这类缺
35
+ CLI 的引擎能一路占住首位,实际交付由 fallback 接管,reason 却写着
36
+ 「→ 小红书」。
37
+
38
+ 顺位不改写 combo 内容,只把「执行不了」的成员换到后面;全组都不可执行
39
+ 时保持原序(fail-open,由执行层报错而不是路由层静默换源)。
40
+ """
41
+ if not combo:
42
+ return combo, None
43
+ # 必须自己取 specs:route 的 _specs_snapshot() 只读已加载的 engines 模块,
44
+ # 路由路径下它恒为空表,依赖判据会因此对全部引擎失效。
45
+ if specs is None:
46
+ try:
47
+ specs = get_engines()
48
+ except Exception:
49
+ specs = {}
50
+ if is_engine_routable(combo[0], enabled=enabled, specs=specs):
51
+ return combo, None
52
+ for cand in combo[1:]:
53
+ if is_engine_routable(cand, enabled=enabled, specs=specs):
54
+ rest = [e for e in combo if e != cand]
55
+ return [cand] + rest, combo[0]
56
+ return combo, None
57
+
58
+
59
+ def domain_vetoed_engines(query: str,
60
+ domains: list[dict[str, Any]] | None = None) -> set[str]:
61
+ """被域规则显式否决的引擎集合(供 TF-IDF 注入层不再复活)。
62
+
63
+ 域规则与 TF-IDF 选源此前是两条互不知情的路径:域规则用 `unless` 否决了
64
+ 某个意图(例如 academic 的「查重/降重」写作语境),TF-IDF 却可以按词面
65
+ 高分把该域的主源重新注入首位——实测「怎么写论文 查重 降重」域判到
66
+ chinese_general、reason 仍写「[TF-IDF→cnii]」,primary 变成日文学术源。
67
+ 把「否决」这个事实交给注入层,让词面分不能覆盖域规则的语义判断。
68
+
69
+ 判据:某域**本可命中**(match 成立)但因 unless 被否决时,该域声明的
70
+ 引擎即视为被否决。与 match_domains 共用 `_ensure_domain_compiled`。
71
+ """
72
+ if domains is None:
73
+ from route_domains import get_domains as _gd, _get_compiled_domains, \
74
+ _ensure_domain_compiled
75
+ domains = _gd()
76
+ else:
77
+ from route_domains import _get_compiled_domains, _ensure_domain_compiled
78
+ compiled = _get_compiled_domains(domains)
79
+ vetoed: set[str] = set()
80
+ for domain in compiled:
81
+ for match_re, unless_re in _ensure_domain_compiled(domain):
82
+ if unless_re is not None and unless_re.search(query):
83
+ if match_re.search(query):
84
+ vetoed.update(domain.get("engines_combo") or [])
85
+ vetoed.update([domain["primary"]] if domain.get("primary") else [])
86
+ break
87
+ return vetoed
88
+
89
+
90
+ def vetoes_apply(query: str, domains: list[dict[str, Any]] | None = None,
91
+ hard_domain: bool = False) -> bool:
92
+ """本次路由是否处在「域规则已否决」状态。
93
+
94
+ 只有**没有实域命中**时才让否决生效:零实域命中说明所有域要么未匹配、
95
+ 要么被 unless 否决,此时 TF-IDF 注入是唯一能改变主源的力量,必须受
96
+ 域规则约束。一旦已有实域命中,该域自身的引擎选择是声明式的,注入只作
97
+ 辅源,不否决。
98
+ """
99
+ if hard_domain:
100
+ return False
101
+ return bool(domain_vetoed_engines(query, domains))
package/scripts/search.py CHANGED
@@ -252,7 +252,8 @@ def _note_remote_quota_exhausted(engine: str, detail: str) -> None:
252
252
  """
253
253
  try:
254
254
  from quota import get_quota_manager
255
- get_quota_manager().mark_remote_exhausted(engine, reason=detail)
255
+ # 带上 category,让余额不足(402)走短冷却、与月度预算周期解耦(#42)
256
+ get_quota_manager().mark_remote_exhausted(engine, reason=detail, category="quota_exhausted")
256
257
  except Exception: # 侧信道:标记失败不得影响搜索主流程(规则见 except_sets)
257
258
  pass
258
259
 
@@ -604,9 +605,6 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
604
605
  注意:路由永远基于原始 query。改写词只用于引擎检索,避免
605
606
  「Python → 追加 pip/库」之类改写污染 package_search 等域规则。
606
607
  """
607
- if cache is None:
608
- from cache import SearchCache # 局部 import;见模块头注释(不能用裸名)
609
- cache = SearchCache()
610
608
  original_query = query
611
609
 
612
610
  # 查询操作符契约层(2026-10-17 query_operators):指令从路由与检索两侧
@@ -630,9 +628,8 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
630
628
  tier = "daily"
631
629
  plan_info: dict[str, Any] | None = None
632
630
  try:
633
- from plan import (
634
- build_plan, classify_input_kind, execution_tier, should_attach_plan,
635
- )
631
+ from plan import (URL_INPUT_ENGINES, build_plan, classify_input_kind,
632
+ execution_tier, should_attach_plan)
636
633
  kind = classify_input_kind(query, input_kind)
637
634
  tier = execution_tier(mode, depth, context)
638
635
  if plan_only:
@@ -641,8 +638,10 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
641
638
  engine=engine if not local_first else "local_search",
642
639
  input_kind=input_kind,
643
640
  context=context,
641
+ timing=timing,
644
642
  )
645
- if kind == "known-url" and not force_search:
643
+ # 按 URL 取单条的抽取引擎(单条推文 / 反搜图)显式指定时不拦截为 handoff。
644
+ if kind == "known-url" and not force_search and (engine or "").strip() not in URL_INPUT_ENGINES:
646
645
  plan_info = build_plan(
647
646
  query, mode=mode, depth=depth, max_results=n,
648
647
  engine=engine, input_kind="known-url", context=context,
@@ -782,6 +781,10 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
782
781
  file=sys.stderr)
783
782
  if search_query != original_query:
784
783
  print(f"[改写] {original_query} → {search_query}", file=sys.stderr)
784
+ if cache is None:
785
+ from cache import SearchCache # 按需延迟初始化,短路/离线计划路径免建 SQLite 缓存
786
+ cache = SearchCache()
787
+
785
788
  # L1 并行化:本地搜索与主搜索并行提交(仅显式开启时在宽根下提示)。
786
789
  _local_seek_explicit = include_local is not None
787
790
  include_local = _resolve_include_local(include_local, mode, query)
@@ -988,11 +991,10 @@ if __name__ == "__main__":
988
991
  # _MODULE_T0` —— 那是**第二次**导入 search(真模块),此刻依赖全在
989
992
  # sys.modules 里,差值 ≈ 0。于是 --explain-timing 的 import_ms 恒为 0.0,
990
993
  # 而它这一栏恰恰是给「优化固定开销」用的,报 0 等于把人指向错的数字。
991
- #
992
- # runpy 不会把 __main__ 留在 sys.modules['__main__'](它会恢复原模块),
993
- # 所以靠 __main__ 取不到;写进 search_cli 的模块属性是唯一稳定的交接点。
994
+ # runpy 不会把 __main__ 留在 sys.modules['__main__'](会恢复原模块),所以靠
995
+ # __main__ 取不到;写进 search_cli 的模块属性是唯一稳定交接点。
994
996
  from search_cli import main # 反向导入放这里:CLI 依赖本模块,模块级会成环
995
- import search_cli as _cli_mod
997
+ import search_cli as _cli_mod # noqa: E402
996
998
  _cli_mod._TRUE_IMPORT_T0 = _MODULE_T0
997
999
  _cli_mod._TRUE_IMPORTS_DONE = _IMPORTS_DONE
998
1000
  main()
@@ -250,6 +250,25 @@ def build_parser() -> argparse.ArgumentParser:
250
250
  metavar="TOP_K",
251
251
  help="证据核验:对 top-k 未核验结果 fetch 正文、回填证据分、输出 evidence_revision 分布(默认 3)",
252
252
  )
253
+ parser.add_argument(
254
+ "--numverify",
255
+ nargs="?",
256
+ const=3,
257
+ type=int,
258
+ default=None,
259
+ metavar="TOP_K",
260
+ help="数值印证:对摘要含价格/百分比/日期的 top-k 结果 fetch 原文比对数字,"
261
+ "对不上者降权(missing 强降、partial 弱降,默认 3)",
262
+ )
263
+ parser.add_argument(
264
+ "--verify-with",
265
+ nargs="?",
266
+ const="auto",
267
+ default=None,
268
+ metavar="ENGINE",
269
+ help="核对配对:主查之外用指定引擎跑一次轻量核对,独立交付官方簇与域级"
270
+ "重叠(缺省 auto=按查询类型选,如价格类→exa;无规则命中则跳过)",
271
+ )
253
272
 
254
273
  return parser
255
274
 
@@ -350,17 +369,18 @@ def _format_engine_summary(summary: dict[str, Any]) -> str:
350
369
  return "\n".join(lines)
351
370
 
352
371
 
353
- def _merge_verify_timing(timing: dict[str, Any], verify_ms: float) -> None:
354
- """把 verify 的墙钟并回 timing 的三个总数,保持互相自洽。
372
+ def _merge_verify_timing(timing: dict[str, Any], verify_ms: float,
373
+ stage: str = "verify") -> None:
374
+ """把后处理(verify/numverify/verify_with)的墙钟并回 timing 三个总数。
355
375
 
356
- why:verify 发生在主搜索快照之后。此前只并回 stages_ms/process_ms,
376
+ why:这些后处理发生在主搜索快照之后。此前只并回 stages_ms/process_ms,
357
377
  elapsed_ms 仍是主搜索的数(实测 1173 vs 10967),调用方最先读的总账
358
378
  比它的分项之和还小 8 倍。三个数必须一起走,否则「这次为什么慢」会被
359
379
  带偏到主搜索上。
360
380
  """
361
381
  total = float(timing.get("stages_ms") or 0) + verify_ms
362
382
  timing.setdefault("stages", []).append({
363
- "stage": "verify",
383
+ "stage": stage,
364
384
  "ms": round(verify_ms, 1),
365
385
  "pct": round(verify_ms * 100.0 / total, 1) if total > 0 else 0.0,
366
386
  })
@@ -645,15 +665,77 @@ def main():
645
665
  except Exception as e:
646
666
  print(f" [verify error] {type(e).__name__}: {e}", file=sys.stderr)
647
667
 
668
+ # 数值印证切片:--numverify 对摘要含关键数字的 top-k fetch 原文比对,
669
+ # 冲突者降权(missing 强降/partial 弱降)。与 --verify 独立:verify 量
670
+ # 「正文吸收分」,这里量「摘要数字与原文对不对得上」——摘要里 5999 与
671
+ # 11999 打架、毒内容套医院域名讲 iPhone,都只有数字比对抓得住。
672
+ _t_numverify0 = time.perf_counter()
673
+ if args.numverify:
674
+ try:
675
+ from numeric_verify import numeric_verify_results, reorder_by_numeric
676
+ nv = numeric_verify_results(results.get("results") or [], args.query,
677
+ top_k=args.numverify)
678
+ if nv is not None:
679
+ results["numverify"] = nv
680
+ try:
681
+ nre = reorder_by_numeric(results.get("results") or [])
682
+ if nre.get("reordered"):
683
+ results["numeric_reorder"] = nre
684
+ except Exception as _nre:
685
+ print(f" [numverify reorder skipped] {type(_nre).__name__}",
686
+ file=sys.stderr)
687
+ if not args.json_output:
688
+ ns = nv.get("summary") or {}
689
+ print(f" [numverify] 核对 {ns.get('checked', 0)} 条,"
690
+ f"confirmed={ns.get('confirmed', 0)} partial={ns.get('partial', 0)} "
691
+ f"missing={ns.get('missing', 0)} unfetchable={ns.get('unfetchable', 0)}",
692
+ file=sys.stderr)
693
+ nro = results.get("numeric_reorder") or {}
694
+ if nro.get("reordered"):
695
+ print(f" [numverify] 冲突降权:调整 {len(nro.get('adjusted') or [])} 条,"
696
+ f"位次变动 {nro.get('moved', 0)} 处", file=sys.stderr)
697
+ except Exception as e:
698
+ print(f" [numverify error] {type(e).__name__}: {e}", file=sys.stderr)
699
+
700
+ # 核对配对:--verify-with 按查询类型用第二个引擎跑轻量核对,独立交付
701
+ # 官方簇与域级重叠(auto=规则表自动选,价格/规格类→exa)。不并入主排序:
702
+ # 核对簇的价值是给 Agent 一眼可对的第二意见,混排反而稀释。
703
+ _t_verifywith0 = time.perf_counter()
704
+ if args.verify_with is not None:
705
+ try:
706
+ from verify_with import attach_verify_with
707
+ vw = attach_verify_with(results, args.query, engine=args.verify_with)
708
+ results["verify_with"] = vw
709
+ if not args.json_output:
710
+ vwe = vw.get("engine")
711
+ if not vwe:
712
+ print(f" [verify-with] skipped: {vw.get('skipped')}",
713
+ file=sys.stderr)
714
+ else:
715
+ ov = (vw.get("overlap") or {})
716
+ print(f" [verify-with] {vwe} {vw.get('elapsed_ms', 0)}ms,"
717
+ f"{len(vw.get('results') or [])} 条,"
718
+ f"域级重叠 {ov.get('count', 0)}:{', '.join(ov.get('domains') or []) or '无'}",
719
+ file=sys.stderr)
720
+ except Exception as e:
721
+ print(f" [verify-with error] {type(e).__name__}: {e}", file=sys.stderr)
722
+
648
723
  # 计时盲区修补(2026-09-29):--verify 的 top-k fetch 发生在上面计时快照
649
724
  # (process_ms 定格处)之后,净增 280–1160ms 完全不进任何账——实测
650
725
  # wall 776–1746ms vs process_ms 494–701ms,「这次为什么慢」归因指错
651
726
  # 方向。快照后移做不到(verify 是装配后的可选后处理),补一个 stage
652
727
  # 并把耗时并回三个总数(stages_ms / process_ms / elapsed_ms),
653
728
  # 三者保持自洽(2026-10-22 补 elapsed_ms)。
654
- if _timing is not None and "timing" in results and args.verify:
655
- _verify_ms = (time.perf_counter() - _t_verify0) * 1000.0
656
- _merge_verify_timing(results["timing"], _verify_ms)
729
+ if _timing is not None and "timing" in results:
730
+ if args.verify:
731
+ _verify_ms = (time.perf_counter() - _t_verify0) * 1000.0
732
+ _merge_verify_timing(results["timing"], _verify_ms)
733
+ if args.numverify:
734
+ _numverify_ms = (time.perf_counter() - _t_numverify0) * 1000.0
735
+ _merge_verify_timing(results["timing"], _numverify_ms, stage="numverify")
736
+ if args.verify_with is not None:
737
+ _vw_ms = (time.perf_counter() - _t_verifywith0) * 1000.0
738
+ _merge_verify_timing(results["timing"], _vw_ms, stage="verify_with")
657
739
 
658
740
  if args.json_output:
659
741
  public = {k: v for k, v in results.items() if not k.startswith("_")}