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
package/core/cli-help.txt CHANGED
@@ -1,14 +1,15 @@
1
1
  usage: bugx [-h] [--version] [--log-level {DEBUG,INFO,WARNING,ERROR}]
2
2
  [--accept-data-sharing] [--privacy {standard,strict}]
3
3
  [--no-backup]
4
- {help,completion,init,dsh,hosts,install,reset,uninstall,doctor,mcp,capability,mcp-runtime,lesson,logic-analysis,probe,knowledge,skill,self-audit,engine,cloud,auth,telemetry,config,daemon,autonomous,goal,supervisor,plugin,update,patch-forge,log,stats,project,view,test-generate,test-audit,mining-audit,test-verify,audit,interaction,advisory,report} ...
4
+ {help,completion,guide,init,dsh,hosts,install,reset,uninstall,doctor,mcp,capability,mcp-runtime,lesson,logic-analysis,probe,knowledge,skill,self-audit,engine,cloud,auth,telemetry,config,daemon,autonomous,goal,supervisor,plugin,update,patch-forge,log,stats,project,view,test-generate,test-audit,mining-audit,test-verify,audit,interaction,issue,feedback,advisory,report} ...
5
5
 
6
6
  BugX 统一命令行入口(模块化调度器)。
7
7
 
8
8
  positional arguments:
9
- {help,completion,init,dsh,hosts,install,reset,uninstall,doctor,mcp,capability,mcp-runtime,lesson,logic-analysis,probe,knowledge,skill,self-audit,engine,cloud,auth,telemetry,config,daemon,autonomous,goal,supervisor,plugin,update,patch-forge,log,stats,project,view,test-generate,test-audit,mining-audit,test-verify,audit,interaction,advisory,report}
9
+ {help,completion,guide,init,dsh,hosts,install,reset,uninstall,doctor,mcp,capability,mcp-runtime,lesson,logic-analysis,probe,knowledge,skill,self-audit,engine,cloud,auth,telemetry,config,daemon,autonomous,goal,supervisor,plugin,update,patch-forge,log,stats,project,view,test-generate,test-audit,mining-audit,test-verify,audit,interaction,issue,feedback,advisory,report}
10
10
  help 显示 BugX 或指定命令的使用说明
11
11
  completion 输出 Bash、Zsh 或 Fish 的 Tab 补全脚本
12
+ guide 检索 BugX 本地文档与操作指南(支持中英文按需检索)
12
13
  init 把宿主无关的 BugX 核心初始化到项目
13
14
  dsh 兼容启动器:为首个 Web Session 绑定项目并启动 DeepSeek Harness
14
15
  hosts 只读发现可接入的 AI 宿主
@@ -33,7 +34,8 @@ positional arguments:
33
34
  config 设置本地 BugX 隐私与遥测配置
34
35
  daemon BugX 自治持续挖掘常驻守护进程管理
35
36
  autonomous 显式启动 Claude Code/Codex/OpenCode/DeepSeek
36
- Harness/Pi/Kimi Code/Cline/ZCode 前台无人值守挖掘
37
+ Harness/Pi/Kimi Code/Cline/ZCode/Google Antigravity
38
+ 前台无人值守挖掘
37
39
  goal 目标导向无人值守自治挖掘与长程自愈循环
38
40
  supervisor 本地监督 MCP:install / status / rpc;带外动作:reset-budget /
39
41
  recover / rebind-target / gate / findings
@@ -50,6 +52,8 @@ positional arguments:
50
52
  test-verify 基于 AST 语义变异与沙箱隔离动态验证测试用例的抓 Bug 杀伤能力
51
53
  audit 在隔离副本中启动 BugX 图审计或执行一键全息攻防渗透审计
52
54
  interaction 查看/回答 BugX 抛出的结构化交互问题(非交互宿主的答案回灌通道)
55
+ issue 问题上报与会话异常诊断(将对话现场脱敏后提交至 BugX 服务端排查)
56
+ feedback 问题与会话现场快速反馈(等同于 bugx issue report)
53
57
  advisory GitHub Security Advisory (GHSA) 标准安全公告与 PR 修复草案管理
54
58
  report 双轨制人性化安全审计报告生成器 (formal 商务正式, visual 高颜值交付)
55
59
 
@@ -177,6 +177,10 @@ DOWNLOAD_PATH = f"{AGENT_API_PREFIX}/download"
177
177
  KNOWLEDGE_PREFETCH_PATH = f"{AGENT_API_PREFIX}/knowledge/prefetch"
178
178
  VULNERABILITY_QUERY_PATH = f"{AGENT_API_PREFIX}/vulnerabilities/query"
179
179
  PATCH_VERIFICATION_PATH = f"{AGENT_API_PREFIX}/patch-verifications"
180
+ DOCS_MANIFEST_PATH = f"{AGENT_API_PREFIX}/docs/manifest"
181
+ DOCS_BUNDLE_PATH = f"{AGENT_API_PREFIX}/docs/bundle"
182
+ DOCS_SEARCH_PATH = f"{AGENT_API_PREFIX}/docs/search"
183
+ DOCS_FETCH_PATH = f"{AGENT_API_PREFIX}/docs/fetch"
180
184
  PROJECT_PROFILE_MAX_BYTES = 256 * 1024
181
185
  VULNERABILITY_QUERY_MAX_COMPONENTS = 100
182
186
 
@@ -569,8 +573,53 @@ class CloudClient:
569
573
  time.sleep(interval)
570
574
  return ReportResult(ok=False, status=None, data=None, error="授权超时")
571
575
 
572
- def login(self, name: str = "", device_id: str | None = None) -> ReportResult:
573
- """完整 device-code 登录:发码→打印 URL→尝试自动打开浏览器→轮询→存凭据。"""
576
+ def verify_device_token(self, device_code: str | None = None, device_id: str | None = None) -> ReportResult:
577
+ """单次非阻塞校验 device-token:由前端或 Agent 在用户完成网页确认后单步核验。"""
578
+ did = device_id or get_device_id()
579
+ pending_path = Path(self.cred_path).parent / "cloud-auth-pending.json"
580
+ if not device_code and pending_path.is_file():
581
+ try:
582
+ pdata = json.loads(pending_path.read_text(encoding="utf-8"))
583
+ device_code = pdata.get("device_code")
584
+ did = device_id or pdata.get("device_id") or did
585
+ except (OSError, json.JSONDecodeError):
586
+ pass
587
+ if not device_code:
588
+ return ReportResult(ok=False, status=400, data=None, error="缺少 device_code,且未发现挂起的授权请求")
589
+
590
+ res = self._request("POST", DEVICE_TOKEN_PATH,
591
+ {"device_code": device_code, "device_id": did},
592
+ auth=False, retry_auth=False)
593
+ data = res.data if isinstance(res.data, dict) else {}
594
+ err = str(data.get("error", "") or "")
595
+ inner = data.get("data") if isinstance(data.get("data"), dict) else {}
596
+ token = inner.get("token") or inner.get("access_token")
597
+ if err in {"access_denied", "expired_token", "expired"}:
598
+ code_to_msg = {
599
+ "access_denied": "用户已拒绝授权",
600
+ "expired_token": "授权码已过期,请重新登录",
601
+ "expired": "授权码已过期,请重新登录",
602
+ }
603
+ return ReportResult(ok=False, status=getattr(res, "status", None),
604
+ data=res.data, error=code_to_msg.get(err, err))
605
+ if token:
606
+ self.cred = CloudCredentials(
607
+ token=token, refresh_token=inner.get("refresh_token"),
608
+ api_key=inner.get("api_key"), user=inner.get("user"),
609
+ )
610
+ self._store_route(inner.get("route"))
611
+ self.cred.save(self.cred_path)
612
+ if pending_path.is_file():
613
+ try:
614
+ pending_path.unlink()
615
+ except OSError:
616
+ pass
617
+ return ReportResult(ok=True, status=getattr(res, "status", 200),
618
+ data=res.data, error=None)
619
+ return ReportResult(ok=False, status=202, data=res.data, error="授权仍在等待中,请确认已在浏览器点击同意")
620
+
621
+ def login(self, name: str = "", device_id: str | None = None, non_blocking: bool = False) -> ReportResult:
622
+ """完整 device-code 登录:发码→打印 URL→尝试自动打开浏览器→(若非阻塞则退出,否则轮询)→存凭据。"""
574
623
  flow = self.start_device(name=name, device_id=device_id)
575
624
  uri = flow.get("verification_uri") or ""
576
625
  # 授权页必须是普通 http(s) 地址:被劫持/被替换的服务端可能借
@@ -605,6 +654,36 @@ class CloudClient:
605
654
  print(f"已打开浏览器授权页:{uri}", flush=True)
606
655
  else:
607
656
  print(f"自动打开浏览器失败,请手动打开授权页:{uri}", flush=True)
657
+
658
+ # 非阻塞模式:保存待办信息并立即返回,由外部交互驱动
659
+ if non_blocking or os.environ.get("BUGX_NON_BLOCKING_AUTH") == "1":
660
+ pending_path = Path(self.cred_path).parent / "cloud-auth-pending.json"
661
+ pending_path.parent.mkdir(parents=True, exist_ok=True)
662
+ try:
663
+ pdata = {
664
+ "device_code": flow.get("device_code"),
665
+ "user_code": flow.get("user_code"),
666
+ "verification_uri": uri,
667
+ "device_id": device_id or get_device_id(),
668
+ "expires_in": flow.get("expires_in"),
669
+ "created_at": time.time(),
670
+ }
671
+ pending_path.write_text(json.dumps(pdata), encoding="utf-8")
672
+ os.chmod(pending_path, 0o600)
673
+ except OSError:
674
+ pass
675
+ return ReportResult(
676
+ ok=True, status=202,
677
+ data={
678
+ "status": "pending_user_confirmation",
679
+ "verification_uri": uri,
680
+ "user_code": flow.get("user_code"),
681
+ "device_code": flow.get("device_code"),
682
+ "expires_in": flow.get("expires_in"),
683
+ },
684
+ error=None,
685
+ )
686
+
608
687
  # 轮询间隔来自服务端,属不可信输入:限幅到 [1,30] 秒,拒绝 0/负值
609
688
  # 造成的忙轮询,也拒绝异常大值把登录挂死。非法类型回退默认 5s。
610
689
  try:
@@ -90,6 +90,9 @@ def load_cloud_config(path: str | Path | None = None) -> dict[str, Any]:
90
90
  dvc = data.get("disable_version_check")
91
91
  if isinstance(dvc, bool):
92
92
  result["disable_version_check"] = dvc
93
+ dre = data.get("docs_remote_enabled")
94
+ if isinstance(dre, bool):
95
+ result["docs_remote_enabled"] = dre
93
96
  # DOC-211:同步内容策略三键;非法值 fail-closed(绝不静默回退默认)。
94
97
  for key, vocab in SYNC_POLICY_VOCABS.items():
95
98
  raw = data.get(key)
@@ -329,9 +332,12 @@ def set_cloud_base_url(base_url: str, path: str | Path | None = None) -> str:
329
332
  dvc = raw.get("disable_version_check")
330
333
  if isinstance(dvc, bool):
331
334
  existing["disable_version_check"] = dvc
335
+ dre = raw.get("docs_remote_enabled")
336
+ if isinstance(dre, bool):
337
+ existing["docs_remote_enabled"] = dre
332
338
  payload = {"schema_version": 1, "base_url": normalized}
333
339
  for key, value in existing.items():
334
- if key in SYNC_POLICY_VOCABS or key == "disable_version_check":
340
+ if key in SYNC_POLICY_VOCABS or key in {"disable_version_check", "docs_remote_enabled"}:
335
341
  payload[key] = value
336
342
  atomic_write_nofollow(
337
343
  p, json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8"),
@@ -349,31 +355,38 @@ def read_cloud_config_raw(path: Path) -> dict[str, Any]:
349
355
  return data if isinstance(data, dict) else {}
350
356
 
351
357
 
352
- def update_cloud_config(updates: dict[str, str]) -> dict[str, str]:
353
- """DOC-211:raw-read 改写云端同步策略键(保留未知键,坏值状态可自修复)。
354
-
355
- 只接受 SYNC_POLICY_VOCABS 内的键,值必须命中词表,否则 ValueError。
356
- """
358
+ def update_cloud_config(updates: dict[str, Any]) -> dict[str, Any]:
359
+ """DOC-211 / DOC-006:raw-read 改写云端配置键(保留未知键,坏值状态可自修复)。"""
360
+ normalized_updates: dict[str, Any] = {}
357
361
  for key, value in updates.items():
362
+ if key == "docs_remote_enabled":
363
+ if isinstance(value, bool):
364
+ normalized_updates[key] = value
365
+ elif isinstance(value, str) and value.strip().lower() in {"true", "false"}:
366
+ normalized_updates[key] = value.strip().lower() == "true"
367
+ else:
368
+ raise ValueError(f"云端配置 {key} 非法: {value!r}(允许值: true/false)")
369
+ continue
358
370
  vocab = SYNC_POLICY_VOCABS.get(key)
359
371
  if vocab is None:
360
372
  raise ValueError(
361
- f"不支持的云端配置键: {key}(支持: {'、'.join(sorted(SYNC_POLICY_VOCABS))})")
373
+ f"不支持的云端配置键: {key}(支持: {'、'.join(sorted(SYNC_POLICY_VOCABS) + ['docs_remote_enabled'])})")
362
374
  if value not in vocab:
363
375
  raise ValueError(f"云端配置 {key} 非法: {value!r}(允许值: {'/'.join(vocab)})")
376
+ normalized_updates[key] = value
364
377
  p = cloud_config_path()
365
378
  try:
366
379
  reject_symlink_components(p)
367
380
  except AtomicWriteError as exc:
368
381
  raise ValueError(f"云端配置路径不安全: {p}") from exc
369
382
  data = read_cloud_config_raw(p)
370
- data.update(updates)
383
+ data.update(normalized_updates)
371
384
  p.parent.mkdir(parents=True, exist_ok=True)
372
385
  atomic_write_nofollow(
373
386
  p, json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8"),
374
387
  parent_mode=0o700,
375
388
  )
376
- return {key: data[key] for key in updates}
389
+ return {key: data[key] for key in normalized_updates}
377
390
 
378
391
 
379
392
  def clear_cloud_base_url(path: str | Path | None = None) -> None:
@@ -0,0 +1,297 @@
1
+ #!/usr/bin/env python3
2
+ """BugX Issue & Session Diagnostics Uploader.
3
+
4
+ Extracts session history from .bugx/sessions/, captures execution logs and
5
+ environment fingerprint, applies 3-level sensitive data redaction, and uploads
6
+ the diagnostic bundle via Gzip to BugX Server.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import gzip
12
+ import json
13
+ import logging
14
+ import os
15
+ import platform
16
+ import re
17
+ import subprocess
18
+ import urllib.error
19
+ import urllib.request
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from core.cloud_sync.device_identity import get_device_id
24
+ from core.cloud_sync.endpoint_router import configured_base_url, select_lowest_latency_endpoint
25
+ from core.cloud_sync.sensitive_filter import redact_diagnostics_payload, redact_sensitive_text
26
+ from core.infra.client_metadata import client_version, tls_context
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ ERROR_PATTERNS = re.compile(
31
+ r"(?i)\b(?:error|exception|fail(?:ed|ure)?|traceback|panic|segfault|crash)\b"
32
+ )
33
+
34
+
35
+ def find_latest_error_session(project_root: Path) -> tuple[str | None, dict[str, Any] | None, str | None]:
36
+ """智能定位最近一次包含错误标记的会话;若无错误会话则回退到最近一次会话。
37
+
38
+ 返回: (session_id, session_data_dict, extracted_error_snippet)
39
+ """
40
+ sessions_dir = project_root / ".bugx" / "sessions"
41
+ if not sessions_dir.is_dir():
42
+ return None, None, None
43
+
44
+ candidate_files = []
45
+ for p in sessions_dir.glob("*.json"):
46
+ if p.name in {"index.json", "s1.json"}:
47
+ continue
48
+ try:
49
+ stat = p.stat()
50
+ candidate_files.append((stat.st_mtime, p))
51
+ except OSError:
52
+ continue
53
+
54
+ if not candidate_files:
55
+ return None, None, None
56
+
57
+ # 按修改时间从新到旧排序
58
+ candidate_files.sort(key=lambda x: x[0], reverse=True)
59
+
60
+ fallback_session_id: str | None = None
61
+ fallback_data: dict[str, Any] | None = None
62
+
63
+ for _, path in candidate_files:
64
+ try:
65
+ content = path.read_text(encoding="utf-8", errors="replace")
66
+ data = json.loads(content)
67
+ except Exception:
68
+ continue
69
+
70
+ sid = data.get("session_id") or data.get("id") or path.stem
71
+ if not fallback_session_id:
72
+ fallback_session_id = sid
73
+ fallback_data = data
74
+
75
+ # 检查 messages 中是否存在错误信息
76
+ messages = data.get("messages") or []
77
+ for msg in reversed(messages):
78
+ text = msg.get("content") or ""
79
+ parts = msg.get("parts") or []
80
+ for part in parts:
81
+ if isinstance(part, dict) and "text" in part:
82
+ text += "\n" + str(part["text"])
83
+
84
+ if ERROR_PATTERNS.search(text):
85
+ # 提取首行或核心错误片段作为摘要
86
+ error_snippet = ""
87
+ for line in text.splitlines():
88
+ sline = line.strip()
89
+ if sline and ERROR_PATTERNS.search(sline):
90
+ error_snippet = sline[:200]
91
+ break
92
+ if not error_snippet and text.strip():
93
+ error_snippet = text.strip().splitlines()[0][:200]
94
+ return sid, data, error_snippet
95
+
96
+ return fallback_session_id, fallback_data, None
97
+
98
+
99
+ def collect_environment_context() -> dict[str, Any]:
100
+ """收集 OS、Python、Node、Git 与宿主环境上下文元数据。"""
101
+ env: dict[str, Any] = {
102
+ "os": platform.system(),
103
+ "os_release": platform.release(),
104
+ "os_arch": platform.machine(),
105
+ "python_version": platform.python_version(),
106
+ "bugx_version": client_version(),
107
+ "device_id": get_device_id(),
108
+ "host": os.environ.get("BUGX_HOST", "cli"),
109
+ "node_version": None,
110
+ "git_commit": None,
111
+ }
112
+
113
+ # 尝试获取 Node 版本
114
+ try:
115
+ proc = subprocess.run(
116
+ ["node", "-v"],
117
+ capture_output=True,
118
+ text=True,
119
+ timeout=1.5,
120
+ check=False,
121
+ )
122
+ if proc.returncode == 0 and proc.stdout.strip():
123
+ env["node_version"] = proc.stdout.strip()
124
+ except Exception:
125
+ pass
126
+
127
+ # 尝试获取 Git Commit
128
+ try:
129
+ proc = subprocess.run(
130
+ ["git", "rev-parse", "--short", "HEAD"],
131
+ capture_output=True,
132
+ text=True,
133
+ timeout=1.5,
134
+ check=False,
135
+ )
136
+ if proc.returncode == 0 and proc.stdout.strip():
137
+ env["git_commit"] = proc.stdout.strip()
138
+ except Exception:
139
+ pass
140
+
141
+ return env
142
+
143
+
144
+ def collect_recent_logs(project_root: Path, max_lines: int = 500) -> list[str]:
145
+ """读取最近的运行态核心日志切片。"""
146
+ log_candidates = [
147
+ project_root / ".bugx" / "logs" / "bugx.jsonl",
148
+ project_root / ".bugx" / "logs" / "audit.log",
149
+ ]
150
+
151
+ for log_path in log_candidates:
152
+ if log_path.is_file():
153
+ try:
154
+ lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines()
155
+ return lines[-max_lines:]
156
+ except Exception:
157
+ continue
158
+
159
+ return []
160
+
161
+
162
+ def build_issue_payload(
163
+ project_root: Path,
164
+ title: str,
165
+ desc: str = "",
166
+ session_id: str | None = None,
167
+ include_logs: bool = True,
168
+ mask_source: bool = False,
169
+ anonymous: bool = False,
170
+ ) -> tuple[dict[str, Any], list[str]]:
171
+ """装配、脱敏并构建问题上报请求 Payload。
172
+
173
+ 返回: (redacted_payload, redacted_categories)
174
+ """
175
+ env = collect_environment_context()
176
+ session_data: dict[str, Any] | None = None
177
+ extracted_error: str | None = None
178
+ sid = session_id
179
+
180
+ if sid:
181
+ sess_file = project_root / ".bugx" / "sessions" / f"{sid}.json"
182
+ if sess_file.is_file():
183
+ try:
184
+ session_data = json.loads(sess_file.read_text(encoding="utf-8", errors="replace"))
185
+ except Exception:
186
+ session_data = None
187
+ else:
188
+ found_sid, found_data, found_err = find_latest_error_session(project_root)
189
+ sid = found_sid
190
+ session_data = found_data
191
+ extracted_error = found_err
192
+
193
+ # 关联读取事件流(若存在)
194
+ events: list[dict[str, Any]] = []
195
+ if sid:
196
+ events_file = project_root / ".bugx" / "sessions" / f"{sid}.events.jsonl"
197
+ if events_file.is_file():
198
+ try:
199
+ for line in events_file.read_text(encoding="utf-8", errors="replace").splitlines():
200
+ if line.strip():
201
+ events.append(json.loads(line))
202
+ except Exception:
203
+ pass
204
+
205
+ logs = collect_recent_logs(project_root) if include_logs else []
206
+
207
+ error_type = "SessionAnomaly"
208
+ error_message = extracted_error or ""
209
+ if not title:
210
+ title = error_message or "Agent 会话异常诊断上报"
211
+
212
+ payload: dict[str, Any] = {
213
+ "device_id": "[ANONYMOUS]" if anonymous else env["device_id"],
214
+ "client_version": env["bugx_version"],
215
+ "host": env["host"],
216
+ "title": title,
217
+ "description": desc,
218
+ "error_type": error_type,
219
+ "error_message": error_message,
220
+ "environment": env,
221
+ "session_id": sid or "",
222
+ "session_data": {
223
+ "session": session_data,
224
+ "events": events[-100:] if events else [],
225
+ },
226
+ "logs_slice": logs,
227
+ }
228
+
229
+ # 执行三级深度脱敏
230
+ redacted_payload, categories = redact_diagnostics_payload(payload, mask_source=mask_source)
231
+ return redacted_payload, categories
232
+
233
+
234
+ def prepare_issue_gzip_package(payload: dict[str, Any]) -> bytes:
235
+ """序列化并使用 Gzip 压缩 Payload。"""
236
+ raw_json = json.dumps(payload, ensure_ascii=False).encode("utf-8")
237
+ return gzip.compress(raw_json)
238
+
239
+
240
+ def upload_issue(
241
+ payload: dict[str, Any],
242
+ api_url: str | None = None,
243
+ token: str | None = None,
244
+ timeout: float = 30.0,
245
+ ) -> dict[str, Any]:
246
+ """将脱敏后的问题现场数据 Gzip 压缩后上传至 BugX 服务端。
247
+
248
+ 端点: POST /api/v1/agent/issues
249
+ """
250
+ base_url = api_url or configured_base_url() or select_lowest_latency_endpoint() or "https://bugx.dev"
251
+ endpoint = f"{base_url.rstrip('/')}/api/v1/agent/issues"
252
+
253
+ # 若未指定 token,尝试从默认凭据文件读取
254
+ if not token and payload.get("device_id") != "[ANONYMOUS]":
255
+ try:
256
+ cred_path = Path(os.environ.get("BUGX_CLOUD_CREDENTIALS", str(Path.home() / ".bugx" / "cloud-credentials.json")))
257
+ if cred_path.is_file():
258
+ creds = json.loads(cred_path.read_text(encoding="utf-8"))
259
+ token = creds.get("token") or creds.get("access_token")
260
+ except Exception:
261
+ pass
262
+
263
+ compressed_body = prepare_issue_gzip_package(payload)
264
+
265
+ headers = {
266
+ "Content-Type": "application/json",
267
+ "Content-Encoding": "gzip",
268
+ "Accept": "application/json",
269
+ "X-BugX-Client-Version": str(payload.get("client_version") or client_version()),
270
+ "X-BugX-Device-ID": str(payload.get("device_id") or ""),
271
+ }
272
+ if token:
273
+ headers["Authorization"] = f"Bearer {token}"
274
+
275
+ req = urllib.request.Request(
276
+ endpoint,
277
+ data=compressed_body,
278
+ headers=headers,
279
+ method="POST",
280
+ )
281
+
282
+ ctx = tls_context()
283
+ try:
284
+ with urllib.request.urlopen(req, timeout=timeout, context=ctx) as resp:
285
+ resp_bytes = resp.read()
286
+ data = json.loads(resp_bytes.decode("utf-8", errors="replace"))
287
+ return data
288
+ except urllib.error.HTTPError as err:
289
+ err_body = err.read().decode("utf-8", errors="replace")
290
+ try:
291
+ err_json = json.loads(err_body)
292
+ msg = err_json.get("message") or err_json.get("error") or err_body
293
+ except Exception:
294
+ msg = err_body
295
+ raise RuntimeError(f"服务端拒绝上报 (HTTP {err.code}): {msg}") from err
296
+ except Exception as err:
297
+ raise RuntimeError(f"网络连接或上报失败: {err}") from err
@@ -60,6 +60,21 @@ _SENSITIVE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
60
60
  )),
61
61
  )
62
62
 
63
+ # DOC-007 强化凭据与密码脱敏正则
64
+ _ADDITIONAL_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = (
65
+ ("ai_api_key", re.compile(r"(?i)\b(?:sk-ant|sk|kimi|moonshot|deepseek)-[a-zA-Z0-9_\-\.]{15,}\b"), "{{REDACTED_API_KEY}}"),
66
+ ("bearer_token", re.compile(r"(?i)\bBearer\s+[A-Za-z0-9_.\-~+/=]{20,}\b"), "Bearer {{REDACTED_TOKEN}}"),
67
+ ("dsn_password", re.compile(r"(?i)(\b(?:postgres(?:ql)?|mysql|redis|rediss|mongo(?:db)?(?:\+srv)?|amqp|amqps)://[^:/@\s]+:)(.*?)(@[a-zA-Z0-9_\-\.:]+(?:/[^\s]*)?)"), r"\1[REDACTED_PASSWORD]\3"),
68
+ )
69
+
70
+ # DOC-007 用户主路径与用户名归一化正则
71
+ _PATH_REDACT_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
72
+ (re.compile(r"/(?:Users|home)/[a-zA-Z0-9_\-\.]+"), "~"),
73
+ (re.compile(r"[a-zA-Z]:\\\\Users\\\\[a-zA-Z0-9_\-\.]+"), "~"),
74
+ )
75
+
76
+ _SOURCE_CODE_PATTERN = re.compile(r"```[\w\s]*?\n[\s\S]*?```")
77
+
63
78
 
64
79
  def scan_sensitive_text(value: object, *, field: str) -> list[str]:
65
80
  """Return sensitive categories found in a wire field without returning values."""
@@ -128,21 +143,76 @@ def scan_kind(kind: str, items: list[dict[str, Any]], *,
128
143
  raise_sensitive_hit(f"{kind}[{index}]", hits, policy=policy)
129
144
 
130
145
 
131
- def redact_sensitive_text(text: str) -> tuple[str, list[str]]:
132
- """DOC-211 redact:按出网闸命中 span 整段替换为 typed 占位符。
146
+ class RedactedTextResult(str):
147
+ """Dual-mode text result: behaves as str (e.g. `assert 'x' in r`) and unpacks as `(str, list[str])`."""
148
+
149
+ def __new__(cls, text: str, categories: list[str] | None = None):
150
+ obj = super().__new__(cls, text)
151
+ obj.categories = categories or []
152
+ return obj
153
+
154
+ def __iter__(self):
155
+ yield str(self)
156
+ yield self.categories
133
157
 
134
- 禁止用通用 redact_text 做闸内脱敏(审计实证:`token: Bearer <真值>` 会把
135
- 方案词掩掉而残留真值,复扫双 miss)。占位符不含 key[:=]16+ 值形态,
136
- 天然不命中 _SENSITIVE_PATTERNS 复扫。
158
+
159
+ def redact_sensitive_text(text: str, mask_source: bool = False) -> RedactedTextResult:
160
+ """DOC-211 / DOC-007 redact:按出网闸命中 span 与三级脱敏管道替换敏感信息。
161
+
162
+ 支持三级过滤:
163
+ - Level 1: 凭据/密钥硬过滤 (API Keys, Bearer tokens, DSN passwords)
164
+ - Level 2: 系统路径与用户身份脱敏 (/Users/<name>, /home/<name> -> ~)
165
+ - Level 3: 源代码片段可选遮蔽 (mask_source=True)
166
+ 返回 RedactedTextResult,既兼容元组解包 (text, categories),又可直接当 str 使用。
137
167
  """
138
168
  categories: list[str] = []
139
- out = text
169
+ out = text or ""
170
+
140
171
  for category, pattern in _SENSITIVE_PATTERNS:
141
172
  replaced, count = pattern.subn("{{REDACTED_%s}}" % category.upper(), out)
142
173
  if count:
143
174
  categories.append(category)
144
175
  out = replaced
145
- return out, categories
176
+
177
+ for category, pattern, replacement in _ADDITIONAL_SECRET_PATTERNS:
178
+ replaced, count = pattern.subn(replacement, out)
179
+ if count:
180
+ categories.append(category)
181
+ out = replaced
182
+
183
+ for pattern, replacement in _PATH_REDACT_PATTERNS:
184
+ replaced, count = pattern.subn(replacement, out)
185
+ if count:
186
+ categories.append("user_path")
187
+ out = replaced
188
+
189
+ if mask_source:
190
+ replaced, count = _SOURCE_CODE_PATTERN.subn("[SOURCE_CODE_REDACTED]", out)
191
+ if count:
192
+ categories.append("source_code")
193
+ out = replaced
194
+
195
+ return RedactedTextResult(out, sorted(set(categories)))
196
+
197
+
198
+ def redact_diagnostics_payload(data: Any, mask_source: bool = False) -> tuple[Any, list[str]]:
199
+ """递归遍历并深度脱敏任意嵌套字典、列表或字符串结构。"""
200
+ categories: set[str] = set()
201
+
202
+ def _walk(val: Any) -> Any:
203
+ if isinstance(val, dict):
204
+ return {k: _walk(v) for k, v in val.items()}
205
+ if isinstance(val, list):
206
+ return [_walk(v) for v in val]
207
+ if isinstance(val, str):
208
+ res = redact_sensitive_text(val, mask_source=mask_source)
209
+ if res.categories:
210
+ categories.update(res.categories)
211
+ return str(res)
212
+ return val
213
+
214
+ processed = _walk(data)
215
+ return processed, sorted(categories)
146
216
 
147
217
 
148
218
  def redact_records_for_sync(records: Mapping[str, list]) -> tuple[dict[str, list], list[str], int]:
@@ -102,9 +102,7 @@ Worker checkpoint 后串行处理 confirmed Finding:红测、最小修复、
102
102
  仅测试通过都不是成功停止条件;仍有未修复/延期/未确认 Finding 时继续下一 Round,无法继续时报告
103
103
  `BLOCKED`/`RECOVERY_REQUIRED`。
104
104
 
105
- `bugx-docs` 是本地项目文档 MCP MVP:只索引 `README.md`、`docs/**/*.md` 和 `core/**/*.md`,
106
- 使用 SQLite FTS5,调用必须提供 project scope;设置 `BUGX_DOCS_TOKEN` 后还必须通过 token 校验。
107
- 它不访问 Context7,也不把文档内容当作可执行指令。
105
+ `bugx-docs` 是双作用域只读文档 MCP(`bugx:official` + `project:<id>`):`bugx:official` 优先挂载经 SHA-256 校验的全局不可变官档缓存(`~/.bugx/cache/docs/<contract_version>/`),离线或只读时自动回退至随包基线(`core/bundled_docs/`);`project:<id>` 仅索引当前项目可控 Markdown(`README*`、`docs/**/*.md`、`core/**/*.md`)到 `.bugx/knowledge/docs.sqlite3`(严格本地隔离,绝不上云)。提供 `resolve_library`、`search_docs`、`list_sections`、`fetch_doc` 四工具;设置 `BUGX_DOCS_TOKEN` 时强制令牌校验,严禁伪造引用或与结构化 `lesson-ledger` 混库。
108
106
 
109
107
  宿主 Agent 的 JSON 事件捕获由 `RealHooks` 使用 16 MiB 有界预算;普通 Worker 仍使用 2 MiB 上限。
110
108
  输出超限必须终止并进入失败状态,禁止将截断事件流视为完成。
@@ -136,7 +134,7 @@ Worker stdio 通道可补齐遗漏的 `caller_role`,但显式错误角色仍
136
134
  开工顺序固定为:
137
135
 
138
136
  1. 读取 README、构建文件、配置、测试、已知问题和安全边界。
139
- 2. 必须检查 codebase-memory-mcp。若 READY 且代际匹配,优先用其架构调用关系增强功能最小化;`symbol_index.py` 仍负责全量基线,`project_graph.py` 交叉校验。若未暴露、未装或未建索引,**严禁消极回退**,必须立即尝试就地自愈装配与建索引(`codebase-memory-mcp cli index_repository` 或包管理安装);仅在不可抗力阻断且自愈失败后,按启动交互记录本地回退,禁静默跳过。
137
+ 2. 必须检查核心依赖 `codebase-memory-mcp==0.12.1` 与 `tree-sitter-language-pack==1.14.3`(两者均为 `critical=True` 必装核心能力,已在 `bugx install` / `bugx doctor --repair` 阶段装配至 `~/.bugx/tools/`)。优先使用 codebase-memory 图谱做架构调用关系分析,并以 `symbol_index.py` / `project_graph.py` 做全量基线交叉校验。若未建索引须立即执行 `codebase-memory-mcp cli index_repository`;若核心包缺失或版本不匹配,**严禁消极降级或绕过放行**,必须立即运行 `bugx doctor --repair` 自愈或阻断停止。按项目栈按需使用的**可选项**(`playwright`、`postmcp`、`codindex`、`dbhub`、`redis`、`mobile`、`semgrep`、`bandit`、`ast-grep` 等)则在审计启动 `pre` 阶段由 AI 与用户共同决策启用。
140
138
  3. 识别入口、模块、数据流、权限、外部服务、状态和并发资源。
141
139
  4. 生成内部最小单元与模块间业务链路。
142
140
  5. 在覆盖清单中记录负责人、工具、证据和状态。
@@ -150,11 +148,7 @@ Web 项目必须额外加入 `web-standards` 审计轨道,先运行
150
148
 
151
149
  最终目标是内部最小单元 100% 且业务链路 100%。环境、授权、设备或依赖导致无法覆盖时,必须标为 `BLOCKED/UNVERIFIED` 并写明原因,不能宣称完成。
152
150
 
153
- **环境加速器降级必须显式汇报**:`pre` 运行 `codebase_memory_probe.py` /
154
- `efficiency_probe.py` 后,任何 `DEGRADED` 项不得静默吞掉。交互模式必须在探针完成后弹出菜单提供
155
- 「立即安装配置 / 本轮跳过使用回退 / 下次再说(停止本轮)」;空回车不默认跳过。自治模式
156
- 不弹菜单,只能自动选探针明确声明的回退并将处置写入开工准备记录;未声明回退的
157
- 降级项仍须停止。无交互终端、配置未完成或存在未决策降级项时交互启动须停止返回待决策状态。
151
+ **项目可选项降级与核心必选项阻断**:`codebase-memory-mcp` 与 `tree-sitter-language-pack` 属于核心必选项(`critical=True`),不得豁免或降级放行;其余项目栈相关可选项(如 `efficiency_probe` 外部工具、SAST/Mobile/UI 驱动)按项目适用性裁剪,仅在适用且未就绪时于交互模式弹出菜单提供「立即安装配置 / 本轮跳过使用回退 / 下次再说(停止本轮)」(空回车不默认跳过)。自治模式不弹菜单,只能自动选探针明确声明的非关键回退并将处置写入开工准备记录;未声明回退或 `critical=True` 的核心能力缺失仍须阻断停止。无交互终端、配置未完成或存在未决策降级项时交互启动须停止返回待决策状态。
158
152
  自治回退不改探针为 READY,不伪造设备或图谱证据;Context7 缺 Key 时使用本地文档检索。禁只看退出码 0 当环境就绪。
159
153
  自动化测试或上层明确批准回退时方可显式传入 `pre --allow-degraded`;不得由宿主默认添加。
160
154
 
@@ -1,6 +1,6 @@
1
1
  # BugX 智能体执行协议与交互契约子系统 (Agent Runtime Contracts & Protocols)
2
2
 
3
- > **版本契约**: `0.1.2` | **父系统**: `core/`
3
+ > **版本契约**: `0.1.4` | **父系统**: `core/`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md) 与 [`docs/02_architecture/06_MODULE_GOVERNANCE_SPEC.md`](../../docs/02_architecture/06_MODULE_GOVERNANCE_SPEC.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 索引对齐防漂移)
6
6