argo-search 2.10.2 → 2.12.0

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 (86) hide show
  1. package/README.en.md +36 -21
  2. package/README.es.md +35 -20
  3. package/README.ja.md +36 -21
  4. package/README.ko.md +35 -20
  5. package/README.md +41 -22
  6. package/SKILL.md +19 -18
  7. package/backends/domain_profiles.json +30 -6
  8. package/backends/engine_registry.yaml +63 -13
  9. package/backends/quota_profiles.json +50 -10
  10. package/bin/argo +13 -0
  11. package/config.yaml +34 -20
  12. package/docs/ENGINE_CATALOG.md +14 -9
  13. package/docs/MCP_SETUP.md +16 -4
  14. package/docs/RELEASE_NOTES_v2.11.2.md +166 -0
  15. package/docs/RELEASE_NOTES_v2.12.0.md +65 -0
  16. package/docs/engines/pixiv.md +27 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/pixiv.yaml +52 -0
  20. package/engines/specs/saucenao.yaml +45 -0
  21. package/engines/specs/tracemoe.yaml +33 -0
  22. package/package.json +4 -2
  23. package/packages/dsh-plugin/README.md +20 -11
  24. package/packages/dsh-plugin/dsh/client.js +3 -3
  25. package/packages/dsh-plugin/dsh/index.js +27 -176
  26. package/packages/dsh-plugin/dsh/runner.js +19 -3
  27. package/packages/dsh-plugin/dsh/specs.js +133 -0
  28. package/packages/dsh-plugin/package.json +10 -2
  29. package/packages/dsh-plugin/test/client.test.js +4 -4
  30. package/packages/dsh-plugin/test/diagnostics.test.js +1 -1
  31. package/packages/dsh-plugin/test/index.test.js +49 -2
  32. package/scripts/adaptive.py +101 -27
  33. package/scripts/budget.py +13 -3
  34. package/scripts/build_route_labels.py +122 -169
  35. package/scripts/caliber_dedupe.py +4 -4
  36. package/scripts/caliber_isolation.py +17 -17
  37. package/scripts/concept_lookup.py +14 -1
  38. package/scripts/config.py +21 -3
  39. package/scripts/engine_admission.py +35 -17
  40. package/scripts/engine_dispatch.py +18 -17
  41. package/scripts/engine_env.py +4 -0
  42. package/scripts/engine_families.py +10 -4
  43. package/scripts/engines.py +15 -2
  44. package/scripts/engines_base.py +1 -1
  45. package/scripts/engines_builders.py +0 -1
  46. package/scripts/engines_builders_data.py +10 -10
  47. package/scripts/engines_builders_intl.py +4 -4
  48. package/scripts/engines_builders_pixiv.py +633 -0
  49. package/scripts/engines_builders_reverse_image.py +958 -0
  50. package/scripts/engines_builders_tech.py +0 -78
  51. package/scripts/env_store.py +216 -0
  52. package/scripts/extend_route_labels_by_capability.py +4 -4
  53. package/scripts/extend_route_labels_by_language.py +306 -0
  54. package/scripts/extend_route_labels_full_coverage.py +329 -0
  55. package/scripts/fetch_v3.py +74 -5
  56. package/scripts/image_vision/vision_probe +0 -0
  57. package/scripts/job.py +33 -7
  58. package/scripts/lint_spec_contracts.py +110 -0
  59. package/scripts/lint_stub_targets.py +130 -0
  60. package/scripts/local_image.py +25 -11
  61. package/scripts/mcp_compact.py +13 -0
  62. package/scripts/mcp_launch.sh +1 -1
  63. package/scripts/mcp_setup.py +85 -1
  64. package/scripts/mcp_transport.py +1 -1
  65. package/scripts/net_proxy.py +47 -0
  66. package/scripts/plan.py +11 -0
  67. package/scripts/pre-commit +24 -13
  68. package/scripts/query_signals.py +35 -20
  69. package/scripts/quota.py +116 -12
  70. package/scripts/recovery.py +38 -13
  71. package/scripts/redskill/redskill_engine.py +33 -10
  72. package/scripts/route.py +2 -2
  73. package/scripts/route_accuracy_eval.py +2 -2
  74. package/scripts/route_combo.py +22 -3
  75. package/scripts/route_domains.py +182 -50
  76. package/scripts/search.py +13 -14
  77. package/scripts/search_entry.py +38 -42
  78. package/scripts/search_output.py +3 -0
  79. package/scripts/search_pipeline.py +18 -23
  80. package/scripts/search_rank.py +22 -7
  81. package/scripts/serp_guard.py +7 -16
  82. package/scripts/settings_page.py +486 -0
  83. package/scripts/social_engines/twitter_engine.py +35 -2
  84. package/scripts/social_engines/xiaohongshu_engine.py +25 -0
  85. package/scripts/straggler_policy.py +8 -4
  86. package/scripts/tfidf_router.py +82 -24
@@ -75,55 +75,129 @@ _ZH_LANG_GATED_DOMAINS = frozenset({
75
75
  _compiled_domains: list[dict[str, Any]] | None = None
76
76
  _compiled_domains_id: tuple | None = None # (name, patterns/exclude_if 内容指纹)
77
77
  _compiled_domains_ref: int | None = None
78
- _anchor_matcher: re.Pattern | None = None
78
+ _anchor_matcher: Any = None
79
79
  _anchor_to_domains: dict[str, list[int]] = {}
80
+ _anchor_first_char_lens: dict[str, list[int]] = {}
80
81
  _unconstrained_domains: set[int] = set()
81
82
 
83
+ _ANCHOR_LOOKAROUND_RE = re.compile(r"\(\?[=!<][^()]*\)")
84
+ _ANCHOR_OPT_GROUP_RE = re.compile(r"\((?:\?:)?[^()]+\)(?:\?|\*|\{0,[^}]*\})")
85
+ _ANCHOR_CHARSET_RE = re.compile(r"\[(?:\\.|[^\]\\])*\]\??\*?\+?(?:\{\d+,?\d*\})?")
86
+ _ANCHOR_ESCAPE_RE = re.compile(r"\\[wWdDsSbB]|\\.")
87
+ _ANCHOR_OPT_CHAR_RE = re.compile(r"[^()|\\]\?|\.\*|\.\+|\.\?")
88
+ _ANCHOR_QUANT_RE = re.compile(r"\{\d+,?\d*\}")
89
+ _ANCHOR_INNER_GROUP_RE = re.compile(r"\((?:\?:)?([^()]+)\)")
90
+ _ANCHOR_RUN_RE = re.compile(
91
+ r"[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]{1,}"
92
+ r"|[a-zA-Z0-9_\-\.\u00c0-\u024f\u0400-\u04ff\u0600-\u06ff\u0590-\u05ff\u0e00-\u0e7f]{2,}"
93
+ )
82
94
 
83
- def _extract_anchors(src: Any) -> set[str] | None:
84
- """从正则源码中提取一组必须包含其一的字面锚点词集合(全小写)。
85
95
 
86
- 若无法提取安全锚点(如含有纯通配、字符集类 []、通用转义字符类),返回 None。
87
- """
88
- if not isinstance(src, str) or not src:
89
- return None
90
- s = re.sub(r"^\(\?[a-zA-Z]+\)", "", src)
91
- s = re.sub(r"\\b", "", s)
92
- if s.startswith("(") and s.endswith(")"):
93
- s = s[1:-1]
96
+ def _split_top_level_pipe(s: str) -> list[str]:
94
97
  parts: list[str] = []
95
98
  depth = 0
99
+ in_br = False
100
+ escape = False
96
101
  cur: list[str] = []
97
102
  for ch in s:
98
- if ch in ("(", "["):
99
- depth += 1
100
- elif ch in (")", "]"):
101
- depth -= 1
102
- if ch == "|" and depth == 0:
103
- parts.append("".join(cur))
104
- cur = []
105
- else:
103
+ if escape:
106
104
  cur.append(ch)
105
+ escape = False
106
+ continue
107
+ if ch == "\\":
108
+ cur.append(ch)
109
+ escape = True
110
+ continue
111
+ if ch == "[" and not in_br:
112
+ in_br = True
113
+ elif ch == "]" and in_br:
114
+ in_br = False
115
+ elif not in_br:
116
+ if ch == "(":
117
+ depth += 1
118
+ elif ch == ")":
119
+ depth -= 1
120
+ elif ch == "|" and depth == 0:
121
+ parts.append("".join(cur))
122
+ cur = []
123
+ continue
124
+ cur.append(ch)
107
125
  if cur:
108
126
  parts.append("".join(cur))
127
+ return parts
128
+
129
+
130
+ def _extract_anchors(src: Any, _depth: int = 0) -> set[str] | None:
131
+ """从正则源码中提取一组必须包含其一的字面锚点词集合(全小写)。
109
132
 
133
+ 对每个顶层 | 分支提取必现字面量(剥离环视断言、字符集、转义类与可选量词),
134
+ 若某分支无顶层字面量但含必现括号组,则递归提取该组的锚点并求并集。
135
+ 若任一分支无法提取安全锚点,返回 None(该域归入 _unconstrained_domains)。
136
+ """
137
+ if not isinstance(src, str) or not src or _depth > 3:
138
+ return None
139
+ s = re.sub(r"^\(\?[a-zA-Z]+\)", "", src.strip())
140
+ while s.startswith("(") and s.endswith(")"):
141
+ inner = s[1:-1]
142
+ if len(_split_top_level_pipe(inner)) >= 1 and inner.count("(") == inner.count(")"):
143
+ d = 0
144
+ ok = True
145
+ for ch in inner:
146
+ if ch == "(":
147
+ d += 1
148
+ elif ch == ")":
149
+ d -= 1
150
+ if d < 0:
151
+ ok = False
152
+ break
153
+ if ok and d == 0:
154
+ s = inner
155
+ continue
156
+ break
157
+ if s.startswith("?:"):
158
+ s = s[2:]
159
+
160
+ parts = _split_top_level_pipe(s)
161
+ if not parts:
162
+ return None
110
163
  anchors: set[str] = set()
111
164
  for part in parts:
112
- # 正则字符类与元字符无法保证字面子串存在
113
- if re.search(r"\[.*?\]", part) or re.search(r"\\[wWdDsS]", part):
114
- return None
115
- runs = re.findall(r"[\u4e00-\u9fff]{1,}|[a-zA-Z0-9_\-\.]{2,}", part)
116
- if not runs:
165
+ p_no_la = _ANCHOR_LOOKAROUND_RE.sub(" ", part)
166
+ p_no_opt_grp = _ANCHOR_OPT_GROUP_RE.sub(" ", p_no_la)
167
+ p_outside = re.sub(r"\([^()]*\)", " ", p_no_opt_grp)
168
+ while "(" in p_outside and ")" in p_outside:
169
+ p_outside_next = re.sub(r"\([^()]*\)", " ", p_outside)
170
+ if p_outside_next == p_outside:
171
+ break
172
+ p_outside = p_outside_next
173
+ p_clean = _ANCHOR_CHARSET_RE.sub(" ", p_outside)
174
+ p_clean = _ANCHOR_ESCAPE_RE.sub(" ", p_clean)
175
+ p_clean = _ANCHOR_OPT_CHAR_RE.sub(" ", p_clean)
176
+ p_clean = _ANCHOR_QUANT_RE.sub(" ", p_clean)
177
+ runs = _ANCHOR_RUN_RE.findall(p_clean)
178
+ # 单字锚点(含 CJK 单字)过滤力接近零、还会把带通配的模式误判成有锚点,
179
+ # 一律不收:宁可落进 _unconstrained_domains 多算几路,也不造假锚点。
180
+ valid = [v for v in (r.strip(".-_").lower() for r in runs) if len(v) >= 2]
181
+ if valid:
182
+ anchors.add(max(valid, key=len))
183
+ continue
184
+ found_grp = False
185
+ for m_grp in _ANCHOR_INNER_GROUP_RE.finditer(p_no_opt_grp):
186
+ grp_anc = _extract_anchors(m_grp.group(1), _depth + 1)
187
+ if grp_anc:
188
+ anchors.update(grp_anc)
189
+ found_grp = True
190
+ break
191
+ if not found_grp:
117
192
  return None
118
- for r in runs:
119
- anchors.add(r.lower())
120
193
  return anchors if anchors else None
121
194
 
122
195
 
123
196
  def _init_anchor_index(compiled: list[dict[str, Any]]) -> None:
124
- """初始化全局锚点自动机索引(方案一:Aho-Corasick 前置快速分桶)。"""
125
- global _anchor_matcher, _anchor_to_domains, _unconstrained_domains
197
+ """初始化全局锚点字典索引(子串闭包 + 首字符长度表贪心扫描)。"""
198
+ global _anchor_matcher, _anchor_to_domains, _anchor_first_char_lens, _unconstrained_domains
126
199
  _anchor_to_domains = {}
200
+ _anchor_first_char_lens = {}
127
201
  _unconstrained_domains = set()
128
202
  all_anchors: set[str] = set()
129
203
 
@@ -149,23 +223,46 @@ def _init_anchor_index(compiled: list[dict[str, Any]]) -> None:
149
223
  all_anchors.add(term)
150
224
 
151
225
  if all_anchors:
152
- sorted_terms = sorted(all_anchors, key=len, reverse=True)
153
- escaped = [re.escape(t) for t in sorted_terms]
154
- _anchor_matcher = re.compile("|".join(escaped), re.IGNORECASE)
226
+ by_fc: dict[str, set[int]] = {}
227
+ for t in all_anchors:
228
+ by_fc.setdefault(t[0], set()).add(len(t))
229
+ _anchor_first_char_lens = {
230
+ k: sorted(v, reverse=True) for k, v in by_fc.items()
231
+ }
232
+ _anchor_matcher = True
155
233
  else:
156
234
  _anchor_matcher = None
157
235
 
158
236
 
159
237
  def _get_candidate_domain_indices(query: str) -> set[int] | None:
160
- """通过锚点词快速扫描返回候选域索引集合;无索引时返回 None。"""
161
- if _anchor_matcher is None:
238
+ """通过锚点字典快速扫描返回候选域索引集合;无索引时返回 None。
239
+
240
+ 为与旧 `_anchor_matcher.finditer` 的非重叠贪心最长匹配语义逐位一致,
241
+ 命中长为 ln 的锚点词后游标推进 ln(不回看其内部被长词覆盖的短子串)。
242
+ """
243
+ if not _anchor_matcher:
162
244
  return None
163
245
  candidates = set(_unconstrained_domains)
164
- for m in _anchor_matcher.finditer(query):
165
- term = m.group(0).lower()
166
- doms = _anchor_to_domains.get(term)
167
- if doms:
168
- candidates.update(doms)
246
+ q_low = query.lower()
247
+ qn = len(q_low)
248
+ fc_map = _anchor_first_char_lens
249
+ a2d = _anchor_to_domains
250
+ i = 0
251
+ while i < qn:
252
+ lens = fc_map.get(q_low[i])
253
+ if not lens:
254
+ i += 1
255
+ continue
256
+ rem = qn - i
257
+ matched_ln = 0
258
+ for ln in lens:
259
+ if ln <= rem:
260
+ doms = a2d.get(q_low[i:i + ln])
261
+ if doms:
262
+ candidates.update(doms)
263
+ matched_ln = ln
264
+ break
265
+ i += matched_ln if matched_ln > 0 else 1
169
266
  return candidates
170
267
 
171
268
 
@@ -292,25 +389,51 @@ class _LiteralMatcher:
292
389
  alternation(如 `(?i)(金十|jin10)`、`(?i)(技术社区|程序员社区)`),它们每次
293
390
  冷进程都要付一次 `re.compile`(326 条全量实测 23.8 ms),而子串查找零编译、
294
391
  更快。判定由 `_literal_alternatives` 保守把关,判不准的一律走原正则路径。
392
+ AC-IGTR 增补首字符分桶索引与预小写复用,消除宽分支字面表的无关扫描。
295
393
  """
296
394
 
297
- __slots__ = ("_words", "_ignore_case")
395
+ __slots__ = ("_words", "_ignore_case", "_by_fc")
298
396
 
299
397
  def __init__(self, words: list[str], ignore_case: bool):
300
398
  self._words = words
301
399
  self._ignore_case = ignore_case
400
+ if len(words) >= 6:
401
+ by_fc: dict[str, list[tuple[int, str]]] = {}
402
+ for idx, w in enumerate(words):
403
+ by_fc.setdefault(w[0], []).append((idx, w))
404
+ self._by_fc: dict[str, list[tuple[int, str]]] | None = by_fc
405
+ else:
406
+ self._by_fc = None
302
407
 
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:
408
+ def search(self, query: str, q_lower: str | None = None) -> _LiteralMatch | None:
409
+ hay = (q_lower if q_lower is not None else query.lower()) if self._ignore_case else query
410
+ if not hay:
411
+ return None
412
+ best: tuple[int, int, int] | None = None
413
+ if self._by_fc is not None:
414
+ seen_fc: set[str] = set()
415
+ for ch in hay:
416
+ if ch in seen_fc:
417
+ continue
418
+ seen_fc.add(ch)
419
+ bucket = self._by_fc.get(ch)
420
+ if not bucket:
421
+ continue
422
+ for idx, w in bucket:
423
+ pos = hay.find(w)
424
+ if pos < 0:
425
+ continue
426
+ if best is None or pos < best[0] or (pos == best[0] and idx < best[1]):
427
+ best = (pos, idx, pos + len(w))
428
+ return _LiteralMatch((best[0], best[2])) if best is not None else None
429
+ for idx, w in enumerate(self._words):
307
430
  pos = hay.find(w)
308
431
  if pos < 0:
309
432
  continue
310
433
  # 与 re 的 leftmost 语义一致:取最早出现;同位置取分支顺序在前者
311
434
  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
435
+ best = (pos, idx, pos + len(w))
436
+ return _LiteralMatch((best[0], best[2])) if best is not None else None
314
437
 
315
438
 
316
439
  def _try_compile(src: Any) -> Any:
@@ -424,12 +547,20 @@ def _split_pattern_entry(entry: Any) -> tuple[Any, Any]:
424
547
  return entry, None
425
548
 
426
549
 
427
- def _domain_fires_with_span(domain: dict[str, Any], query: str) -> tuple[bool, int, int]:
550
+ def _domain_fires_with_span(
551
+ domain: dict[str, Any], query: str, q_lower: str | None = None
552
+ ) -> tuple[bool, int, int]:
428
553
  """一个域是否成立,并返回命中的 (是否成立, match_span_start, match_span_len)。"""
429
554
  for match_re, unless_re in _ensure_domain_compiled(domain):
430
- if unless_re is not None and unless_re.search(query):
431
- continue
432
- m = match_re.search(query)
555
+ if unless_re is not None:
556
+ u_hit = (unless_re.search(query, q_lower)
557
+ if isinstance(unless_re, _LiteralMatcher)
558
+ else unless_re.search(query))
559
+ if u_hit:
560
+ continue
561
+ m = (match_re.search(query, q_lower)
562
+ if isinstance(match_re, _LiteralMatcher)
563
+ else match_re.search(query))
433
564
  if m is not None:
434
565
  start, end = m.span()
435
566
  return True, start, end - start
@@ -676,6 +807,7 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
676
807
  non_zh = bool(primary_lang and primary_lang not in ("zh", "mixed", "other"))
677
808
  candidates = _get_candidate_domain_indices(query)
678
809
  q_len = max(len(query), 1)
810
+ q_lower = query.lower()
679
811
 
680
812
  for idx, domain in enumerate(compiled):
681
813
  if not domain.get("patterns", []):
@@ -685,7 +817,7 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
685
817
  continue
686
818
  if candidates is not None and idx not in candidates:
687
819
  continue
688
- fires, span_start, span_len = _domain_fires_with_span(domain, query)
820
+ fires, span_start, span_len = _domain_fires_with_span(domain, query, q_lower)
689
821
  if fires:
690
822
  if not hits:
691
823
  hits.append(domain)
package/scripts/search.py CHANGED
@@ -235,8 +235,6 @@ def _local_seek_grace_s() -> float:
235
235
  return 0.25
236
236
 
237
237
 
238
- _LOCAL_SEEK_GRACE_S = _local_seek_grace_s()
239
-
240
238
  # include-local 的本地搜索 worker:单例下沉到 local_seek 模块,避免 search.py
241
239
  # 在 daemon.py 的 runpy.run_module("search", run_name="__main__") 下重跑顶层时
242
240
  # 把 _LOCAL_SEEK_EXECUTOR 覆写为 None、导致每次调用泄漏一个 ThreadPoolExecutor。
@@ -252,7 +250,8 @@ def _note_remote_quota_exhausted(engine: str, detail: str) -> None:
252
250
  """
253
251
  try:
254
252
  from quota import get_quota_manager
255
- get_quota_manager().mark_remote_exhausted(engine, reason=detail)
253
+ # 带上 category,让余额不足(402)走短冷却、与月度预算周期解耦(#42)
254
+ get_quota_manager().mark_remote_exhausted(engine, reason=detail, category="quota_exhausted")
256
255
  except Exception: # 侧信道:标记失败不得影响搜索主流程(规则见 except_sets)
257
256
  pass
258
257
 
@@ -604,9 +603,6 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
604
603
  注意:路由永远基于原始 query。改写词只用于引擎检索,避免
605
604
  「Python → 追加 pip/库」之类改写污染 package_search 等域规则。
606
605
  """
607
- if cache is None:
608
- from cache import SearchCache # 局部 import;见模块头注释(不能用裸名)
609
- cache = SearchCache()
610
606
  original_query = query
611
607
 
612
608
  # 查询操作符契约层(2026-10-17 query_operators):指令从路由与检索两侧
@@ -630,9 +626,8 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
630
626
  tier = "daily"
631
627
  plan_info: dict[str, Any] | None = None
632
628
  try:
633
- from plan import (
634
- build_plan, classify_input_kind, execution_tier, should_attach_plan,
635
- )
629
+ from plan import (URL_INPUT_ENGINES, build_plan, classify_input_kind,
630
+ execution_tier, should_attach_plan)
636
631
  kind = classify_input_kind(query, input_kind)
637
632
  tier = execution_tier(mode, depth, context)
638
633
  if plan_only:
@@ -643,7 +638,8 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
643
638
  context=context,
644
639
  timing=timing,
645
640
  )
646
- if kind == "known-url" and not force_search:
641
+ # 按 URL 取单条的抽取引擎(单条推文 / 反搜图)显式指定时不拦截为 handoff。
642
+ if kind == "known-url" and not force_search and (engine or "").strip() not in URL_INPUT_ENGINES:
647
643
  plan_info = build_plan(
648
644
  query, mode=mode, depth=depth, max_results=n,
649
645
  engine=engine, input_kind="known-url", context=context,
@@ -783,6 +779,10 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
783
779
  file=sys.stderr)
784
780
  if search_query != original_query:
785
781
  print(f"[改写] {original_query} → {search_query}", file=sys.stderr)
782
+ if cache is None:
783
+ from cache import SearchCache # 按需延迟初始化,短路/离线计划路径免建 SQLite 缓存
784
+ cache = SearchCache()
785
+
786
786
  # L1 并行化:本地搜索与主搜索并行提交(仅显式开启时在宽根下提示)。
787
787
  _local_seek_explicit = include_local is not None
788
788
  include_local = _resolve_include_local(include_local, mode, query)
@@ -989,11 +989,10 @@ if __name__ == "__main__":
989
989
  # _MODULE_T0` —— 那是**第二次**导入 search(真模块),此刻依赖全在
990
990
  # sys.modules 里,差值 ≈ 0。于是 --explain-timing 的 import_ms 恒为 0.0,
991
991
  # 而它这一栏恰恰是给「优化固定开销」用的,报 0 等于把人指向错的数字。
992
- #
993
- # runpy 不会把 __main__ 留在 sys.modules['__main__'](它会恢复原模块),
994
- # 所以靠 __main__ 取不到;写进 search_cli 的模块属性是唯一稳定的交接点。
992
+ # runpy 不会把 __main__ 留在 sys.modules['__main__'](会恢复原模块),所以靠
993
+ # __main__ 取不到;写进 search_cli 的模块属性是唯一稳定交接点。
995
994
  from search_cli import main # 反向导入放这里:CLI 依赖本模块,模块级会成环
996
- import search_cli as _cli_mod
995
+ import search_cli as _cli_mod # noqa: E402
997
996
  _cli_mod._TRUE_IMPORT_T0 = _MODULE_T0
998
997
  _cli_mod._TRUE_IMPORTS_DONE = _IMPORTS_DONE
999
998
  main()
@@ -120,51 +120,9 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
120
120
  engines = [e for e in engines_combo if e] or ["anysearch"]
121
121
  parallel = decision.get("parallel", False) and len(engines) > 1
122
122
 
123
- # P0-001:查询理解 — clean_query 用于检索,exclude_terms 用于融合后过滤
124
- exclude_terms: list[str] = []
125
- retrieval_query = query
126
- qu = None
127
- try:
128
- from query_understanding import _understand_cached as understand
129
- qu = understand(query)
130
- exclude_terms = qu.exclude_terms
131
- # 查询操作符 -词/-"短语" 的排除项汇合(2026-10-17 query_operators):
132
- # 与否定理解共用同一「融合后过滤」通道,去重保序。
133
- _op_excl = ((decision or {}).get("operators") or {}).get("exclude_terms") or []
134
- for t in _op_excl:
135
- if t and t not in exclude_terms:
136
- exclude_terms.append(t)
137
- # 仅当去否定片段后仍有实义内容时才替换检索词,避免空检索
138
- if qu.clean_query and qu.clean_query.strip():
139
- retrieval_query = qu.clean_query
140
- except ImportError:
141
- pass # query_understanding 不可用
142
- except Exception as e:
143
- _log(f"查询理解跳过: {type(e).__name__}")
144
-
145
- # 词形规范化:全角→半角、拆斜杠、压多余空格(提升精确源命中,治型号/日期分隔符)
146
- try:
147
- from query_enhance import normalize_query
148
- retrieval_query = normalize_query(retrieval_query)
149
- except ImportError:
150
- pass
151
-
152
123
  if on_progress:
153
124
  on_progress(Stage.START, {"query": query})
154
125
 
155
- # 网络环境感知:慢网放大超时预算(避免误杀),快网收紧(更快响应)
156
- _eff_timeout = timeout
157
- try:
158
- from network_aware import adjusted_timeout, network_profile
159
- _eff_timeout = adjusted_timeout(timeout, engines)
160
- if _eff_timeout != timeout:
161
- _log(
162
- f"网络感知超时: {timeout}s → {_eff_timeout}s "
163
- f"({network_profile(engines).get('network')})",
164
- )
165
- except ImportError:
166
- pass
167
-
168
126
  # 时间窗归一化:下推/缓存键用归一化 ISO(相对值转绝对日期),
169
127
  # 后过滤用 epoch 秒;非法输入保持原样下推、不参与后过滤。
170
128
  since_iso, until_iso, since_ts, until_ts = _normalize_time_window(since, until)
@@ -281,6 +239,44 @@ def prepare(query: str, decision: dict[str, Any], max_results: int,
281
239
  if timing is not None:
282
240
  _hit["timing"] = timing.summary()
283
241
  return _Prepared(cached=_hit)
242
+
243
+ # 缓存未命中才拉起查询理解、词形规范化与网络感知超时(缓存命中热路径零开销)
244
+ exclude_terms: list[str] = []
245
+ retrieval_query = query
246
+ qu = None
247
+ try:
248
+ from query_understanding import _understand_cached as understand
249
+ qu = understand(query)
250
+ exclude_terms = qu.exclude_terms
251
+ _op_excl = ((decision or {}).get("operators") or {}).get("exclude_terms") or []
252
+ for t in _op_excl:
253
+ if t and t not in exclude_terms:
254
+ exclude_terms.append(t)
255
+ if qu.clean_query and qu.clean_query.strip():
256
+ retrieval_query = qu.clean_query
257
+ except ImportError:
258
+ pass
259
+ except Exception as e:
260
+ _log(f"查询理解跳过: {type(e).__name__}")
261
+
262
+ try:
263
+ from query_enhance import normalize_query
264
+ retrieval_query = normalize_query(retrieval_query)
265
+ except ImportError:
266
+ pass
267
+
268
+ _eff_timeout = timeout
269
+ try:
270
+ from network_aware import adjusted_timeout, network_profile
271
+ _eff_timeout = adjusted_timeout(timeout, engines)
272
+ if _eff_timeout != timeout:
273
+ _log(
274
+ f"网络感知超时: {timeout}s → {_eff_timeout}s "
275
+ f"({network_profile(engines).get('network')})",
276
+ )
277
+ except ImportError:
278
+ pass
279
+
284
280
  try:
285
281
  from circuit_breaker import get_breaker
286
282
  breaker = get_breaker()
@@ -70,6 +70,9 @@ _AGENT_RESULT_FIELDS = (
70
70
  # 出现(backfill_results 回填),未核验结果不造假摘要。
71
71
  "summary",
72
72
  "image_url", "image_license",
73
+ # 双通道引擎(同一引擎名背后有匿名与认证两条取数通路)标出本条实际走的
74
+ # 通道:内容范围差异正是两条通路的区别,剥掉它就只能靠猜。
75
+ "channel",
73
76
  "episode_count", "duration_minutes",
74
77
  # 本地已有正文:是可操作提示而非观测数据——告诉 Agent 这条不必重新联网,
75
78
  # 以及全文在哪(被截断时还给出 full_text_path)。剥掉它等于把「随时
@@ -486,14 +486,14 @@ def postprocess(req: _SearchRequest, run: _SearchRun, hooks: Any) -> _SearchRun:
486
486
  _tock(timing, "filter", _tk_filter)
487
487
 
488
488
  # ── 图片可用性过滤(仅图片检索域)─────────────────────────────────
489
- # 只在 image_search 这种「用户要的就是图」的查询上启用:普通网页搜索的
490
- # 结果里也可能带 image_url(正文配图),那里图小不构成丢弃整篇文章的理由。
491
- # 判据与阈值见 image_ops(分辨率下限、极端长宽比、明确非商用)。
492
- # 默认只剔「字段层面即可确定不可用」的(无图/过小/极端比例);非商用图
493
- # 不剔——「搜图看看」和「找能发布的素材」是两个需求,后者由调用方显式
494
- # 开启。剔除明细进 image_dropped,供诊断「为什么少了 N 条」。
489
+ # 只在 image_search 这种「用户要的就是图」的查询上启用:普通网页搜索的结果
490
+ # 也可能带 image_url(正文配图),图小不构成丢弃整篇文章的理由。判据与阈值见
491
+ # image_ops。以图搜图的条目是出处页(pixiv/bgm),按分辨率判它们全数不合格,
492
+ # 故显式只点反搜图引擎时跳过。剔除明细进 image_dropped 供诊断。
495
493
  image_dropped: dict[str, int] = {}
496
- if merged and domain == "image_search":
494
+ from plan import REVERSE_IMAGE_ENGINES, URL_INPUT_ENGINES # plan 模块级拖 argparse,热路径外导入
495
+ _reverse_scope = bool(engines) and set(engines) <= REVERSE_IMAGE_ENGINES
496
+ if merged and domain == "image_search" and not _reverse_scope:
497
497
  try:
498
498
  from image_ops import filter_usable_images as _filter_imgs
499
499
  merged, image_dropped = _filter_imgs(merged)
@@ -526,19 +526,19 @@ def postprocess(req: _SearchRequest, run: _SearchRun, hooks: Any) -> _SearchRun:
526
526
  pass
527
527
  _tk_recovery = _tick(timing)
528
528
  _recovery_engines: set[str] = set()
529
- # 查询词回声(2026-10-17 实锤):有结果但整批退化时同样要恢复——
530
- # `if not merged` 只看「有没有结果」,不看「是不是垃圾」。判据与理由见
531
- # query_signals.is_query_echo(rerank 尚未执行,只能用零网络成本的词面)。
529
+ # 查询词回声(2026-10-17 实锤):有结果但整批退化时同样要恢复——`if not merged`
530
+ # 只看「有没有结果」,不看「是不是垃圾」。判据见 query_signals.is_query_echo。
532
531
  try:
533
532
  from postprocess_signals import echo_recovery_needed as _echo_needed
534
533
  _echo_triggered = _echo_needed(merged, query)
535
534
  except OPT_IMPORT + SHAPE_BENIGN: # 守卫不可用不设卡(fail-open)
536
535
  _echo_triggered = False
537
- # 视频/时长模式不做恢复链:恢复链会跨域补搜普通网页,补进来的结果要么
538
- # 被 video_only 过滤掉(白付一轮网络),要么绕过时长过滤(把已筛掉的
539
- # 长/短视频重新带回来)。0 条就直接返回空,条件由调用方自己放宽。
536
+ # 视频/时长模式不做恢复链:恢复链会跨域补搜普通网页,补进来的结果要么被
537
+ # video_only 过滤掉(白付一轮网络),要么绕过时长过滤(带回已筛掉的长/短视频)。
538
+ # 0 条就直接返回空,条件由调用方自己放宽。
540
539
  _video_scope = (_video_only or _min_d is not None or _max_d is not None)
541
- if (not merged or _echo_triggered) and not _video_scope:
540
+ _url_extract_only = bool(engines) and set(engines) <= URL_INPUT_ENGINES # 目标就是那一条,替身网页不是它
541
+ if (not merged or _echo_triggered) and not _video_scope and not _url_extract_only:
542
542
  from recovery_runner import run_pipeline_recovery
543
543
  _dk = {k: v for k in ("domain", "sub_domain") if (v := getattr(req, "engine_" + k, None))}
544
544
  merged, _rec_info = run_pipeline_recovery(
@@ -810,11 +810,12 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
810
810
  # 自适应学习(单事务批量写入 + cache_guard 统一状态态过滤)
811
811
  try:
812
812
  import contextlib
813
- from adaptive import get_learner, scenario_of
813
+ from adaptive import get_learner, marginal_contribution, scenario_of
814
814
  learner = get_learner()
815
815
  _outcome_of = {o.get("engine"): o
816
816
  for o in engine_outcomes if isinstance(o, dict)}
817
817
  _batch_ctx = learner.batch() if hasattr(learner, "batch") else contextlib.nullcontext()
818
+ _shares = marginal_contribution(merged, max_results, [e for e, r in raw_results.items() if r]) # 终榜边际贡献,见 adaptive
818
819
  with _batch_ctx:
819
820
  for eng, res in raw_results.items():
820
821
  outcome = _outcome_of.get(eng)
@@ -826,13 +827,7 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
826
827
  empty = (not success) and st in ("no-results", "no-results-cached")
827
828
  latency = engine_latency.get(eng, elapsed / max(len(raw_results), 1))
828
829
  cost = get_cost_factor(eng)
829
- quality = None
830
- if success:
831
- try:
832
- from query_signals import result_relevance
833
- quality = result_relevance(query, res)
834
- except Exception:
835
- quality = None
830
+ quality = _shares.get(eng) if success else None
836
831
  learner.record(eng, success=success, latency_ms=latency,
837
832
  cost=0.0 if cost >= 0.85 else 0.001, empty=empty,
838
833
  quality=quality, **scenario_of(decision))
@@ -986,4 +981,4 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
986
981
  # timing 在 agent 档保留,预算可见性随答案一起到达。
987
982
  out["timing"]["budget"] = {"used_ms": budget_used_ms,
988
983
  "total_ms": budget_total_ms}
989
- return out
984
+ return out
@@ -500,7 +500,7 @@ def rerank_results(query: str, results: list[dict[str, Any]],
500
500
  """使用博查语义排序模型对搜索结果二次精排。
501
501
 
502
502
  返回 (results, status):status ∈ ok | skipped_no_key | skipped_short |
503
- skipped_fast | skipped_circuit_open | fallback
503
+ skipped_fast | skipped_circuit_open | skipped_quota | fallback
504
504
  """
505
505
  if not results or len(results) <= 1:
506
506
  return results, "skipped_short"
@@ -509,6 +509,20 @@ def rerank_results(query: str, results: list[dict[str, Any]],
509
509
  if not api_key:
510
510
  return results, "skipped_no_key"
511
511
 
512
+ # 配额联动(在熔断器之前):bocha 搜索侧已归因 quota_exhausted(同源同
513
+ # key)时,精排端点连「半开探测」都不必打。此前 rerank 的 403 归 auth 走
514
+ # 熔断器,冷却结束就放一次真实探测(实测 opens=18、间隔 ~100s,折合
515
+ # ~866 次无效 403/天);联动后行为与搜索端点对称——冷却期由
516
+ # quota._quota_cooldown_seconds 单点决定(余额类 1h,免费额度类按 period),
517
+ # 充值/换 Key 后随搜索端点一起自愈。fail-open:quota 层读不到就照旧走
518
+ # 熔断器,联动检查不成为新的单点故障。
519
+ try:
520
+ from quota import get_quota_manager
521
+ if get_quota_manager().is_remote_exhausted("bocha"):
522
+ return results, "skipped_quota"
523
+ except Exception:
524
+ pass
525
+
512
526
  # 端点熔断:先问「还该不该打这一枪」。
513
527
  #
514
528
  # 为什么必须记住失败:这是一次**同步阻塞**的网络调用,压在 CPU 后处理链上。
@@ -611,7 +625,6 @@ def _jaccard(a: set[str], b: set[str]) -> float:
611
625
 
612
626
 
613
627
 
614
-
615
628
  def _consensus_prior(results: list[dict[str, Any]]) -> list[float]:
616
629
  """融合先验:把 RRF 分与跨引擎共识数归一化成 [0,1](逐条保持一致 results)。
617
630
 
@@ -635,18 +648,19 @@ def _consensus_prior(results: list[dict[str, Any]]) -> list[float]:
635
648
  priors: list[float] = []
636
649
  raw = [float(r.get("_rrf_score", 0.0) or 0.0) for r in results]
637
650
  peak = max(raw) if raw else 0.0
651
+ from caliber_isolation import caliber_of
638
652
  for r, rrf in zip(results, raw):
639
653
  rrf_norm = (rrf / peak) if peak > 0 else 0.0
640
- cons = len(r.get("consensus_engines") or [])
654
+ cons_engs = r.get("consensus_engines") or []
655
+ cons = len(cons_engs)
641
656
  cons_norm = min(max(cons - 1, 0), 3) / 3.0
642
- # 两个子信号取均值:单纯多引擎重复 != 更可信,RRF 分还含引擎权重
657
+ if cons >= 2 and len({caliber_of(e) for e in cons_engs if e}) >= 2:
658
+ cons_norm = min(1.0, cons_norm + 0.15)
659
+ # 两个子信号取均值:跨口径独立共识额外获 0.15 异质印证增益
643
660
  priors.append(0.5 * rrf_norm + 0.5 * cons_norm)
644
661
  return priors
645
662
 
646
663
 
647
-
648
-
649
-
650
664
  def local_five_dim_rerank(query: str, results: list[dict[str, Any]],
651
665
  domain: str = "general", top_n: int = 10
652
666
  ) -> list[dict[str, Any]]:
@@ -996,5 +1010,6 @@ _RERANK_DEGRADED_STATUSES = frozenset({
996
1010
  "skipped_short", # 结果太少,不值得精排
997
1011
  "skipped_fast", # fast 档不付远程精排
998
1012
  "skipped_circuit_open", # 端点熔断中(见 _RERANK_BREAKER_KEY)
1013
+ "skipped_quota", # 搜索端点已归因配额耗尽,联动跳过(同源同 key)
999
1014
  "fallback", # 端点报错或返回不可用数据
1000
1015
  })