argo-search 2.16.0 → 2.18.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 (126) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.es.md +15 -5
  3. package/README.ja.md +15 -5
  4. package/README.ko.md +15 -5
  5. package/README.md +16 -6
  6. package/README.zh.md +16 -6
  7. package/SKILL.md +12 -11
  8. package/assets/readme/counts.json +1 -1
  9. package/assets/readme/hero.svg +3 -3
  10. package/assets/readme/hero.template.svg +121 -0
  11. package/assets/readme/proof-routes.svg +17 -16
  12. package/backends/domain_profiles.json +121 -18
  13. package/backends/engine_registry.yaml +23 -0
  14. package/backends/env_passthrough.txt +2 -0
  15. package/backends/quota_profiles.json +20 -0
  16. package/bin/argo +78 -12
  17. package/docs/CHANGELOG.md +35 -1
  18. package/docs/COMMIT_STANDARD.md +12 -2
  19. package/docs/ENGINE_CATALOG.md +36 -33
  20. package/docs/RELEASE_NOTES_v2.17.0.md +66 -0
  21. package/docs/RELEASE_NOTES_v2.18.0.md +87 -0
  22. package/docs/RELEASING.md +2 -2
  23. package/engines/specs/crossref.yaml +2 -0
  24. package/engines/specs/hackernews.yaml +2 -0
  25. package/engines/specs/helve.yaml +49 -0
  26. package/engines/specs/hf_papers.yaml +2 -0
  27. package/engines/specs/openalex.yaml +9 -2
  28. package/engines/specs/twitter_cli.yaml +17 -0
  29. package/engines/specs/twitter_syndication.yaml +2 -3
  30. package/package.json +3 -1
  31. package/packages/dsh-plugin/README.md +5 -2
  32. package/packages/dsh-plugin/cordis.patch.yml +4 -1
  33. package/packages/dsh-plugin/dsh/client.js +57 -63
  34. package/packages/dsh-plugin/dsh/diagnostics.js +25 -4
  35. package/packages/dsh-plugin/dsh/index.js +109 -21
  36. package/packages/dsh-plugin/dsh/native-tools.mjs +10 -0
  37. package/packages/dsh-plugin/dsh/route-guard.js +95 -0
  38. package/packages/dsh-plugin/dsh/runner.js +49 -6
  39. package/packages/dsh-plugin/dsh/wide-research.js +20 -18
  40. package/packages/dsh-plugin/dsh/workbench-client.js +119 -20
  41. package/packages/dsh-plugin/dsh/workbench-io.js +182 -0
  42. package/packages/dsh-plugin/dsh/workbench-search.js +445 -0
  43. package/packages/dsh-plugin/dsh/workbench-suggestions.js +387 -75
  44. package/packages/dsh-plugin/dsh/workbench.js +277 -497
  45. package/packages/dsh-plugin/package.json +4 -3
  46. package/packages/dsh-plugin/scripts/sync-local.mjs +4 -2
  47. package/packages/dsh-plugin/scripts/sync-local.sh +4 -2
  48. package/packages/dsh-plugin/test/client.test.js +26 -0
  49. package/packages/dsh-plugin/test/diagnostics.test.js +5 -2
  50. package/packages/dsh-plugin/test/index.test.js +150 -1
  51. package/packages/dsh-plugin/test/workbench-concurrency.test.js +96 -0
  52. package/packages/dsh-plugin/test/workbench.test.js +422 -9
  53. package/scripts/adaptive.py +13 -11
  54. package/scripts/affected_tests.py +324 -0
  55. package/scripts/badcase_ledger.py +93 -2
  56. package/scripts/browser_auth.py +178 -4
  57. package/scripts/cache.py +68 -69
  58. package/scripts/check_commit_report.py +59 -9
  59. package/scripts/chrome_cdp.py +71 -0
  60. package/scripts/circuit_breaker.py +77 -12
  61. package/scripts/cli_io.py +8 -3
  62. package/scripts/config_cache.py +4 -3
  63. package/scripts/daemon.py +9 -2
  64. package/scripts/engine_add.py +45 -0
  65. package/scripts/engine_dispatch.py +27 -47
  66. package/scripts/engine_failure.py +33 -0
  67. package/scripts/engine_families.py +1 -0
  68. package/scripts/engine_fingerprint.py +114 -0
  69. package/scripts/engine_health.py +130 -0
  70. package/scripts/engine_states.py +54 -4
  71. package/scripts/engines.py +2 -0
  72. package/scripts/engines_base.py +19 -44
  73. package/scripts/engines_builders_intl.py +20 -94
  74. package/scripts/engines_builders_search.py +19 -8
  75. package/scripts/engines_builders_tech.py +16 -16
  76. package/scripts/engines_fields.py +23 -0
  77. package/scripts/engines_twitter_cli.py +182 -0
  78. package/scripts/evidence_grounding.py +182 -0
  79. package/scripts/fetch_browser.py +25 -10
  80. package/scripts/fetch_cli_output.py +75 -0
  81. package/scripts/fetch_dispatch.py +248 -0
  82. package/scripts/fetch_quality.py +11 -0
  83. package/scripts/fetch_v3.py +48 -114
  84. package/scripts/gate_manifest_check.py +75 -0
  85. package/scripts/gen_readme_art.py +264 -0
  86. package/scripts/intent_router.py +224 -0
  87. package/scripts/mcp_compact.py +3 -0
  88. package/scripts/mcp_handlers.py +24 -4
  89. package/scripts/mcp_tools.py +2 -0
  90. package/scripts/mcp_transport.py +24 -5
  91. package/scripts/mcp_warm.py +15 -11
  92. package/scripts/numeric_verify.py +9 -0
  93. package/scripts/output_transparency.py +10 -0
  94. package/scripts/pre-commit +65 -8
  95. package/scripts/query_operators.py +229 -1
  96. package/scripts/quota.py +19 -37
  97. package/scripts/release.py +16 -1
  98. package/scripts/release_check.py +1 -2
  99. package/scripts/research_gates.py +85 -1
  100. package/scripts/research_notes.py +52 -5
  101. package/scripts/retry_policy.py +17 -3
  102. package/scripts/route_combo.py +21 -4
  103. package/scripts/search.py +29 -29
  104. package/scripts/search_cli.py +104 -8
  105. package/scripts/search_output.py +4 -1
  106. package/scripts/social_research.py +8 -6
  107. package/scripts/source_discovery.py +611 -0
  108. package/scripts/sync_backends.py +45 -0
  109. package/scripts/time_utils.py +28 -0
  110. package/scripts/twitter_single_read.py +107 -0
  111. package/scripts/x_keyword_route.py +138 -0
  112. package/scripts/x_search.py +24 -33
  113. package/scripts/zhihu_answer_body.py +96 -0
  114. package/scripts/zhihu_answer_fetch.py +66 -0
  115. package/scripts/zhihu_answer_lookup.py +138 -0
  116. package/sub-skills/ego-search/README.md +9 -0
  117. package/sub-skills/ego-search/scripts/ego_search.py +182 -15
  118. package/sub-skills/ego-search/scripts/pacing.py +291 -0
  119. package/sub-skills/ego-search/scripts/quality.py +262 -6
  120. package/sub-skills/ego-search/scripts/runtime.py +7 -1
  121. package/sub-skills/ego-search/scripts/site_profiles.py +157 -0
  122. package/sub-skills/ego-search/scripts/webbridge_adapter.py +7 -1
  123. package/sub-skills/local-seek/SKILL.md +3 -1
  124. package/sub-skills/local-seek/scripts/seek.py +80 -109
  125. package/sub-skills/local-seek/scripts/seek_git.py +65 -0
  126. package/sub-skills/local-seek/scripts/seek_inspect.py +242 -0
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env python3
2
+ """affected_tests.py — L2 变更感知增量选测引擎。
3
+
4
+ 定位(MECE 三层测试分流):
5
+ - L1 全局硬契约门:tests/gate_manifest.txt(每次 commit 必全跑);
6
+ - L2 变更感知选测:本脚本按 git 改动模块反查 343 个未入册单测中的受影响子集,
7
+ 在严格时间预算内随 pre-commit 自动执行,补齐「本地绿、全量红」盲区;
8
+ - L3 全量回归:pytest tests/ -q(发版前或 CI 运行)。
9
+
10
+ 判定规则(纯标准库 AST,无外部依赖):
11
+ 1. 扫描 scripts/ 与 tests/test_*.py 的静态 import / from-import 关系;
12
+ 2. 对改动模块沿反向依赖图做最多 2 跳传递展开,找出导入它们的未入册测试;
13
+ 3. 叠加文件名 stem 启发式召回(如 scripts/foo.py → tests/test_foo*.py),
14
+ 覆盖通过 importlib 动态加载的测试;
15
+ 4. 排除已在 gate_manifest.txt 中的 L1 测试(避免重复执行),按
16
+ tests/.test_durations 历史耗时升序挑选,单文件超阈值或超总预算的慢测
17
+ 显式跳过并打印提示,留给 L3 全量回归。
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import ast
24
+ import json
25
+ import subprocess
26
+ import sys
27
+ from collections import defaultdict, deque
28
+ from pathlib import Path
29
+ from typing import Iterable
30
+
31
+ ROOT = Path(__file__).resolve().parent.parent
32
+ SCRIPTS_DIR = ROOT / "scripts"
33
+ TESTS_DIR = ROOT / "tests"
34
+ MANIFEST_PATH = TESTS_DIR / "gate_manifest.txt"
35
+ DURATIONS_PATH = TESTS_DIR / ".test_durations"
36
+
37
+
38
+ def extract_imported_modules(path: Path) -> set[str]:
39
+ """用 AST 提取 Python 文件中直接导入的顶层/子模块名。"""
40
+ try:
41
+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"), filename=str(path))
42
+ except (OSError, SyntaxError, ValueError):
43
+ return set()
44
+ mods: set[str] = set()
45
+ for node in ast.walk(tree):
46
+ if isinstance(node, ast.Import):
47
+ for alias in node.names:
48
+ name = alias.name
49
+ mods.add(name)
50
+ mods.add(name.split(".", 1)[0])
51
+ elif isinstance(node, ast.ImportFrom) and node.module:
52
+ mods.add(node.module)
53
+ mods.add(node.module.split(".", 1)[0])
54
+ for alias in node.names:
55
+ if alias.name != "*":
56
+ mods.add(f"{node.module}.{alias.name}")
57
+ return mods
58
+
59
+
60
+ def load_manifest_entries(manifest_path: Path = MANIFEST_PATH) -> set[str]:
61
+ """读取 L1 gate_manifest.txt 中已登记的测试相对路径集合。"""
62
+ if not manifest_path.is_file():
63
+ return set()
64
+ entries: set[str] = set()
65
+ for raw in manifest_path.read_text(encoding="utf-8").splitlines():
66
+ line = raw.strip()
67
+ if line and not line.startswith("#"):
68
+ entries.add(line)
69
+ return entries
70
+
71
+
72
+ def load_file_durations(durations_path: Path = DURATIONS_PATH) -> dict[str, float]:
73
+ """将 tests/.test_durations 按测试文件聚合为 {rel_path: total_seconds}。"""
74
+ if not durations_path.is_file():
75
+ return {}
76
+ try:
77
+ raw = json.loads(durations_path.read_text(encoding="utf-8"))
78
+ except (OSError, json.JSONDecodeError, ValueError):
79
+ return {}
80
+ totals: dict[str, float] = defaultdict(float)
81
+ if isinstance(raw, dict):
82
+ for nodeid, secs in raw.items():
83
+ if not isinstance(nodeid, str) or not isinstance(secs, (int, float)):
84
+ continue
85
+ rel = nodeid.split("::", 1)[0]
86
+ totals[rel] += float(secs)
87
+ return dict(totals)
88
+
89
+
90
+ def _path_to_module_names(rel_path: str) -> set[str]:
91
+ """将仓内脚本路径转为可能的 import 模块名集合。"""
92
+ p = Path(rel_path)
93
+ if p.suffix != ".py":
94
+ return set()
95
+ parts = p.parts
96
+ names: set[str] = set()
97
+ if len(parts) >= 2 and parts[0] == "scripts":
98
+ sub = parts[1:]
99
+ stem_parts = list(sub[:-1]) + [p.stem]
100
+ if p.stem == "__init__" and len(stem_parts) >= 2:
101
+ stem_parts = stem_parts[:-1]
102
+ dotted = ".".join(stem_parts)
103
+ if dotted:
104
+ names.add(dotted)
105
+ names.add(stem_parts[-1])
106
+ names.add(f"scripts.{dotted}")
107
+ else:
108
+ names.add(p.stem)
109
+ return names
110
+
111
+
112
+ def build_reverse_script_graph(scripts_dir: Path = SCRIPTS_DIR) -> dict[str, set[str]]:
113
+ """构建 scripts/ 内部的反向依赖图:{被导入模块: {导入它的模块, ...}}。"""
114
+ rev: dict[str, set[str]] = defaultdict(set)
115
+ if not scripts_dir.is_dir():
116
+ return rev
117
+ for py in sorted(scripts_dir.rglob("*.py")):
118
+ rel = py.relative_to(scripts_dir.parent).as_posix()
119
+ mod_names = _path_to_module_names(rel)
120
+ if not mod_names:
121
+ continue
122
+ imported = extract_imported_modules(py)
123
+ for dep in imported:
124
+ rev[dep].update(mod_names)
125
+ return rev
126
+
127
+
128
+ def expand_affected_modules(
129
+ changed_files: Iterable[str],
130
+ reverse_graph: dict[str, set[str]],
131
+ *,
132
+ max_hops: int = 2,
133
+ ) -> tuple[set[str], set[str]]:
134
+ """展开改动文件对应的模块集合及直接改动测试集合。
135
+
136
+ 返回 (受影响模块名集合, 直接改动的测试文件相对路径集合)。
137
+ """
138
+ seeds: set[str] = set()
139
+ direct_tests: set[str] = set()
140
+ for raw in changed_files:
141
+ norm = Path(raw).as_posix().lstrip("./")
142
+ if norm.startswith("tests/test_") and norm.endswith(".py"):
143
+ direct_tests.add(norm)
144
+ elif norm.startswith("scripts/") and norm.endswith(".py"):
145
+ seeds.update(_path_to_module_names(norm))
146
+
147
+ visited = set(seeds)
148
+ queue: deque[tuple[str, int]] = deque((m, 0) for m in seeds)
149
+ while queue:
150
+ mod, hop = queue.popleft()
151
+ if hop >= max_hops:
152
+ continue
153
+ for dependent in reverse_graph.get(mod, ()):
154
+ if dependent not in visited:
155
+ visited.add(dependent)
156
+ queue.append((dependent, hop + 1))
157
+ return visited, direct_tests
158
+
159
+
160
+ def select_affected_tests(
161
+ changed_files: Iterable[str],
162
+ *,
163
+ root: Path = ROOT,
164
+ manifest_entries: set[str] | None = None,
165
+ file_durations: dict[str, float] | None = None,
166
+ budget_seconds: float = 8.0,
167
+ max_single_seconds: float = 3.0,
168
+ max_files: int = 12,
169
+ max_hops: int = 2,
170
+ ) -> dict[str, object]:
171
+ """根据改动文件列表,筛选应执行的 L2 未入册测试。"""
172
+ scripts_dir = root / "scripts"
173
+ tests_dir = root / "tests"
174
+ manifest = load_manifest_entries(tests_dir / "gate_manifest.txt") if manifest_entries is None else manifest_entries
175
+ durations = load_file_durations(tests_dir / ".test_durations") if file_durations is None else file_durations
176
+
177
+ rev_graph = build_reverse_script_graph(scripts_dir)
178
+ affected_mods, direct_tests = expand_affected_modules(
179
+ changed_files, rev_graph, max_hops=max_hops,
180
+ )
181
+
182
+ # 改动脚本的原始模块名与 stem(优先于间接传递依赖进入预算)
183
+ direct_mods: set[str] = set()
184
+ changed_stems: set[str] = set()
185
+ for f in changed_files:
186
+ norm = Path(f).as_posix().lstrip("./")
187
+ if norm.startswith("scripts/") and norm.endswith(".py"):
188
+ direct_mods.update(_path_to_module_names(norm))
189
+ if Path(norm).stem != "__init__":
190
+ changed_stems.add(Path(norm).stem)
191
+
192
+ direct_candidates: set[str] = set()
193
+ transitive_candidates: set[str] = set()
194
+ for rel in direct_tests:
195
+ if rel not in manifest and (root / rel).is_file():
196
+ direct_candidates.add(rel)
197
+
198
+ if (affected_mods or changed_stems) and tests_dir.is_dir():
199
+ for test_file in sorted(tests_dir.glob("test_*.py")):
200
+ rel = f"tests/{test_file.name}"
201
+ if rel in manifest or rel in direct_candidates:
202
+ continue
203
+ stem_hit = any(
204
+ test_file.stem == f"test_{s}" or test_file.stem.startswith(f"test_{s}_")
205
+ for s in changed_stems
206
+ )
207
+ if stem_hit:
208
+ direct_candidates.add(rel)
209
+ continue
210
+ imported = extract_imported_modules(test_file)
211
+ if direct_mods and (imported & direct_mods):
212
+ direct_candidates.add(rel)
213
+ elif affected_mods and (imported & affected_mods):
214
+ transitive_candidates.add(rel)
215
+
216
+ # 直接相关测试优先,同层内按历史耗时升序(无历史记录默认估 0.5s)
217
+ scored = sorted(
218
+ direct_candidates | transitive_candidates,
219
+ key=lambda r: (0 if r in direct_candidates else 1, durations.get(r, 0.5), r),
220
+ )
221
+ selected: list[str] = []
222
+ skipped_slow: list[dict[str, object]] = []
223
+ est_total = 0.0
224
+
225
+ for rel in scored:
226
+ est = round(durations.get(rel, 0.5), 3)
227
+ if est > max_single_seconds:
228
+ skipped_slow.append({"file": rel, "est_seconds": est, "reason": "single_file_slow"})
229
+ continue
230
+ if len(selected) >= max_files or (selected and est_total + est > budget_seconds):
231
+ skipped_slow.append({"file": rel, "est_seconds": est, "reason": "budget_exceeded"})
232
+ continue
233
+ selected.append(rel)
234
+ est_total += est
235
+
236
+ return {
237
+ "selected": selected,
238
+ "skipped": skipped_slow,
239
+ "estimated_seconds": round(est_total, 3),
240
+ "affected_modules_count": len(affected_mods),
241
+ }
242
+
243
+
244
+ def git_changed_files(*, staged: bool = False, diff_ref: str | None = None, root: Path = ROOT) -> list[str]:
245
+ """获取 git 暂存区或相对 ref 的改动文件列表。"""
246
+ if staged:
247
+ cmd = ["git", "diff", "--cached", "--name-only", "--diff-filter=ACMR"]
248
+ elif diff_ref:
249
+ cmd = ["git", "diff", "--name-only", "--diff-filter=ACMR", diff_ref]
250
+ else:
251
+ cmd = ["git", "status", "--porcelain"]
252
+ proc = subprocess.run(
253
+ cmd, cwd=str(root), capture_output=True, text=True,
254
+ encoding="utf-8", errors="replace", check=False,
255
+ )
256
+ if proc.returncode != 0:
257
+ return []
258
+ files: list[str] = []
259
+ for line in proc.stdout.splitlines():
260
+ s = line.strip()
261
+ if not s:
262
+ continue
263
+ if not staged and not diff_ref:
264
+ s = s[3:].strip()
265
+ files.append(s)
266
+ return files
267
+
268
+
269
+ def main(argv: list[str] | None = None) -> int:
270
+ ap = argparse.ArgumentParser(description="L2 变更感知增量选测(补齐未入册单测盲区)")
271
+ ap.add_argument("--staged", action="store_true", help="读取 git staged 改动文件")
272
+ ap.add_argument("--diff-ref", default=None, help="对比指定 git ref 的改动文件(如 HEAD~1)")
273
+ ap.add_argument("--files", nargs="*", default=None, help="显式指定改动文件列表")
274
+ ap.add_argument("--budget", type=float, default=8.0, help="L2 选测总耗时预算(秒,默认 8.0)")
275
+ ap.add_argument("--max-single", type=float, default=3.0, help="单文件最大允许预估耗时(秒)")
276
+ ap.add_argument("--max-files", type=int, default=12, help="单次最多执行的 L2 文件数")
277
+ ap.add_argument("--json", action="store_true", dest="as_json", help="JSON 格式输出")
278
+ ap.add_argument("--run", action="store_true", help="直接用当前解释器执行选中的 L2 测试")
279
+ args = ap.parse_args(argv)
280
+
281
+ if args.files is not None:
282
+ changed = list(args.files)
283
+ else:
284
+ changed = git_changed_files(staged=args.staged, diff_ref=args.diff_ref)
285
+
286
+ plan = select_affected_tests(
287
+ changed,
288
+ budget_seconds=args.budget,
289
+ max_single_seconds=args.max_single,
290
+ max_files=args.max_files,
291
+ )
292
+
293
+ if args.as_json and not args.run:
294
+ print(json.dumps(plan, ensure_ascii=False))
295
+ return 0
296
+
297
+ selected: list[str] = plan["selected"] # type: ignore[assignment]
298
+ skipped: list[dict[str, object]] = plan["skipped"] # type: ignore[assignment]
299
+
300
+ if not args.run:
301
+ for rel in selected:
302
+ print(rel)
303
+ return 0
304
+
305
+ if not selected:
306
+ if skipped:
307
+ print(f"[L2-affected] 无预算内增量单测(跳过 {len(skipped)} 个慢测,留给 L3 全量回归)")
308
+ return 0
309
+
310
+ print(
311
+ f"[L2-affected] 变更命中 {len(selected)} 个未入册单测"
312
+ f"(预估 {plan['estimated_seconds']}s,跳过 {len(skipped)} 个慢测): "
313
+ + ", ".join(selected)
314
+ )
315
+ proc = subprocess.run(
316
+ [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", *selected],
317
+ cwd=str(ROOT),
318
+ check=False,
319
+ )
320
+ return proc.returncode
321
+
322
+
323
+ if __name__ == "__main__":
324
+ sys.exit(main())
@@ -470,10 +470,23 @@ def stats() -> dict:
470
470
  "SELECT engine, COUNT(*) FROM badcases WHERE engine != ''"
471
471
  " GROUP BY engine ORDER BY COUNT(*) DESC LIMIT 8").fetchall())
472
472
  total = con.execute("SELECT COUNT(*) FROM badcases").fetchone()[0]
473
+ rec_no_strategy = con.execute(
474
+ "SELECT COUNT(*) FROM badcases WHERE kind = 'recovery' "
475
+ "AND detail LIKE 'level=None strategy=None%'"
476
+ ).fetchone()[0]
473
477
  finally:
474
478
  con.close()
475
- return {"total": total, "by_kind": by_kind, "top_engines": by_engine,
476
- "by_root_cause": root_cause_stats()}
479
+ rec_total = int(by_kind.get("recovery", 0))
480
+ return {
481
+ "total": total,
482
+ "by_kind": by_kind,
483
+ "recovery_breakdown": {
484
+ "no_strategy": rec_no_strategy,
485
+ "strategy_failed": max(0, rec_total - rec_no_strategy),
486
+ },
487
+ "top_engines": by_engine,
488
+ "by_root_cause": root_cause_stats(),
489
+ }
477
490
 
478
491
 
479
492
  # ── LESSONS.md 导出 ─────────────────────────────────────────────────────────
@@ -625,6 +638,76 @@ def overview() -> dict[str, Any]:
625
638
  return out
626
639
 
627
640
 
641
+ def propose_actions(
642
+ *,
643
+ min_count: int = 5,
644
+ min_days: int = 3,
645
+ rows: list[dict[str, Any]] | None = None,
646
+ engines_cfg: dict[str, dict[str, Any]] | None = None,
647
+ ) -> dict[str, Any]:
648
+ """将坏例账本转化为可审阅的自动降级/治理提案(只读,不自动改配置)。
649
+
650
+ 聚焦「仍在自动路由池(非 explicit_only)且跨多日高频失败」的单引擎:
651
+ - unattributed 占比最高 → fix_attribution(补齐异常归因)
652
+ - quota_exhausted / rate_limited / auth_expired → demote_to_explicit_only
653
+ - 其余持续网络/故障 → review_or_demote
654
+ """
655
+ if rows is None:
656
+ rows = [dict(r) for r in _fetch(None, None, 10000)]
657
+ if engines_cfg is None:
658
+ try:
659
+ from config import get_engines
660
+ engines_cfg = get_engines()
661
+ except (ImportError, OSError, ValueError):
662
+ engines_cfg = {}
663
+
664
+ per_engine: dict[str, dict[str, Any]] = {}
665
+ for r in rows:
666
+ eng_raw = str(r.get("engine") or "").strip()
667
+ if not eng_raw or "," in eng_raw:
668
+ continue
669
+ rc = str(r.get("root_cause") or "unattributed")
670
+ day = str(r.get("ts") or "")[:10]
671
+ bucket = per_engine.setdefault(eng_raw, {"count": 0, "days": set(), "causes": {}})
672
+ bucket["count"] += 1
673
+ if len(day) == 10:
674
+ bucket["days"].add(day)
675
+ bucket["causes"][rc] = bucket["causes"].get(rc, 0) + 1
676
+
677
+ proposals: list[dict[str, Any]] = []
678
+ for eng, info in sorted(per_engine.items(), key=lambda kv: (-kv[1]["count"], kv[0])):
679
+ cnt = info["count"]
680
+ day_cnt = len(info["days"])
681
+ if cnt < min_count or day_cnt < min_days:
682
+ continue
683
+ spec = engines_cfg.get(eng) if isinstance(engines_cfg, dict) else None
684
+ if isinstance(spec, dict) and spec.get("explicit_only"):
685
+ continue
686
+ top_cause = max(info["causes"].items(), key=lambda kv: kv[1])[0]
687
+ if top_cause == "unattributed":
688
+ action = "fix_attribution"
689
+ elif top_cause in ("quota_exhausted", "rate_limited", "auth_expired"):
690
+ action = "demote_to_explicit_only"
691
+ else:
692
+ action = "review_or_demote"
693
+ proposals.append({
694
+ "engine": eng,
695
+ "count": cnt,
696
+ "seen_days": day_cnt,
697
+ "top_root_cause": top_cause,
698
+ "causes": info["causes"],
699
+ "recommended_action": action,
700
+ "in_registry": isinstance(spec, dict),
701
+ })
702
+
703
+ return {
704
+ "min_count": min_count,
705
+ "min_days": min_days,
706
+ "proposal_count": len(proposals),
707
+ "proposals": proposals,
708
+ }
709
+
710
+
628
711
  def main(argv: list[str] | None = None) -> int:
629
712
  ap = argparse.ArgumentParser(description="坏例账本(badcase 管理)")
630
713
  sub = ap.add_subparsers(dest="cmd", required=True)
@@ -636,6 +719,9 @@ def main(argv: list[str] | None = None) -> int:
636
719
  p_list.add_argument("--limit", type=int, default=10)
637
720
  sub.add_parser("stats")
638
721
  sub.add_parser("overview")
722
+ p_propose = sub.add_parser("propose")
723
+ p_propose.add_argument("--min-count", type=int, default=5)
724
+ p_propose.add_argument("--min-days", type=int, default=3)
639
725
  p_check = sub.add_parser("check")
640
726
  p_check.add_argument("--since", default="7d")
641
727
  p_check.add_argument("--max", type=int, default=50)
@@ -661,6 +747,11 @@ def main(argv: list[str] | None = None) -> int:
661
747
  print("[overview] dormant_sources 取数失败(见输出 error 字段)",
662
748
  file=sys.stderr)
663
749
  return 1
750
+ elif args.cmd == "propose":
751
+ print(json.dumps(
752
+ propose_actions(min_count=args.min_count, min_days=args.min_days),
753
+ ensure_ascii=False,
754
+ ))
664
755
  elif args.cmd == "check":
665
756
  report = check(args.since, args.max, args.promote_days)
666
757
  print(json.dumps(report, ensure_ascii=False))
@@ -105,6 +105,7 @@ def _read_meta(d: Path) -> dict:
105
105
 
106
106
  def _write_meta(d: Path, host: str, created: str | None = None) -> None:
107
107
  """原子写 meta.json:profile 的 argo 登记标记(Chrome 不认识也不在乎它)。"""
108
+ import argo_paths
108
109
  prev = _read_meta(d)
109
110
  meta = {
110
111
  "site": host,
@@ -112,9 +113,7 @@ def _write_meta(d: Path, host: str, created: str | None = None) -> None:
112
113
  "last_used": time.strftime("%Y-%m-%dT%H:%M:%S"),
113
114
  "argo": "browser-profiles/v1",
114
115
  }
115
- tmp = d / f"meta.json.tmp.{os.getpid()}"
116
- tmp.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
117
- os.replace(tmp, d / "meta.json")
116
+ argo_paths.atomic_write_json(d / "meta.json", meta)
118
117
 
119
118
 
120
119
  def profile_for(url_or_host: str) -> str | None:
@@ -174,6 +173,7 @@ def login(url_or_host: str, chrome_path: str | None = None,
174
173
  msg += "(该 profile 可能已有 Chrome 在跑:关掉它或先 argo auth logout)"
175
174
  return {"ok": False, "site": host, "error": msg[:200]}
176
175
 
176
+ saved = False
177
177
  try:
178
178
  if confirm is None:
179
179
  print(f"\n[{host}] 已在打开的 Chrome 窗口中登录/扫码。", file=sys.stderr)
@@ -186,12 +186,15 @@ def login(url_or_host: str, chrome_path: str | None = None,
186
186
  else:
187
187
  confirm()
188
188
  _write_meta(d, host)
189
+ saved = True
189
190
  return {"ok": True, "site": host, "profile": str(d)}
190
191
  finally:
191
192
  try:
192
193
  proc.stop()
193
194
  except Exception:
194
195
  pass
196
+ if fresh and not saved:
197
+ shutil.rmtree(d, ignore_errors=True)
195
198
 
196
199
 
197
200
  def status() -> list[dict]:
@@ -246,6 +249,162 @@ def touch(url_or_host: str) -> None:
246
249
  pass
247
250
 
248
251
 
252
+ # ─── 四态防抖判别、活体会话校验与评论上下文封顶 ─────────────────────────────
253
+
254
+ _SEC_VERIFY_URL_RE = re.compile(r"captcha|security[._-]?verif|challenge|/account/access", re.I)
255
+ _SEC_VERIFY_TEXT_RE = re.compile(
256
+ r"安全验证|安全限制|IP存在风险|访问受限|异常访问|操作频繁|请完成验证|verify you are human",
257
+ re.I,
258
+ )
259
+ _SIGNED_OUT_URL_RE = re.compile(r"website-login|/i/flow/login|/login(?:/|\?|$)|/signin(?:/|\?|$)", re.I)
260
+ _LOGIN_WALL_TEXT_RE = re.compile(
261
+ r"登录后推荐更懂你的笔记|登录后查看|请先登录|立即登录以继续|log in to continue|sign in to view",
262
+ re.I,
263
+ )
264
+
265
+
266
+ def detect_page_auth_state(
267
+ url: str,
268
+ title: str = "",
269
+ body_text: str = "",
270
+ *,
271
+ has_security_modal: bool = False,
272
+ has_login_modal: bool = False,
273
+ after_search: bool = False,
274
+ ) -> str:
275
+ """四态(+搜索受限)判别纯函数:全部返回 engine_states.PAGE_AUTH_* 常量。"""
276
+ import engine_states as _es
277
+
278
+ # 入口统一收敛 str:调用方可能传非 str(测试桩的 MagicMock 等),
279
+ # regex 收到非 str 会 TypeError 顺异常链拖垮整条 fetch
280
+ # (tests/test_fetch_auth_lane.py::test_browser_fetch_marks_login_provenance 回归)。
281
+ href = str(url) if url else ""
282
+ combined = "{}\n{}".format(str(title or ""), str(body_text or "")[:4000])
283
+ if has_security_modal or _SEC_VERIFY_URL_RE.search(href) or _SEC_VERIFY_TEXT_RE.search(combined):
284
+ return _es.PAGE_AUTH_SECURITY_VERIFY
285
+ if _SIGNED_OUT_URL_RE.search(href):
286
+ return _es.PAGE_AUTH_SIGNED_OUT
287
+ if has_login_modal or _LOGIN_WALL_TEXT_RE.search(combined):
288
+ return _es.PAGE_AUTH_SEARCH_RESTRICTED if after_search else _es.PAGE_AUTH_LOGIN_WALL
289
+ return _es.PAGE_AUTH_READY
290
+
291
+
292
+ def wait_for_stable_page_auth_state(
293
+ probe_fn,
294
+ *,
295
+ settle_s: float = 0.6,
296
+ interval_s: float = 0.25,
297
+ consecutive: int = 3,
298
+ max_samples: int = 7,
299
+ sleep_fn=time.sleep,
300
+ ) -> str:
301
+ """多帧防抖状态机:连续 consecutive 次观测一致才裁决,避免 SPA 水合瞬间误判。"""
302
+ import engine_states as _es
303
+
304
+ if settle_s > 0:
305
+ sleep_fn(settle_s)
306
+ last: str | None = None
307
+ repeated = 0
308
+ for idx in range(max(1, max_samples)):
309
+ current = probe_fn()
310
+ if current == last:
311
+ repeated += 1
312
+ else:
313
+ last = current
314
+ repeated = 1
315
+ if repeated >= max(1, consecutive):
316
+ return current
317
+ if interval_s > 0 and idx + 1 < max_samples:
318
+ sleep_fn(interval_s)
319
+ return last or _es.PAGE_AUTH_SIGNED_OUT
320
+
321
+
322
+ def verify_live_session(
323
+ url_or_host: str,
324
+ *,
325
+ cdp_factory=None,
326
+ timeout: float = 10.0,
327
+ settle_s: float = 0.6,
328
+ interval_s: float = 0.25,
329
+ ) -> dict:
330
+ """活体会话校验:确认持久 profile 存在且打开页面后经多帧防抖处于 PAGE_AUTH_READY。"""
331
+ import engine_states as _es
332
+
333
+ host = site_host(url_or_host)
334
+ prof = profile_for(host)
335
+ if not prof:
336
+ return {
337
+ "ok": False, "site": host, "state": _es.PAGE_AUTH_SIGNED_OUT,
338
+ "retryable": False, "handoff_required": True,
339
+ "error": f"未找到 {host} 的登录态 profile(请先 argo auth login {host})",
340
+ }
341
+ target = url_or_host.strip()
342
+ if "://" not in target:
343
+ target = "https://" + target
344
+
345
+ if cdp_factory is None:
346
+ from chrome_cdp import ChromeCDP
347
+ cdp_factory = lambda: ChromeCDP(auto_start=True, user_data_dir=prof)
348
+
349
+ cdp = None
350
+ try:
351
+ cdp = cdp_factory()
352
+ cdp.navigate(target, wait_until="networkidle", timeout=timeout)
353
+
354
+ def _probe() -> str:
355
+ return detect_page_auth_state(
356
+ cdp.get_url() or target,
357
+ cdp.get_title() or "",
358
+ cdp.get_text() or "",
359
+ )
360
+
361
+ state = wait_for_stable_page_auth_state(
362
+ _probe, settle_s=settle_s, interval_s=interval_s,
363
+ )
364
+ usable = _es.is_page_auth_usable(state)
365
+ non_retry = _es.is_page_auth_non_retryable(state)
366
+ return {
367
+ "ok": usable, "site": host, "state": state,
368
+ "retryable": not non_retry, "handoff_required": non_retry,
369
+ "error": None if usable else f"{host} 会话不可用(state={state}),请人工重新登录或通过验证",
370
+ }
371
+ except (OSError, RuntimeError, ValueError) as e:
372
+ return {
373
+ "ok": False, "site": host, "state": _es.PAGE_AUTH_SIGNED_OUT,
374
+ "retryable": True, "handoff_required": False,
375
+ "error": f"活体探测失败: {str(e)[:120]}",
376
+ }
377
+ finally:
378
+ if cdp is not None:
379
+ try:
380
+ cdp.stop()
381
+ except (OSError, RuntimeError):
382
+ pass
383
+
384
+
385
+ def bound_comments(
386
+ comments: list[dict],
387
+ *,
388
+ max_items: int = 30,
389
+ max_chars: int = 800,
390
+ ) -> dict:
391
+ """评论/回复上下文封顶器:最多保留 max_items 条,单条正文截断至 max_chars,显式标 truncated。"""
392
+ total = len(comments or [])
393
+ kept: list[dict] = []
394
+ truncated = total > max_items
395
+ for raw in (comments or [])[:max_items]:
396
+ if not isinstance(raw, dict):
397
+ continue
398
+ item = dict(raw)
399
+ for text_key in ("text", "content", "body"):
400
+ val = item.get(text_key)
401
+ if isinstance(val, str) and len(val) > max_chars:
402
+ item[text_key] = val[:max_chars] + "…"
403
+ truncated = True
404
+ kept.append(item)
405
+ return {"items": kept, "total": total, "truncated": truncated}
406
+
407
+
249
408
  # ─── CLI(bin/argo 的 auth 子命令入口)──────────────────────────────────────
250
409
 
251
410
  def main(argv: list[str] | None = None) -> None:
@@ -314,7 +473,22 @@ def main(argv: list[str] | None = None) -> None:
314
473
  print(f"删除失败:{out.get('error')}", file=sys.stderr)
315
474
  sys.exit(0 if out.get("ok") else 1)
316
475
 
317
- print(f"Unknown auth subcommand: {cmd}(可用:login / status / logout)",
476
+ if cmd == "verify":
477
+ if not rest:
478
+ print("用法:argo auth verify <url_or_host>(活体验证已保存会话)",
479
+ file=sys.stderr)
480
+ sys.exit(1)
481
+ out = verify_live_session(rest[0])
482
+ if use_json:
483
+ _emit_json(out)
484
+ elif out.get("ok"):
485
+ print(f"{out['site']} 登录态活体校验通过(state={out['state']})。")
486
+ else:
487
+ print(f"{out['site']} 校验未通过(state={out.get('state')}):{out.get('error')}",
488
+ file=sys.stderr)
489
+ sys.exit(0 if out.get("ok") else 1)
490
+
491
+ print(f"Unknown auth subcommand: {cmd}(可用:login / status / verify / logout)",
318
492
  file=sys.stderr)
319
493
  sys.exit(1)
320
494