bugx-cli 0.1.3 → 0.1.5

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 (167) hide show
  1. package/core/README.md +5 -3
  2. package/core/agent/agent_execution.py +7 -0
  3. package/core/assets/bugx-wechat-group.png +0 -0
  4. package/core/bugx.md +2 -2
  5. package/core/bugx_paths.py +10 -2
  6. package/core/bundled_docs/OVERVIEW.md +311 -0
  7. package/core/bundled_docs/README.md +10 -0
  8. package/core/bundled_docs/README_EN.md +278 -0
  9. package/core/bundled_docs/ai/01_AI_REFERENCE.md +838 -0
  10. package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
  11. package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
  12. package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
  13. package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
  14. package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
  15. package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
  16. package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +25 -0
  17. package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
  18. package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
  19. package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
  20. package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
  21. package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
  22. package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
  23. package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
  24. package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
  25. package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
  26. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
  27. package/core/bundled_docs/manifest.json +140 -0
  28. package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +422 -0
  29. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
  30. package/core/cli-help.txt +7 -3
  31. package/core/cloud_sync/cloud_client.py +81 -2
  32. package/core/cloud_sync/endpoint_router.py +22 -9
  33. package/core/cloud_sync/issue_uploader.py +297 -0
  34. package/core/cloud_sync/sensitive_filter.py +77 -7
  35. package/core/contracts/AGENT_GUIDE.md +3 -9
  36. package/core/contracts/README.md +1 -1
  37. package/core/contracts/bugx-runtime-contract.md +10 -20
  38. package/core/contracts/bugx-worker.md +1 -1
  39. package/core/coverage/coverage_ai_review.py +15 -11
  40. package/core/coverage/coverage_bootstrap.py +18 -13
  41. package/core/coverage/coverage_discovery.py +1 -1
  42. package/core/dev_harness/interaction_preset.py +1 -1
  43. package/core/engine-integrity.json +283 -159
  44. package/core/host_acp/README.md +4 -0
  45. package/core/host_acp/agnescode.py +128 -0
  46. package/core/host_acp/antigravity.py +153 -0
  47. package/core/host_runtime/README.md +3 -0
  48. package/core/host_runtime/adapters.py +5 -1
  49. package/core/host_runtime/antigravity.py +162 -0
  50. package/core/host_runtime/host_bootstrap.py +18 -7
  51. package/core/host_runtime/host_evaluators.py +4 -4
  52. package/core/host_runtime/host_registry.py +3 -1
  53. package/core/host_runtime/mcp_process_tracker.py +30 -3
  54. package/core/host_runtime/mcp_registry_gate.py +34 -11
  55. package/core/hosts/README.md +4 -0
  56. package/core/hosts/agnescode.py +415 -0
  57. package/core/hosts/antigravity.py +115 -0
  58. package/core/hosts/codex.py +3 -0
  59. package/core/hosts/dsh.py +42 -23
  60. package/core/hosts/minimax.py +5 -4
  61. package/core/hosts/opencode.py +11 -3
  62. package/core/i18n.py +94 -5
  63. package/core/infra/README.md +1 -1
  64. package/core/infra/build_info.py +2 -2
  65. package/core/infra/python_runtime.py +4 -1
  66. package/core/launch_phases/README.md +2 -2
  67. package/core/launch_phases/finding_confirm_phase.py +1 -1
  68. package/core/launch_phases/semantic_recon.py +3 -19
  69. package/core/launch_phases/startup_version_gate.py +2 -2
  70. package/core/launch_phases/supervisor_bridge.py +2 -0
  71. package/core/launch_phases/supervisor_degraded.py +7 -5
  72. package/core/launch_phases/verify_loop.py +3 -19
  73. package/core/ledger/README.md +1 -1
  74. package/core/ledger/finding_confirmation.py +1 -1
  75. package/core/ledger/finding_verification.py +2 -20
  76. package/core/ledger/fp_ledger.py +3 -19
  77. package/core/ledger/life_ledger.py +7 -33
  78. package/core/ledger/schema.py +1 -1
  79. package/core/locales/en-US.json +3 -3
  80. package/core/locales/zh-CN.json +3 -3
  81. package/core/mcp_handlers/supervisor_handlers.py +1 -1
  82. package/core/mcp_runtime_support/common.py +6 -0
  83. package/core/mcp_runtime_support/environment.py +88 -24
  84. package/core/metadata.txt +1 -1
  85. package/core/planning/README.md +1 -1
  86. package/core/planning/prompt_harness.py +2 -2
  87. package/core/planning/target_sandbox_manager.py +2 -0
  88. package/core/probes/codebase_memory_probe.py +43 -24
  89. package/core/probes/mobile_probe.py +1 -0
  90. package/core/probes/probe_registry.py +10 -7
  91. package/core/probes/sast_probe.py +1 -1
  92. package/core/probes/sca_scanner.py +1 -1
  93. package/core/project_profiler/constants.py +1 -1
  94. package/core/prompts/command_routing_en.md +6 -5
  95. package/core/prompts/command_routing_zh.md +6 -5
  96. package/core/repair/rsi_rounds.py +3 -0
  97. package/core/repair/self_heal.py +160 -6
  98. package/core/retrieval/README.md +1 -1
  99. package/core/retrieval/symbol_index.py +227 -52
  100. package/core/runtime/README.md +1 -1
  101. package/core/runtime/daemon_runner.py +3 -2
  102. package/core/runtime/project_init.py +1 -1
  103. package/core/runtime/scenario_eval.py +5 -1
  104. package/core/runtime/tool_install_targets.py +12 -2
  105. package/core/skills/README.md +4 -2
  106. package/core/skills/bugx_docs_cloud_sync.py +658 -0
  107. package/core/skills/bugx_docs_mcp_server.py +966 -140
  108. package/core/skills/bugx_mcp_server.py +9 -0
  109. package/core/skills/mcp_session_proof.py +3 -31
  110. package/core/supervisor/README.md +1 -1
  111. package/core/supervisor/finding_commit.py +3 -24
  112. package/core/supervisor/task_scheduler.py +5 -2
  113. package/core/supervisor/worker_execution.py +16 -3
  114. package/core/supervisor/worker_handoff.py +2 -2
  115. package/core/webui/docs_session_service.py +40 -2
  116. package/core/webui/mcp_inspector.py +6 -6
  117. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
  118. package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
  119. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  120. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +5 -5
  121. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  122. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  123. package/ecosystem/integrations/opencode/mcp-lock.json +1 -1
  124. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  125. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +5 -5
  126. package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
  127. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  128. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  129. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
  130. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  131. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  132. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  133. package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
  134. package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
  135. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +7 -7
  136. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +2 -2
  137. package/interfaces/cli/bugx_cli/__init__.py +1 -1
  138. package/interfaces/cli/bugx_cli/cli.py +153 -8
  139. package/interfaces/cli/bugx_cli/commands/agent.py +376 -69
  140. package/interfaces/cli/bugx_cli/commands/audit.py +2 -1
  141. package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
  142. package/interfaces/cli/bugx_cli/commands/doctor.py +650 -223
  143. package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
  144. package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
  145. package/interfaces/cli/bugx_cli/commands/lifecycle.py +56 -26
  146. package/interfaces/cli/bugx_cli/commands/patch.py +5 -1
  147. package/interfaces/cli/bugx_cli/commands/plugin.py +306 -56
  148. package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
  149. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  150. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +154 -62
  151. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +308 -108
  152. package/interfaces/cli/bugx_cli/commands/system.py +11 -1
  153. package/interfaces/cli/bugx_cli/common.py +39 -8
  154. package/interfaces/cli/bugx_cli/host_adapters.py +46 -3
  155. package/interfaces/cli/bugx_cli/hosts/registry.py +3 -2
  156. package/interfaces/cli/bugx_cli/hosts/template_engine.py +21 -2
  157. package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
  158. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
  159. package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
  160. package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
  161. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +240 -50
  162. package/package.json +3 -2
  163. package/pyproject.toml +22 -2
  164. package/scripts/sync-version.mjs +1 -1
  165. package/skills/README.md +1 -2
  166. package/skills/platform/bugx/SKILL.md +50 -0
  167. package/skills/platform/bugx-user/SKILL.md +0 -92
@@ -48,7 +48,7 @@ SKIP_DIRS = {
48
48
  ".agents", ".cursor", ".gemini", "node_modules", ".venv",
49
49
  "venv", "env", "__pycache__", "dist", "build", ".idea", ".tox", ".mypy_cache",
50
50
  ".pytest_cache", "target", "vendor", "Pods", "DerivedData", ".next", ".nuxt",
51
- "evals",
51
+ "evals", "artifacts", ".tools",
52
52
  }
53
53
  _SKIP_DIRS = SKIP_DIRS
54
54
 
@@ -23,6 +23,7 @@ In the first second of receiving a task, classify which branch it belongs to:
23
23
  5. **Close the Loop**: Defects require standalone reproduction scripts (PoC) and call-stack evidence; report truthfully using the 6 standard status terms (read-only inspection, project ready, gate ready, test execution, mining launched, mining completed).
24
24
 
25
25
  ### 3. Core Action Matrix (High-Frequency Commands Covering 90% of Calls)
26
+ - **Live Guide Lookup**: `bugx guide "<keyword>"` (`--offline` queries bundled official baseline + project docs without network)
26
27
  - **Environment Diagnosis**: `bugx doctor --root <ROOT> --json` (`--repair-assets` for repair)
27
28
  - **Startup and Gates**: `bugx engine --root <ROOT> status --json` / `bugx engine --root <ROOT> pre` (fresh projects use `bugx init --root <ROOT>`)
28
29
  - **Reproduction and Mutation**: `bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`
@@ -30,12 +31,12 @@ In the first second of receiving a task, classify which branch it belongs to:
30
31
  - **Telemetry and Logs**: `bugx telemetry inspect` / `bugx log --root <ROOT> --errors`
31
32
  - **Dual Reports and Preview**: `bugx report both --eval-dir verification/evals/oss --out verification/evals/oss` / `bugx report serve --port 18991`
32
33
 
33
- ### 4. Compact Command Radar (41 Top-level Commands Classified Index)
34
+ ### 4. Compact Command Radar (43 Top-level Commands Classified Index)
34
35
  To invoke any command below, inspect exact parameters dynamically via `bugx help <cmd>`; never guess:
35
- - **Diagnostics and Inspection (9)**: `help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`
36
- - **Core Lifecycle and Hosts (14)**: `init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`
37
- - **Deep Audit and Verification (10)**: `audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`
38
- - **Knowledge Flywheel and Delivery (8)**: `report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`
36
+ - **Diagnostics and Inspection (10)**: `help`, `completion`, `guide`, `hosts`, `doctor`, `log`, `stats`, `view`, `project`, `self-audit`
37
+ - **Core Lifecycle and Hosts (15)**: `init`, `install`, `reset`, `uninstall`, `dsh`, `engine`, `supervisor`, `daemon`, `config`, `plugin`, `mcp`, `capability`, `mcp-runtime`, `update`, `interaction`
38
+ - **Deep Audit and Verification (10)**: `audit`, `probe`, `logic-analysis`, `mining-audit`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `autonomous`, `goal`
39
+ - **Cloud, Knowledge, and Delivery (8)**: `cloud`, `auth`, `telemetry`, `knowledge`, `lesson`, `skill`, `advisory`, `report`
39
40
 
40
41
  ### 5. Mandatory Rules and Deprecated Command Redirection
41
42
  - **Gate Blockage Forbids Destructive Repairs**: `FATAL_BLOCKED` must never be bypassed using `init`, `reset`, or `--force`; preserve logs and state first.
@@ -23,6 +23,7 @@
23
23
  5. **闭环**:缺陷必须给出最小独立复现脚本(PoC)与完整调用栈证据;使用 6 大标准汇报用词(只读检查、项目就绪、门禁就绪、测试执行、挖掘启动、挖掘完成)如实汇报。
24
24
 
25
25
  ### 3. 高频场景命令(覆盖 90% 日常调用)
26
+ - **手册即时检索**:`bugx guide "<关键词>"`(支持 `--offline` 离线查官档与当前项目文档)
26
27
  - **环境诊断**:`bugx doctor --root <ROOT> --json`(`--repair-assets` 按需修复)
27
28
  - **启动与门禁**:`bugx engine --root <ROOT> status --json` / `bugx engine --root <ROOT> pre`(全新项目使用 `bugx init --root <ROOT>` 初始化)
28
29
  - **单点复现与变异**:`bugx test-generate --root <ROOT> --scope <PATH::SYM> --out <FILE>` / `bugx test-verify verify --scope <SCOPE>`
@@ -30,12 +31,12 @@
30
31
  - **脱敏飞轮与日志**:`bugx telemetry inspect` / `bugx log --root <ROOT> --errors`
31
32
  - **双轨报告与预览**:`bugx report both --eval-dir verification/evals/oss --out verification/evals/oss` / `bugx report serve --port 18991`
32
33
 
33
- ### 4. 紧凑型命令全景雷达(41 个顶层命令分类索引)
34
+ ### 4. 紧凑型命令全景雷达(43 个顶层命令分类索引)
34
35
  如需调用以下命令,通过 `bugx help <命令>` 动态获取具体参数与子命令,严禁盲猜:
35
- - **诊断探索 (9)**:`help`, `doctor`, `hosts`, `completion`, `log`, `stats`, `view`, `project`, `self-audit`
36
- - **核心生命周期 (14)**:`init`, `engine`, `supervisor`, `daemon`, `config`, `reset`, `install`, `uninstall`, `dsh`, `plugin`, `mcp`, `mcp-runtime`, `capability`, `logic-analysis`
37
- - **深度审计验证 (10)**:`audit`, `probe`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `test-strategy`, `fuzz-input`, `differential-probe`, `mining-audit`
38
- - **知识飞轮交付 (8)**:`report`, `lesson`, `knowledge`, `skill`, `cloud`, `auth`, `telemetry`, `advisory`
36
+ - **诊断与探索 (10)**:`help`, `completion`, `guide`, `hosts`, `doctor`, `log`, `stats`, `view`, `project`, `self-audit`
37
+ - **核心生命周期与宿主 (15)**:`init`, `install`, `reset`, `uninstall`, `dsh`, `engine`, `supervisor`, `daemon`, `config`, `plugin`, `mcp`, `capability`, `mcp-runtime`, `update`, `interaction`
38
+ - **深度审计与测试验证 (10)**:`audit`, `probe`, `logic-analysis`, `mining-audit`, `test-generate`, `test-audit`, `test-verify`, `patch-forge`, `autonomous`, `goal`
39
+ - **云端、知识与交付 (8)**:`cloud`, `auth`, `telemetry`, `knowledge`, `lesson`, `skill`, `advisory`, `report`
39
40
 
40
41
  ### 5. 核心军规与废弃命令重定向
41
42
  - **阻断不授权暴力修复**:`FATAL_BLOCKED` 严禁使用 `init`、`reset`、`--force` 绕过,先保留报告和日志。
@@ -64,6 +64,9 @@ def _run_round(*, level_ids: list[str] | None, baseline: Path | None,
64
64
  try:
65
65
  proc = subprocess.run(
66
66
  argv, cwd=str(REPO_ROOT), capture_output=True, text=True,
67
+ # RSI 轮次是机器编排,不允许 scenario_eval 继承宿主 TTY 后
68
+ # 在任何未预期的交互门禁上无限等待。
69
+ stdin=subprocess.DEVNULL,
67
70
  timeout=timeout, check=False,
68
71
  )
69
72
  except subprocess.TimeoutExpired:
@@ -19,17 +19,24 @@
19
19
 
20
20
  from __future__ import annotations
21
21
 
22
+ import importlib
23
+ import importlib.util
22
24
  import json
23
25
  import os
24
26
  import re
25
27
  import shutil
26
28
  import subprocess
29
+ import sys
27
30
  import time
28
31
  from dataclasses import dataclass, field
29
32
  from pathlib import Path
30
33
  from typing import Any, Callable
31
34
 
32
- from core.runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
35
+ from core.runtime.tool_install_targets import (
36
+ OPTIONAL_TOOL_PACKAGE_SPECS,
37
+ REQUIRED_TOOL_PACKAGE_SPECS,
38
+ TOOL_PACKAGE_SPECS,
39
+ )
33
40
 
34
41
  DEFAULT_MAX_ATTEMPTS = 6
35
42
  DEFAULT_ATTEMPT_TIMEOUT = 120.0
@@ -125,15 +132,20 @@ def resolve_budget() -> Budget:
125
132
  PLAN_REGISTRY: dict[str, tuple[Plan, ...]] = {
126
133
  "codebase-memory": (
127
134
  Plan("pipx 隔离重装固定版本", (
128
- "pipx", "install", "--force", OPTIONAL_TOOL_PACKAGE_SPECS["codebase-memory"],
135
+ "pipx", "install", "--force", REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"],
129
136
  ),
130
137
  requires="pipx", verify=("codebase-memory-mcp",),
131
- verify_version_spec=OPTIONAL_TOOL_PACKAGE_SPECS["codebase-memory"]),
138
+ verify_version_spec=REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"]),
132
139
  Plan("uv tool 隔离重装固定版本", (
133
- "uv", "tool", "install", "--reinstall", OPTIONAL_TOOL_PACKAGE_SPECS["codebase-memory"],
140
+ "uv", "tool", "install", "--reinstall", REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"],
134
141
  ),
135
142
  requires="uv", verify=("codebase-memory-mcp",),
136
- verify_version_spec=OPTIONAL_TOOL_PACKAGE_SPECS["codebase-memory"]),
143
+ verify_version_spec=REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"]),
144
+ Plan("BugX 隔离 venv 安装固定版本", (
145
+ "__bugx_venv_pip__", "codebase-memory", REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"],
146
+ ),
147
+ requires=None, verify=("codebase-memory-mcp",),
148
+ verify_version_spec=REQUIRED_TOOL_PACKAGE_SPECS["codebase-memory"]),
137
149
  ),
138
150
  "ast-grep": (
139
151
  Plan("pipx 隔离重装固定版本", (
@@ -217,7 +229,65 @@ Which = Callable[[str], str | None]
217
229
  Clock = Callable[[], float]
218
230
 
219
231
 
232
+ def _bugx_home_root() -> Path:
233
+ configured = os.environ.get("BUGX_HOME", "").strip()
234
+ if configured:
235
+ return Path(configured).expanduser().resolve()
236
+ return (Path.home() / ".bugx").resolve()
237
+
238
+
239
+ def bugx_pydeps_dir() -> Path:
240
+ return _bugx_home_root() / "tools" / "pydeps"
241
+
242
+
243
+ def mount_bugx_pydeps() -> Path | None:
244
+ target = bugx_pydeps_dir()
245
+ if target.is_symlink() or not target.is_dir():
246
+ return None
247
+ text = str(target)
248
+ if text not in sys.path:
249
+ sys.path.insert(0, text)
250
+ return target
251
+
252
+
253
+ def _run_isolated_venv_pip(tool_dir_name: str, package_spec: str, timeout: float) -> tuple[int | None, str]:
254
+ venv_dir = _bugx_home_root() / "tools" / tool_dir_name
255
+ scripts = "Scripts" if os.name == "nt" else "bin"
256
+ py_name = "python.exe" if os.name == "nt" else "python"
257
+ venv_py = venv_dir / scripts / py_name
258
+ outputs: list[str] = []
259
+ if not venv_py.is_file():
260
+ if venv_dir.exists() and not venv_dir.is_symlink():
261
+ shutil.rmtree(venv_dir, ignore_errors=True)
262
+ venv_dir.parent.mkdir(parents=True, exist_ok=True)
263
+ try:
264
+ proc = subprocess.run(
265
+ [sys.executable, "-m", "venv", str(venv_dir)],
266
+ capture_output=True, text=True, timeout=min(timeout, 120.0), check=False,
267
+ )
268
+ outputs.append(f"{proc.stdout or ''}\n{proc.stderr or ''}")
269
+ if proc.returncode != 0 or not venv_py.is_file():
270
+ return proc.returncode or 1, "\n".join(outputs)
271
+ except subprocess.TimeoutExpired:
272
+ return None, f"timeout creating venv after {timeout}s"
273
+ except OSError as exc:
274
+ return None, f"{exc.__class__.__name__}: {exc}"
275
+ try:
276
+ proc = subprocess.run(
277
+ [str(venv_py), "-m", "pip", "install", "--no-input", "--upgrade", package_spec],
278
+ capture_output=True, text=True, timeout=timeout, check=False,
279
+ )
280
+ outputs.append(f"{proc.stdout or ''}\n{proc.stderr or ''}")
281
+ return proc.returncode, "\n".join(outputs)
282
+ except subprocess.TimeoutExpired:
283
+ return None, f"timeout after {timeout}s"
284
+ except OSError as exc:
285
+ return None, f"{exc.__class__.__name__}: {exc}"
286
+
287
+
220
288
  def _default_runner(argv: tuple[str, ...], timeout: float) -> tuple[int | None, str]:
289
+ if len(argv) >= 3 and argv[0] == "__bugx_venv_pip__":
290
+ return _run_isolated_venv_pip(argv[1], argv[2], timeout)
221
291
  try:
222
292
  proc = subprocess.run(list(argv), capture_output=True, text=True,
223
293
  timeout=timeout, check=False)
@@ -383,21 +453,29 @@ def _verified(
383
453
  )
384
454
  if not match:
385
455
  return False
386
- if plan.verify_version_spec not in OPTIONAL_TOOL_PACKAGE_SPECS.values():
456
+ if plan.verify_version_spec not in TOOL_PACKAGE_SPECS.values():
387
457
  return False
388
458
  package = match.group("package")
389
459
  expected = match.group("version")
390
460
  if package == "codebase-memory-mcp":
461
+ used_default = False
391
462
  if version_resolver is None:
392
463
  try:
393
464
  from core.probes import codebase_memory_probe
394
465
  version_resolver = codebase_memory_probe.resolve_compatible_binary
466
+ used_default = True
395
467
  except ImportError:
396
468
  return False
397
469
  try:
470
+ if used_default:
471
+ return bool(version_resolver(expected_version=expected, timeout_seconds=120.0))
398
472
  return bool(version_resolver(expected_version=expected))
399
473
  except Exception:
400
474
  return False
475
+ if package == "tree-sitter-language-pack":
476
+ mount_bugx_pydeps()
477
+ importlib.invalidate_caches()
478
+ return importlib.util.find_spec("tree_sitter_language_pack") is not None
401
479
  try:
402
480
  if package in {"semgrep", "bandit"}:
403
481
  from core.probes import sast_probe
@@ -602,3 +680,79 @@ def escalation_lines(report: HealReport) -> list[str]:
602
680
  if not lines:
603
681
  lines.append(" · 无可用方案(该工具未登记方案阶梯)")
604
682
  return lines
683
+
684
+
685
+ def ensure_codebase_memory_ready(root: Path | None = None) -> tuple[bool, str]:
686
+ """校验并在缺失/错版时直接安装 codebase-memory-mcp 固定版本,禁止降级。"""
687
+ try:
688
+ from core.probes import codebase_memory_probe
689
+ expected = codebase_memory_probe._pinned_cli_version()
690
+ executable = codebase_memory_probe.resolve_compatible_binary(
691
+ expected_version=expected, timeout_seconds=30.0,
692
+ )
693
+ if executable:
694
+ return True, f"已就绪 ({executable} == {expected})"
695
+ except Exception:
696
+ pass
697
+
698
+ ok, heal_report = heal_tool(
699
+ "codebase-memory",
700
+ detail=f"缺失必装核心图谱组件 {REQUIRED_TOOL_PACKAGE_SPECS['codebase-memory']}",
701
+ root=root,
702
+ )
703
+ if ok:
704
+ detail = "; ".join(heal_report.healed) or f"已安装 {REQUIRED_TOOL_PACKAGE_SPECS['codebase-memory']}"
705
+ return True, detail
706
+ details = [line.strip() for line in escalation_lines(heal_report)]
707
+ return False, ";".join(details) if details else f"安装失败:{REQUIRED_TOOL_PACKAGE_SPECS['codebase-memory']}"
708
+
709
+
710
+ def ensure_tree_sitter_ready(timeout: float = 120.0) -> tuple[bool, str]:
711
+ """校验并在缺失时安装 tree-sitter-language-pack(含 PEP 668 隔离目录兜底)。"""
712
+ mount_bugx_pydeps()
713
+ importlib.invalidate_caches()
714
+ if importlib.util.find_spec("tree_sitter_language_pack") is not None:
715
+ return True, "已就绪"
716
+
717
+ spec = REQUIRED_TOOL_PACKAGE_SPECS["tree-sitter"]
718
+ errors: list[str] = []
719
+
720
+ try:
721
+ proc = subprocess.run(
722
+ [sys.executable, "-m", "pip", "install", "--no-input", spec, "--no-warn-script-location"],
723
+ capture_output=True, text=True, timeout=timeout, check=False,
724
+ )
725
+ importlib.invalidate_caches()
726
+ if proc.returncode == 0 and importlib.util.find_spec("tree_sitter_language_pack") is not None:
727
+ return True, f"已安装 {spec}"
728
+ tail = ((proc.stderr or "") + "\n" + (proc.stdout or "")).strip()[-300:]
729
+ if tail:
730
+ errors.append(f"pip: {tail}")
731
+ except (OSError, subprocess.TimeoutExpired) as exc:
732
+ errors.append(f"pip: {exc}")
733
+
734
+ target_dir = bugx_pydeps_dir()
735
+ if target_dir.is_symlink():
736
+ return False, f"隔离依赖路径不能是符号链接: {target_dir}"
737
+ try:
738
+ target_dir.mkdir(parents=True, exist_ok=True)
739
+ for cmd in (
740
+ [sys.executable, "-m", "pip", "install", "--no-input", "--upgrade", "--target", str(target_dir), spec],
741
+ *(
742
+ [[uv_bin, "pip", "install", "--python", sys.executable, "--target", str(target_dir), spec]]
743
+ if (uv_bin := shutil.which("uv")) else []
744
+ ),
745
+ ):
746
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
747
+ mount_bugx_pydeps()
748
+ importlib.invalidate_caches()
749
+ if proc.returncode == 0 and importlib.util.find_spec("tree_sitter_language_pack") is not None:
750
+ return True, f"已安装到隔离目录 {target_dir}"
751
+ tail = ((proc.stderr or "") + "\n" + (proc.stdout or "")).strip()[-300:]
752
+ if tail:
753
+ errors.append(tail)
754
+ except (OSError, subprocess.TimeoutExpired) as exc:
755
+ errors.append(str(exc))
756
+
757
+ return False, ";".join(errors[-2:]) if errors else f"无法安装 {spec}"
758
+
@@ -1,6 +1,6 @@
1
1
  # BugX Retrieval Engine (代码切片、拓扑与混合检索增强引擎)
2
2
 
3
- > **版本契约**: `0.1.2` | **所属分层**: `Layer 2: 分析、切片与探测引擎`
3
+ > **版本契约**: `0.1.5` | **所属分层**: `Layer 2: 分析、切片与探测引擎`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 物理条目索引覆盖)
6
6
 
@@ -22,10 +22,12 @@ from pathlib import Path
22
22
 
23
23
  import argparse
24
24
  import ast
25
+ import concurrent.futures
25
26
  import json
26
27
  import hashlib
27
28
  import os
28
29
  import re
30
+ import sqlite3
29
31
  from dataclasses import asdict, dataclass, field, replace
30
32
  from fnmatch import fnmatchcase
31
33
 
@@ -91,7 +93,7 @@ HOST_ROOT_CONFIG_NAMES = {
91
93
  }
92
94
  DEPENDENCY_OR_GENERATED_DIRS = {
93
95
  ".git", "node_modules", "target", "dist", ".venv", "venv", "__pycache__",
94
- ".gradle", "vendor", "third_party", ".pytest_cache", ".ruff_cache",
96
+ ".gradle", "vendor", "third_party", ".pytest_cache", ".ruff_cache", ".tools",
95
97
  }
96
98
  # Keep the old public name for callers that used it, but do not use it as a
97
99
  # blunt ``any path segment`` filter: product code may legitimately contain a
@@ -237,11 +239,14 @@ _PROJECT_EXCLUDE_TOP_DIRS_CACHE: dict[Path, frozenset[str]] = {}
237
239
 
238
240
 
239
241
  def _project_exclude_top_dirs(root: Path) -> frozenset[str]:
240
- """项目级覆盖排除,两路来源取并集(AI 复核为主,手工配置为辅):
242
+ """项目级覆盖排除(DOC-AIREV 双轨中的 Track 2 动态语义收敛 + 手工配置):
241
243
 
242
- 1. **AI 复核定案**(主通道):``.bugx/knowledge/coverage-review.json``
243
- 里宿主 AI 逐目录排查后的 ``exclude`` 裁决——裁决带理由/时间/裁决者,
244
- 换项目时由该机制重新排查,不携带任何项目名清单(DOC-AIREV)。
244
+ 在 Track 1(``HOST_RUNTIME_DIRS`` / ``DEPENDENCY_OR_GENERATED_DIRS`` 等静态白名单)
245
+ 自动排除公认基础设施与工具链之后,剩余目录由 AI 复核再过一遍,两路来源取并集:
246
+
247
+ 1. **AI 复核定案**(Track 2 主通道):``.bugx/knowledge/coverage-review.json``
248
+ 里宿主 AI 对白名单放行目录逐一排查后的 ``exclude`` 裁决——裁决带理由/时间/
249
+ 裁决者,换项目时动态重查,不携带任何项目名清单(DOC-AIREV)。
245
250
  2. **手工覆盖**(辅助):``.bugx/config.json`` 的
246
251
  ``coverage.exclude_top_dirs`` 顶层目录名列表,供人工紧急纠偏。
247
252
 
@@ -994,60 +999,230 @@ def index_repository(
994
999
  }
995
1000
 
996
1001
 
1002
+ def _build_file_audit_units(
1003
+ root: Path, path: Path, backend: str, strict: bool,
1004
+ *, cache: SourceContentCache | None = None,
1005
+ ) -> tuple[str, int, int, str, list[dict]]:
1006
+ """Parse one source file into its leaf-symbol or file-level audit units."""
1007
+ relative = path.relative_to(root).as_posix()
1008
+ st = path.stat()
1009
+ size = int(st.st_size)
1010
+ mtime_ns = int(st.st_mtime_ns)
1011
+ symbols, error, language = parse_file(path, backend, cache=cache)
1012
+ try:
1013
+ digest = file_sha256(path, cache)
1014
+ except OSError as exc:
1015
+ if strict:
1016
+ raise SourceDiscoveryError(f"源码读取失败 {path}: {exc}") from exc
1017
+ digest = ""
1018
+ # F-RSI-20261115-284 同型输出面:与 index_repository 的 digest_status
1019
+ # 对齐,避免读失败单元以空 content_hash 静默进入下游审计/覆盖清单。
1020
+ digest_status = "error"
1021
+ else:
1022
+ digest_status = "ok"
1023
+ leaves = _leaf_symbols(symbols)
1024
+ if leaves and all(symbol.kind == "module" for symbol in leaves):
1025
+ # A file containing only constants/configuration remains a useful
1026
+ # file-level task; do not manufacture a synthetic callable task.
1027
+ leaves = []
1028
+ if leaves:
1029
+ units = [{
1030
+ "scope": f"{relative}::{symbol.scope_name}",
1031
+ "path": relative,
1032
+ "name": symbol.name,
1033
+ "kind": symbol.kind,
1034
+ "line": symbol.start_line,
1035
+ "parser": symbol.parser,
1036
+ "error": error,
1037
+ "end_line": symbol.end_line,
1038
+ "content_hash": digest,
1039
+ "digest_status": digest_status,
1040
+ "language": language,
1041
+ } for symbol in leaves]
1042
+ else:
1043
+ units = [{
1044
+ "scope": relative,
1045
+ "path": relative,
1046
+ "name": path.stem,
1047
+ "kind": "file",
1048
+ "line": 1,
1049
+ "parser": "fallback-file",
1050
+ "error": error,
1051
+ "language": language,
1052
+ "content_hash": digest,
1053
+ "digest_status": digest_status,
1054
+ }]
1055
+ return relative, size, mtime_ns, digest, units
1056
+
1057
+
1058
+ def _parse_audit_unit_worker(args: tuple[str, str, str, bool]) -> tuple[str, int, int, str, list[dict]]:
1059
+ """Top-level picklable worker for parallel ProcessPoolExecutor indexing."""
1060
+ root_str, path_str, backend, strict = args
1061
+ return _build_file_audit_units(Path(root_str), Path(path_str), backend, strict)
1062
+
1063
+
1064
+ class _PersistentSymbolCache:
1065
+ """Content-addressed SQLite cache for audit_units under ``.bugx/cache/``."""
1066
+
1067
+ def __init__(self, root: Path) -> None:
1068
+ self._conn: sqlite3.Connection | None = None
1069
+ bugx_dir = root / ".bugx"
1070
+ if not bugx_dir.is_dir() or bugx_dir.is_symlink():
1071
+ return
1072
+ cache_dir = bugx_dir / "cache"
1073
+ try:
1074
+ cache_dir.mkdir(parents=True, exist_ok=True)
1075
+ db_path = cache_dir / "symbol_cache.db"
1076
+ conn = sqlite3.connect(str(db_path), timeout=5.0)
1077
+ conn.execute(
1078
+ "CREATE TABLE IF NOT EXISTS unit_cache ("
1079
+ "rel_path TEXT NOT NULL, backend TEXT NOT NULL, "
1080
+ "size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL, "
1081
+ "sha256 TEXT NOT NULL, units_json TEXT NOT NULL, "
1082
+ "PRIMARY KEY (rel_path, backend))"
1083
+ )
1084
+ self._conn = conn
1085
+ except (OSError, sqlite3.Error):
1086
+ self._conn = None
1087
+
1088
+ def get_by_stat(self, rel_path: str, backend: str, size: int, mtime_ns: int) -> list[dict] | None:
1089
+ if self._conn is None:
1090
+ return None
1091
+ try:
1092
+ row = self._conn.execute(
1093
+ "SELECT units_json FROM unit_cache "
1094
+ "WHERE rel_path = ? AND backend = ? AND size = ? AND mtime_ns = ?",
1095
+ (rel_path, backend, size, mtime_ns),
1096
+ ).fetchone()
1097
+ if row is not None:
1098
+ data = json.loads(row[0])
1099
+ if isinstance(data, list):
1100
+ return data
1101
+ except (sqlite3.Error, ValueError, TypeError):
1102
+ pass
1103
+ return None
1104
+
1105
+ def put_many(self, rows: list[tuple[str, str, int, int, str, list[dict]]]) -> None:
1106
+ if self._conn is None or not rows:
1107
+ return
1108
+ try:
1109
+ with self._conn:
1110
+ self._conn.executemany(
1111
+ "INSERT OR REPLACE INTO unit_cache "
1112
+ "(rel_path, backend, size, mtime_ns, sha256, units_json) "
1113
+ "VALUES (?, ?, ?, ?, ?, ?)",
1114
+ [
1115
+ (rel, backend, size, mtime_ns, digest, json.dumps(units, ensure_ascii=False))
1116
+ for rel, backend, size, mtime_ns, digest, units in rows
1117
+ ],
1118
+ )
1119
+ except (sqlite3.Error, TypeError, ValueError):
1120
+ pass
1121
+
1122
+ def close(self) -> None:
1123
+ if self._conn is not None:
1124
+ try:
1125
+ self._conn.close()
1126
+ except sqlite3.Error:
1127
+ pass
1128
+ self._conn = None
1129
+
1130
+
997
1131
  def audit_units(
998
1132
  root: Path, backend: str = "auto", strict: bool = False,
999
1133
  *, cache: SourceContentCache | None = None,
1134
+ parallel: bool = True,
1135
+ use_persistent_cache: bool = True,
1000
1136
  ) -> list[dict]:
1001
- """返回最细审计单元;有符号时取叶子符号,否则退回文件。"""
1137
+ """返回最细审计单元;有符号时取叶子符号,否则退回文件。
1138
+
1139
+ 支持:
1140
+ 1. 基于 ``.bugx/cache/symbol_cache.db`` 的文件级内容/stat 持久化缓存;
1141
+ 2. 超过 32 个未命中文件时自动启用多进程并发 AST 解析;
1142
+ 3. 大规模扫描时定期向 stderr 输出心跳进度,避免宿主误判挂死。
1143
+ """
1002
1144
  root = root.resolve()
1003
1145
  cache = cache if cache is not None else SourceContentCache()
1004
- result: list[dict] = []
1005
- for path in discover_source_paths(root, strict=strict):
1006
- relative = path.relative_to(root).as_posix()
1007
- symbols, error, language = parse_file(path, backend, cache=cache)
1008
- try:
1009
- digest = file_sha256(path, cache)
1010
- except OSError as exc:
1011
- if strict:
1012
- raise SourceDiscoveryError(f"源码读取失败 {path}: {exc}") from exc
1013
- digest = ""
1014
- # F-RSI-20261115-284 同型输出面:与 index_repository 的 digest_status
1015
- # 对齐,避免读失败单元以空 content_hash 静默进入下游审计/覆盖清单。
1016
- digest_status = "error"
1017
- else:
1018
- digest_status = "ok"
1019
- leaves = _leaf_symbols(symbols)
1020
- if leaves and all(symbol.kind == "module" for symbol in leaves):
1021
- # A file containing only constants/configuration remains a useful
1022
- # file-level task; do not manufacture a synthetic callable task.
1023
- leaves = []
1024
- if leaves:
1025
- result.extend({
1026
- "scope": f"{relative}::{symbol.scope_name}",
1027
- "path": relative,
1028
- "name": symbol.name,
1029
- "kind": symbol.kind,
1030
- "line": symbol.start_line,
1031
- "parser": symbol.parser,
1032
- "error": error,
1033
- "end_line": symbol.end_line,
1034
- "content_hash": digest,
1035
- "digest_status": digest_status,
1036
- "language": language,
1037
- } for symbol in leaves)
1146
+ source_paths = discover_source_paths(root, strict=strict)
1147
+ persistent = _PersistentSymbolCache(root) if use_persistent_cache else None
1148
+
1149
+ units_by_rel: dict[str, list[dict]] = {}
1150
+ uncached: list[Path] = []
1151
+ ordered_rels: list[str] = []
1152
+
1153
+ try:
1154
+ for path in source_paths:
1155
+ relative = path.relative_to(root).as_posix()
1156
+ ordered_rels.append(relative)
1157
+ if persistent is not None:
1158
+ try:
1159
+ st = path.stat()
1160
+ cached_units = persistent.get_by_stat(
1161
+ relative, backend, int(st.st_size), int(st.st_mtime_ns),
1162
+ )
1163
+ if cached_units is not None:
1164
+ units_by_rel[relative] = cached_units
1165
+ continue
1166
+ except OSError:
1167
+ pass
1168
+ uncached.append(path)
1169
+
1170
+ total_uncached = len(uncached)
1171
+ new_cache_rows: list[tuple[str, str, int, int, str, list[dict]]] = []
1172
+
1173
+ main_file = getattr(sys.modules.get("__main__"), "__file__", None)
1174
+ can_spawn = bool(main_file and os.path.isfile(main_file))
1175
+ if parallel and can_spawn and total_uncached >= 32 and (os.cpu_count() or 1) > 1:
1176
+ workers = min(os.cpu_count() or 4, 8)
1177
+ tasks = [(str(root), str(p), backend, strict) for p in uncached]
1178
+ try:
1179
+ with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as pool:
1180
+ for idx, (rel, size, mtime_ns, digest, file_units) in enumerate(
1181
+ pool.map(_parse_audit_unit_worker, tasks, chunksize=16), 1,
1182
+ ):
1183
+ units_by_rel[rel] = file_units
1184
+ if digest:
1185
+ new_cache_rows.append((rel, backend, size, mtime_ns, digest, file_units))
1186
+ if total_uncached >= 200 and idx % 200 == 0:
1187
+ print(
1188
+ f"[symbol_index] 并发解析进度: {idx}/{total_uncached}",
1189
+ file=sys.stderr, flush=True,
1190
+ )
1191
+ except (OSError, PermissionError, RuntimeError, ValueError):
1192
+ # 受限沙箱或子进程启动失败时安全退回单进程路径
1193
+ units_by_rel = {k: v for k, v in units_by_rel.items()}
1194
+ new_cache_rows.clear()
1195
+ for p in uncached:
1196
+ if p.relative_to(root).as_posix() not in units_by_rel:
1197
+ rel, size, mtime_ns, digest, file_units = _build_file_audit_units(
1198
+ root, p, backend, strict, cache=cache,
1199
+ )
1200
+ units_by_rel[rel] = file_units
1201
+ if digest:
1202
+ new_cache_rows.append((rel, backend, size, mtime_ns, digest, file_units))
1038
1203
  else:
1039
- result.append({
1040
- "scope": relative,
1041
- "path": relative,
1042
- "name": path.stem,
1043
- "kind": "file",
1044
- "line": 1,
1045
- "parser": "fallback-file",
1046
- "error": error,
1047
- "language": language,
1048
- "content_hash": digest,
1049
- "digest_status": digest_status,
1050
- })
1204
+ for idx, p in enumerate(uncached, 1):
1205
+ rel, size, mtime_ns, digest, file_units = _build_file_audit_units(
1206
+ root, p, backend, strict, cache=cache,
1207
+ )
1208
+ units_by_rel[rel] = file_units
1209
+ if digest:
1210
+ new_cache_rows.append((rel, backend, size, mtime_ns, digest, file_units))
1211
+ if total_uncached >= 200 and idx % 200 == 0:
1212
+ print(
1213
+ f"[symbol_index] 解析进度: {idx}/{total_uncached}",
1214
+ file=sys.stderr, flush=True,
1215
+ )
1216
+
1217
+ if persistent is not None and new_cache_rows:
1218
+ persistent.put_many(new_cache_rows)
1219
+ finally:
1220
+ if persistent is not None:
1221
+ persistent.close()
1222
+
1223
+ result: list[dict] = []
1224
+ for rel in ordered_rels:
1225
+ result.extend(units_by_rel.get(rel, ()))
1051
1226
  return result
1052
1227
 
1053
1228
 
@@ -1,6 +1,6 @@
1
1
  # BugX Core Runtime Subsystem (核心运行时、环境与基础设施)
2
2
 
3
- > **版本契约**: `0.1.2` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
3
+ > **版本契约**: `0.1.5` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 物理条目索引覆盖)
6
6