argo-search 2.13.0 → 2.14.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 (89) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.en.md +16 -4
  3. package/README.es.md +16 -4
  4. package/README.ja.md +16 -4
  5. package/README.ko.md +16 -4
  6. package/README.md +16 -4
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/backends/domain_profiles.json +66 -6
  10. package/backends/engine_registry.yaml +154 -15
  11. package/backends/env_passthrough.txt +2 -0
  12. package/backends/quota_profiles.json +111 -11
  13. package/bin/argo +3 -0
  14. package/config.yaml +27 -1
  15. package/docs/CHANGELOG.md +23 -0
  16. package/docs/COMMIT_STANDARD.md +98 -0
  17. package/docs/ENGINE_CATALOG.md +94 -79
  18. package/docs/RELEASE_NOTES_v2.14.0.md +77 -0
  19. package/engines/specs/clinicaltrials.yaml +8 -0
  20. package/engines/specs/cnii.yaml +5 -0
  21. package/engines/specs/coingecko.yaml +10 -2
  22. package/engines/specs/dbpedia.yaml +32 -0
  23. package/engines/specs/fourget.yaml +23 -0
  24. package/engines/specs/grep_app.yaml +19 -0
  25. package/engines/specs/hackernews.yaml +1 -0
  26. package/engines/specs/hf_papers.yaml +26 -0
  27. package/engines/specs/kaggle.yaml +44 -0
  28. package/engines/specs/local_baidu.yaml +5 -0
  29. package/engines/specs/local_seek.yaml +34 -0
  30. package/engines/specs/local_yandex.yaml +37 -0
  31. package/engines/specs/mojeek.yaml +31 -0
  32. package/engines/specs/mwmbl.yaml +39 -0
  33. package/engines/specs/openaire.yaml +34 -0
  34. package/engines/specs/repology.yaml +18 -0
  35. package/package.json +13 -10
  36. package/packages/dsh-plugin/dsh/client.js +1 -0
  37. package/packages/dsh-plugin/dsh/native-tools.mjs +24 -3
  38. package/packages/dsh-plugin/dsh/runner.js +35 -1
  39. package/packages/dsh-plugin/dsh/specs.js +3 -1
  40. package/packages/dsh-plugin/dsh/wide-research.js +4 -2
  41. package/packages/dsh-plugin/package.json +1 -1
  42. package/packages/dsh-plugin/test/client.test.js +6 -0
  43. package/packages/dsh-plugin/test/config.test.js +5 -1
  44. package/packages/dsh-plugin/test/index.test.js +3 -1
  45. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  46. package/scripts/badcase_causes.py +81 -0
  47. package/scripts/badcase_ledger.py +287 -14
  48. package/scripts/cache.py +3 -3
  49. package/scripts/check_commit_report.py +168 -0
  50. package/scripts/engine_admission.py +9 -5
  51. package/scripts/engine_families.py +13 -2
  52. package/scripts/engine_policy.py +1 -1
  53. package/scripts/engine_states.py +393 -8
  54. package/scripts/engine_status.py +31 -0
  55. package/scripts/engine_validate.py +47 -39
  56. package/scripts/engines.py +6 -0
  57. package/scripts/engines_base.py +26 -80
  58. package/scripts/engines_builders.py +5 -0
  59. package/scripts/engines_builders_batch12.py +168 -0
  60. package/scripts/engines_builders_batch16.py +186 -0
  61. package/scripts/engines_parsers.py +399 -0
  62. package/scripts/fetch_browser.py +4 -2
  63. package/scripts/fetch_jsrun.py +2 -1
  64. package/scripts/fetch_v3.py +22 -22
  65. package/scripts/gen_native_tools.py +44 -17
  66. package/scripts/local_intent.py +139 -0
  67. package/scripts/local_seek.py +223 -91
  68. package/scripts/local_seek_adapter.py +87 -0
  69. package/scripts/mcp_transport.py +1 -1
  70. package/scripts/pre-commit +44 -1
  71. package/scripts/recovery.py +14 -5
  72. package/scripts/recovery_l0.py +5 -3
  73. package/scripts/research.py +1 -1
  74. package/scripts/research_gates.py +3 -3
  75. package/scripts/route_lang.py +6 -1
  76. package/scripts/route_policy.py +21 -14
  77. package/scripts/search.py +33 -25
  78. package/scripts/search_cli.py +10 -1
  79. package/scripts/search_output.py +83 -16
  80. package/scripts/source_audit.py +331 -0
  81. package/scripts/sync_backends.py +31 -1
  82. package/scripts/wechat_article.py +5 -3
  83. package/scripts/wide_research.py +4 -1
  84. package/scripts/x_article_fetch.py +2 -1
  85. package/sub-skills/local-search/parsers.py +6 -1
  86. package/sub-skills/local-seek/scripts/seek.py +390 -24
  87. package/sub-skills/local-seek/scripts/seek_fts.py +20 -9
  88. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  89. package/engines/specs/cinii.yaml +0 -44
@@ -38,7 +38,16 @@ _VERTICAL_NEW_SOURCE: dict[str, tuple[str, ...]] = {
38
38
  # local_pubmed 是**修复**(旧实现静默 400 且解析不出字符串数组,实测 0 条,
39
39
  # 详见 engines_builders_batch9._build_pubmed_engine 文档串)。两者声明在
40
40
  # 既有源之后,由本表加槽,不挤掉 arxiv/openreview 等既有位次。
41
- "academic": ("local_pubmed", "core", "cinii"), # 生物医学全文 + 机构仓储开放获取 + 日本学术 + 数学索引
41
+ #
42
+ # 2026-11-10:core 移出本表。四个加槽源(hf_papers@5 / local_pubmed@6 /
43
+ # cinii@7 / core@8)的最深位次 8 需要 extra=5,超出 auto/balanced 的
44
+ # cap=4(base 3 + 4 = 7)——四源不可兼得。取舍依据是**能力独特性**:
45
+ # · cinii 是本域唯一的亚洲学术源(日本总库),其余源全是欧美;
46
+ # · core 与 local_pubmed 同属「开放获取全文」层,能力重叠;
47
+ # · crossref/europepmc/dblp 本就与 openalex 高度重叠,靠 deep 触达。
48
+ # 故保 cinii、舍 core:core 退回普通 combo 成员,deep/research 与
49
+ # 恢复链可达(它的位次 8 在 deep 档不截断路径上)。
50
+ "academic": ("local_pubmed", "cnii", "hf_papers"), # 生物医学全文 + 日本学术 + HF 论文社交信号
42
51
  # 2026-09-21:academic 补两个国别/学科专门源。位次 5/6 是照本域上方注释
43
52
  # 的既有实践选的(deepest=6 → 加槽后预算覆盖到 6,前四位次一律不动)。
44
53
  # cinii 声明 langs=ja,靠 engines_demote_for_lang 的语言专用源降级,
@@ -50,6 +59,11 @@ _VERTICAL_NEW_SOURCE: dict[str, tuple[str, ...]] = {
50
59
  # redskill 只有小红书站内口径)都给不出。声明在既有源之后,由本表加槽,
51
60
  # 不挤掉 skillsmp/clawhub/redskill 的位次。
52
61
  "skill_search": ("explainx", "skills_sh"),
62
+ # 2026-11-10:三个新源。mwmbl 补独立搜索引擎族(非大厂代理);
63
+ # kaggle 补社区数据集(DataCite/Zenodo 是机构仓储,Kaggle 是社区);
64
+ # hf_papers 补论文社交信号(upvotes/作者,arXiv/OpenAlex 无)。
65
+ "semantic_discovery": ("mwmbl",),
66
+ "dataset_search": ("kaggle",),
53
67
  }
54
68
 
55
69
 
@@ -99,19 +113,12 @@ def _new_source_budget_extra(
99
113
  if not domain or not engines_combo:
100
114
  return 0
101
115
 
102
- # 学术域固定加成:该域有 11+ 个引擎(arxiv/openreview/biorxiv/openalex/
103
- # crossref/europepmc/dblp/semantic_scholar/local_pubmed/core/cinii),
104
- # auto 模式 budget=3 只够前 3 个,后 8 个永远轮不到。学术搜索需要多源
105
- # 交叉验证才严谨,固定 +3 让 budget 达到 6,覆盖到 semantic_scholar。
106
- if domain.get("name") == "academic":
107
- try:
108
- from engine_policy import combo_budget
109
- base = combo_budget(mode=mode, depth=depth, context=context)
110
- if base is not None:
111
- return min(3, max(0, 6 - base))
112
- except Exception:
113
- pass
114
-
116
+ # 2026-11-10 撤掉 academic 域的固定 +3 加成分支:固定值写死「budget 达到
117
+ # 6」,而 combo 随新源接入增长(hf_papers 插入第 5 位,local_pubmed/core/
118
+ # cinii 顺延到 6/7/8)。固定分支**提前 return**,跳过下方按最深位次算额
119
+ # 度的通用逻辑,三者叠加后 hf_papers 之后的源全被截断。通用逻辑本就覆盖
120
+ # 这个场景(deepest=6 → extra=3),固定分支是它的劣化版:既不能自适应,
121
+ # 又阻断自适应。cinii(位次 8)超出 cap=4 的射程,由休眠台账登记。
115
122
  pending = [
116
123
  e for e in _VERTICAL_NEW_SOURCE.get(domain.get("name"), ())
117
124
  if e in engines_combo and e in enabled
package/scripts/search.py CHANGED
@@ -217,7 +217,11 @@ from engine_dispatch import ( # noqa: E402
217
217
  classify_engine_outcome as _classify_engine_outcome,
218
218
  run_dispatch,
219
219
  )
220
- from local_seek import _run_local_seek, _LOCAL_SEEK_TIMEOUT_S # noqa: E402
220
+ from local_seek import ( # noqa: E402
221
+ _run_local_seek,
222
+ _LOCAL_SEEK_TIMEOUT_S,
223
+ local_seek_accounting,
224
+ )
221
225
 
222
226
 
223
227
  # 缓存命中路径的 include-local 宽限窗(秒):主结果命中缓存时墙钟已极小
@@ -778,7 +782,15 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
778
782
 
779
783
  # L1 并行化:本地搜索与主搜索并行提交(仅显式开启时在宽根下提示)。
780
784
  _local_seek_explicit = include_local is not None
781
- include_local = _resolve_include_local(include_local, mode, query)
785
+ # 「用户没有显式关掉」= 自动路径或显式 True;显式 False 不报跳过
786
+ # (用户说了不要,不必再解释)。None 是自动路径,必须算「请求过」。
787
+ _include_local_requested = include_local is not False
788
+ include_local = _resolve_include_local(include_local, mode, query,
789
+ decision.get("domain"))
790
+ # 自动路径被判据跳过(公域查询 + 无本地信号):这是「没跑」而非「跑了没
791
+ # 命中」,必须留痕,否则与显式 --no-local 无法区分(前者是系统优化,
792
+ # 后者是用户选择)。显式 False 不写——用户已经说了不要,不必再报。
793
+ _local_seek_intent_skipped = (_include_local_requested and not include_local)
782
794
  _local_seek_future = None
783
795
  if include_local:
784
796
  _local_seek_future = _get_local_seek_executor().submit(
@@ -944,34 +956,30 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
944
956
  result.setdefault("errors", []).append(
945
957
  f"{_name}: registry 查无此引擎(拼写错误,或该源未随本版发布)")
946
958
 
947
- return result
948
-
949
-
950
- # ── 信源标准化 ─────────────────────────────────────────────────────────────────
951
-
952
- # --fields agent:每条 result 保留的答案字段(P2-2)。
953
- # 媒体专属字段按需登记——非该媒体的结果此键为 None,_strip_for_agent 会自动
954
- # 丢弃,其他查询不付代价:image_* 来自图源,episode_count/duration_minutes
955
- # 来自 itunes 的播客结果。
956
-
957
-
958
-
959
-
960
-
961
-
962
-
963
-
964
-
965
-
966
-
967
-
968
-
959
+ # 本机检索账(耗时/命中数/跳过):口径单点在 local_seek_accounting()。
960
+ # 意图跳过(公域查询)与用户显式 --no-local 都要留痕,但语义不同:
961
+ # 前者是系统判据,后者是用户选择——分开标记,日志里可归因。
962
+ try:
963
+ _ls_acct = ({"local_seek_skipped": True,
964
+ "skip_reason": "public_domain_intent"}
965
+ if _local_seek_intent_skipped else local_seek_accounting())
966
+ result.update(_ls_acct)
967
+ from usage_log import emit as _emit_usage_log
968
+ from search_attribution import is_synthetic_run as _is_syn
969
+ if include_local or _local_seek_intent_skipped:
970
+ if not _is_syn(result.get("engines_used")):
971
+ _ls_acct.update(query=(original_query or "")[:60],
972
+ elapsed_ms=result.get("elapsed_ms"),
973
+ count=result.get("count"))
974
+ _emit_usage_log("local_seek", _ls_acct)
975
+ except Exception:
976
+ pass
969
977
 
978
+ return result
970
979
 
971
980
 
972
981
  # ── 输出格式化 ─────────────────────────────────────────────────────────────────
973
982
 
974
-
975
983
  if __name__ == "__main__":
976
984
  # 把本模块(此刻身份是 __main__)的 import 时点交给 search_cli。
977
985
  #
@@ -421,6 +421,7 @@ def main():
421
421
  try:
422
422
  from engine_status import (list_engines_detail,
423
423
  compact_engine_row,
424
+ compact_engine_table,
424
425
  format_engines_table)
425
426
  rows = list_engines_detail(routable_only=args.routable_only,
426
427
  engines=_wanted)
@@ -452,7 +453,15 @@ def main():
452
453
  print(f"[list-engines] 未收录的引擎: {', '.join(_missing)}",
453
454
  file=sys.stderr)
454
455
  if args.json_output:
455
- print(dumps(rows))
456
+ # --all 的 JSON 走列式投影(2026-11-10):逐条对象在 301 个
457
+ # 引擎上重复 15 个键名,键名本身就 70 KB,超过 64 KB 上限。
458
+ # 列式把键名降到 1 份,实测 67.7 KB → 25.8 KB。
459
+ # 单引擎诊断(--engine <名>)仍给逐条全量对象——那一档
460
+ # 只有 1 条,键名成本可忽略,且需要嵌套的 runtime/admission。
461
+ if not _wanted:
462
+ print(dumps(compact_engine_table(rows)))
463
+ else:
464
+ print(dumps(rows))
456
465
  else:
457
466
  print(format_engines_table(rows))
458
467
  except Exception as e:
@@ -62,6 +62,8 @@ def _warn(message: str) -> None:
62
62
  _AGENT_RESULT_FIELDS = (
63
63
  "title", "url", "snippet", "source", "score", "ref",
64
64
  "published_at", "fetch_suggested", "full_text_url",
65
+ # 本地命中标记:明确区分本地文件与联网结果,供 Agent 分面过滤
66
+ "is_local",
65
67
  # 离散权威等级(0-4,≥3 极权威):Agent 的廉价可信闸门——连续 authority
66
68
  # 分不知道该在哪切,等级才能直接当门用(DeepSeek Search 同款语义)。
67
69
  # 整数字段约 6 字节,剥掉它等于把「先信谁」重新推回给调用方猜。
@@ -227,6 +229,8 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
227
229
  # 信任级别:网页文本一律是不可信外部数据,随答案一起到达,
228
230
  # 避免调用方把摘要里的指令当任务执行(输出层声明,非提示词)。
229
231
  "content_trust",
232
+ # 本地与公网分面契约(方案三):通道隔离,避免本地命中与联网结果在同一列表里混淆
233
+ "local_results", "web_results", "local_seek_skipped", "local_seek_skip_reason", "facets",
230
234
  # 核验产出:verify/evidence_reorder 是**花了墙钟换来的**,且是
231
235
  # 「该不该引用这批结果」的直接依据。此前被整块剥掉,调用方付了
232
236
  # 几秒核验却只看到 verified_count 一个数(2026-10-22 实测)。
@@ -256,6 +260,18 @@ def _strip_for_agent(payload: dict[str, Any]) -> dict[str, Any]:
256
260
  slim_results.append(slim)
257
261
  out["results"] = slim_results
258
262
  out["count"] = len(slim_results)
263
+
264
+ # 分面通道:对 local_results 与 web_results 按同一字段白名单瘦身
265
+ if "local_results" in payload:
266
+ out["local_results"] = [
267
+ {k: r[k] for k in _AGENT_RESULT_FIELDS if r.get(k) is not None}
268
+ for r in (payload.get("local_results") or []) if isinstance(r, dict)
269
+ ]
270
+ if "web_results" in payload:
271
+ out["web_results"] = [
272
+ {k: r[k] for k in _AGENT_RESULT_FIELDS if r.get(k) is not None}
273
+ for r in (payload.get("web_results") or []) if isinstance(r, dict)
274
+ ]
259
275
  return out
260
276
 
261
277
 
@@ -424,7 +440,7 @@ def format_text_output(results: dict[str, Any]) -> str:
424
440
  for err in results.get("errors", [])[:3]:
425
441
  lines.append(f" [ERROR] {err}")
426
442
 
427
- # 正文区:编号 + 标题 + 摘要(链接沉底,避免噪声)
443
+ # 正文区:分桶呈现【本地搜索】与【联网搜索】,避免来源混淆
428
444
  sources = results.get("sources")
429
445
  if not isinstance(sources, list) or not sources:
430
446
  sources = build_sources(results.get("results") or [])
@@ -432,15 +448,19 @@ def format_text_output(results: dict[str, Any]) -> str:
432
448
  # 用 URL 保持一致 ref
433
449
  url_to_ref = {s.get("url"): s.get("ref") for s in sources if isinstance(s, dict)}
434
450
  body_items = [r for r in (results.get("results") or []) if isinstance(r, dict)]
435
- for r in body_items:
451
+
452
+ def _is_local_item(it: dict[str, Any]) -> bool:
453
+ return bool(it.get("is_local") or it.get("source") == "local_files"
454
+ or str(it.get("url", "")).startswith("file://")
455
+ or str(it.get("source", "")).startswith("local_"))
456
+
457
+ local_items = [r for r in body_items if _is_local_item(r)]
458
+ web_items = [r for r in body_items if not _is_local_item(r)]
459
+
460
+ def _render_item(r: dict[str, Any], is_local_sec: bool = False) -> None:
436
461
  url = (r.get("url") or "").strip()
437
462
  ref = url_to_ref.get(url)
438
463
  if ref is None:
439
- # 未进 sources 时临时编号。分两种:有 URL 但没被收进 sources
440
- # (编号未知,用 ?);以及**本就没有 URL** 的条目——天气/行情/
441
- # 宏观这类结构化快照走的就是这条。此前两种情况共用一个分支,
442
- # 且分支条件是 `and url`,于是无 URL 的条目 ref 保持 None,
443
- # 正文里直接打成 `[None]`(2026-09-19 实测「北京天气」复现)。
444
464
  ref = "?" if url else "—"
445
465
  score = r.get("score", 0)
446
466
  title = (r.get("title") or "?")[:80]
@@ -451,21 +471,33 @@ def format_text_output(results: dict[str, Any]) -> str:
451
471
  lines.append(f" {snippet[:140]}")
452
472
  elif score:
453
473
  lines.append(f" (score={score_s})")
474
+ if is_local_sec and url.startswith("file://"):
475
+ lines.append(f" {url}")
454
476
 
455
- # 底部相关信源(传统搜索引擎形态)
456
- # sources 只保留 ref/url/engine(A2 引用式),title 从 results 回查
457
- if sources:
477
+ if local_items:
478
+ lines.append("")
479
+ lines.append(f"【本地搜索】({len(local_items)} 项命中)")
480
+ for r in local_items:
481
+ _render_item(r, is_local_sec=True)
482
+
483
+ if web_items:
484
+ lines.append("")
485
+ lines.append(f"【联网搜索】({len(web_items)} 项命中)")
486
+ for r in web_items:
487
+ _render_item(r, is_local_sec=False)
488
+
489
+ # 底部相关信源(仅呈现联网 URL)
490
+ web_sources = [s for s in sources if isinstance(s, dict)
491
+ and not str(s.get("url", "")).startswith("file://")]
492
+ if web_sources:
458
493
  lines.append("")
459
- lines.append("── 相关信源 ──")
494
+ lines.append("── 联网信源 ──")
460
495
  _results_list = results.get("results") or []
461
- for s in sources:
462
- if not isinstance(s, dict):
463
- continue
496
+ for s in web_sources:
464
497
  ref = s.get("ref", "?")
465
498
  eng = s.get("engine") or ""
466
499
  url = s.get("url") or ""
467
500
  eng_s = f" · {eng}" if eng else ""
468
- # 通过 ref 回查 results 获取 title(A2:sources 不再重复 title)
469
501
  _title = ""
470
502
  if isinstance(ref, int) and 1 <= ref <= len(_results_list):
471
503
  _title = (_results_list[ref - 1].get("title") or "")[:60]
@@ -711,12 +743,33 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
711
743
  #(宽根守卫 + 3s 超时兜底),--include-local / MCP include_local 显式开,
712
744
  # --no-local / include_local=false 关。按 URL 去重后并入,防止与既有
713
745
  # 结果(或未来评分变化)产生双份条目。
746
+ # 内容形态约束优先于双轨并发:--video / --min-duration 是用户对「结果形态」
747
+ # 的硬要求,本机文件(.md/.py/.txt…)永远不满足。此前不判形态直接并入,
748
+ # 实测 --video 的 3 条视频会被 3 条本机 markdown 挤成 6 条混合结果。
749
+ # 判据与 search_pipeline 的视频过滤同源(decision 的 video_only/min/max_duration)。
750
+ _video_scope = bool((decision or {}).get("video_only")) \
751
+ or (decision or {}).get("min_duration") is not None \
752
+ or (decision or {}).get("max_duration") is not None
753
+ if include_local and _video_scope:
754
+ result["local_seek_skipped"] = True
755
+ result["local_seek_skip_reason"] = "content_shape_video"
756
+ include_local = False
757
+
714
758
  if include_local:
715
759
  try:
716
760
  local_hits = _run_local_seek(query, n)
717
761
  except Exception as e:
718
762
  local_hits = []
719
763
  _log(f"[include-local] {type(e).__name__}: {e}")
764
+ # 本地轨意图预判跳过了(公域答案型查询 + 无本地信号):显式标记,
765
+ # 让调用方看到「本地轨没跑」而不是误以为「本地没有匹配」。
766
+ # 与 local_seek_skipped 的另两个来源(宽根守卫 / seek.py 缺失)同义。
767
+ try:
768
+ from local_seek import local_seek_last_skipped
769
+ if local_seek_last_skipped():
770
+ result["local_seek_skipped"] = True
771
+ except Exception:
772
+ pass
720
773
  if local_hits:
721
774
  _seen_urls = {r.get("url") for r in (result.get("results") or [])
722
775
  if isinstance(r, dict)}
@@ -724,8 +777,22 @@ def shape_response(ctx: _ShapeContext, result: dict[str, Any]) -> dict[str, Any]
724
777
  if isinstance(h, dict) and h.get("url") not in _seen_urls]
725
778
  if _fresh_local:
726
779
  result.setdefault("results", []).extend(_fresh_local)
727
- result["local_results"] = _fresh_local
728
780
  result["include_local"] = True
781
+
782
+ # ── 来源分桶:构建独立的 local_results 与 web_results,杜绝来源混淆 ──────────
783
+ _all_res = [r for r in (result.get("results") or []) if isinstance(r, dict)]
784
+ _loc_b = [r for r in _all_res if r.get("is_local") or r.get("source") == "local_files"
785
+ or str(r.get("url", "")).startswith("file://") or str(r.get("source", "")).startswith("local_")]
786
+ _web_b = [r for r in _all_res if r not in _loc_b]
787
+ for _lr in _loc_b:
788
+ _lr["is_local"] = True
789
+ result["local_results"] = _loc_b
790
+ result["web_results"] = _web_b
791
+ result["facets"] = {
792
+ "web_count": len(_web_b),
793
+ "local_count": len(_loc_b),
794
+ "total_count": len(_all_res),
795
+ }
729
796
  # ── 收口:重算一切「由 results 派生」的字段 ────────────────────────────────
730
797
  #
731
798
  # why:本函数**后置**改 results 的地方不止一处(域过滤裁剪、本地命中并入),
@@ -0,0 +1,331 @@
1
+ #!/usr/bin/env python3
2
+ """source_audit.py — 源健康度审计(`argo doctor` 的实现)。
3
+
4
+ ## 为什么需要
5
+
6
+ 300 个源里,真正进自动路由的只有 ~250 个,其中 15 个已停用、30 个显式专用。
7
+ 接入源时只有「准入」,没有「退出」——低价值源只增不减,每个都要维护
8
+ spec、派生件、文档、测试。
9
+
10
+ 本模块用**真实使用数据**(usage_log)给出去留建议,而不是靠猜。
11
+
12
+ ## 判据(第一性原理:价值 = 命中率 × 结果质量 / 成本)
13
+
14
+ - `route_hits`:过去 N 天被路由命中的次数
15
+ - `result_rate`:命中后返回非空结果的比例
16
+ - `value_score`:route_hits × result_rate(命中率 × 交付率)
17
+ - `cost`:总调用成本(按 spec.cost_per_call 累加)
18
+
19
+ 去留规则:
20
+ - 90 天 route_hits == 0 且非显式专用 → 建议停用(demote)
21
+ - 90 天 value_score < 5 且非显式专用 → 建议降级为 explicit_only(review)
22
+ - 30 天 result_rate < 20% 且 route_hits > 0 → 建议隔离(quarantine)
23
+ - 需密钥且本机未配置 → 提示(info)
24
+
25
+ ## 输出
26
+
27
+ `argo doctor` 输出三类:建议动作(demote/review/quarantine)、提示(info)、
28
+ 健康摘要。`--fix` 自动执行 demote(停用)与 quarantine(隔离),
29
+ review 只提示不改(降级需要人工判断是否还有垂直价值)。
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import os
36
+ import sys
37
+ from collections import defaultdict
38
+ from datetime import datetime, timedelta
39
+ from pathlib import Path
40
+ from typing import Any
41
+
42
+
43
+ def _usage_dir() -> Path:
44
+ """使用日志目录(ARGO_USAGE_LOG_DIR 可覆盖)。"""
45
+ override = os.environ.get("ARGO_USAGE_LOG_DIR")
46
+ if override:
47
+ return Path(override)
48
+ try:
49
+ import usage_log
50
+ return usage_log.usage_log_dir()
51
+ except Exception:
52
+ return Path.home() / ".cache" / "unified-search" / "usage_log"
53
+
54
+
55
+ def _load_query_log(days: int) -> list[dict]:
56
+ """读最近 N 天的 query 流日志。"""
57
+ d = _usage_dir()
58
+ path = d / "query.jsonl"
59
+ if not path.exists():
60
+ return []
61
+ cutoff = datetime.now().timestamp() - days * 86400
62
+ rows = []
63
+ for line in path.read_text(encoding="utf-8").splitlines():
64
+ line = line.strip()
65
+ if not line:
66
+ continue
67
+ try:
68
+ r = json.loads(line)
69
+ except json.JSONDecodeError:
70
+ continue
71
+ ts = r.get("ts", "")
72
+ try:
73
+ dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
74
+ if dt.timestamp() < cutoff:
75
+ continue
76
+ except Exception:
77
+ pass
78
+ rows.append(r)
79
+ return rows
80
+
81
+
82
+ def _load_route_log(days: int) -> list[dict]:
83
+ """读最近 N 天的 route 流日志。"""
84
+ d = _usage_dir()
85
+ path = d / "route.jsonl"
86
+ if not path.exists():
87
+ return []
88
+ cutoff = datetime.now().timestamp() - days * 86400
89
+ rows = []
90
+ for line in path.read_text(encoding="utf-8").splitlines():
91
+ line = line.strip()
92
+ if not line:
93
+ continue
94
+ try:
95
+ r = json.loads(line)
96
+ except json.JSONDecodeError:
97
+ continue
98
+ ts = r.get("ts", "")
99
+ try:
100
+ dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
101
+ if dt.timestamp() < cutoff:
102
+ continue
103
+ except Exception:
104
+ pass
105
+ rows.append(r)
106
+ return rows
107
+
108
+
109
+ def _engine_usage(days: int = 90) -> dict[str, dict[str, Any]]:
110
+ """统计每个引擎的使用情况。"""
111
+ queries = _load_query_log(days)
112
+ routes = _load_route_log(days)
113
+
114
+ stats: dict[str, dict[str, Any]] = defaultdict(lambda: {
115
+ "route_hits": 0, "calls": 0, "results": 0, "errors": 0,
116
+ "domains": set(),
117
+ })
118
+
119
+ # route 流:被路由命中
120
+ for r in routes:
121
+ engines = r.get("engines") or r.get("engines_used") or []
122
+ if isinstance(engines, str):
123
+ engines = [engines]
124
+ for e in engines:
125
+ stats[e]["route_hits"] += 1
126
+ dom = r.get("domain")
127
+ if dom:
128
+ stats[e]["domains"].add(dom)
129
+
130
+ # query 流:实际调用与结果。
131
+ # 口径注意:engine_results 字段 2026-10-26 才加入(v2.13.0),
132
+ # 历史日志里 92% 是 null——不能拿它算交付率。改用 count(最终结果数)
133
+ # 作为「这次调用有没有交付」的粗信号:count > 0 且该引擎在 engines_used
134
+ # 里,就记一次交付。
135
+ for r in queries:
136
+ used = r.get("engines_used") or []
137
+ if isinstance(used, str):
138
+ used = [used]
139
+ count = r.get("count") or 0
140
+ er = r.get("engine_results") or {}
141
+ for e in used:
142
+ stats[e]["calls"] += 1
143
+ # 优先用 engine_results(精确),缺失时用 count > 0(粗)
144
+ n = er.get(e)
145
+ if isinstance(n, int):
146
+ if n > 0:
147
+ stats[e]["results"] += 1
148
+ elif count > 0:
149
+ stats[e]["results"] += 1
150
+ for f in (r.get("failures") or []):
151
+ if isinstance(f, dict) and f.get("engine"):
152
+ stats[f["engine"]]["errors"] += 1
153
+
154
+ return dict(stats)
155
+
156
+
157
+ def audit(days: int = 90, verbose: bool = False) -> dict[str, Any]:
158
+ """审计全部源,返回建议清单与摘要。"""
159
+ try:
160
+ import engines
161
+ all_specs = engines.get_all_engine_specs() if hasattr(engines, "get_all_engine_specs") else {}
162
+ except Exception:
163
+ all_specs = {}
164
+
165
+ if not all_specs:
166
+ # 兜底:直接读 specs 目录
167
+ from yaml_load import loads as yaml_loads
168
+ spec_dir = Path(__file__).parent.parent / "engines" / "specs"
169
+ for f in spec_dir.glob("*.yaml"):
170
+ try:
171
+ d = yaml_loads(f.read_text(encoding="utf-8"))
172
+ if isinstance(d, dict) and d.get("engine_id"):
173
+ all_specs[d["engine_id"]] = d
174
+ except Exception:
175
+ continue
176
+
177
+ usage = _engine_usage(days)
178
+
179
+ demote: list[dict] = [] # 建议停用
180
+ review: list[dict] = [] # 建议降级 explicit_only
181
+ quarantine: list[dict] = [] # 建议隔离
182
+ info: list[dict] = [] # 提示
183
+
184
+ for name, spec in sorted(all_specs.items()):
185
+ explicit = bool(spec.get("explicit_only"))
186
+ enabled = spec.get("enabled", True)
187
+ cost_per_call = spec.get("cost_per_call", 0.0) or 0.0
188
+
189
+ u = usage.get(name, {})
190
+ route_hits = u.get("route_hits", 0)
191
+ calls = u.get("calls", 0)
192
+ results = u.get("results", 0)
193
+ errors = u.get("errors", 0)
194
+
195
+ result_rate = (results / calls) if calls > 0 else 0.0
196
+ value_score = route_hits * result_rate
197
+
198
+ record = {
199
+ "engine": name,
200
+ "explicit_only": explicit,
201
+ "enabled": enabled,
202
+ "route_hits": route_hits,
203
+ "calls": calls,
204
+ "results": results,
205
+ "errors": errors,
206
+ "result_rate": round(result_rate, 3),
207
+ "value_score": round(value_score, 2),
208
+ "cost_per_call": cost_per_call,
209
+ "domains": sorted(u.get("domains", set())),
210
+ }
211
+
212
+ if not enabled:
213
+ continue
214
+
215
+ # 需密钥且未配置 → 提示
216
+ # required_env 形态:['KEY'] 或 [['KEY_A', 'KEY_B']](别名链,任一就绪即可)
217
+ required_env = spec.get("required_env") or []
218
+ if isinstance(required_env, str):
219
+ required_env = [required_env]
220
+ missing_group = []
221
+ for group in required_env:
222
+ names = group if isinstance(group, list) else [group]
223
+ if not any(os.environ.get(n) for n in names):
224
+ missing_group.append(names)
225
+ if missing_group and not explicit:
226
+ shown = ', '.join('/'.join(g[:3]) for g in missing_group[:3])
227
+ record["reason"] = f"需密钥未配置: {shown}"
228
+ info.append(record)
229
+ continue
230
+
231
+ if explicit:
232
+ continue # 显式专用源不进自动路由,不参与去留判定
233
+
234
+ if route_hits == 0:
235
+ record["reason"] = f"{days} 天 0 次路由命中"
236
+ demote.append(record)
237
+ elif value_score < 5:
238
+ record["reason"] = f"价值分 {value_score} < 5(命中 {route_hits} 次,交付率 {result_rate:.0%})"
239
+ review.append(record)
240
+ elif calls > 0 and result_rate < 0.2:
241
+ record["reason"] = f"交付率 {result_rate:.0%} < 20%(命中 {route_hits} 次,错误 {errors} 次)"
242
+ quarantine.append(record)
243
+
244
+ return {
245
+ "days": days,
246
+ "total_specs": len(all_specs),
247
+ "enabled_specs": sum(1 for s in all_specs.values() if s.get("enabled", True)),
248
+ "explicit_specs": sum(1 for s in all_specs.values() if s.get("explicit_only")),
249
+ "used_engines": len(usage),
250
+ "demote": demote,
251
+ "review": review,
252
+ "quarantine": quarantine,
253
+ "info": info,
254
+ }
255
+
256
+
257
+ def render(report: dict, verbose: bool = False) -> str:
258
+ """渲染审计报告(人读)。"""
259
+ lines: list[str] = []
260
+ lines.append(f"源健康度审计(过去 {report['days']} 天)")
261
+ lines.append(
262
+ f" 收录 {report['total_specs']} 个源,启用 {report['enabled_specs']} 个,"
263
+ f"显式专用 {report['explicit_specs']} 个,日志出现 {report['used_engines']} 个"
264
+ )
265
+ lines.append("")
266
+
267
+ if report["demote"]:
268
+ lines.append(f" 建议停用({len(report['demote'])} 个,0 命中):")
269
+ for r in report["demote"][:10]:
270
+ lines.append(f" - {r['engine']}: {r['reason']}")
271
+ if len(report["demote"]) > 10:
272
+ lines.append(f" ... 另有 {len(report['demote']) - 10} 个")
273
+ lines.append("")
274
+
275
+ if report["review"]:
276
+ lines.append(f" 建议降级为 explicit_only({len(report['review'])} 个,低价值):")
277
+ for r in report["review"][:10]:
278
+ lines.append(f" - {r['engine']}: {r['reason']}")
279
+ if len(report["review"]) > 10:
280
+ lines.append(f" ... 另有 {len(report['review']) - 10} 个")
281
+ lines.append("")
282
+
283
+ if report["quarantine"]:
284
+ lines.append(f" 建议隔离({len(report['quarantine'])} 个,低交付率):")
285
+ for r in report["quarantine"]:
286
+ lines.append(f" - {r['engine']}: {r['reason']}")
287
+ lines.append("")
288
+
289
+ if report["info"]:
290
+ lines.append(f" 提示({len(report['info'])} 个,需密钥未配置):")
291
+ for r in report["info"][:5]:
292
+ lines.append(f" - {r['engine']}: {r['reason']}")
293
+ if len(report["info"]) > 5:
294
+ lines.append(f" ... 另有 {len(report['info']) - 5} 个")
295
+ lines.append("")
296
+
297
+ if not (report["demote"] or report["review"] or report["quarantine"]):
298
+ lines.append(" ✔ 全部源健康,无去留建议")
299
+ lines.append("")
300
+
301
+ lines.append(" 运行 `argo doctor --fix` 自动执行停用与隔离;降级需人工判断。")
302
+ return "\n".join(lines)
303
+
304
+
305
+ def main() -> int:
306
+ import argparse
307
+ parser = argparse.ArgumentParser(
308
+ description="源健康度审计(基于真实使用日志给出去留建议)")
309
+ parser.add_argument("--days", type=int, default=90,
310
+ help="审计窗口(天),默认 90")
311
+ parser.add_argument("--json", action="store_true", help="JSON 输出")
312
+ parser.add_argument("--verbose", action="store_true", help="显示全部明细")
313
+ args = parser.parse_args()
314
+
315
+ report = audit(days=args.days, verbose=args.verbose)
316
+
317
+ if args.json:
318
+ # CLI stdout 必须紧凑 JSON(cli_io.dumps)——缩进 JSON 会被
319
+ # test_context_budget 判为「CLI 输出污染管道」。
320
+ try:
321
+ import cli_io
322
+ print(cli_io.dumps(report))
323
+ except ImportError:
324
+ print(json.dumps(report, ensure_ascii=False, separators=(",", ":")))
325
+ else:
326
+ print(render(report, verbose=args.verbose))
327
+ return 0
328
+
329
+
330
+ if __name__ == "__main__":
331
+ sys.exit(main())