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
@@ -0,0 +1,329 @@
1
+ #!/usr/bin/env python3
2
+ """extend_route_labels_full_coverage.py — 把域覆盖补到 99/99(全构造、全精确命中)。
3
+
4
+ ## 为什么需要它
5
+
6
+ 2026-11-05 语料改为全构造用例后(`build_route_labels.py` 的隐私边界),域覆盖从
7
+ 99/99 掉到 58/99:差的 41 个域此前靠真实查询覆盖,构造用例里没有对应条目,
8
+ 覆盖门下限被迫从 0.85 降到 0.55,未覆盖域逐个登记在
9
+ `test_route_capability_coverage._KNOWN_GAPS` 里「由快照门/人工集覆盖」。
10
+
11
+ 那份缺口登记里有两条假设是**错的**,本脚本逐条证伪:
12
+
13
+ 1. 「平台专属语法无法构造自然用例」——`wechat_search` / `zhihu_content` /
14
+ `skill_search` / `dsh_plugin_search` 的触发词是**普通中文说法**(「公众号
15
+ 文章」「知乎 如何评价」「agent skills 技能市场」),不是平台操作符;
16
+ 2. 「语义过专的域无法构造」——`modal_card` 的「今日油价 / 火车票 车次 /
17
+ 手机参数 对比」是日常问法,`medical` 的「临床试验 适应症 不良反应」是
18
+ 标准医学问法。
19
+
20
+ 真正需要区分的不是「能不能构造」,而是**构造出的查询路由到哪个域**:
21
+ `test_route_labeled_regression` 判的是 `route_query(q).domain == expect_domain`
22
+ (精确相等),而旧能力扩展脚本的判据是「目标域出现在 `match_domains` 前 5 名」
23
+ ——两者差出 4 条既有失配(同族域被兄弟域抢主位)。
24
+
25
+ ## 第一性原理:一条用例 = 一句真会有人这么问的话
26
+
27
+ 判据三选一,全部满足才入库:
28
+
29
+ 1. **自然性**:这句话是真实用户会打的(不是把正则原样塞进去);
30
+ 2. **能力必要性**:这句话确实需要该域的能力才能答好(不是「刚好命中」);
31
+ 3. **精确命中**:`route_query(q).domain == 该域`(回归门的判据,不是前 5 名)。
32
+
33
+ 第 3 条把「标注」和「实测」分开:标注来自 1+2 的人工判断,实测只用来**剔除**
34
+ 达不到 3 的候选。达不到的候选不写进语料(宁缺勿滥),由
35
+ `--report` 打印出来供人工判断「是查询不自然,还是域规则坏了」。
36
+
37
+ ## 与既有扩展的分工
38
+
39
+ | 脚本 | 语料来源 | 判据 |
40
+ |---|---|---|
41
+ | `build_route_labels.py` | 空基底(隐私边界) | —— |
42
+ | `extend_route_labels_by_capability.py` | 域触发词自然化 | 目标域在前 5 名 |
43
+ | `extend_route_labels_by_language.py` | 各语言特征词 | 期望域精确命中 |
44
+ | `extend_route_labels.py` | 外部反馈撞车 | 加意图标签 |
45
+ | **本脚本** | 未覆盖域的人工自然问法 | **期望域精确命中** |
46
+
47
+ ## 用法
48
+
49
+ python3 scripts/extend_route_labels_full_coverage.py # 扩展并写回
50
+ python3 scripts/extend_route_labels_full_coverage.py --dry-run # 只统计
51
+ python3 scripts/extend_route_labels_full_coverage.py --report # 打印失配候选
52
+ """
53
+
54
+ from __future__ import annotations
55
+
56
+ import argparse
57
+ import json
58
+ import sys
59
+ from collections import Counter
60
+ from pathlib import Path
61
+ from typing import Any
62
+
63
+ ROOT = Path(__file__).resolve().parent.parent
64
+ SCRIPTS = ROOT / "scripts"
65
+ sys.path.insert(0, str(SCRIPTS))
66
+
67
+ LABELS = ROOT / "tests" / "golden" / "route_labeled.jsonl"
68
+
69
+ # ── 未覆盖域的人工问法(MECE:每个域只在这一处出现)──────────────────────────
70
+ # 顺序按域名字母序,便于与 config 对账。notes 写「为什么这句话需要该域」,
71
+ # 不写「它命中了什么正则」——后者改规则就过期,前者不会。
72
+ _CASES: list[tuple[str, str, str]] = [
73
+ ("ai_model", "GPT-4o 上下文窗口 多少",
74
+ "问模型的上下文窗口规格,只有 models.dev 这类模型目录答得了"),
75
+ ("ai_model", "大模型 API 定价 每百万 token 多少钱",
76
+ "问 API 计价口径,需要模型目录的价格字段"),
77
+ ("book_search", "刘慈欣 三体 小说 书评",
78
+ "找书与书评,需要图书源(微信读书/豆瓣读书)"),
79
+ ("book_search", "有什么好书推荐 科幻小说 书单",
80
+ "要书单,百科与新闻都答不了"),
81
+ ("cn_encyclopedia", "量子纠缠 百度百科 词条",
82
+ "点名要百科词条,需要百科源"),
83
+ ("cn_encyclopedia", "什么是碳中和 词条解释",
84
+ "概念定义,走百科点查"),
85
+ ("cls_telegraph_search", "财联社 电报 快讯 央行",
86
+ "点名财联社电报,只有该源有电报原文"),
87
+ ("code_search", "python 快速排序 实现 源码",
88
+ "找实现源码,需要代码托管源"),
89
+ ("code_search", "github 上有没有类似的 开源项目",
90
+ "找同类开源项目,需要 GitHub 检索"),
91
+ ("company_search", "某公司 统一社会信用代码 工商信息",
92
+ "工商登记信息,需要法人主数据/注册库"),
93
+ ("company_search", "查一下这家公司的 法人 注册资本",
94
+ "查法人/注册资本,百科答不了"),
95
+ ("dictionary_search", "ephemeral 这个英文单词什么意思",
96
+ "查英文单词释义,需要词典源"),
97
+ ("dictionary_search", "词典 查询 成语 意思",
98
+ "中文词典查询"),
99
+ ("dsh_plugin_search", "dsh 插件 推荐 有哪些",
100
+ "找 DSH 插件,需要插件目录源"),
101
+ ("dsh_plugin_search", "DSH 插件市场 搜索",
102
+ "点名插件市场"),
103
+ ("em_news_search", "东财资讯 7x24 全球资讯",
104
+ "点名东财资讯,只有该源有 7x24 快讯"),
105
+ ("english_tech", "Rust async performance best practices",
106
+ "英文技术实践,octen/anysearch 主搜"),
107
+ ("english_tech", "Kubernetes tutorial how to",
108
+ "英文教程检索"),
109
+ ("fact_check", "爱因斯坦 是谁",
110
+ "人物事实点查,走 wikipedia/byted"),
111
+ ("fact_check", "光速 是多少",
112
+ "数值事实点查,走 wolframalpha/wikipedia"),
113
+ ("financial_news", "上市公司 财报 研报 公告 汇总",
114
+ "财报/研报/公告三件套,需要财经资讯源"),
115
+ ("financial_news", "央行 降准 政策 解读",
116
+ "货币政策解读,需要财经资讯与研报"),
117
+ ("fund_query", "沪深300 ETF 基金净值 排行",
118
+ "基金净值排行,需要基金源"),
119
+ ("fund_query", "主动权益 基金经理 业绩 排名",
120
+ "基金经理业绩,只有基金源有"),
121
+ ("geo_places", "长江 流经 哪些 省份",
122
+ "地理水系问题,需要 OSM/百科地物"),
123
+ ("geo_places", "上海 位于 哪个 省 地理 位置",
124
+ "行政区位置,百科地理域"),
125
+ ("hk_filings", "香港上市 招股说明书 披露易",
126
+ "港股披露易招股书,只有港交所源有"),
127
+ ("hk_filings", "港股 公告 披露",
128
+ "港股公告披露"),
129
+ ("image_search", "免费 无版权 图片 素材 下载",
130
+ "找可商用图片素材,需要图库源"),
131
+ ("image_search", "找一张 星空 壁纸",
132
+ "壁纸检索"),
133
+ ("law_text", "民法典 一千二百六十条 条文 全文",
134
+ "要法条全文原文,需要法规全文源"),
135
+ ("law_text", "个人信息保护法 全文 条文",
136
+ "要法律全文"),
137
+ ("legal", "故意伤害罪 量刑 标准 刑法",
138
+ "罪名与量刑标准,需要法律专业源"),
139
+ ("legal", "正当防卫 认定 标准 判例",
140
+ "认定标准与判例"),
141
+ ("macro_data", "美国 CPI 通胀 最新 数据",
142
+ "美国宏观时序数据,需要 FRED 类源"),
143
+ ("macro_data", "中国 2024 GDP 增速 统计",
144
+ "中国宏观统计口径"),
145
+ ("medical", "临床试验 适应症 不良反应 记录",
146
+ "临床试验记录,需要 clinicaltrials/OpenFDA"),
147
+ ("medical", "阿司匹林 用法用量 说明书 不良反应",
148
+ "药品说明书与不良反应"),
149
+ ("media_search", "周杰伦 新歌 专辑 歌词",
150
+ "音乐媒体检索,需要曲库源"),
151
+ ("media_search", "有什么好听的 播客 推荐",
152
+ "播客推荐"),
153
+ ("meme_slang", "yyds 是什么梗",
154
+ "网络梗释义,需要梗百科/俚语源"),
155
+ ("meme_slang", "网络流行语 抽象话 什么意思",
156
+ "流行语释义"),
157
+ ("ml_models", "huggingface 预训练模型 权重 下载",
158
+ "模型权重检索,需要 HuggingFace"),
159
+ ("ml_models", "开源 embedding 模型 检索",
160
+ "找开源模型"),
161
+ ("modal_card", "今日油价 92号汽油 多少钱一升",
162
+ "油价模态卡(结构化实时值)"),
163
+ ("modal_card", "火车票 余票 查询 车次",
164
+ "车次余票模态卡"),
165
+ ("modal_card", "手机参数 配置 对比 报价",
166
+ "手机规格模态卡"),
167
+ ("news_realtime", "今天 最新 突发 新闻",
168
+ "实时突发新闻,需要实时新闻源"),
169
+ ("news_realtime", "breaking news latest developments",
170
+ "英文实时新闻"),
171
+ ("org_entity", "外交部 发言人 表态",
172
+ "政府机构实体,需要权威实体源"),
173
+ ("org_entity", "联合国 安理会 决议",
174
+ "国际组织实体"),
175
+ ("security_search", "CVE-2024-3094 漏洞 细节",
176
+ "CVE 漏洞详情,需要 NVD"),
177
+ ("security_search", "这个 npm 包 有没有 已知漏洞",
178
+ "开源依赖漏洞,需要 OSV"),
179
+ ("semantic_discovery", "find me the best emerging AI agent tools 2026",
180
+ "开放式发现类查询,语义引擎(Exa)主场"),
181
+ ("semantic_discovery", "有哪些值得关注的 开源 数据库 项目",
182
+ "行业盘点类发现"),
183
+ ("skill_search", "agent skills 技能市场 搜索",
184
+ "跨生态技能目录,需要 SkillsMP/ClawHub"),
185
+ ("skill_search", "claude skill 目录 找技能",
186
+ "点名技能目录"),
187
+ ("sports_search", "NBA 季后赛 总决赛 比分",
188
+ "赛事比分,需要体育源"),
189
+ ("sports_search", "英超 转会 球员 新闻",
190
+ "转会与球员动态"),
191
+ ("tech_deep", "联邦学习 SOTA 研究进展",
192
+ "技术研究进展(非单篇论文),走 openalex/arxiv 聚合"),
193
+ ("tech_deep", "deep dive research on vector database internals",
194
+ "英文深度技术调研"),
195
+ ("trade_stats", "海关总署 进出口 数据 统计",
196
+ "海关进出口统计,需要贸易统计源"),
197
+ ("us_fundamentals", "AAPL annual revenue net income financials",
198
+ "美股结构化财务(SEC XBRL),英文词形"),
199
+ ("us_stock", "NASDAQ 美股 盘前 行情",
200
+ "美股盘前行情,需要美股源"),
201
+ ("us_stock", "NVDA 盘后 美股 行情",
202
+ "美股盘后行情"),
203
+ ("video", "B站 视频 合集",
204
+ "视频内容检索,需要 B 站源"),
205
+ ("video", "视频 攻略 bilibili",
206
+ "视频攻略"),
207
+ ("wechat_search", "公众号 文章 搜索 深度学习 部署",
208
+ "公众号文章检索,需要微信搜索源"),
209
+ ("wechat_search", "微信公众号 关于 RAG 的文章",
210
+ "点名公众号"),
211
+ ("zhihu_content", "知乎 如何评价 这件事",
212
+ "知乎观点/评价,需要知乎源"),
213
+ ("zhihu_content", "知友 怎么看待 远程办公",
214
+ "知乎答主观点"),
215
+ ]
216
+
217
+
218
+ def _load(path: Path) -> list[dict[str, Any]]:
219
+ if not path.is_file():
220
+ return []
221
+ return [json.loads(l) for l in path.read_text(encoding="utf-8").splitlines()
222
+ if l.strip()]
223
+
224
+
225
+ def build(entries: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
226
+ """为未覆盖域补用例:候选须**精确命中**目标域,否则不入库。"""
227
+ from config import get_domains
228
+ from route import route_query
229
+
230
+ doms = {d["name"] for d in get_domains()}
231
+ existing = {e["query"] for e in entries}
232
+ covered = {e.get("expect_domain") for e in entries}
233
+
234
+ out = list(entries)
235
+ added = 0
236
+ hit = 0
237
+ misses: list[str] = []
238
+ covered_now: set[str] = set()
239
+
240
+ for domain, query, note in _CASES:
241
+ if query in existing:
242
+ continue
243
+ if domain not in doms:
244
+ misses.append(f" 域不存在: {domain}({query})")
245
+ continue
246
+ if domain in covered or domain in covered_now:
247
+ continue # 该域已有用例,不重复补
248
+ try:
249
+ r = route_query(query, mode="auto", depth="fast")
250
+ except Exception as exc: # 路由异常不写入语料
251
+ misses.append(f" 路由异常 {query!r}: {exc}")
252
+ continue
253
+ got = r.get("domain")
254
+ if got != domain:
255
+ misses.append(f" {query[:36]!r:40} want={domain:22} got={got}")
256
+ continue
257
+ hit += 1
258
+ covered_now.add(domain)
259
+ out.append({
260
+ "query": query,
261
+ "expect_domain": domain,
262
+ "expect_family": None,
263
+ "evidence": "capability",
264
+ "quality": {"errors": False, "recovered": False,
265
+ "count": 0, "occurrences": 1},
266
+ "source": "coverage:full",
267
+ "intent": None, # 由 extend_route_labels 补
268
+ "note": note,
269
+ })
270
+ added += 1
271
+
272
+ # 补 intent 标签(与既有扩展同一口径)
273
+ try:
274
+ from extend_route_labels import classify_intent
275
+ for e in out:
276
+ if not e.get("intent"):
277
+ e["intent"] = classify_intent(e["query"], e.get("expect_domain"))
278
+ except Exception:
279
+ pass
280
+
281
+ total_covered = sorted((covered | covered_now) & doms)
282
+ stats = {
283
+ "total": len(out),
284
+ "added": added,
285
+ "hit": hit,
286
+ "miss": len(misses),
287
+ "covered_domains_total": len(total_covered),
288
+ "all_domains": len(doms),
289
+ "uncovered": sorted(doms - set(total_covered)),
290
+ "misses": misses,
291
+ }
292
+ return out, stats
293
+
294
+
295
+ def main() -> int:
296
+ ap = argparse.ArgumentParser(description="把路由标注集域覆盖补到 99/99")
297
+ ap.add_argument("--dry-run", action="store_true")
298
+ ap.add_argument("--report", action="store_true")
299
+ args = ap.parse_args()
300
+
301
+ if not LABELS.is_file():
302
+ print(f"[coverage-extend] 语料不存在:{LABELS}", file=sys.stderr)
303
+ return 1
304
+
305
+ entries = _load(LABELS)
306
+ extended, stats = build(entries)
307
+ print(f"[coverage-extend] 语料 {len(entries)} -> {stats['total']} 条"
308
+ f"(新增 {stats['added']},精确命中 {stats['hit']},失配候选 {stats['miss']})")
309
+ print(f"[coverage-extend] 域覆盖 {stats['covered_domains_total']}/"
310
+ f"{stats['all_domains']}")
311
+ if stats["uncovered"]:
312
+ print(f"[coverage-extend] 仍未覆盖:{stats['uncovered']}")
313
+ if args.report and stats["misses"]:
314
+ print("失配候选(人工判断:查询不自然 → 换问法;规则坏了 → 改域规则):")
315
+ for m in stats["misses"]:
316
+ print(m)
317
+
318
+ if args.dry_run:
319
+ return 0
320
+
321
+ with LABELS.open("w", encoding="utf-8") as f:
322
+ for e in extended:
323
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
324
+ print(f"[coverage-extend] 已写回 {LABELS}")
325
+ return 0
326
+
327
+
328
+ if __name__ == "__main__":
329
+ raise SystemExit(main())
@@ -554,9 +554,30 @@ def _mobile_first_host(url: str) -> bool:
554
554
  # 直接移动首发(1 次触碰)。实测依据:抖音类站点按 IP 递进限速,请求节奏比
555
555
  # 身份选择重要一个数量级,省掉的每次试错都是真实的封禁风险。
556
556
  _IDENTITY_TTL = 86400
557
- _IDENTITY_PATH = os.environ.get(
558
- "ARGO_IDENTITY_MEMORY",
559
- str(_paths.state_path("fetch-identity.json")))
557
+
558
+
559
+ def _identity_path() -> str:
560
+ """身份记忆文件路径:模块属性(测试 monkeypatch 的真名)优先,否则按当前 env 解析。"""
561
+ patched = globals().get("_IDENTITY_PATH")
562
+ if patched is not None:
563
+ return patched
564
+ return os.environ.get(
565
+ "ARGO_IDENTITY_MEMORY",
566
+ str(_paths.state_path("fetch-identity.json")))
567
+
568
+
569
+ def __getattr__(name: str):
570
+ """`_IDENTITY_PATH` 每次访问按当前 ARGO_IDENTITY_MEMORY 解析(PEP 562)。
571
+
572
+ 290d3d8 同口径:状态根在导入后被改写是常态(测试临时目录、多工作树)。
573
+ 模块内裸名查找不触发本函数(LOAD_GLOBAL 语义),函数体一律走
574
+ _identity_path();这里只维持外部属性访问与 monkeypatch 契约。
575
+ """
576
+ if name == "_IDENTITY_PATH":
577
+ return _identity_path()
578
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
579
+
580
+
560
581
  _identity_mem: dict[str, float] = {}
561
582
  _identity_loaded = False
562
583
  _identity_dirty = False
@@ -570,7 +591,7 @@ def _identity_load() -> None:
570
591
  return
571
592
  _identity_loaded = True
572
593
  try:
573
- with open(_IDENTITY_PATH, encoding="utf-8") as f: # 写侧 atomic_write_text 恒 UTF-8,读侧同编码
594
+ with open(_identity_path(), encoding="utf-8") as f: # 写侧 atomic_write_text 恒 UTF-8,读侧同编码
574
595
  raw = json.load(f)
575
596
  now = time.time()
576
597
  mem: dict[str, float] = {}
@@ -603,7 +624,7 @@ def _identity_remember_mobile(host: str) -> None:
603
624
  try:
604
625
  # 原子写走 argo_paths 唯一来源(唯一 tmp 名);旧实现固定 `.tmp` 名,
605
626
  # 并发抓取进程会互相搬走临时文件,身份记忆静默丢失。
606
- _paths.atomic_write_json(Path(_IDENTITY_PATH), _identity_mem, indent=None)
627
+ _paths.atomic_write_json(Path(_identity_path()), _identity_mem, indent=None)
607
628
  _identity_dirty = False
608
629
  except Exception:
609
630
  pass
@@ -1210,6 +1231,12 @@ def _strip_html_unless_needed(result: dict, need_html: bool) -> dict:
1210
1231
  return result
1211
1232
 
1212
1233
 
1234
+ def _is_wechat_article_url(url: str) -> bool:
1235
+ """公众号文章页(/s?__biz= 与 /s/ 两种)。按 host+path 判,代理 URL 不误分流。"""
1236
+ p = urlparse(url)
1237
+ return (p.hostname or "") == "mp.weixin.qq.com" and (p.path == "/s" or p.path.startswith("/s/"))
1238
+
1239
+
1213
1240
  def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1214
1241
  use_browser_fallback: bool = True,
1215
1242
  actions: list[dict] | None = None,
@@ -1300,6 +1327,48 @@ def fetch_v3(url: str, max_chars: int = 8000, timeout: float = 8.0,
1300
1327
  except ImportError:
1301
1328
  pass
1302
1329
 
1330
+ # 微信公众号文章走专用降级链(HTTP→CDP→搜狗,唯一来源 wechat_article.py,
1331
+ # 即 `argo wx` 同一实现):通用 HTML 链对 mp.weixin 只能拿到 JS 骨架,
1332
+ # 正文全空(2026-11-01 实测缺口:fetch 对 mp.weixin 零处理)。robots 已在
1333
+ # 上方拦截,这里只做域名分流;need_html/actions/force_browser 同视频分支让路。
1334
+ if (_is_wechat_article_url(url) and not need_html and not actions
1335
+ and not force_browser):
1336
+ try:
1337
+ from wechat_article import fetch_wechat_article
1338
+ _wx = fetch_wechat_article(url)
1339
+ except Exception:
1340
+ _wx = None
1341
+ if _wx and _wx.get("ok"):
1342
+ _wx_result = {
1343
+ "url": url,
1344
+ "title": _wx.get("title") or "",
1345
+ "content": (_wx.get("content") or "")[:max_chars],
1346
+ "html": "",
1347
+ "length": int(_wx.get("char_count") or 0),
1348
+ "success": True,
1349
+ "fetch_method": "wechat:" + str(
1350
+ _wx.get("fetch_method") or "http_direct"),
1351
+ "author": _wx.get("author") or "",
1352
+ "publish_time": _wx.get("publish_time") or "",
1353
+ }
1354
+ try:
1355
+ _wx_result = _assess_quality(_wx_result)
1356
+ except Exception:
1357
+ pass
1358
+ _wx_result["cached"] = False
1359
+ return _strip_html_unless_needed(_wx_result, need_html)
1360
+ # 专用链三级全败即结构化失败、不落回通用链:通用链对 mp.weixin 只会拿
1361
+ # JS 骨架冒充成功(11-01 实测病灶);_has_content 保证到这里的是真失败。
1362
+ return _strip_html_unless_needed({
1363
+ "url": url,
1364
+ "title": "", "content": "", "html": "",
1365
+ "length": 0, "success": False,
1366
+ "error": (_wx or {}).get("error")
1367
+ or "微信公众号文章抓取失败(HTTP/浏览器/搜狗三通道均未取到正文)",
1368
+ "fetch_method": "wechat_failed",
1369
+ "cached": False,
1370
+ }, need_html)
1371
+
1303
1372
  # 登录态车道(A2):站点有 argo auth 持久 profile → 跳过匿名链直进浏览器。
1304
1373
  # 匿名 HTTP 对已登录站只会拿到「登出态」内容——那是成功的假象,比失败更糟。
1305
1374
  # 判断本体在 browser_auth(含开关与 use_browser_fallback=False 让路);
package/scripts/job.py CHANGED
@@ -734,9 +734,33 @@ def _search_jobspy(q: str, n: int) -> list:
734
734
  _MCPJ = {"proc": None, "id": 0}
735
735
  from argo_paths import platform_cache_default # noqa: E402
736
736
 
737
- MCPJOBS_DIR = os.environ.get("ARGO_MCPJOBS_DIR") or str(
738
- platform_cache_default() / "argo-mcpjobs")
739
- MCPJOBS_ENTRY = os.path.join(MCPJOBS_DIR, "node_modules", "mcp-jobs", "dist", "mcp.js")
737
+
738
+ def _mcpjobs_dir() -> str:
739
+ """mcp-jobs 安装根:模块属性(测试 patch 的真名)优先,否则按当前 env 解析。"""
740
+ patched = globals().get("MCPJOBS_DIR")
741
+ if patched is not None:
742
+ return patched
743
+ return os.environ.get("ARGO_MCPJOBS_DIR") or str(
744
+ platform_cache_default() / "argo-mcpjobs")
745
+
746
+
747
+ def _mcpjobs_entry() -> str:
748
+ return os.path.join(
749
+ _mcpjobs_dir(), "node_modules", "mcp-jobs", "dist", "mcp.js")
750
+
751
+
752
+ def __getattr__(name: str):
753
+ """`MCPJOBS_DIR`/`MCPJOBS_ENTRY` 按当前 ARGO_MCPJOBS_DIR 解析(PEP 562)。
754
+
755
+ 290d3d8 同口径:导入期绑定在 env 改写后(测试隔离临时目录、换缓存根)
756
+ 仍持旧值。模块内裸名查找不触发本函数(LOAD_GLOBAL 语义),函数体一律走
757
+ _mcpjobs_dir()/_mcpjobs_entry();这里只维持外部属性访问契约。
758
+ """
759
+ if name == "MCPJOBS_DIR":
760
+ return _mcpjobs_dir()
761
+ if name == "MCPJOBS_ENTRY":
762
+ return _mcpjobs_entry()
763
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
740
764
 
741
765
 
742
766
  def _mcpjobs_send(method: str, params: dict, timeout: int = 60) -> dict:
@@ -764,14 +788,15 @@ def _mcpjobs_ensure() -> bool:
764
788
  if _MCPJ["proc"] and _MCPJ["proc"].poll() is None:
765
789
  return True
766
790
  try:
767
- if not os.path.exists(MCPJOBS_ENTRY):
791
+ entry = _mcpjobs_entry()
792
+ if not os.path.exists(entry):
768
793
  r = subprocess.run(
769
- ["npm", "install", "--prefix", MCPJOBS_DIR, "--no-audit", "--no-fund",
794
+ ["npm", "install", "--prefix", _mcpjobs_dir(), "--no-audit", "--no-fund",
770
795
  "mcp-jobs"], capture_output=True, text=True, timeout=240,
771
796
  encoding="utf-8", errors="replace") # Windows GBK 控制台读 stderr 需显式 UTF-8
772
797
  if r.returncode != 0:
773
798
  raise RuntimeError(f"npm install mcp-jobs 失败:{(r.stderr or r.stdout)[:120]}")
774
- p = subprocess.Popen(["node", MCPJOBS_ENTRY],
799
+ p = subprocess.Popen(["node", entry],
775
800
  stdin=subprocess.PIPE, stdout=subprocess.PIPE,
776
801
  stderr=subprocess.DEVNULL, text=True, bufsize=1,
777
802
  encoding="utf-8", errors="replace") # node JSON-RPC 恒 UTF-8,Windows 默认 GBK 会对不上
@@ -919,7 +944,8 @@ def _mark_source_down(name: str, detail: str) -> None:
919
944
  """
920
945
  try:
921
946
  from quota import get_quota_manager
922
- get_quota_manager().mark_remote_exhausted(name, reason=detail[:160])
947
+ get_quota_manager().mark_remote_exhausted(
948
+ name, reason=detail[:160], category="quota_exhausted")
923
949
  except Exception:
924
950
  pass
925
951
 
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env python3
2
+ """lint_spec_contracts.py — 引擎规格契约 lint(声明层复发护栏)。
3
+
4
+ 背景:声明式引擎规格与消费层之间隔了四层契约(spec.search_args → CLI 实参
5
+ → 解析格式 → output_map/envelope 键),历史上反复出的事故都卡在「层与层
6
+ 之间没有机器校验」:
7
+ - 2026-10-27 bilibili.search_args 少传 --json,social_meta 在 JSON 解析前
8
+ 就不存在,三层各错一点(video P0)
9
+ - 2026-11-03 xhs CLI 未下发 --json,_parse_xhs_output 的 json.loads 失败
10
+ 静默返回空列表(issue #36)
11
+ 本 lint 不做运行时校验(那是引擎与用例的职责),只在声明层钉不变式,让同
12
+ 类规格在提交前被拦下。只读 YAML、零运行时导入,供门禁与
13
+ tests/test_spec_contracts.py 调用。
14
+
15
+ 不变式:
16
+ C1 type: cli 且声明了 output_map ⇒ search_args 必须显式请求机器可读输
17
+ 出(含 "json" 的旗标)或声明 output_format。output_map 是结构化输出
18
+ 的字段映射,人读文本流上它整体是死代码——spec 必须表态。
19
+ C2 结构完整性:type: cli 必须带 cmd;engine_id 必填且不得为空。
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import sys
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ SKILL_DIR = Path(__file__).resolve().parent.parent
29
+ SPECS_DIR = SKILL_DIR / "engines" / "specs"
30
+ CONFIG_PATH = SKILL_DIR / "config.yaml"
31
+
32
+ # C1 的显式豁免名单(engine_id):规格声明的 CLI 默认输出就是机器可读、
33
+ # 且无 --json 类旗标可传时,在此登记并注明依据。当前为空——出现新豁免
34
+ # 必须在行内写清实测依据,否则优先改 spec。
35
+ JSON_FLAG_EXEMPT: set[str] = set()
36
+
37
+
38
+ def load_specs() -> list[tuple[str, str, dict[str, Any]]]:
39
+ """收集声明式规格:(来源标签, engine_id, spec)。含 engines/specs/*.yaml
40
+ 与 config.yaml engines 段里的 dict 条目。读不了的文件计为一条结构违例。"""
41
+ out: list[tuple[str, str, dict[str, Any]]] = []
42
+ for p in sorted(SPECS_DIR.glob("*.yaml")):
43
+ try:
44
+ from yaml_load import loads
45
+
46
+ data = loads(p.read_text(encoding="utf-8"))
47
+ except Exception as e: # 坏 YAML 本身就是结构违例
48
+ out.append((f"specs/{p.name}", "", {"_load_error": str(e)}))
49
+ continue
50
+ if isinstance(data, dict):
51
+ out.append((f"specs/{p.name}", str(data.get("engine_id", "")), data))
52
+ try:
53
+ from yaml_load import loads
54
+
55
+ cfg = loads(CONFIG_PATH.read_text(encoding="utf-8")) or {}
56
+ except Exception:
57
+ cfg = {}
58
+ for name, spec in (cfg.get("engines") or {}).items():
59
+ if isinstance(spec, dict) and spec.get("type") == "cli":
60
+ out.append(("config.yaml", str(name), spec))
61
+ return out
62
+
63
+
64
+ def lint_specs(specs: list[tuple[str, str, dict[str, Any]]]) -> list[str]:
65
+ """返回违例列表(空 = 通过)。每条带不变式编号与文件出处。"""
66
+ violations: list[str] = []
67
+ for origin, engine_id, spec in specs:
68
+ where = f"{origin}:{engine_id or '?'}"
69
+ if spec.get("_load_error"):
70
+ violations.append(f"C2 {where}: YAML 解析失败 {spec['_load_error']}")
71
+ continue
72
+ etype = spec.get("type")
73
+ # C2 结构完整性
74
+ if etype == "cli":
75
+ cmd = spec.get("cmd")
76
+ if not cmd or (isinstance(cmd, list) and not cmd):
77
+ violations.append(f"C2 {where}: type: cli 缺 cmd,规格永远发不出请求")
78
+ if not str(engine_id or "").strip() and origin.startswith("specs/"):
79
+ violations.append(f"C2 {origin}: 缺 engine_id")
80
+ # C1 机器可读输出契约
81
+ if etype == "cli":
82
+ omap = spec.get("output_map")
83
+ if isinstance(omap, dict) and omap and engine_id not in JSON_FLAG_EXEMPT:
84
+ args = [str(a) for a in (spec.get("search_args") or [])]
85
+ fmt = str(spec.get("output_format", "")).strip().lower()
86
+ asks_machine_readable = fmt in ("json", "yaml") or any(
87
+ "json" in a.lower() for a in args
88
+ )
89
+ if not asks_machine_readable:
90
+ violations.append(
91
+ f"C1 {where}: 声明了 output_map 但 search_args 未请求 "
92
+ f"JSON 且未声明 output_format——人读文本流上 output_map "
93
+ f"整体是死代码(bilibili/xhs 同类根因)"
94
+ )
95
+ return violations
96
+
97
+
98
+ def main(argv: list[str] | None = None) -> int:
99
+ violations = lint_specs(load_specs())
100
+ if violations:
101
+ for v in violations:
102
+ print(f"❌ {v}", file=sys.stderr)
103
+ print(f"spec 契约 lint:{len(violations)} 条违例", file=sys.stderr)
104
+ return 1
105
+ print(f"✅ spec 契约一致({len(load_specs())} 份规格)")
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ sys.exit(main())