bugx-cli 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/core/README.md +5 -3
  2. package/core/assets/bugx-wechat-group.png +0 -0
  3. package/core/bugx.md +2 -2
  4. package/core/bugx_paths.py +10 -2
  5. package/core/bundled_docs/OVERVIEW.md +310 -0
  6. package/core/bundled_docs/README.md +10 -0
  7. package/core/bundled_docs/README_EN.md +278 -0
  8. package/core/bundled_docs/ai/01_AI_REFERENCE.md +833 -0
  9. package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
  10. package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
  11. package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
  12. package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
  13. package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
  14. package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
  15. package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +23 -0
  16. package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
  17. package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
  18. package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
  19. package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
  20. package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
  21. package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
  22. package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
  23. package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
  24. package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
  25. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
  26. package/core/bundled_docs/manifest.json +140 -0
  27. package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +421 -0
  28. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
  29. package/core/cli-help.txt +7 -3
  30. package/core/cloud_sync/cloud_client.py +81 -2
  31. package/core/cloud_sync/endpoint_router.py +22 -9
  32. package/core/cloud_sync/issue_uploader.py +297 -0
  33. package/core/cloud_sync/sensitive_filter.py +77 -7
  34. package/core/contracts/AGENT_GUIDE.md +3 -9
  35. package/core/contracts/README.md +1 -1
  36. package/core/contracts/bugx-runtime-contract.md +10 -20
  37. package/core/contracts/bugx-worker.md +1 -1
  38. package/core/engine-integrity.json +209 -93
  39. package/core/host_acp/antigravity.py +153 -0
  40. package/core/host_runtime/adapters.py +5 -1
  41. package/core/host_runtime/antigravity.py +162 -0
  42. package/core/host_runtime/host_bootstrap.py +18 -7
  43. package/core/host_runtime/host_evaluators.py +4 -4
  44. package/core/host_runtime/host_registry.py +2 -1
  45. package/core/host_runtime/mcp_process_tracker.py +30 -3
  46. package/core/host_runtime/mcp_registry_gate.py +34 -11
  47. package/core/hosts/antigravity.py +115 -0
  48. package/core/hosts/codex.py +3 -0
  49. package/core/hosts/dsh.py +42 -23
  50. package/core/hosts/minimax.py +5 -4
  51. package/core/i18n.py +94 -5
  52. package/core/infra/README.md +1 -1
  53. package/core/infra/build_info.py +2 -2
  54. package/core/launch_phases/README.md +2 -2
  55. package/core/launch_phases/startup_version_gate.py +2 -2
  56. package/core/launch_phases/supervisor_bridge.py +2 -0
  57. package/core/launch_phases/supervisor_degraded.py +7 -5
  58. package/core/ledger/README.md +1 -1
  59. package/core/locales/en-US.json +3 -3
  60. package/core/locales/zh-CN.json +3 -3
  61. package/core/mcp_runtime_support/environment.py +6 -1
  62. package/core/metadata.txt +1 -1
  63. package/core/planning/README.md +1 -1
  64. package/core/planning/prompt_harness.py +2 -2
  65. package/core/probes/codebase_memory_probe.py +43 -24
  66. package/core/probes/probe_registry.py +10 -7
  67. package/core/prompts/command_routing_en.md +6 -5
  68. package/core/prompts/command_routing_zh.md +6 -5
  69. package/core/repair/rsi_rounds.py +3 -0
  70. package/core/repair/self_heal.py +160 -6
  71. package/core/retrieval/README.md +1 -1
  72. package/core/runtime/README.md +1 -1
  73. package/core/runtime/scenario_eval.py +5 -1
  74. package/core/runtime/tool_install_targets.py +12 -2
  75. package/core/skills/README.md +4 -2
  76. package/core/skills/bugx_docs_cloud_sync.py +658 -0
  77. package/core/skills/bugx_docs_mcp_server.py +966 -140
  78. package/core/supervisor/README.md +1 -1
  79. package/core/supervisor/worker_execution.py +16 -3
  80. package/core/webui/docs_session_service.py +40 -2
  81. package/core/webui/mcp_inspector.py +6 -6
  82. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
  83. package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
  84. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  85. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +5 -5
  86. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  87. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +2 -2
  88. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  89. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +5 -5
  90. package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
  91. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  92. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  93. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
  94. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  95. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  96. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  97. package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
  98. package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
  99. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +7 -7
  100. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +2 -2
  101. package/interfaces/cli/bugx_cli/__init__.py +1 -1
  102. package/interfaces/cli/bugx_cli/cli.py +138 -8
  103. package/interfaces/cli/bugx_cli/commands/agent.py +376 -69
  104. package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
  105. package/interfaces/cli/bugx_cli/commands/doctor.py +650 -223
  106. package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
  107. package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
  108. package/interfaces/cli/bugx_cli/commands/lifecycle.py +55 -25
  109. package/interfaces/cli/bugx_cli/commands/plugin.py +295 -54
  110. package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
  111. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  112. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +154 -62
  113. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +308 -108
  114. package/interfaces/cli/bugx_cli/commands/system.py +11 -1
  115. package/interfaces/cli/bugx_cli/common.py +39 -8
  116. package/interfaces/cli/bugx_cli/host_adapters.py +40 -3
  117. package/interfaces/cli/bugx_cli/hosts/registry.py +3 -2
  118. package/interfaces/cli/bugx_cli/hosts/template_engine.py +21 -2
  119. package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
  120. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
  121. package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
  122. package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
  123. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +240 -50
  124. package/package.json +3 -2
  125. package/pyproject.toml +22 -2
  126. package/scripts/sync-version.mjs +1 -1
  127. package/skills/README.md +1 -2
  128. package/skills/platform/bugx/SKILL.md +50 -0
  129. package/skills/platform/bugx-user/SKILL.md +0 -92
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env python3
2
2
  """探测 codebase-memory-mcp 安装、版本和当前仓库索引状态。
3
3
 
4
- 它是功能拆分和业务链路的首选语义增强层,但不是全量覆盖的硬依赖:缺失或索引
5
- 异常返回 DEGRADED,调用方必须取得用户的回退决定;本地 symbol_index/project_graph
6
- 仍负责不漏文件、不漏配置资产的覆盖事实。审计必须在准备记录中保存本命令结果。
4
+ 它是 BugX 的必装核心代码图谱引擎:缺失或版本不匹配时必须直接安装修复,
5
+ 严禁静默降级或豁免放行;本地 symbol_index/project_graph 负责全量资产清单与交叉校验。
7
6
  """
8
7
 
9
8
  from __future__ import annotations
@@ -25,12 +24,14 @@ import re
25
24
  import signal
26
25
  import shutil
27
26
  import subprocess
27
+ import sys
28
+ import sysconfig
28
29
  from pathlib import Path
29
30
 
30
31
  if __package__:
31
- from ..runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
32
+ from ..runtime.tool_install_targets import REQUIRED_TOOL_PACKAGE_SPECS
32
33
  else:
33
- from core.runtime.tool_install_targets import OPTIONAL_TOOL_PACKAGE_SPECS
34
+ from core.runtime.tool_install_targets import REQUIRED_TOOL_PACKAGE_SPECS
34
35
 
35
36
  PROJECT_URL = "https://github.com/DeusData/codebase-memory-mcp"
36
37
  RELEASE_URL = f"{PROJECT_URL}/releases"
@@ -79,7 +80,7 @@ def _probe_environment() -> dict[str, str]:
79
80
 
80
81
 
81
82
  def _pinned_cli_version() -> str | None:
82
- spec = OPTIONAL_TOOL_PACKAGE_SPECS.get("codebase-memory", "").strip()
83
+ spec = REQUIRED_TOOL_PACKAGE_SPECS.get("codebase-memory", "").strip()
83
84
  match = re.fullmatch(r"codebase-memory-mcp==(?P<version>\d+(?:\.\d+){1,3})", spec)
84
85
  return match.group("version") if match else None
85
86
 
@@ -98,21 +99,34 @@ def _binary_candidates(
98
99
  """Return bounded, deduplicated candidates, preferring managed user bin dirs.
99
100
 
100
101
  A caller-supplied binary is an explicit selection and remains authoritative.
101
- Otherwise, inspect the configured uv/XDG executable directories before
102
+ Otherwise, inspect the configured BugX/uv/XDG executable directories before
102
103
  arbitrary PATH entries so an unrelated workspace binary cannot shadow the
103
104
  installed tool.
104
105
  """
105
106
  if binary:
106
107
  return [str(binary)], False
107
108
 
108
- home = Path(environment.get("HOME") or str(Path.home()))
109
+ home = Path(environment.get("HOME") or environment.get("USERPROFILE") or str(Path.home()))
110
+ scripts_dir = "Scripts" if os.name == "nt" else "bin"
111
+ bugx_tool_bin = str(home / ".bugx" / "tools" / "codebase-memory" / scripts_dir)
112
+ bugx_bin = str(home / ".bugx" / "bin")
113
+ python_scripts = None
114
+ try:
115
+ python_scripts = sysconfig.get_path("scripts")
116
+ except (KeyError, TypeError, ValueError):
117
+ python_scripts = None
118
+
109
119
  directories: list[str] = []
110
120
  for value in (
121
+ bugx_tool_bin,
122
+ bugx_bin,
111
123
  environment.get("UV_TOOL_BIN_DIR"),
112
124
  environment.get("XDG_BIN_HOME"),
113
125
  str(Path(environment["XDG_DATA_HOME"]).parent / "bin")
114
126
  if environment.get("XDG_DATA_HOME") else None,
115
127
  str(home / ".local" / "bin"),
128
+ str(Path(sys.executable).parent),
129
+ python_scripts,
116
130
  *environment.get("PATH", "").split(os.pathsep),
117
131
  ):
118
132
  if not value:
@@ -141,7 +155,7 @@ def _binary_candidates(
141
155
 
142
156
  def _resolve_binary(
143
157
  environment: dict[str, str], expected_version: str, binary: str | None = None,
144
- *, timeout_seconds: float = 10.0,
158
+ *, timeout_seconds: float = 30.0,
145
159
  ) -> tuple[str | None, str | None, list[dict[str, str]], bool]:
146
160
  """Find an executable whose strict ``--version`` output matches the pin."""
147
161
  candidates, truncated = _binary_candidates(environment, binary)
@@ -170,7 +184,7 @@ def resolve_compatible_binary(
170
184
  *, environment: dict[str, str] | None = None,
171
185
  expected_version: str | None = None,
172
186
  binary: str | None = None,
173
- timeout_seconds: float = 10.0,
187
+ timeout_seconds: float = 30.0,
174
188
  ) -> str | None:
175
189
  """Return only a CLI that reports the repository's exact pinned version."""
176
190
  environment = environment or _probe_environment()
@@ -321,7 +335,12 @@ def _unsupported_output_detail(stdout: str, stderr: str) -> str:
321
335
  )
322
336
 
323
337
 
324
- def inspect(root: Path, binary: str | None = None) -> dict:
338
+ def inspect(
339
+ root: Path,
340
+ binary: str | None = None,
341
+ *,
342
+ check_project_index: bool = True,
343
+ ) -> dict:
325
344
  root = root.resolve()
326
345
  environment = _probe_environment()
327
346
  checks: list[dict] = []
@@ -387,6 +406,8 @@ def inspect(root: Path, binary: str | None = None) -> dict:
387
406
  "expected": expected_version,
388
407
  },
389
408
  ))
409
+ if not check_project_index:
410
+ return _report(root, checks, version_text, None)
390
411
  projects_result, retry_note, transient = _list_projects_with_retry(executable, environment)
391
412
  if projects_result is None:
392
413
  checks.append({
@@ -528,14 +549,12 @@ def _report(root: Path, checks: list[dict], version: str | None,
528
549
  ready = all(check["ok"] for check in checks)
529
550
  return {
530
551
  "status": "READY" if ready else "DEGRADED",
531
- # required_check means the startup environment must inspect and report
532
- # this capability. required remains false because local enumeration is
533
- # a valid fallback for small/offline projects.
552
+ # 必装核心能力:缺失或版本不匹配时必须阻断修复,禁止降级放行。
534
553
  "required_check": True,
535
- "required": False,
554
+ "required": True,
536
555
  "recommended": True,
537
- "hard_dependency": False,
538
- "role": "semantic-graph-enhancement",
556
+ "hard_dependency": True,
557
+ "role": "semantic-graph-core",
539
558
  "required_for": [
540
559
  "functional-minimization",
541
560
  "business-flow-discovery",
@@ -552,8 +571,8 @@ def _report(root: Path, checks: list[dict], version: str | None,
552
571
  ),
553
572
  "project": project.get("name") if project else None,
554
573
  "checks": checks,
555
- "fallback": "symbol_index.py + project_graph.py",
556
- "install": f"pipx install --force {OPTIONAL_TOOL_PACKAGE_SPECS['codebase-memory']}",
574
+ "fallback": "symbol_index.py + project_graph.py(仅作辅助基线对照,不得替代必装组件)",
575
+ "install": f"pipx install --force {REQUIRED_TOOL_PACKAGE_SPECS['codebase-memory']}(或 bugx doctor --repair)",
557
576
  "configure": "codebase-memory-mcp install,然后重启 AI 编程工具并索引项目",
558
577
  "source": RELEASE_URL,
559
578
  }
@@ -564,14 +583,13 @@ def print_report(report: dict, as_json: bool = False) -> None:
564
583
  print(json.dumps(report, ensure_ascii=False, indent=2))
565
584
  return
566
585
  print(
567
- f"[{report['status']}] codebase-memory-mcp(环境必检;语义拆分首选,非全量硬依赖)"
586
+ f"[{report['status']}] codebase-memory-mcp(必装核心代码图谱;缺失时阻断,不做降级放行)"
568
587
  )
569
588
  for check in report["checks"]:
570
589
  print(f" {'✓' if check['ok'] else '!'} {check['name']}: {check['detail']}")
571
590
  if report["status"] != "READY":
572
- print(f" → 推荐:{report['install']}")
591
+ print(f" → 安装:{report['install']}")
573
592
  print(f" → 配置:{report['configure']}")
574
- print(f" → 本轮回退:{report['fallback']}")
575
593
 
576
594
 
577
595
  def main(argv: list[str] | None = None) -> int:
@@ -580,8 +598,9 @@ def main(argv: list[str] | None = None) -> int:
580
598
  parser.add_argument("--root", type=Path, default=Path.cwd())
581
599
  parser.add_argument("--json", action="store_true")
582
600
  parser.add_argument("--strict", action="store_true")
601
+ parser.add_argument("--installation-only", action="store_true")
583
602
  args = parser.parse_args(argv)
584
- report = inspect(args.root)
603
+ report = inspect(args.root, check_project_index=not args.installation_only)
585
604
  print_report(report, args.json)
586
605
  return 1 if args.strict and report["status"] != "READY" else 0
587
606
 
@@ -635,7 +654,7 @@ def run_static_degraded(root: Path, *, binary: str | None = None) -> dict:
635
654
  "findings": [],
636
655
  "evidence": evidence,
637
656
  "fallback": "symbol_index.py + project_graph.py(本地全量枚举,不依赖语义图谱)",
638
- "install": f"pipx install --force {OPTIONAL_TOOL_PACKAGE_SPECS['codebase-memory']}",
657
+ "install": f"pipx install --force {REQUIRED_TOOL_PACKAGE_SPECS['codebase-memory']}",
639
658
  "metadata": {
640
659
  "degraded_mode": "local_coverage_facts_only",
641
660
  "semantic_graph_available": False,
@@ -55,12 +55,17 @@ def normalized_tool_environment(environ: Mapping[str, str] | None = None) -> dic
55
55
  """Return a child environment that can see common user tool locations."""
56
56
  environment = dict(os.environ if environ is None else environ)
57
57
  entries = [item for item in environment.get("PATH", "").split(os.pathsep) if item]
58
- candidates = [environment.get("BUGX_TOOL_PATH", "")]
58
+ scripts_dir = "Scripts" if os.name == "nt" else "bin"
59
+ candidates = [
60
+ environment.get("BUGX_TOOL_PATH", ""),
61
+ str(Path.home() / ".bugx" / "tools" / "codebase-memory" / scripts_dir),
62
+ str(Path.home() / ".bugx" / "bin"),
63
+ str(Path.home() / ".local" / "bin"),
64
+ ]
59
65
  if os.name != "nt":
60
66
  candidates.extend((
61
67
  "/opt/homebrew/bin", "/usr/local/bin",
62
68
  "/home/linuxbrew/.linuxbrew/bin",
63
- str(Path.home() / ".local" / "bin"),
64
69
  str(Path.home() / ".cargo" / "bin"),
65
70
  ))
66
71
  for candidate in candidates:
@@ -161,13 +166,11 @@ _BUILTIN_PROBES: tuple[ProbeDescriptor, ...] = (
161
166
  script="codebase_memory_probe.py",
162
167
  domain="knowledge",
163
168
  accepts_root=True,
164
- description="Codebase Memory MCP 图谱语义与知识索引探针",
169
+ description="Codebase Memory MCP 必装核心代码图谱探针",
165
170
  priority=30,
166
171
  lifecycle="preflight",
167
- # 加速器而非硬依赖:引擎自带 symbol_index/project_graph 回退
168
- # (``BUGX_USE_CODEBASE_MEMORY=0`` 是受支持运行模式),因此可经
169
- # 项目 ``tooling_exemptions`` 显式豁免;critical 能力不得豁免。
170
- critical=False,
172
+ # 必装核心组件:缺失或未就绪必须安装修复并阻断,禁止经 tooling_exemptions 豁免降级。
173
+ critical=True,
171
174
  ),
172
175
  ProbeDescriptor(
173
176
  name="pattern",
@@ -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.4` | **所属分层**: `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
 
@@ -1,6 +1,6 @@
1
1
  # BugX Core Runtime Subsystem (核心运行时、环境与基础设施)
2
2
 
3
- > **版本契约**: `0.1.2` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
3
+ > **版本契约**: `0.1.4` | **所属分层**: `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
 
@@ -141,11 +141,15 @@ def _run(argv: list[str], *, cwd: Path, timeout: float = 120.0,
141
141
  # L3 等场景验证当前 checkout;不让已安装的旧引擎成为量具。
142
142
  merged["BUGX_DEV_MODE"] = "1"
143
143
  # 源码树里的版本声明是构建模板;开发态启动门禁需要同一解析值。
144
- merged["BUGX_VERSION"] = os.environ.get("BUGX_VERSION", "0.1.3")
144
+ merged["BUGX_VERSION"] = os.environ.get("BUGX_VERSION", "0.1.4")
145
145
  merged["HOME"] = str(_sandbox_home())
146
146
  try:
147
147
  proc = subprocess.run(
148
148
  argv, cwd=str(cwd), capture_output=True, text=True,
149
+ # 场景评测是无人值守量具;如果外层宿主恰好有 TTY,子命令不能
150
+ # 继承它再偷偷阻塞在 input()。显式关闭 stdin,让意外交互立即
151
+ # 得到 EOF/失败,而不是把 RSI 轮次挂成数分钟的假运行。
152
+ stdin=subprocess.DEVNULL,
149
153
  timeout=timeout, env=merged, check=False,
150
154
  )
151
155
  return proc.returncode, proc.stdout, proc.stderr
@@ -1,16 +1,26 @@
1
- """Pinned top-level package specs used by optional-tool probes and self-heal."""
1
+ """Pinned top-level package specs used by required and optional tool probes."""
2
2
 
3
- OPTIONAL_TOOL_PACKAGE_SPECS = {
3
+ REQUIRED_TOOL_PACKAGE_SPECS = {
4
4
  "codebase-memory": "codebase-memory-mcp==0.12.1",
5
+ "tree-sitter": "tree-sitter-language-pack==1.14.3",
6
+ }
7
+
8
+ OPTIONAL_TOOL_PACKAGE_SPECS = {
5
9
  "ast-grep": "ast-grep-cli==0.45.1",
6
10
  "semgrep": "semgrep==1.182.0",
7
11
  "bandit": "bandit==1.9.4",
8
12
  }
9
13
 
14
+ TOOL_PACKAGE_SPECS = {
15
+ **REQUIRED_TOOL_PACKAGE_SPECS,
16
+ **OPTIONAL_TOOL_PACKAGE_SPECS,
17
+ }
18
+
10
19
  # Only these probe capabilities may trigger self-healing. Values are trusted
11
20
  # registry keys, never package names copied from probe output.
12
21
  PROBE_REPAIR_TARGETS = {
13
22
  "codebase-memory": ("codebase-memory",),
23
+ "tree-sitter": ("tree-sitter",),
14
24
  "efficiency": ("ast-grep",),
15
25
  "sast": ("bandit", "semgrep"),
16
26
  "bandit": ("bandit",),
@@ -16,7 +16,8 @@ flowchart TD
16
16
 
17
17
  subgraph MCPServer["2. MCP 协议服务 (Model Context Protocol Services)"]
18
18
  BMS["bugx_mcp_server.py<br/>BugX 官方标准 MCP Server 入口与状态机暴露"]
19
- BDMS["bugx_docs_mcp_server.py<br/>本地项目文档与架构知识库检索服务"]
19
+ BDMS["bugx_docs_mcp_server.py<br/>双作用域章节级文档与架构知识库检索服务"]
20
+ BDCS["bugx_docs_cloud_sync.py<br/>官方文档不可变内容寻址缓存与热同步引擎"]
20
21
  MSP["mcp_session_proof.py<br/>MCP 会话自证明与受控退休协议"]
21
22
  MR["mcp_runtime.py<br/>离线锁定版本 MCP 包安装与生命周期管理"]
22
23
  end
@@ -36,7 +37,8 @@ flowchart TD
36
37
  | 文件名 | 职责与功能定位 | 关键类 / 函数 |
37
38
  | :--- | :--- | :--- |
38
39
  | `__init__.py` | 技能与 MCP 子系统聚合导出与包入口 | `__all__` |
39
- | `bugx_docs_mcp_server.py` | 文档 MCP 服务端,基于 SQLite FTS5 提供本地代码库架构与知识检索 | `DocsMcpError`, `index_documents`, `call_tool`, `serve` |
40
+ | `bugx_docs_cloud_sync.py` | 官方文档云端热同步客户端,管理不可变 SHA-256 缓存、单飞锁与安全 GC | `sync_official_docs`, `current_cached_db`, `remote_search_docs` |
41
+ | `bugx_docs_mcp_server.py` | 双作用域文档 MCP 服务端,基于 FTS5 trigram 与章节索引提供检索与目录浏览 | `DocsMcpError`, `index_documents`, `call_tool`, `serve` |
40
42
  | `bugx_mcp_server.py` | BugX 核心 Supervisor MCP 服务端,向外部 Agent 暴露审计状态机 | `BugxMcpService`, `SERVER_NAME`, `SERVER_VERSION` |
41
43
  | `mcp_runtime.py` | 离线 MCP 运行时,负责包隔离安装、版本回滚与沙箱启动 | `install_runtime`, `rollback_runtime`, `start_server`, `doctor_runtime` |
42
44
  | `mcp_session_proof.py` | MCP 会话自证明与安全退役握手协议,防止 PID 复用与状态竞争 | `write_proof`, `read_proof`, `validate_proof`, `retire_target` |