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
@@ -1390,84 +1390,23 @@ def filter_by_mtime(results, since: str | None, until: str | None):
1390
1390
  if _in_time_window(fp, since_ts, until_ts)]
1391
1391
 
1392
1392
 
1393
- _OUTLINE_RULES = {
1394
- ".py": [re.compile(r'^\s*(async\s+)?(def|class)\s+\w+')],
1395
- ".pyi": [re.compile(r'^\s*(async\s+)?(def|class)\s+\w+')],
1396
- ".js": [re.compile(r'^\s*(export\s+)?(async\s+)?(function|class)\s+\w+'),
1397
- re.compile(r'^\s*(export\s+)?(const|let|var)\s+\w+')],
1398
- ".jsx": [re.compile(r'^\s*(export\s+)?(async\s+)?(function|class)\s+\w+'),
1399
- re.compile(r'^\s*(export\s+)?(const|let|var)\s+\w+')],
1400
- ".ts": [re.compile(r'^\s*(export\s+)?(async\s+)?(function|class|interface|type|enum)\s+\w+'),
1401
- re.compile(r'^\s*(export\s+)?(const|let|var)\s+\w+')],
1402
- ".tsx": [re.compile(r'^\s*(export\s+)?(async\s+)?(function|class|interface|type|enum)\s+\w+'),
1403
- re.compile(r'^\s*(export\s+)?(const|let|var)\s+\w+')],
1404
- ".go": [re.compile(r'^\s*func\s+\w+'),
1405
- re.compile(r'^\s*type\s+\w+\s+(struct|interface)\b')],
1406
- ".rs": [re.compile(r'^\s*(pub\s+)?(fn|struct|enum|impl|trait|mod|type)\s+\w+')],
1407
- ".java": [re.compile(r'^\s*(public|private|protected|static|\s)*(class|interface|enum)\s+\w+'),
1408
- re.compile(r'^\s*(public|private|protected|static|\s)*[\w<>,\[\] ]+\s+\w+\s*\(')],
1409
- ".sh": [re.compile(r'^\s*function\s+\w+'),
1410
- re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
1411
- ".bash": [re.compile(r'^\s*function\s+\w+'),
1412
- re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
1413
- ".zsh": [re.compile(r'^\s*function\s+\w+'),
1414
- re.compile(r'^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?')],
1415
- ".md": [re.compile(r'^#{1,6}\s+')],
1416
- ".mdx": [re.compile(r'^#{1,6}\s+')],
1417
- ".json": [re.compile(r'^\s*"[^"]+"\s*:')],
1418
- ".yaml": [re.compile(r'^[a-zA-Z_][\w.-]*\s*:')],
1419
- ".yml": [re.compile(r'^[a-zA-Z_][\w.-]*\s*:')],
1420
- }
1421
-
1422
-
1423
- def outline_file(path):
1424
- """输出代码/文档文件结构,替代整文件读取。返回 (输出文本, 退出码)。"""
1425
- p = Path(path)
1426
- if not p.is_file():
1427
- return f"local-seek: {path} 不是文件", 1
1428
- try:
1429
- lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
1430
- except OSError as e:
1431
- return f"local-seek: 读取失败 {e}", 1
1432
- rules = _OUTLINE_RULES.get(p.suffix.lower())
1433
- if not rules:
1434
- return (f"local-seek: {p.name} 共 {len(lines)} 行"
1435
- f"({p.suffix or '无扩展名'} 暂无结构规则)"), 0
1436
- hits = []
1437
- for i, ln in enumerate(lines, 1):
1438
- if any(r.match(ln) for r in rules):
1439
- hits.append(f"{i}: {ln.strip()[:100]}")
1440
- head = f"local-seek: {p.name} 结构 {len(hits)} 处 / 共 {len(lines)} 行"
1441
- return "\n".join([head] + hits), 0
1442
-
1443
-
1444
- def read_lines(path, spec):
1445
- """按行读取文件(单遍流式,不加载全文)。返回 (输出文本, 退出码)。"""
1446
- m = re.fullmatch(r"(\d+)-(\d+)", spec)
1447
- if not m:
1448
- return "local-seek: --lines 格式应为 N-M(如 10-20)", 1
1449
- a, b = int(m.group(1)), int(m.group(2))
1450
- if a < 1 or b < a:
1451
- return f"local-seek: 行范围无效 {spec}", 1
1452
- p = Path(path)
1453
- if not p.is_file():
1454
- return f"local-seek: {path} 不是文件", 1
1455
- # 单遍流式读取:边数总行数边收集目标区间。原实现先 open 数行、再 open
1456
- # 读区间,同一文件开两遍——大文件时 IO 翻倍(2026-10-06 收口)。
1457
- picked, total = [], 0
1458
- try:
1459
- with open(p, encoding="utf-8", errors="replace") as f:
1460
- for i, ln in enumerate(f, 1):
1461
- total = i
1462
- if a <= i <= b:
1463
- picked.append(f"{i}: {ln.rstrip()}")
1464
- except OSError as e:
1465
- return f"local-seek: 读取失败 {e}", 1
1466
- if a > total:
1467
- return f"local-seek: {p.name} 只有 {total} 行,请求从 {a} 行开始", 1
1468
- end = min(b, total)
1469
- out = [f"local-seek: {p.name} 第 {a}-{end} 行 / 共 {total} 行"]
1470
- return "\n".join(out + picked), 0
1393
+ # 精读层与历史层已拆至 seek_inspect.py / seek_git.py(保持同名 re-export 兼容既有测试)
1394
+ _SEEK_SCRIPTS_DIR = str(Path(__file__).resolve().parent)
1395
+ if _SEEK_SCRIPTS_DIR not in sys.path:
1396
+ sys.path.insert(0, _SEEK_SCRIPTS_DIR)
1397
+
1398
+ from seek_inspect import ( # noqa: E402
1399
+ _OUTLINE_RULES,
1400
+ _compute_outline_entries,
1401
+ _outline_level,
1402
+ outline_file,
1403
+ read_lines,
1404
+ read_symbol_body,
1405
+ )
1406
+ from seek_git import ( # noqa: E402
1407
+ git_blame as _git_blame_impl,
1408
+ git_log as _git_log_impl,
1409
+ )
1471
1410
 
1472
1411
 
1473
1412
  STRUCTURAL_RULES = {
@@ -1561,33 +1500,13 @@ def structural_search(rule_name, path, excludes, max_results, dots=False,
1561
1500
 
1562
1501
 
1563
1502
  def git_log(path, n=10, timeout=None):
1564
- """输出文件的最近提交历史(git log --oneline)。"""
1565
- p = Path(path).expanduser()
1566
- if not p.is_file():
1567
- return f"local-seek: {path} 不是文件", 1
1568
- proc = run(["git", "-C", str(p.parent), "log", "--oneline", f"-{n}", "--", p.name],
1569
- timeout=timeout)
1570
- if proc is None:
1571
- return "local-seek: git 执行失败", 1
1572
- if proc.returncode == 128 or (proc.returncode == 0 and not proc.stdout.strip()):
1573
- inside = run(["git", "-C", str(p.parent), "rev-parse", "--is-inside-work-tree"])
1574
- if inside is None or inside.returncode != 0:
1575
- return f"local-seek: {p.name} 不在 git 仓库中", 1
1576
- return f"local-seek: {p.name} 无提交历史", 0
1577
- lines = proc.stdout.splitlines()
1578
- return "\n".join([f"local-seek: {p.name} 最近 {len(lines)} 条提交"] + lines), 0
1503
+ """输出文件的最近提交历史(委托至 seek_git,注入本模块 run 以兼容单测 monkeypatch)。"""
1504
+ return _git_log_impl(path, n=n, timeout=timeout, runner=run)
1579
1505
 
1580
1506
 
1581
1507
  def git_blame(path, line, timeout=None):
1582
- """输出文件第 N 行的 blame 信息(谁在哪个提交改的)。"""
1583
- p = Path(path).expanduser()
1584
- if not p.is_file():
1585
- return f"local-seek: {path} 不是文件", 1
1586
- proc = run(["git", "-C", str(p.parent), "blame", "-L", f"{line},{line}", "--", p.name],
1587
- timeout=timeout)
1588
- if proc is None or proc.returncode != 0:
1589
- return f"local-seek: git blame 失败({p.name} 可能在 git 仓库外或行号无效)", 1
1590
- return f"local-seek: {p.name} 第 {line} 行\n{proc.stdout.strip()}", 0
1508
+ """输出文件第 N 行的 blame 信息(委托至 seek_git)。"""
1509
+ return _git_blame_impl(path, line, timeout=timeout, runner=run)
1591
1510
 
1592
1511
 
1593
1512
  def _run_grep_fallback(args, patterns, fixed, path, excludes, exts, max_results,
@@ -1671,6 +1590,8 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1671
1590
  ap.add_argument("--count", action="store_true", help="只输出每文件命中数")
1672
1591
  ap.add_argument("--context", type=int, default=0, help="上下文行数(默认 0)")
1673
1592
  ap.add_argument("--json", action="store_true", help="JSON 输出")
1593
+ ap.add_argument("--agent", action="store_true",
1594
+ help="Agent 消费单开关:等价 --json + 紧凑序列化 + 默认 --max 20 上限")
1674
1595
  ap.add_argument("--max", type=int, default=0, help="最大结果数(默认读配置)")
1675
1596
  ap.add_argument("--exact", action="store_true", help="关闭中文扩展(精确匹配)")
1676
1597
  ap.add_argument("--symbol", action="store_true",
@@ -1681,9 +1602,11 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1681
1602
  help="文件修改时间下限(7d / 2026-08-01),过滤命中文件的 mtime")
1682
1603
  ap.add_argument("--until", default=None,
1683
1604
  help="文件修改时间上限(7d / 2026-08-01),过滤命中文件的 mtime")
1684
- ap.add_argument("--outline", action="store_true", help="输出文件结构(文件路径为位置参数)")
1605
+ ap.add_argument("--outline", action="store_true", help="输出文件结构与精确起止行跨度(文件路径为位置参数)")
1685
1606
  ap.add_argument("--lines", default="", metavar="N-M",
1686
1607
  help="按行读取文件(文件路径为位置参数)")
1608
+ ap.add_argument("--symbol-body", default="", metavar="NAME",
1609
+ help="按符号名一跳读取定义区间源码,≤200 行封顶(文件路径为位置参数)")
1687
1610
  ap.add_argument("--structural", action="store_true",
1688
1611
  help="结构搜索:按语义检索(裸except/空catch/装饰函数/函数定义等)")
1689
1612
  ap.add_argument("--git-log", action="store_true",
@@ -1693,18 +1616,44 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1693
1616
  ap.add_argument("--domains", action="store_true", help="列出知识域与排除规则")
1694
1617
  args = ap.parse_args(argv)
1695
1618
 
1619
+ # --agent 单开关展开:等价 --json + 预算封顶(默认 --max 20,防止大仓库吐爆上下文)
1620
+ if args.agent:
1621
+ args.json = True
1622
+ if not args.max:
1623
+ args.max = 20
1624
+
1625
+ # 互斥动作模式 Fail-Fast 校验(避免位置参数在「查询词」与「文件路径」间静默误判)
1626
+ _active_modes: list[str] = []
1627
+ if args.outline or args.lines or args.symbol_body:
1628
+ _active_modes.append("精读模式(--outline/--lines/--symbol-body)")
1629
+ if args.git_log or args.git_blame:
1630
+ _active_modes.append("历史模式(--git-log/--git-blame)")
1631
+ if args.structural:
1632
+ _active_modes.append("结构搜索(--structural)")
1633
+ if args.filename:
1634
+ _active_modes.append("文件名搜索(--filename)")
1635
+ if args.spotlight:
1636
+ _active_modes.append("Spotlight(--spotlight)")
1637
+ if len(_active_modes) > 1:
1638
+ return f"local-seek: 动作模式互斥({' 与 '.join(_active_modes)} 不能同时指定)", 2
1639
+ if (args.outline or args.lines or args.symbol_body) and (args.count or args.context):
1640
+ return "local-seek: 精读模式与 --count/--context 互斥", 2
1641
+
1696
1642
  # 知识域展示模式
1697
1643
  if args.domains:
1698
1644
  if DOMAINS_FILE.exists():
1699
1645
  return DOMAINS_FILE.read_text(encoding="utf-8"), 0
1700
1646
  return "未找到 config/domains.yaml,使用内置默认规则", 0
1701
1647
 
1702
- # 文件结构 / 按行读取模式(文件路径优先取位置参数,否则取 --path)
1703
- if args.outline or args.lines:
1648
+ # 文件结构 / 符号体 / 按行读取模式(文件路径优先取位置参数,否则取 --path)
1649
+ if args.outline or args.lines or args.symbol_body:
1704
1650
  target = args.query or str(args.path)
1651
+ if args.symbol_body:
1652
+ cap = args.max if (args.max and not args.agent) else 200
1653
+ return read_symbol_body(target, args.symbol_body, max_lines=cap, as_json=args.json)
1705
1654
  if args.lines:
1706
- return read_lines(target, args.lines)
1707
- return outline_file(target)
1655
+ return read_lines(target, args.lines, as_json=args.json)
1656
+ return outline_file(target, as_json=args.json)
1708
1657
 
1709
1658
  # git 联动模式:查文件提交历史 / 单行归属
1710
1659
  if args.git_log or args.git_blame:
@@ -1933,13 +1882,35 @@ def run_query(argv=None, time_budget=None) -> tuple[str, int]:
1933
1882
  pass
1934
1883
 
1935
1884
  if err:
1885
+ if args.agent:
1886
+ return json.dumps({"ok": False, "query": args.query, "engine": engine, "error": err}, ensure_ascii=False), 1
1936
1887
  return f"local-seek: {err}", 1
1937
1888
  if not results:
1889
+ if args.agent:
1890
+ handoff = {
1891
+ "expand_path": f'argo seek "{args.query}" --path ~ --spotlight',
1892
+ "web_fallback": f'argo search "{args.query}" --agent',
1893
+ }
1894
+ return json.dumps({
1895
+ "query": args.query,
1896
+ "engine": engine,
1897
+ "mode": mode,
1898
+ "scope": scope,
1899
+ "path": str(path),
1900
+ "elapsed_ms": elapsed,
1901
+ "count": 0,
1902
+ "results": [],
1903
+ "handoff_hint": handoff,
1904
+ }, ensure_ascii=False), 1
1938
1905
  return f"local-seek: 未找到匹配({engine} · {path} · {elapsed}ms)", 1
1939
1906
 
1940
1907
  if args.json:
1941
- return to_json(results, engine, mode, scope, path, elapsed, args.query,
1942
- since=args.since, until=args.until), 0
1908
+ raw_json = to_json(results, engine, mode, scope, path, elapsed, args.query,
1909
+ since=args.since, until=args.until)
1910
+ if args.agent:
1911
+ # --agent 输出紧凑单行 JSON(省空白字节)
1912
+ return json.dumps(json.loads(raw_json), ensure_ascii=False, separators=(",", ":")), 0
1913
+ return raw_json, 0
1943
1914
  return format_output(results, engine, mode, path, elapsed, args.query,
1944
1915
  len(results)), 0
1945
1916
 
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python3
2
+ """seek_git.py — local-seek 历史层(文件提交历史与单行 blame)。
3
+
4
+ 从 seek.py 拆出:独立封装 git 只读查询,runner 支持注入以兼容既有单测 monkeypatch。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import subprocess
10
+ from pathlib import Path
11
+ from typing import Any, Callable
12
+
13
+
14
+ def _default_run(cmd: list[str], timeout: float | None = 30) -> Any:
15
+ try:
16
+ return subprocess.run(
17
+ cmd, capture_output=True, text=True,
18
+ encoding="utf-8", errors="replace", timeout=timeout or 30,
19
+ )
20
+ except (OSError, subprocess.TimeoutExpired):
21
+ return None
22
+
23
+
24
+ def git_log(
25
+ path: str | Path,
26
+ n: int = 10,
27
+ timeout: float | None = None,
28
+ *,
29
+ runner: Callable[..., Any] | None = None,
30
+ ) -> tuple[str, int]:
31
+ """输出文件的最近提交历史(git log --oneline)。"""
32
+ run_fn = runner or _default_run
33
+ p = Path(path).expanduser()
34
+ if not p.is_file():
35
+ return f"local-seek: {path} 不是文件", 1
36
+ proc = run_fn(["git", "-C", str(p.parent), "log", "--oneline", f"-{n}", "--", p.name],
37
+ timeout=timeout)
38
+ if proc is None:
39
+ return "local-seek: git 执行失败", 1
40
+ if proc.returncode == 128 or (proc.returncode == 0 and not proc.stdout.strip()):
41
+ inside = run_fn(["git", "-C", str(p.parent), "rev-parse", "--is-inside-work-tree"])
42
+ if inside is None or inside.returncode != 0:
43
+ return f"local-seek: {p.name} 不在 git 仓库中", 1
44
+ return f"local-seek: {p.name} 无提交历史", 0
45
+ lines = proc.stdout.splitlines()
46
+ return "\n".join([f"local-seek: {p.name} 最近 {len(lines)} 条提交"] + lines), 0
47
+
48
+
49
+ def git_blame(
50
+ path: str | Path,
51
+ line: str | int,
52
+ timeout: float | None = None,
53
+ *,
54
+ runner: Callable[..., Any] | None = None,
55
+ ) -> tuple[str, int]:
56
+ """输出文件第 N 行的 blame 信息(谁在哪个提交改的)。"""
57
+ run_fn = runner or _default_run
58
+ p = Path(path).expanduser()
59
+ if not p.is_file():
60
+ return f"local-seek: {path} 不是文件", 1
61
+ proc = run_fn(["git", "-C", str(p.parent), "blame", "-L", f"{line},{line}", "--", p.name],
62
+ timeout=timeout)
63
+ if proc is None or proc.returncode != 0:
64
+ return f"local-seek: git blame 失败({p.name} 可能在 git 仓库外或行号无效)", 1
65
+ return f"local-seek: {p.name} 第 {line} 行\n{proc.stdout.strip()}", 0
@@ -0,0 +1,242 @@
1
+ #!/usr/bin/env python3
2
+ """seek_inspect.py — local-seek 精读层(文件结构大纲、符号体一跳直读、流式按行读取)。
3
+
4
+ 从 seek.py 拆出:纯标准库实现,职责严格限定在「已知单文件后的局部结构与源码读取」。
5
+ 支持文本与结构化 JSON 双形态输出(供 --agent / DSH 工作台直接消费)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ _OUTLINE_RULES: dict[str, list[re.Pattern[str]]] = {
16
+ ".py": [re.compile(r"^\s*(async\s+)?(def|class)\s+\w+")],
17
+ ".pyi": [re.compile(r"^\s*(async\s+)?(def|class)\s+\w+")],
18
+ ".js": [
19
+ re.compile(r"^\s*(export\s+)?(async\s+)?(function|class)\s+\w+"),
20
+ re.compile(r"^\s*(export\s+)?(const|let|var)\s+\w+"),
21
+ ],
22
+ ".jsx": [
23
+ re.compile(r"^\s*(export\s+)?(async\s+)?(function|class)\s+\w+"),
24
+ re.compile(r"^\s*(export\s+)?(const|let|var)\s+\w+"),
25
+ ],
26
+ ".ts": [
27
+ re.compile(r"^\s*(export\s+)?(async\s+)?(function|class|interface|type|enum)\s+\w+"),
28
+ re.compile(r"^\s*(export\s+)?(const|let|var)\s+\w+"),
29
+ ],
30
+ ".tsx": [
31
+ re.compile(r"^\s*(export\s+)?(async\s+)?(function|class|interface|type|enum)\s+\w+"),
32
+ re.compile(r"^\s*(export\s+)?(const|let|var)\s+\w+"),
33
+ ],
34
+ ".go": [
35
+ re.compile(r"^\s*func\s+\w+"),
36
+ re.compile(r"^\s*type\s+\w+\s+(struct|interface)\b"),
37
+ ],
38
+ ".rs": [re.compile(r"^\s*(pub\s+)?(fn|struct|enum|impl|trait|mod|type)\s+\w+")],
39
+ ".java": [
40
+ re.compile(r"^\s*(public|private|protected|static|\s)*(class|interface|enum)\s+\w+"),
41
+ re.compile(r"^\s*(public|private|protected|static|\s)*[\w<>,\[\] ]+\s+\w+\s*\("),
42
+ ],
43
+ ".sh": [
44
+ re.compile(r"^\s*function\s+\w+"),
45
+ re.compile(r"^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?"),
46
+ ],
47
+ ".bash": [
48
+ re.compile(r"^\s*function\s+\w+"),
49
+ re.compile(r"^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?"),
50
+ ],
51
+ ".zsh": [
52
+ re.compile(r"^\s*function\s+\w+"),
53
+ re.compile(r"^\s*[a-zA-Z_]\w*\s*\(\)\s*\{?"),
54
+ ],
55
+ ".md": [re.compile(r"^#{1,6}\s+")],
56
+ ".mdx": [re.compile(r"^#{1,6}\s+")],
57
+ ".json": [re.compile(r'^\s*"[^"]+"\s*:')],
58
+ ".yaml": [re.compile(r"^[a-zA-Z_][\w.-]*\s*:")],
59
+ ".yml": [re.compile(r"^[a-zA-Z_][\w.-]*\s*:")],
60
+ }
61
+
62
+
63
+ def _outline_level(line: str, suffix: str) -> int:
64
+ """返回结构行的层级:Markdown 按 # 数量,其余按前导空白长度。"""
65
+ if suffix in (".md", ".mdx"):
66
+ m = re.match(r"^(#{1,6})\s+", line)
67
+ return len(m.group(1)) if m else 99
68
+ return len(line) - len(line.lstrip(" \t"))
69
+
70
+
71
+ def _compute_outline_entries(
72
+ lines: list[str], rules: list[re.Pattern[str]], suffix: str
73
+ ) -> list[tuple[int, int, int, str]]:
74
+ """计算文件结构项及其精确起止行 [(start, end, span, text), ...]。"""
75
+ raw_hits = []
76
+ for i, ln in enumerate(lines, 1):
77
+ if any(r.match(ln) for r in rules):
78
+ raw_hits.append((i, _outline_level(ln, suffix), ln.strip()))
79
+ total = len(lines)
80
+ entries = []
81
+ for idx, (start, lvl, text) in enumerate(raw_hits):
82
+ end = total
83
+ for nxt_start, nxt_lvl, _ in raw_hits[idx + 1:]:
84
+ if nxt_lvl <= lvl:
85
+ end = nxt_start - 1
86
+ break
87
+ while end > start and not lines[end - 1].strip():
88
+ end -= 1
89
+ entries.append((start, end, end - start + 1, text))
90
+ return entries
91
+
92
+
93
+ def outline_file(path: str | Path, *, as_json: bool = False) -> tuple[str, int]:
94
+ """输出代码/文档文件结构(含精确起止行跨度),替代整文件读取。返回 (输出文本, 退出码)。"""
95
+ p = Path(path)
96
+ if not p.is_file():
97
+ msg = f"local-seek: {path} 不是文件"
98
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
99
+ try:
100
+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
101
+ except OSError as e:
102
+ msg = f"local-seek: 读取失败 {e}"
103
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
104
+ suffix = p.suffix.lower()
105
+ rules = _OUTLINE_RULES.get(suffix)
106
+ if not rules:
107
+ if as_json:
108
+ return json.dumps({
109
+ "ok": True, "path": str(p), "total_lines": len(lines),
110
+ "entries": [], "note": f"{p.suffix or '无扩展名'} 暂无结构规则",
111
+ }, ensure_ascii=False), 0
112
+ return (f"local-seek: {p.name} 共 {len(lines)} 行"
113
+ f"({p.suffix or '无扩展名'} 暂无结构规则)"), 0
114
+ entries = _compute_outline_entries(lines, rules, suffix)
115
+ if as_json:
116
+ return json.dumps({
117
+ "ok": True,
118
+ "path": str(p),
119
+ "total_lines": len(lines),
120
+ "count": len(entries),
121
+ "entries": [
122
+ {"start": s, "end": e, "span": span, "signature": txt[:120]}
123
+ for s, e, span, txt in entries
124
+ ],
125
+ }, ensure_ascii=False), 0
126
+ hits = [f"{s}-{e} ({span}L): {txt[:100]}" for s, e, span, txt in entries]
127
+ head = f"local-seek: {p.name} 结构 {len(hits)} 处 / 共 {len(lines)} 行"
128
+ return "\n".join([head] + hits), 0
129
+
130
+
131
+ def read_symbol_body(
132
+ path: str | Path,
133
+ symbol_name: str,
134
+ max_lines: int = 200,
135
+ *,
136
+ as_json: bool = False,
137
+ ) -> tuple[str, int]:
138
+ """按符号名一跳读取定义区间源码(带真实行号,默认 ≤ 200 行封顶)。返回 (输出文本, 退出码)。"""
139
+ symbol_name = (symbol_name or "").strip()
140
+ if not symbol_name:
141
+ msg = "local-seek: --symbol-body 需要指定符号名"
142
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
143
+ p = Path(path)
144
+ if not p.is_file():
145
+ msg = f"local-seek: {path} 不是文件"
146
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
147
+ try:
148
+ lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
149
+ except OSError as e:
150
+ msg = f"local-seek: 读取失败 {e}"
151
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
152
+ suffix = p.suffix.lower()
153
+ rules = _OUTLINE_RULES.get(suffix)
154
+ if not rules:
155
+ msg = f"local-seek: {p.name} 暂无结构规则({p.suffix or '无扩展名'}),请改用 --lines"
156
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
157
+ entries = _compute_outline_entries(lines, rules, suffix)
158
+ pat = re.compile(r"(?<!\w)" + re.escape(symbol_name) + r"(?!\w)")
159
+ matched = [item for item in entries if pat.search(item[3])]
160
+ if not matched:
161
+ low = symbol_name.lower()
162
+ matched = [item for item in entries if low in item[3].lower()]
163
+ if not matched:
164
+ msg = f"local-seek: {p.name} 中未找到符号 {symbol_name!r}(可先运行 --outline 查看结构)"
165
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
166
+
167
+ start, end, span, sig = matched[0]
168
+ cap = max(1, int(max_lines))
169
+ shown_end = min(end, start + cap - 1)
170
+ body = [f"{i}: {lines[i - 1]}" for i in range(start, shown_end + 1)]
171
+ if as_json:
172
+ payload: dict[str, Any] = {
173
+ "ok": True,
174
+ "path": str(p),
175
+ "symbol": symbol_name,
176
+ "signature": sig[:160],
177
+ "start": start,
178
+ "end": shown_end,
179
+ "symbol_end": end,
180
+ "span": span,
181
+ "total_lines": len(lines),
182
+ "truncated": shown_end < end,
183
+ "content": "\n".join(body),
184
+ }
185
+ if shown_end < end:
186
+ payload["next_range"] = f"{shown_end + 1}-{end}"
187
+ return json.dumps(payload, ensure_ascii=False), 0
188
+
189
+ extra = ""
190
+ if len(matched) > 1:
191
+ others = ", ".join(f"{s}-{e}" for s, e, _, _ in matched[1:5])
192
+ extra = f";另有 {len(matched) - 1} 处同名: {others}"
193
+ head = (
194
+ f"local-seek: {p.name} 符号 {symbol_name} 第 {start}-{shown_end} 行"
195
+ f"(共 {span} 行 / 文件 {len(lines)} 行{extra})"
196
+ )
197
+ if shown_end < end:
198
+ body.append(
199
+ f"... 已截断(上限 {cap} 行),继续读取:argo seek --lines {shown_end + 1}-{end} {path}"
200
+ )
201
+ return "\n".join([head] + body), 0
202
+
203
+
204
+ def read_lines(path: str | Path, spec: str, *, as_json: bool = False) -> tuple[str, int]:
205
+ """按行读取文件(单遍流式,不加载全文)。返回 (输出文本, 退出码)。"""
206
+ m = re.fullmatch(r"(\d+)-(\d+)", spec)
207
+ if not m:
208
+ msg = "local-seek: --lines 格式应为 N-M(如 10-20)"
209
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
210
+ a, b = int(m.group(1)), int(m.group(2))
211
+ if a < 1 or b < a:
212
+ msg = f"local-seek: 行范围无效 {spec}"
213
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
214
+ p = Path(path)
215
+ if not p.is_file():
216
+ msg = f"local-seek: {path} 不是文件"
217
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
218
+ picked, total = [], 0
219
+ try:
220
+ with open(p, encoding="utf-8", errors="replace") as f:
221
+ for i, ln in enumerate(f, 1):
222
+ total = i
223
+ if a <= i <= b:
224
+ picked.append(f"{i}: {ln.rstrip()}")
225
+ except OSError as e:
226
+ msg = f"local-seek: 读取失败 {e}"
227
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
228
+ if a > total:
229
+ msg = f"local-seek: {p.name} 只有 {total} 行,请求从 {a} 行开始"
230
+ return (json.dumps({"ok": False, "error": msg}, ensure_ascii=False) if as_json else msg), 1
231
+ end = min(b, total)
232
+ if as_json:
233
+ return json.dumps({
234
+ "ok": True,
235
+ "path": str(p),
236
+ "start": a,
237
+ "end": end,
238
+ "total_lines": total,
239
+ "content": "\n".join(picked),
240
+ }, ensure_ascii=False), 0
241
+ out = [f"local-seek: {p.name} 第 {a}-{end} 行 / 共 {total} 行"]
242
+ return "\n".join(out + picked), 0