argo-search 2.10.1 → 2.10.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 (66) hide show
  1. package/README.en.md +30 -4
  2. package/README.es.md +30 -4
  3. package/README.ja.md +30 -4
  4. package/README.ko.md +30 -4
  5. package/README.md +30 -24
  6. package/SKILL.md +1 -1
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/engine_concept_vectors.json +3104 -0
  9. package/config.yaml +82 -14
  10. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  11. package/package.json +2 -1
  12. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  13. package/packages/dsh-plugin/dsh/index.js +7 -7
  14. package/packages/dsh-plugin/dsh/runner.js +72 -46
  15. package/packages/dsh-plugin/package.json +1 -1
  16. package/packages/dsh-plugin/test/index.test.js +43 -0
  17. package/scripts/argo_engine_registry.py +30 -4
  18. package/scripts/argo_paths.py +7 -1
  19. package/scripts/build_concept_table.py +612 -0
  20. package/scripts/build_route_labels.py +285 -0
  21. package/scripts/caliber_dedupe.py +66 -0
  22. package/scripts/caliber_isolation.py +4 -2
  23. package/scripts/circuit_breaker.py +25 -3
  24. package/scripts/concept_lookup.py +212 -0
  25. package/scripts/engines.py +24 -7
  26. package/scripts/engines_base.py +17 -2
  27. package/scripts/engines_builders_skill.py +87 -10
  28. package/scripts/extend_route_labels.py +239 -0
  29. package/scripts/extend_route_labels_by_capability.py +344 -0
  30. package/scripts/gen_routing_snapshot.py +22 -3
  31. package/scripts/lang_detect.py +12 -3
  32. package/scripts/local_seek.py +13 -3
  33. package/scripts/mcp_transport.py +1 -1
  34. package/scripts/numeric_verify.py +330 -0
  35. package/scripts/plan.py +25 -4
  36. package/scripts/pre-commit +2 -2
  37. package/scripts/rank_signals.py +48 -4
  38. package/scripts/ranking_eval.py +23 -1
  39. package/scripts/regression_p0p1.py +7 -2
  40. package/scripts/route.py +24 -3
  41. package/scripts/route_accuracy_eval.py +191 -0
  42. package/scripts/route_combo.py +32 -1
  43. package/scripts/route_domains.py +242 -5
  44. package/scripts/route_primary.py +101 -0
  45. package/scripts/search.py +1 -0
  46. package/scripts/search_cli.py +89 -7
  47. package/scripts/search_output.py +59 -1
  48. package/scripts/search_pipeline.py +5 -0
  49. package/scripts/snippet_clean.py +60 -0
  50. package/scripts/social_engines/twitter_engine.py +127 -43
  51. package/scripts/social_engines/xiaohongshu_engine.py +11 -1
  52. package/scripts/tfidf_router.py +52 -2
  53. package/scripts/train.py +15 -0
  54. package/scripts/verify_with.py +124 -0
  55. package/sub-skills/local-search/SKILL.md +3 -2
  56. package/sub-skills/local-search/bm25.py +89 -8
  57. package/sub-skills/local-search/config.yaml +12 -0
  58. package/sub-skills/local-search/parse_maps.yaml +8 -0
  59. package/sub-skills/local-search/parsers.py +5 -2
  60. package/sub-skills/local-search/search_v3.py +87 -1
  61. package/sub-skills/local-search/smart_router.py +1 -1
  62. package/sub-skills/local-seek/SKILL.md +6 -5
  63. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  64. package/sub-skills/local-seek/scripts/seek.py +152 -36
  65. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
  66. package/scripts/image_vision/vision_probe +0 -0
@@ -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("_")}
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  from search_rank import filter_results_by_domains
12
12
  from search_types import slot_record as dataclass
13
+ from snippet_clean import clean_snippet
13
14
  from typing import Any
14
15
  from output_transparency import ( # noqa: F401
15
16
  _AGGREGATOR_HOSTS,
@@ -143,6 +144,49 @@ def _slim_reorder(r: Any) -> dict[str, Any] | None:
143
144
  return out or None
144
145
 
145
146
 
147
+ def _slim_numverify(v: Any) -> dict[str, Any] | None:
148
+ """numverify 块的 agent 精简版:保 summary + 逐条 verdict/misses。
149
+
150
+ why:数值印证是「该不该引用这条的数字」的直接依据(摘要 5999 与原文
151
+ 11999 打架只有这里看得见),checked/hits 细节可由 url 对回 results,
152
+ 不重复携带。
153
+ """
154
+ if not isinstance(v, dict):
155
+ return None
156
+ out: dict[str, Any] = {}
157
+ if v.get("summary") is not None:
158
+ out["summary"] = v["summary"]
159
+ if v.get("pending"):
160
+ out["pending"] = v["pending"]
161
+ rows = []
162
+ for r in v.get("verified") or []:
163
+ if not isinstance(r, dict):
164
+ continue
165
+ rows.append({k: r[k] for k in ("url", "verdict", "misses", "fetch_method")
166
+ if r.get(k) is not None})
167
+ if rows:
168
+ out["verified"] = rows
169
+ return out or None
170
+
171
+
172
+ def _slim_verify_with(v: Any) -> dict[str, Any] | None:
173
+ """verify_with 段的 agent 精简版:核对引擎 + 域级重叠 + 官方簇条数。
174
+
175
+ why:核对簇的价值是「一眼可对的第二意见」,Agent 只需要引擎、耗时、
176
+ 重叠域与条数;逐条 title/snippet 与主查重复度高,剥掉(要看全簇走
177
+ --fields full)。
178
+ """
179
+ if not isinstance(v, dict):
180
+ return None
181
+ out = {k: v[k] for k in ("engine", "skipped", "elapsed_ms") if v.get(k) is not None}
182
+ if v.get("overlap") is not None:
183
+ out["overlap"] = v["overlap"]
184
+ n = len(v.get("results") or [])
185
+ if n:
186
+ out["result_count"] = n
187
+ return out or None
188
+
189
+
146
190
  def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
147
191
  """--fields agent:输出只留答案内容(P2-2,2026-09-13)。
148
192
 
@@ -184,11 +228,16 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
184
228
  # 几秒核验却只看到 verified_count 一个数(2026-10-22 实测)。
185
229
  # 值由下方 _slim_verify/_slim_reorder 压缩,不整块照搬。
186
230
  "verify", "evidence_reorder",
231
+ # 数值印证与核对配对(2026-11-01):同上「花了墙钟换来的」逻辑——
232
+ # 摘要数字与原文冲突、独立官方核对簇,都是 Agent 引用前的直接依据。
233
+ "numverify", "numeric_reorder", "verify_with",
187
234
  )
188
235
  out: dict[str, Any] = {k: payload[k] for k in keep_top
189
236
  if payload.get(k) is not None}
190
237
  for _key, _slim in (("verify", _slim_verify),
191
- ("evidence_reorder", _slim_reorder)):
238
+ ("evidence_reorder", _slim_reorder),
239
+ ("numverify", _slim_numverify),
240
+ ("verify_with", _slim_verify_with)):
192
241
  if payload.get(_key) is not None:
193
242
  _value = _slim(payload[_key])
194
243
  if _value is not None:
@@ -711,6 +760,15 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
711
760
  result["failures"] = failures
712
761
  except Exception as e:
713
762
  _log(f"失败清单跳过: {type(e).__name__}")
763
+ # 摘要装饰清洗(输出质量):剥 markdown 列表/标题标记、站导航链与重复
764
+ # 站名前缀,压空白。放在收口处,full/agent/人读三种出口共享同一份文本;
765
+ # 不改 schema、不截断,失败静默跳过。
766
+ try:
767
+ for _r in (result.get("results") or []):
768
+ if isinstance(_r, dict) and isinstance(_r.get("snippet"), str):
769
+ _r["snippet"] = clean_snippet(_r["snippet"])
770
+ except Exception as e:
771
+ _log(f"摘要清洗跳过: {type(e).__name__}")
714
772
  # 信任级别与边界清洗:所有入口(full/agent/MCP)共用同一个收口,
715
773
  # 避免 CLI/agent 档带 content_trust 却未剥离网页自带的 </untrusted-web-content>。
716
774
  try:
@@ -892,6 +892,11 @@ def finalize(req: _SearchRequest, run: _SearchRun, hooks: Any) -> dict[str, Any]
892
892
  "count": len(merged),
893
893
  "elapsed_ms": round(elapsed),
894
894
  "engines_used": list(raw_results.keys())[:8],
895
+ # 头部结果 URL(采纳回放地基):此前账本只有查询与计数,无任何
896
+ # 结果 URL,「哪条结果被上游采纳、坏例来自哪个链接」无法回放。
897
+ # 取 merged(此刻已重排、未做时间排序,与默认展示序一致);
898
+ # 截 5 条、每条 200 字符,上限与 query 的 60 字符同属账本瘦身纪律。
899
+ "top_urls": [(r.get("url") or "")[:200] for r in merged[:5] if r.get("url")],
895
900
  **usage_log_attribution(engine_latency, engine_outcomes=engine_outcomes),
896
901
  "errors": len(_collect_errors(raw_results, engine_outcomes)),
897
902
  "recovered": bool(recovery_info.get("recovered")) if recovery_info else False,
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ """snippet_clean.py — 交付前的摘要清洗(输出质量层,纯函数)。
3
+
4
+ ## 为什么需要
5
+
6
+ 搜索源返回的 snippet 经常是「页面开头的一段原文」,而不是编辑过的摘要:
7
+ anysearch 的条目以 `- #` 这类 markdown 列表/标题标记开头,站点导航
8
+ (首页/登录/注册/关于我们)直接粘在正文前面,站名还会重复一遍
9
+ (`技术栈技术栈Python asyncio…`)。这些字符对 Agent 没有信息增量,
10
+ 却挤占上下文、干扰标题与摘要的对齐。
11
+
12
+ 实测(2026-11-02,8 条日常查询 × 5 条结果):38 条 snippet 里 8 条以
13
+ markdown 标记开头(21%),4 条含站点导航词(11%)。
14
+
15
+ ## 边界
16
+
17
+ 只做**可逆的装饰性清洗**:剥开头标记/导航链/重复站名前缀、压空白。
18
+ 不改写正文、不截断、不做语义判断。清洗失败(空串/非字符串)原样返回,
19
+ 绝不因输出层装饰让一次搜索失败。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+
26
+ __all__ = ["clean_snippet", "NAV_WORDS"]
27
+
28
+ # 只有「站点框架」词进表;搜索/分享/评论这类既可能是导航也可能是正文的
29
+ # 词刻意不收——它们被误剥的代价高于收益。
30
+ NAV_WORDS: tuple[str, ...] = (
31
+ "首页", "登录", "注册", "菜单", "导航", "关于我们", "联系我们",
32
+ "版权所有", "下载APP", "APP下载", "扫码下载", "返回顶部", "网站地图",
33
+ )
34
+
35
+ _MD_LEAD = re.compile(r"^\s*(?:[-*+>#]+\s*)+")
36
+ _DUP_PREFIX = re.compile(r"^([\u4e00-\u9fff]{2,8})\1")
37
+ _NAV_LEAD = re.compile(
38
+ r"^(?:(?:" + "|".join(map(re.escape, NAV_WORDS)) + r")[\s·|/、,,。::\-]*)+",
39
+ re.IGNORECASE,
40
+ )
41
+ _NAV_TRAIL = re.compile(
42
+ r"[\s·|/、,,。::\-]*(?:(?:" + "|".join(map(re.escape, NAV_WORDS))
43
+ + r")[\s·|/、,,。::\-]*)+$",
44
+ re.IGNORECASE,
45
+ )
46
+
47
+
48
+ def clean_snippet(text: str) -> str:
49
+ """清洗一条摘要;非字符串或空串原样返回。"""
50
+ if not isinstance(text, str):
51
+ return text
52
+ s = text.strip()
53
+ if not s:
54
+ return s
55
+ s = _MD_LEAD.sub("", s)
56
+ s = _DUP_PREFIX.sub(r"\1", s)
57
+ s = _NAV_LEAD.sub("", s)
58
+ s = re.sub(r"\s+", " ", s).strip()
59
+ s = _NAV_TRAIL.sub("", s).strip()
60
+ return s
@@ -290,62 +290,146 @@ def _parse_nitter_html(html: str, n: int) -> list[dict]:
290
290
 
291
291
 
292
292
  def search(query: str, n: int = 5) -> list[dict]:
293
- """主搜索入口:FxTwitter → tw CLI → nitter。"""
293
+ """主搜索入口:FxTwitter → twitter/tw CLI → nitter。"""
294
294
  # 1) FxTwitter(主路径)
295
+ # 注意:search_fxtwitter 在异常时返回带 error 字段的占位(不是空列表),
296
+ # 那是给 MCP 的「失败可见」契约用的;但在这里它**不能阻断后续通道**——
297
+ # 否则一次网络抖动就让整条兜底链失效(2026-11-03 issue #36 实测)。
298
+ fx_errors: list[dict] = []
295
299
  try:
296
300
  results = search_fxtwitter(query, n=n, timeout=10)
297
- if results:
298
- return results
301
+ valid = [r for r in results
302
+ if isinstance(r, dict) and not r.get("error")]
303
+ if valid:
304
+ return valid
305
+ fx_errors = [r for r in results
306
+ if isinstance(r, dict) and r.get("error")]
299
307
  except Exception:
300
308
  pass
301
309
 
302
- # 2) twitter CLI
303
- try:
304
- result = subprocess.run(
305
- ["tw", "search", query, "--limit", str(n), "--json"],
306
- capture_output=True,
307
- text=True,
308
- encoding="utf-8", # Windows GBK locale 下 UTF-8 输出会解码崩
309
- errors="replace",
310
- timeout=10,
311
- )
312
- if result.returncode == 0 and result.stdout.strip():
313
- parsed = _parse_tw_json(result.stdout, n)
314
- if parsed:
315
- return parsed
316
- except (FileNotFoundError, subprocess.TimeoutExpired):
317
- pass
310
+ # 2) twitter-cli(`twitter`)/ `tw` CLI,两者参数形态不同,逐个试
311
+ for cmd in (
312
+ ["twitter", "search", query, "-n", str(n), "--json"],
313
+ ["tw", "search", query, "--limit", str(n), "--json"],
314
+ ):
315
+ try:
316
+ result = subprocess.run(
317
+ cmd,
318
+ capture_output=True,
319
+ text=True,
320
+ encoding="utf-8", # Windows GBK locale 下 UTF-8 输出会解码崩
321
+ errors="replace",
322
+ timeout=10,
323
+ )
324
+ if result.returncode == 0 and result.stdout.strip():
325
+ parsed = _parse_tw_json(result.stdout, n)
326
+ if parsed:
327
+ return parsed
328
+ except (FileNotFoundError, subprocess.TimeoutExpired):
329
+ continue
318
330
 
319
331
  # 3) nitter 保底
320
- return search_nitter(query, n)
332
+ nitter_res = search_nitter(query, n)
333
+ if nitter_res:
334
+ return nitter_res
335
+ # 全部通道不可用:把 FxTwitter 的 error 占位带回去,保持「失败可见」契约
336
+ return fx_errors
321
337
 
322
338
 
323
339
  def _parse_tw_json(raw: str, n: int) -> list[dict]:
324
- """解析 twitter CLI JSON 输出。"""
325
- results = []
326
- for line in raw.strip().split("\n"):
327
- try:
328
- tweet = json.loads(line)
329
- if not isinstance(tweet, dict):
340
+ """解析 twitter-cli / tw CLI 的 JSON 输出。
341
+
342
+ 三种形态都要认(不同版本/不同 CLI 的输出并不统一):
343
+
344
+ - JSONL:每行一个 tweet 对象(`tw` 的默认形态)
345
+ - 数组:`[{...}, {...}]`
346
+ - envelope:`{"ok": true, "data": [{...}]}`(`twitter` CLI 的形态)
347
+ - 单对象:`{...}`(单条结果时)
348
+
349
+ 错误字典(如 `{"error": "No tweets found for ..."}`)与非 tweet 对象
350
+ 一律跳过——issue #36 的根因之一就是它曾被当成有效条目产出。
351
+ """
352
+ results: list[dict] = []
353
+ stripped = raw.strip()
354
+ if not stripped:
355
+ return results
356
+
357
+ items: list[dict] = []
358
+ try:
359
+ payload = json.loads(stripped)
360
+ except (json.JSONDecodeError, ValueError):
361
+ payload = None
362
+ # JSONL 兜底:整体解析失败时逐行试
363
+ for line in stripped.split("\n"):
364
+ try:
365
+ obj = json.loads(line)
366
+ except (json.JSONDecodeError, ValueError):
330
367
  continue
331
- results.append({
332
- "title": (tweet.get("text", "") or tweet.get("full_text", ""))[:100],
333
- "url": tweet.get("url", f"https://twitter.com/i/status/{tweet.get('id', '')}"),
334
- "snippet": tweet.get("text", "") or tweet.get("full_text", ""),
335
- "source": "twitter",
336
- "score": max(1.0 - len(results) * 0.1, 0.1),
337
- "social_meta": {
338
- "platform": "twitter",
339
- "content_type": "tweet",
340
- "author": tweet.get("user", {}).get("screen_name", ""),
341
- "likes": tweet.get("favorite_count", 0),
342
- "retweets": tweet.get("retweet_count", 0),
343
- "replies": tweet.get("reply_count", 0),
344
- "provider": "tw_cli",
345
- },
346
- })
347
- except (json.JSONDecodeError, ValueError):
368
+ if isinstance(obj, dict):
369
+ items.append(obj)
370
+ elif isinstance(obj, list):
371
+ items.extend(x for x in obj if isinstance(x, dict))
372
+
373
+ if payload is not None:
374
+ if isinstance(payload, list):
375
+ items.extend(x for x in payload if isinstance(x, dict))
376
+ elif isinstance(payload, dict):
377
+ # 错误/空结果信封:ok 为假,或带 error 字段
378
+ if payload.get("ok") in (False, 0, "false", "False"):
379
+ return results
380
+ if payload.get("error"):
381
+ return results
382
+ data = payload.get("data")
383
+ if isinstance(data, list):
384
+ items.extend(x for x in data if isinstance(x, dict))
385
+ elif isinstance(data, dict):
386
+ items.append(data)
387
+ elif isinstance(payload, dict) and (
388
+ "text" in payload or "full_text" in payload or "id" in payload):
389
+ # 单条 tweet 对象
390
+ items.append(payload)
391
+
392
+ for tweet in items:
393
+ if not isinstance(tweet, dict):
394
+ continue
395
+ text = (tweet.get("text") or tweet.get("full_text") or "").strip()
396
+ tid = str(tweet.get("id") or "")
397
+ if not text and not tid:
348
398
  continue
399
+ author_obj = tweet.get("author") or tweet.get("user") or {}
400
+ if not isinstance(author_obj, dict):
401
+ author_obj = {}
402
+ handle = (author_obj.get("screenName") or author_obj.get("screen_name") or "")
403
+ metrics = tweet.get("metrics") or {}
404
+ if not isinstance(metrics, dict):
405
+ metrics = {}
406
+ likes = metrics.get("likes") if "likes" in metrics else tweet.get("favorite_count", 0)
407
+ retweets = (metrics.get("retweets") if "retweets" in metrics
408
+ else tweet.get("retweet_count", 0))
409
+ replies = metrics.get("replies") if "replies" in metrics else tweet.get("reply_count", 0)
410
+ views = metrics.get("views") if "views" in metrics else tweet.get("views")
411
+ url = tweet.get("url") or (f"https://x.com/{handle}/status/{tid}" if tid else "")
412
+ results.append({
413
+ "title": text[:100] + ("..." if len(text) > 100 else ""),
414
+ "url": url,
415
+ "snippet": text[:300],
416
+ "source": "twitter",
417
+ "published_at": tweet.get("createdAtISO") or tweet.get("createdAt") or None,
418
+ "score": max(1.0 - len(results) * 0.1, 0.1),
419
+ "social_meta": {
420
+ "platform": "twitter",
421
+ "content_type": "tweet",
422
+ "id": tid,
423
+ "author": handle,
424
+ "author_name": author_obj.get("name") or "",
425
+ "likes": likes or 0,
426
+ "retweets": retweets or 0,
427
+ "reposts": retweets or 0,
428
+ "replies": replies or 0,
429
+ "views": views,
430
+ "provider": "twitter_cli",
431
+ },
432
+ })
349
433
  if len(results) >= n:
350
434
  break
351
435
  return results
@@ -30,12 +30,22 @@ def search(query: str, n: int = 5) -> list[dict]:
30
30
  """主搜索入口"""
31
31
  try:
32
32
  result = subprocess.run(
33
- ["xhs", "search", query],
33
+ # --json 必须传:xhs-cli 的 argparse 接受该 flag 但**不传时只打印
34
+ # 人类可读文本**,_parse_xhs_output 的 json.loads 会失败并静默返回
35
+ # 空列表(2026-11-03 issue #36 实测)。
36
+ ["xhs", "search", "--json", query],
34
37
  capture_output=True, text=True, timeout=_subprocess_timeout(),
35
38
  encoding="utf-8", errors="replace", # Windows GBK locale 下 UTF-8 输出会解码崩
36
39
  )
37
40
  if result.returncode == 0 and result.stdout.strip():
38
41
  return _parse_xhs_output(result.stdout, n)
42
+ if result.returncode != 0:
43
+ # 未登录不是「平台 0 结果」:带可归因 error 浮上来,避免与「查了没有」
44
+ # 同形(同 zhihu_engine / 社交引擎统一范式)。
45
+ err_msg = (result.stdout or result.stderr or "").strip()
46
+ if "not_authenticated" in err_msg or "NoCookieError" in err_msg:
47
+ return [{"error": "xhs not_authenticated (run `xhs login --qrcode`)",
48
+ "source": "xiaohongshu"}]
39
49
  except (FileNotFoundError, subprocess.TimeoutExpired) as e:
40
50
  # CLI 未安装/超时不是「平台 0 结果」:带 error 浮上来,与社交引擎
41
51
  # 统一范式一致(zhihu_engine 范式,mcp_handlers 的 err=None 设计
@@ -37,6 +37,14 @@ DOMAIN_PROFILES_PATH = BACKENDS_DIR / "domain_profiles.json"
37
37
 
38
38
  _TOKEN_PATTERN = re.compile(r"[一-鿿\u3040-\u30ff\uac00-\ud7af]|[a-zA-Z0-9]+")
39
39
 
40
+ # 通用搜索泛域(与 route_combo._GENERAL_ENGINES 的 catch-all 部分对齐,但不含
41
+ # arxiv/wikipedia 这类有明确用途的宽域源):这些引擎的 domain_profiles 文档
42
+ # 覆盖大量通用词,概念向量对它们几乎恒为高值,会挤掉垂直引擎。
43
+ _CATCH_ALL_CONCEPT = frozenset({
44
+ "anysearch", "byted", "bocha", "octen", "local_search", "zhihu",
45
+ "wechat_sogou", "uapi", "tavily", "brave", "bocha_ai", "seltz",
46
+ })
47
+
40
48
 
41
49
  def tokenize(text: str) -> list[str]:
42
50
  """简单分词:中文/日文/韩文单字 + 英文单词,统一小写。
@@ -262,6 +270,23 @@ class SemanticRouter:
262
270
  return [("anysearch", 0.0, "无领域文档,回退 AnySearch")]
263
271
 
264
272
  query_vec = self.vectorizer.transform(query)
273
+ # P2: 静态概念语义向量 (Model2Vec 思想,零依赖快速查表)
274
+ concept_vec = None
275
+ cl = None
276
+ try:
277
+ from concept_lookup import (
278
+ get_concept_lookup,
279
+ concept_router_enabled,
280
+ strip_context_dims,
281
+ )
282
+ if concept_router_enabled():
283
+ cl = get_concept_lookup()
284
+ if cl.is_available:
285
+ # 地名维清零:避免含地名的查询被航空/测绘类引擎凭地名重叠拉高
286
+ concept_vec = strip_context_dims(cl.text_vector(query))
287
+ except Exception:
288
+ concept_vec = None
289
+
265
290
  scores = []
266
291
  quota_state = _load_quota_state() if quota_aware else {}
267
292
  cost_profiles = _load_cost_profiles()
@@ -269,7 +294,32 @@ class SemanticRouter:
269
294
 
270
295
  for name in self.engine_names:
271
296
  sim = cosine_similarity(query_vec, self.engine_vectors[name])
297
+ eff_sim = sim
298
+ c_sim = 0.0
299
+ if concept_vec is not None and cl is not None:
300
+ eng_cvec = strip_context_dims(cl.get_engine_vector(name))
301
+ if eng_cvec is not None:
302
+ c_sim = cl.vector_cosine(concept_vec, eng_cvec)
303
+ catch_all = name in _CATCH_ALL_CONCEPT
304
+ if c_sim >= 0.75:
305
+ if catch_all:
306
+ # 泛域引擎词表覆盖面广,概念相似度易虚高,只作弱辅助;
307
+ # 无词面交集时不允许概念单独把它拉上第一
308
+ eff_sim = (max(sim, 0.90 * sim + 0.10 * c_sim)
309
+ if sim > 0 else sim)
310
+ elif sim > 0:
311
+ eff_sim = max(sim, 0.70 * sim + 0.30 * c_sim)
312
+ else:
313
+ eff_sim = c_sim * 0.50
314
+ elif sim > 0 and c_sim > 0.40:
315
+ if catch_all:
316
+ eff_sim = max(sim, 0.95 * sim + 0.05 * c_sim)
317
+ else:
318
+ eff_sim = max(sim, 0.80 * sim + 0.20 * c_sim)
319
+
272
320
  parts = []
321
+ if c_sim >= 0.75 and sim <= 0:
322
+ parts.append(f"concept={c_sim:.2f}")
273
323
 
274
324
  # boost 加权
275
325
  boost = 1.0
@@ -290,7 +340,7 @@ class SemanticRouter:
290
340
  if hit_combos:
291
341
  parts.append(f"combo:{','.join(hit_combos)}")
292
342
 
293
- final_score = sim * boost
343
+ final_score = eff_sim * boost
294
344
 
295
345
  # 成本感知(profiles 已缓存,不再每引擎读盘)
296
346
  cf = _cost_factor(name, cost_profiles)
@@ -308,7 +358,7 @@ class SemanticRouter:
308
358
  final_score *= 0.5 + qr
309
359
  parts.append(f"配额偏低({qr:.0%})")
310
360
 
311
- reason = f"sim={sim:.3f}" + (f", {', '.join(parts)}" if parts else "")
361
+ reason = f"sim={eff_sim:.3f}" + (f", {', '.join(parts)}" if parts else "")
312
362
  scores.append((name, round(final_score, 4), reason))
313
363
 
314
364
  scores.sort(key=lambda x: -x[1])
package/scripts/train.py CHANGED
@@ -131,6 +131,16 @@ def _parse_travel_date(text: str) -> tuple[date | None, str]:
131
131
  return None, text
132
132
 
133
133
 
134
+ # 口语填充词(2026-10-31 评测 fz07 实测):「杭州到黄山坐高铁最快需要多久?」
135
+ # 拆分后到站段是「黄山坐高铁最快需要多久」,站名匹配必败、整条静默返回空。
136
+ # 只剥多字交通/时长词,不做单字剥离——站名剥字教训(「张家口」→「家口」)
137
+ # 在此同样适用;剥完仍以站名表为准解析,表里没有的站照旧失败。
138
+ _QUERY_FILLER_RE = re.compile(
139
+ r"坐高铁|坐火车|高铁|火车|列车|动车|最快需要多久|需要多久|最快多久|多久"
140
+ r"|多长时间|几个小时|几小时|怎么走|时刻表|车次表"
141
+ )
142
+
143
+
134
144
  def _parse_query(q: str) -> dict | None:
135
145
  """从自然语言查询词解析 出发站/到达站/日期/车次类型。
136
146
 
@@ -165,6 +175,11 @@ def _parse_query(q: str) -> dict | None:
165
175
  # 「高碑店」→「碑店」、「次渠」→「渠」。站名后缀(北京站/上海市)由
166
176
  # _resolve_station 统一剥离(它已有 `[市站]$`),这里不必也不该再剥一遍。
167
177
  parts = [p.strip(" \t,。!?、") for p in parts if p.strip()]
178
+ parts = [_QUERY_FILLER_RE.sub(" ", p).strip(" \t,。!?、") for p in parts]
179
+ # 悬挂字:填充词被车次类型/本剥离先后摘掉后,「坐/的」可能残在段尾
180
+ # (实测「黄山坐」「黄山北的」);行尾锚只动段尾,不碰站名内部。
181
+ parts = [re.sub(r"[坐的]\s*$", "", p).strip() for p in parts]
182
+ parts = [p for p in parts if p]
168
183
  if len(parts) < 2:
169
184
  return None
170
185
  from_name, to_name = parts[0], parts[1]