argo-search 2.13.0 → 2.14.1

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 (129) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.es.md +30 -8
  3. package/README.ja.md +30 -8
  4. package/README.ko.md +30 -8
  5. package/README.md +511 -596
  6. package/README.zh.md +975 -0
  7. package/SKILL.md +1 -1
  8. package/assets/readme/counts.json +1 -1
  9. package/backends/domain_profiles.json +90 -6
  10. package/backends/engine_registry.yaml +222 -32
  11. package/backends/env_passthrough.txt +2 -0
  12. package/backends/quota_profiles.json +151 -11
  13. package/bin/argo +3 -0
  14. package/config.yaml +50 -4
  15. package/docs/CHANGELOG.md +45 -0
  16. package/docs/COMMIT_STANDARD.md +98 -0
  17. package/docs/ENGINE_CATALOG.md +100 -81
  18. package/docs/MCP_SETUP.md +1 -1
  19. package/docs/RELEASE_NOTES_v2.14.0.md +88 -0
  20. package/docs/RELEASE_NOTES_v2.14.1.md +80 -0
  21. package/docs/RELEASING.md +52 -0
  22. package/engines/specs/artic.yaml +11 -1
  23. package/engines/specs/cleveland.yaml +15 -1
  24. package/engines/specs/clinicaltrials.yaml +24 -1
  25. package/engines/specs/cnii.yaml +17 -1
  26. package/engines/specs/coingecko.yaml +10 -2
  27. package/engines/specs/dbpedia.yaml +32 -0
  28. package/engines/specs/deezer.yaml +12 -1
  29. package/engines/specs/doaj.yaml +14 -1
  30. package/engines/specs/endoflife.yaml +16 -1
  31. package/engines/specs/eu_opendata.yaml +11 -1
  32. package/engines/specs/europeana.yaml +19 -1
  33. package/engines/specs/feed.yaml +62 -0
  34. package/engines/specs/figshare.yaml +12 -1
  35. package/engines/specs/fourget.yaml +23 -0
  36. package/engines/specs/grep_app.yaml +19 -0
  37. package/engines/specs/hackernews.yaml +17 -1
  38. package/engines/specs/hal.yaml +19 -1
  39. package/engines/specs/hf_datasets.yaml +59 -0
  40. package/engines/specs/hf_papers.yaml +42 -0
  41. package/engines/specs/jikan.yaml +12 -10
  42. package/engines/specs/kaggle.yaml +46 -0
  43. package/engines/specs/local_baidu.yaml +5 -0
  44. package/engines/specs/local_seek.yaml +34 -0
  45. package/engines/specs/local_yandex.yaml +37 -0
  46. package/engines/specs/maven.yaml +61 -0
  47. package/engines/specs/mojeek.yaml +31 -0
  48. package/engines/specs/mwmbl.yaml +39 -0
  49. package/engines/specs/nasa_cmr.yaml +12 -1
  50. package/engines/specs/nuget.yaml +57 -0
  51. package/engines/specs/openaire.yaml +34 -0
  52. package/engines/specs/repology.yaml +18 -0
  53. package/engines/specs/tatoeba.yaml +14 -1
  54. package/engines/specs/tvmaze.yaml +5 -1
  55. package/engines/specs/usda.yaml +14 -1
  56. package/package.json +14 -10
  57. package/packages/dsh-plugin/dsh/client.js +1 -0
  58. package/packages/dsh-plugin/dsh/native-tools.mjs +85 -116
  59. package/packages/dsh-plugin/dsh/runner.js +35 -1
  60. package/packages/dsh-plugin/dsh/specs.js +3 -1
  61. package/packages/dsh-plugin/dsh/wide-research.js +5 -3
  62. package/packages/dsh-plugin/package.json +1 -1
  63. package/packages/dsh-plugin/test/client.test.js +6 -0
  64. package/packages/dsh-plugin/test/config.test.js +5 -1
  65. package/packages/dsh-plugin/test/index.test.js +3 -1
  66. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  67. package/scripts/badcase_causes.py +81 -0
  68. package/scripts/badcase_ledger.py +336 -19
  69. package/scripts/build_release_assets.sh +43 -15
  70. package/scripts/cache.py +3 -3
  71. package/scripts/check_commit_report.py +168 -0
  72. package/scripts/dormant_ledger.py +225 -0
  73. package/scripts/engine_admission.py +9 -5
  74. package/scripts/engine_families.py +13 -2
  75. package/scripts/engine_policy.py +1 -1
  76. package/scripts/engine_states.py +398 -8
  77. package/scripts/engine_status.py +31 -0
  78. package/scripts/engine_validate.py +224 -40
  79. package/scripts/engines.py +4 -34
  80. package/scripts/engines_base.py +53 -147
  81. package/scripts/engines_builders.py +2 -33
  82. package/scripts/engines_builders_batch12.py +168 -0
  83. package/scripts/engines_builders_batch16.py +13 -0
  84. package/scripts/engines_builders_batch9.py +0 -204
  85. package/scripts/engines_builders_feeds.py +148 -30
  86. package/scripts/engines_builders_intl.py +0 -328
  87. package/scripts/engines_builders_science.py +0 -85
  88. package/scripts/engines_builders_tech.py +0 -98
  89. package/scripts/engines_parsers.py +924 -0
  90. package/scripts/evidence_loop.py +91 -4
  91. package/scripts/fetch_browser.py +4 -2
  92. package/scripts/fetch_jsrun.py +2 -1
  93. package/scripts/fetch_v3.py +22 -22
  94. package/scripts/gen_engine_catalog.py +2 -2
  95. package/scripts/gen_native_tools.py +46 -18
  96. package/scripts/local_intent.py +175 -0
  97. package/scripts/local_seek.py +256 -91
  98. package/scripts/local_seek_adapter.py +87 -0
  99. package/scripts/mcp_handlers.py +124 -72
  100. package/scripts/mcp_server.py +1 -1
  101. package/scripts/mcp_tools.py +143 -61
  102. package/scripts/mcp_transport.py +42 -10
  103. package/scripts/pre-commit +68 -1
  104. package/scripts/recovery.py +14 -5
  105. package/scripts/recovery_l0.py +5 -3
  106. package/scripts/release.py +20 -11
  107. package/scripts/release_check.py +1 -1
  108. package/scripts/research.py +1 -1
  109. package/scripts/research_gates.py +3 -3
  110. package/scripts/route_lang.py +6 -1
  111. package/scripts/route_policy.py +26 -14
  112. package/scripts/search.py +33 -25
  113. package/scripts/search_cli.py +52 -6
  114. package/scripts/search_output.py +83 -16
  115. package/scripts/secret_guard.py +106 -0
  116. package/scripts/semantic_evidence.py +230 -15
  117. package/scripts/settings_page.py +80 -8
  118. package/scripts/source_audit.py +408 -0
  119. package/scripts/sync_backends.py +38 -1
  120. package/scripts/wechat_article.py +5 -3
  121. package/scripts/wide_research.py +4 -1
  122. package/scripts/x_article_fetch.py +2 -1
  123. package/sub-skills/local-search/parsers.py +6 -1
  124. package/sub-skills/local-seek/scripts/seek.py +390 -24
  125. package/sub-skills/local-seek/scripts/seek_fts.py +28 -9
  126. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  127. package/README.en.md +0 -814
  128. package/engines/specs/cinii.yaml +0 -44
  129. package/scripts/image_vision/vision_probe +0 -0
@@ -50,6 +50,23 @@ _KNOWN_SWITCHES = [
50
50
  ("ARGO_FETCH_DEADLINE_S", "单次 fetch 总耗时上限(秒,0 关闭)"),
51
51
  ]
52
52
 
53
+ # 核心全局与管线服务凭据(非单个引擎独占)
54
+ _GLOBAL_SERVICES_KEYS = [
55
+ ("jev", "TypeSafe JEV 语义核验 (一手源加权/反驳预警)", ["ARGO_JEV_API_KEY", "TYPESAFE_API_KEY"]),
56
+ ("semantic_scholar", "Semantic Scholar 学术论文增强", ["SEMANTIC_SCHOLAR_API_KEY"]),
57
+ ("twitter_session", "X / Twitter 会话鉴权", ["TWITTER_AUTH_TOKEN", "TWITTER_CT0"]),
58
+ ("network_proxy", "出站网络代理通道", ["ARGO_PROXY", "HTTPS_PROXY"]),
59
+ ]
60
+
61
+ # 可选增强引擎凭据(免 Key 可跑,配置后解除限频或解锁高级通道)
62
+ _OPTIONAL_BOOST_KEYS = [
63
+ ("github", "GitHub 限频提升 (可选)", ["GITHUB_TOKEN", "ARGO_GITHUB_TOKEN"]),
64
+ ("exa", "Exa 语义搜索增强 (可选)", ["EXA_API_KEY", "ARGO_EXA_API_KEY"]),
65
+ ("firecrawl", "Firecrawl 深度清洗 (可选)", ["FIRECRAWL_API_KEY", "ARGO_FIRECRAWL_API_KEY"]),
66
+ ("anysearch", "AnySearch 搜索通道 (可选)", ["ANYSEARCH_API_KEY", "ARGO_ANYSEARCH_API_KEY"]),
67
+ ("pixiv", "Pixiv App OAuth (可选)", ["ARGO_PIXIV_REFRESH_TOKEN"]),
68
+ ]
69
+
53
70
  # MCP / CLI 接入示例(片段不含密钥;密钥由 mcp_launch.sh 启动时注入)
54
71
  _CLI_EXAMPLES = [
55
72
  ("搜索", 'argo search "查询词" --json'),
@@ -109,15 +126,29 @@ def collect() -> dict[str, Any]:
109
126
  except Exception:
110
127
  names = []
111
128
 
112
- # 密钥状态只列「声明了 required_env」的引擎——这正是 #41 里
113
- # 「装了 13 个引擎全 skipped」的痛点位;无密钥要求的引擎不上表。
114
- # 判定与 runtime 同源:缺失与否以 missing_env_for(候选链)为准,
115
- # 掩码值以 get_env 为准——显示层绝不自建第二套口径(#41/#42 的教训)。
129
+ # 密钥状态收集:覆盖全局核心服务、商业数据引擎、可选增强源
116
130
  try:
117
131
  from engines import get_engine_spec
118
132
  from engine_env import (required_env_for, missing_env_for, get_env,
119
133
  PLACEHOLDER_ALIASES)
120
134
 
135
+ # 1. 核心全局与管线服务
136
+ for s_id, s_label, s_vars in _GLOBAL_SERVICES_KEYS:
137
+ env_items = []
138
+ for var in s_vars:
139
+ val = get_env(var)
140
+ env_items.append({
141
+ "name": var,
142
+ "status": env_store.mask(val) if val else "缺失",
143
+ })
144
+ data["key_rows"].append({
145
+ "engine": s_id,
146
+ "label": s_label,
147
+ "kind": "service",
148
+ "envs": env_items,
149
+ })
150
+
151
+ # 2. 商业与声明 required_env 的引擎
121
152
  for name in names:
122
153
  spec = get_engine_spec(name) or {}
123
154
  try:
@@ -132,6 +163,8 @@ def collect() -> dict[str, Any]:
132
163
  missing = set(reqs)
133
164
  data["key_rows"].append({
134
165
  "engine": name,
166
+ "label": spec.get("label") or name,
167
+ "kind": "engine",
135
168
  "envs": [{"name": r,
136
169
  "status": (env_store.mask(
137
170
  get_env(PLACEHOLDER_ALIASES.get(r) or _runtime_candidates(r))
@@ -139,6 +172,22 @@ def collect() -> dict[str, Any]:
139
172
  if r not in missing else "缺失")}
140
173
  for r in reqs],
141
174
  })
175
+
176
+ # 3. 可选增强源
177
+ for o_id, o_label, o_vars in _OPTIONAL_BOOST_KEYS:
178
+ env_items = []
179
+ for var in o_vars:
180
+ val = get_env(var)
181
+ env_items.append({
182
+ "name": var,
183
+ "status": env_store.mask(val) if val else "未配置(可选)",
184
+ })
185
+ data["key_rows"].append({
186
+ "engine": o_id,
187
+ "label": o_label,
188
+ "kind": "optional",
189
+ "envs": env_items,
190
+ })
142
191
  except Exception:
143
192
  pass
144
193
 
@@ -369,12 +418,35 @@ def _run_list() -> int:
369
418
  env_in_use = (data.get("paths") or {}).get("env_file_in_use")
370
419
  if env_in_use:
371
420
  print(f"密钥文件:{env_in_use}")
372
- for r in data.get("key_rows", []):
373
- envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
374
- print(f" {r['engine']}: {envs}")
421
+
422
+ services = [r for r in data.get("key_rows", []) if r.get("kind") == "service"]
423
+ engines = [r for r in data.get("key_rows", []) if r.get("kind") == "engine"]
424
+ optionals = [r for r in data.get("key_rows", []) if r.get("kind") == "optional"]
425
+
426
+ if services:
427
+ print("\n[核心与管线服务凭据]")
428
+ for r in services:
429
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
430
+ desc = f" ({r['label']})" if r.get("label") else ""
431
+ print(f" {r['engine']}{desc}: {envs}")
432
+
433
+ if engines:
434
+ print("\n[商业搜索与数据源密钥]")
435
+ for r in engines:
436
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
437
+ print(f" {r['engine']}: {envs}")
438
+
439
+ if optionals:
440
+ print("\n[可选增强源凭据 (免 Key 可用,配置后提权)]")
441
+ for r in optionals:
442
+ envs = "、".join(f"{v['name']} {v['status']}" for v in r["envs"])
443
+ desc = f" ({r['label']})" if r.get("label") else ""
444
+ print(f" {r['engine']}{desc}: {envs}")
445
+
446
+ print("\n[常用功能开关]")
375
447
  for s in data.get("switches", []):
376
448
  print(f" [{s['name']}] {s['value']} — {s['desc']}")
377
- print("修改:echo <值> | argo settings set <变量名>;"
449
+ print("\n修改:echo <值> | argo settings set <变量名>;"
378
450
  "清除:argo settings unset <变量名>。")
379
451
  return 0
380
452
 
@@ -0,0 +1,408 @@
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
+ lines.append(" 对交付率异常的声明式源,可运行 `python3 scripts/engine_validate.py -e <id> --diagnose`"
303
+ " (或 `--fix`) 探测结构漂移并输出建议补丁(预览态,不写盘);"
304
+ "确认无误后加 `--apply` 才落盘。")
305
+ return "\n".join(lines)
306
+
307
+
308
+ def _apply_fix(report: dict[str, Any], days: int,
309
+ spec_dir: Path | None = None) -> dict[str, Any]:
310
+ """执行 demote(停用)与 quarantine(隔离)。
311
+
312
+ 改写的是 spec 文件里的 `enabled` 与 `disabled_reason` 两个键,保留其余
313
+ 内容(注释、字段顺序、授权常量)不动——整文件重写会丢注释,而 spec 是
314
+ 人工维护的真源。改写后不自动跑 sync_backends:调用方需自行决定何时同步
315
+ 派生件(见 main 的提示)。
316
+
317
+ quarantine 与 demote 落到同一个 `enabled: false`,但 disabled_reason
318
+ 前缀不同,便于区分「低价值停用」与「低交付率隔离」。
319
+ """
320
+ import re as _re
321
+
322
+ target_dir = spec_dir or (Path(__file__).parent.parent / "engines" / "specs")
323
+ actions: list[dict[str, str]] = []
324
+ for action, items in (("demote", report.get("demote") or []),
325
+ ("quarantine", report.get("quarantine") or [])):
326
+ for rec in items:
327
+ name = rec.get("engine") or ""
328
+ path = target_dir / f"{name}.yaml"
329
+ if not path.is_file():
330
+ actions.append({"engine": name, "action": action,
331
+ "status": "spec 不存在"})
332
+ continue
333
+ text = path.read_text(encoding="utf-8")
334
+ reason = (f"{action} by argo doctor --fix "
335
+ f"({rec.get('reason', '')};审计窗口 {days} 天)")
336
+ # 幂等:已停用且原因已标注的跳过
337
+ if _re.search(r"^enabled:\s*false", text, _re.M) and action in text:
338
+ actions.append({"engine": name, "action": action,
339
+ "status": "已停用(跳过)"})
340
+ continue
341
+ if _re.search(r"^enabled:\s*true", text, _re.M):
342
+ text = _re.sub(r"^enabled:\s*true.*$",
343
+ "enabled: false", text, count=1, flags=_re.M)
344
+ else:
345
+ # 无 enabled 键:补在 engine_id 之后
346
+ text = _re.sub(r"^(engine_id:.*)$",
347
+ r"\1\nenabled: false", text, count=1, flags=_re.M)
348
+ # 写 disabled_reason(已有则替换,没有则补在 enabled 之后;用 lambda 避免 reason 中特殊符号引起转义异常)
349
+ if _re.search(r"^disabled_reason:", text, _re.M):
350
+ text = _re.sub(r"^disabled_reason:.*$",
351
+ lambda _: f"disabled_reason: {reason}", text,
352
+ count=1, flags=_re.M)
353
+ else:
354
+ text = _re.sub(r"^(enabled: false.*)$",
355
+ lambda m: f"{m.group(1)}\ndisabled_reason: {reason}", text,
356
+ count=1, flags=_re.M)
357
+ path.write_text(text, encoding="utf-8")
358
+ actions.append({"engine": name, "action": action,
359
+ "status": "已停用"})
360
+ return {"actions": actions}
361
+
362
+
363
+ def main() -> int:
364
+ import argparse
365
+ parser = argparse.ArgumentParser(
366
+ description="源健康度审计(基于真实使用日志给出去留建议)")
367
+ parser.add_argument("--days", type=int, default=90,
368
+ help="审计窗口(天),默认 90")
369
+ parser.add_argument("--json", action="store_true", help="JSON 输出")
370
+ parser.add_argument("--verbose", action="store_true", help="显示全部明细")
371
+ parser.add_argument("--fix", action="store_true",
372
+ help="执行 demote(停用)与 quarantine(隔离)")
373
+ args = parser.parse_args()
374
+
375
+ report = audit(days=args.days, verbose=args.verbose)
376
+
377
+ if args.fix:
378
+ fixed = _apply_fix(report, args.days)
379
+ if args.json:
380
+ try:
381
+ import cli_io
382
+ print(cli_io.dumps(fixed))
383
+ except ImportError:
384
+ print(json.dumps(fixed, ensure_ascii=False, separators=(",", ":")))
385
+ else:
386
+ print(f"已执行 {len(fixed['actions'])} 项动作:")
387
+ for a in fixed["actions"][:20]:
388
+ print(f" - {a['engine']}: {a['action']} → {a['status']}")
389
+ if len(fixed["actions"]) > 20:
390
+ print(f" ... 另有 {len(fixed['actions']) - 20} 项")
391
+ print("\n改写 spec 后请同步派生件:python3 scripts/sync_backends.py")
392
+ return 0
393
+
394
+ if args.json:
395
+ # CLI stdout 必须紧凑 JSON(cli_io.dumps)——缩进 JSON 会被
396
+ # test_context_budget 判为「CLI 输出污染管道」。
397
+ try:
398
+ import cli_io
399
+ print(cli_io.dumps(report))
400
+ except ImportError:
401
+ print(json.dumps(report, ensure_ascii=False, separators=(",", ":")))
402
+ else:
403
+ print(render(report, verbose=args.verbose))
404
+ return 0
405
+
406
+
407
+ if __name__ == "__main__":
408
+ sys.exit(main())
@@ -55,6 +55,9 @@ PASSTHROUGH_PATH = BACKENDS_DIR / "env_passthrough.txt"
55
55
  DSH_CLIENT_PATH = SKILL_DIR / "packages" / "dsh-plugin" / "dsh" / "client.js"
56
56
  _KEYS_BEGIN = " // <generated:keys> 由 scripts/sync_backends.py 从引擎声明生成,勿手改\n"
57
57
  _KEYS_END = " // </generated:keys>\n"
58
+ DSH_RUNNER_PATH = SKILL_DIR / "packages" / "dsh-plugin" / "dsh" / "runner.js"
59
+ _KEYREFS_BEGIN = " // <generated:keyrefs> 由 scripts/sync_backends.py 从引擎声明生成,勿手改\n"
60
+ _KEYREFS_END = " // </generated:keyrefs>\n"
58
61
  # 面板常用组:首屏直接显示的那几把 key(其余在「显示全部」里)
59
62
  # 旧面板手写名单里与候选链规则不一致的 ref(候选链里确实有这个名字,运行时
60
63
  # get_env 能读到):保留旧名,否则 DSH 凭证库里已存的 key 改名后面板显示未配置
@@ -337,6 +340,27 @@ def write_dsh_keys_block(block: str) -> None:
337
340
  atomic_write_text(DSH_CLIENT_PATH, s[:i] + block + s[j + len(_KEYS_END):], mode=0o644)
338
341
 
339
342
 
343
+ def render_keyrefs(rows: list[dict[str, Any]]) -> str:
344
+ body = "".join(" '%s',\n" % r["ref"] for r in rows)
345
+ return _KEYREFS_BEGIN + " keyRefs: [\n" + body + " ],\n" + _KEYREFS_END
346
+
347
+
348
+ def read_keyrefs_block() -> str:
349
+ if not DSH_RUNNER_PATH.exists():
350
+ return ""
351
+ s = DSH_RUNNER_PATH.read_text(encoding="utf-8")
352
+ i, j = s.find(_KEYREFS_BEGIN), s.find(_KEYREFS_END)
353
+ return s[i:j + len(_KEYREFS_END)] if i >= 0 and j > i else ""
354
+
355
+
356
+ def write_keyrefs_block(block: str) -> None:
357
+ s = DSH_RUNNER_PATH.read_text(encoding="utf-8")
358
+ i, j = s.find(_KEYREFS_BEGIN), s.find(_KEYREFS_END)
359
+ if i < 0 or j < i:
360
+ raise SystemExit(f"{DSH_RUNNER_PATH} 缺 <generated:keyrefs> 标记区")
361
+ atomic_write_text(DSH_RUNNER_PATH, s[:i] + block + s[j + len(_KEYREFS_END):], mode=0o644)
362
+
363
+
340
364
  # ── 校验/补全:domain_profiles.json ─────────────────────────────────────────
341
365
 
342
366
  def check_domain_profiles(engines: dict[str, dict[str, Any]], profiles: dict[str, Any]) -> list[str]:
@@ -432,8 +456,18 @@ def collect_issues(engines: dict[str, dict[str, Any]],
432
456
  miss = sorted(set(want_pt) - set(cur_pt))
433
457
  extra = sorted(set(cur_pt) - set(want_pt))
434
458
  issues.append(f"env_passthrough.txt 与声明不一致: 缺 {miss} 多 {extra}")
435
- if DSH_CLIENT_PATH.exists() and read_dsh_keys_block() != render_dsh_keys(derive_dsh_keys(engines)):
459
+ dsh_rows = derive_dsh_keys(engines)
460
+ if DSH_CLIENT_PATH.exists() and read_dsh_keys_block() != render_dsh_keys(dsh_rows):
436
461
  issues.append("packages/dsh-plugin/dsh/client.js 的 KEYS 标记区与引擎声明不一致")
462
+ if DSH_RUNNER_PATH.exists() and read_keyrefs_block() != render_keyrefs(dsh_rows):
463
+ issues.append("packages/dsh-plugin/dsh/runner.js 的 keyRefs 标记区与引擎声明不一致")
464
+ # 休眠台账对账:domains/combo 变更后位置性休眠会漂移,sync 即发现
465
+ # (判定与台账真源在 dormant_ledger,测试同消费;异常可见而非静默跳过)
466
+ try:
467
+ import dormant_ledger
468
+ issues.extend(dormant_ledger.check_dormant_ledger())
469
+ except Exception as exc:
470
+ issues.append(f"dormant_ledger 对账异常: {exc}")
437
471
  return issues
438
472
 
439
473
 
@@ -533,6 +567,9 @@ def main() -> int:
533
567
  if DSH_CLIENT_PATH.exists():
534
568
  keys_new = derive_dsh_keys(engines)
535
569
  write_dsh_keys_block(render_dsh_keys(keys_new))
570
+ if DSH_RUNNER_PATH.exists():
571
+ write_keyrefs_block(render_keyrefs(keys_new))
572
+ print(f" dsh runner.js keyRefs {len(keys_new)} 个转发名")
536
573
  print(f" dsh client.js KEYS {len(keys_new)} 把 key")
537
574
  print(f" quota_profiles.json {len(quota_new) - 1} 条")
538
575
  print(f" engine_registry.yaml {len(registry_new['engines'])} 条")
@@ -14,6 +14,8 @@
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
+ import engine_states
18
+
17
19
  import argparse
18
20
  import json
19
21
  import os
@@ -84,7 +86,7 @@ def _cdp_fetch(url: str, timeout: int = 15) -> dict:
84
86
  "image_count": len(imgs),
85
87
  "images": imgs,
86
88
  "content": content,
87
- "fetch_method": "chrome_cdp",
89
+ "fetch_method": engine_states.FETCH_CHROME_CDP,
88
90
  }
89
91
  except Exception as e:
90
92
  return {"ok": False, "error": f"CDP 通道异常: {e}"}
@@ -141,7 +143,7 @@ def _sogou_fallback(url: str) -> dict:
141
143
  "image_count": 0,
142
144
  "images": [],
143
145
  "content": best.get("snippet", ""),
144
- "fetch_method": "sogou_fallback",
146
+ "fetch_method": engine_states.FETCH_SOGOU_FALLBACK,
145
147
  "note": "通过搜狗搜索间接获取,内容可能不完整",
146
148
  }
147
149
  except Exception as e:
@@ -198,7 +200,7 @@ def fetch_wechat_article(url: str) -> dict:
198
200
  # 通道1: HTTP 直取(快速失败)
199
201
  result = _http_fetch(url, timeout=5)
200
202
  if _has_content(result):
201
- result["fetch_method"] = "http_direct"
203
+ result["fetch_method"] = engine_states.FETCH_HTTP_DIRECT
202
204
  result.setdefault("char_count", len(result.get("content") or ""))
203
205
  return result
204
206
 
@@ -40,6 +40,7 @@ from urllib.parse import urlparse
40
40
  sys.path.insert(0, str(Path(__file__).resolve().parent))
41
41
 
42
42
  from cli_io import dumps # noqa: E402
43
+ import engine_states # noqa: E402
43
44
  from research_work_packages import stage_work_packages # noqa: E402
44
45
 
45
46
  MAX_SOURCES_PER_TRACK = 8
@@ -300,7 +301,9 @@ def evaluate_gates(
300
301
  "detail": f"{len(farm_hits)} sources originate from content farms or SEO scraper mirrors; evidence quality severely degraded.",
301
302
  })
302
303
 
303
- cap = "low" if failures else ("medium" if warnings else "high")
304
+ cap = (engine_states.CONCLUSION_CAP_LOW if failures
305
+ else (engine_states.CONCLUSION_CAP_MEDIUM if warnings
306
+ else engine_states.CONCLUSION_CAP_HIGH))
304
307
  return {"passed": not failures, "conclusion_cap": cap, "failures": failures, "warnings": warnings}
305
308
 
306
309
 
@@ -11,6 +11,7 @@ entityMap 里 MEDIA/MARKDOWN 原子块还原为带内嵌图片 Markdown。
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import engine_states
14
15
  import json
15
16
  import os
16
17
  import re
@@ -124,7 +125,7 @@ def fetch_x_article(url: str, max_chars: int = 8000,
124
125
  "length": min(len(content), max_chars),
125
126
  "success": True,
126
127
  "error": None,
127
- "fetch_method": "x_article",
128
+ "fetch_method": engine_states.FETCH_X_ARTICLE,
128
129
  }
129
130
  except Exception:
130
131
  return None