bugx-cli 0.1.1 → 0.1.3

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 (131) hide show
  1. package/README.md +36 -35
  2. package/core/README.md +1 -1
  3. package/core/agent/agent_orchestrator.py +3 -0
  4. package/core/agent/agent_workspace.py +14 -2
  5. package/core/assets/README.md +3 -2
  6. package/core/assets/bugx-social-preview.svg +71 -0
  7. package/core/assets/bugx-wechat-group.png +0 -0
  8. package/core/assets/twitter_promo_art.jpg +0 -0
  9. package/core/assets/twitter_promo_card.svg +166 -0
  10. package/core/assets/twitter_promo_clean.jpg +0 -0
  11. package/core/assets/twitter_terminal_real.png +0 -0
  12. package/core/audit_packs/README.md +2 -0
  13. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  14. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  15. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  16. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  17. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  18. package/core/audit_packs/pitfalls/python_web.json +82 -0
  19. package/core/bugx.md +2 -2
  20. package/core/bugx_paths.py +2 -2
  21. package/core/cli-help.txt +1 -1
  22. package/core/cloud_sync/cloud_client.py +56 -5
  23. package/core/cloud_sync/consent.py +33 -3
  24. package/core/cloud_sync/flywheel_client.py +186 -24
  25. package/core/contracts/README.md +1 -1
  26. package/core/contracts/bugx-opencode.md +1 -1
  27. package/core/contracts/bugx-runtime-contract.md +1 -1
  28. package/core/contracts/bugx-worker.md +1 -1
  29. package/core/engine-integrity.json +191 -95
  30. package/core/host_acp/kimi.py +175 -0
  31. package/core/host_acp/minimax.py +28 -0
  32. package/core/host_runtime/host_registry.py +23 -3
  33. package/core/hosts/dsh.py +1 -1
  34. package/core/hosts/kimi.py +293 -0
  35. package/core/hosts/minimax.py +248 -0
  36. package/core/hosts/zcode.py +5 -0
  37. package/core/infra/README.md +1 -1
  38. package/core/infra/build_info.py +30 -5
  39. package/core/launch_phases/README.md +6 -3
  40. package/core/launch_phases/finding_confirm_phase.py +168 -7
  41. package/core/launch_phases/post_phase.py +5 -5
  42. package/core/launch_phases/pre_recon_scout.py +13 -0
  43. package/core/launch_phases/report_sharing.py +3 -7
  44. package/core/launch_phases/round_orchestrator.py +114 -26
  45. package/core/launch_phases/semantic_recon.py +545 -0
  46. package/core/launch_phases/startup_version_gate.py +6 -2
  47. package/core/launch_phases/supervisor_bridge.py +14 -23
  48. package/core/launch_phases/verify_loop.py +767 -0
  49. package/core/launch_phases/worker_prior.py +115 -0
  50. package/core/ledger/README.md +2 -1
  51. package/core/ledger/finding_verification.py +511 -2
  52. package/core/ledger/fp_ledger.py +255 -0
  53. package/core/metadata.txt +2 -2
  54. package/core/planning/README.md +2 -1
  55. package/core/planning/prompt_harness.py +50 -10
  56. package/core/planning/prompt_policy_engine.py +386 -0
  57. package/core/prompts/README.md +4 -2
  58. package/core/prompts/policies/prompt_policies.json +101 -0
  59. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  60. package/core/prompts/stages/stage_verify.md +44 -0
  61. package/core/report_engine/report_share.py +0 -8
  62. package/core/retrieval/README.md +2 -1
  63. package/core/retrieval/pitfall_packs.py +277 -0
  64. package/core/runtime/README.md +1 -1
  65. package/core/runtime/global_telemetry.py +20 -0
  66. package/core/runtime/scenario_eval.py +1 -1
  67. package/core/runtime/setup_ui_env.py +4 -7
  68. package/core/supervisor/README.md +1 -1
  69. package/core/supervisor/cli.py +2 -2
  70. package/core/webui/mcp_inspector.py +6 -0
  71. package/core/webui/static/index.html +51 -3
  72. package/core/webui/static/manifest.webmanifest +1 -1
  73. package/core/webui/static/project-settings.js +18 -3
  74. package/core/webui/static/robots.txt +36 -0
  75. package/core/webui/static/sitemap.xml +15 -0
  76. package/docs/07_distribution/01_README_NPM.md +36 -35
  77. package/ecosystem/integrations/cline/skills/bugx/SKILL.md +1 -1
  78. package/ecosystem/integrations/dsh/agents/bugx.md +1 -1
  79. package/ecosystem/integrations/dsh/dsh-patch.yml +2 -2
  80. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  81. package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +1 -1
  82. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  83. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  84. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
  85. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  86. package/ecosystem/integrations/pi/skills/bugx/SKILL.md +1 -1
  87. package/ecosystem/integrations/qoder/connector-meta.json +9 -9
  88. package/ecosystem/integrations/workbuddy/connector-meta.json +9 -9
  89. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +2 -2
  90. package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +2 -2
  91. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +2 -2
  92. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +4 -4
  93. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +2 -2
  94. package/ecosystem/plugins/bugx/agents/bugx-worker.md +1 -1
  95. package/ecosystem/plugins/bugx/agents/bugx.md +1 -1
  96. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +3 -3
  97. package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +1 -1
  98. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  99. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  100. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  101. package/interfaces/bin/bugx.js +9 -7
  102. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  103. package/interfaces/cli/bugx_cli/cli.py +178 -67
  104. package/interfaces/cli/bugx_cli/commands/agent.py +313 -127
  105. package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
  106. package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
  107. package/interfaces/cli/bugx_cli/commands/doctor.py +18 -0
  108. package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
  109. package/interfaces/cli/bugx_cli/commands/lifecycle.py +54 -47
  110. package/interfaces/cli/bugx_cli/commands/plugin.py +9 -9
  111. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +27 -13
  112. package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +348 -0
  113. package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +322 -0
  114. package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +3 -4
  115. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +4 -5
  116. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  117. package/interfaces/cli/bugx_cli/commands/system.py +577 -162
  118. package/interfaces/cli/bugx_cli/common.py +102 -15
  119. package/interfaces/cli/bugx_cli/host_adapters.py +150 -4
  120. package/interfaces/cli/bugx_cli/hosts/registry.py +4 -2
  121. package/interfaces/cli/bugx_cli/hosts/template_engine.py +10 -9
  122. package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
  123. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  124. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +2 -2
  125. package/package.json +54 -16
  126. package/pyproject.toml +64 -1
  127. package/scripts/sync-version.mjs +1 -1
  128. package/skills/README.md +25 -0
  129. package/skills/platform/bugx-user/SKILL.md +92 -0
  130. package/core/assets/bugx-hero-cn.png +0 -0
  131. package/core/assets/bugx-hero-en.png +0 -0
@@ -8,6 +8,7 @@ import hashlib
8
8
  import importlib.metadata
9
9
  import io
10
10
  import json
11
+ import math
11
12
  import os
12
13
  import re
13
14
  import shutil
@@ -38,19 +39,6 @@ from ..infra.security import _assert_no_symlink_components
38
39
  from .cloud import _supervisor_deploy, _supervisor_status
39
40
 
40
41
 
41
- _COMPLETION_CHILDREN = {
42
- "auth": ("login", "status", "set-key", "logout"),
43
- "cloud": (
44
- "config", "status", "log-report", "feedback", "sync", "export",
45
- "upload", "conflicts", "projects", "devices", "onboard",
46
- ),
47
- "completion": ("bash", "zsh", "fish"),
48
- "hosts": ("--json", "--root"),
49
- "install": ("--agent", "--allow-missing", "--force", "--json", "--non-interactive", "--root"),
50
- "autonomous": ("--agent-timeout", "--host", "--json", "--max-turns", "--max-wall-time", "--root"),
51
- "skill": ("list", "status", "validate", "rollback"),
52
- "update": ("--allow-downgrade", "--channel", "--check", "--force", "--repair-assets", "--root"),
53
- }
54
42
 
55
43
  _ASSET_REPAIR_ATTEMPT_ENV = "BUGX_ASSET_REPAIR_ATTEMPTED"
56
44
  # Stable package recovery is a separate trust path from the user's configurable
@@ -62,79 +50,90 @@ _STABLE_AGENT_FILES_HOST = "files.pythonhosted.org"
62
50
  _MAX_PYPI_METADATA_BYTES = 4 * 1024 * 1024
63
51
  _MAX_PYPI_WHEEL_BYTES = 128 * 1024 * 1024
64
52
 
53
+ DEFAULT_PROBE_TIMEOUT_SECONDS = 120.0
54
+ MAX_PROBE_TIMEOUT_SECONDS = 1800.0
55
+
56
+
57
+ def completion_tree(parser: argparse.ArgumentParser) -> dict[str, tuple[str, ...]]:
58
+ """Derive nested commands, enum selectors and options from the CLI parser."""
59
+ tree: dict[str, tuple[str, ...]] = {}
60
+
61
+ def collect(current: argparse.ArgumentParser, route: str) -> None:
62
+ words: set[str] = set()
63
+ for action in current._actions:
64
+ if action.help == argparse.SUPPRESS:
65
+ continue
66
+ if isinstance(action, argparse._SubParsersAction):
67
+ words.update(action.choices)
68
+ for name, child in action.choices.items():
69
+ collect(child, f"{route}/{name}")
70
+ elif action.option_strings:
71
+ words.update(action.option_strings)
72
+ elif action.choices:
73
+ words.update(str(choice) for choice in action.choices)
74
+ tree[route] = tuple(sorted(words))
75
+
76
+ collect(parser, "")
77
+ return tree
78
+
65
79
 
66
80
  def command_completion(args: argparse.Namespace) -> int:
67
- """Print a small, dependency-free shell completion script."""
68
- commands = tuple(getattr(args, "completion_commands", ()))
69
- if not commands:
70
- commands = (
71
- "auth", "autonomous", "cloud", "completion", "daemon", "doctor", "dsh", "help", "hosts",
72
- "init", "install", "knowledge", "lesson", "log", "logic-analysis",
73
- "mcp", "mcp-runtime", "mining-audit", "patch-forge", "plugin", "probe",
74
- "project", "reset", "self-audit", "skill", "stats", "supervisor", "test-audit",
75
- "test-generate", "test-verify", "uninstall", "update",
76
- )
77
- words = " ".join(commands)
78
- children = {name: " ".join(values) for name, values in _COMPLETION_CHILDREN.items()}
81
+ """Print shell completions for the same commands and options as help."""
82
+ tree = args.completion_tree
79
83
  shell = args.shell
80
- if shell == "bash":
81
- print(f'''_bugx_complete() {{
82
- local cur="${{COMP_WORDS[COMP_CWORD]}}"
83
- local cmd="${{COMP_WORDS[1]:-}}"
84
- local words="{words}"
85
- if [[ "$COMP_CWORD" -eq 1 ]]; then
86
- COMPREPLY=( $(compgen -W "$words" -- "$cur") )
87
- return
88
- fi
89
- case "$cmd" in
90
- auth) words="{children['auth']}" ;;
91
- cloud) words="{children['cloud']}" ;;
92
- completion) words="{children['completion']}" ;;
93
- hosts) words="{children['hosts']}" ;;
94
- install) words="{children['install']}" ;;
95
- autonomous) words="{children['autonomous']}" ;;
96
- skill) words="{children['skill']}" ;;
97
- update) words="{children['update']}" ;;
98
- *) return ;;
99
- esac
100
- COMPREPLY=( $(compgen -W "$words" -- "$cur") )
101
- }}
102
- complete -F _bugx_complete bugx''')
103
- elif shell == "zsh":
104
- command_items = " ".join(f"'{item}'" for item in commands)
105
- print(f'''#compdef bugx
106
- _bugx() {{
107
- local -a commands
108
- commands=({command_items})
109
- _arguments '1:command:->command' '*::arg:->args'
110
- case $state in
111
- command) _describe 'command' commands ;;
112
- args)
113
- case $words[2] in
114
- auth) _describe 'auth action' ({children['auth'].replace(' ', ' ')}) ;;
115
- cloud) _describe 'cloud command' ({children['cloud']}) ;;
116
- completion) _describe 'shell' ({children['completion']}) ;;
117
- hosts) _describe 'option' ({children['hosts']}) ;;
118
- install) _describe 'option' ({children['install']}) ;;
119
- autonomous) _describe 'option' ({children['autonomous']}) ;;
120
- skill) _describe 'skill action' ({children['skill']}) ;;
121
- update) _describe 'option' ({children['update']}) ;;
122
- esac
123
- ;;
84
+ routes = "\n".join(f" '{route}') candidates='{' '.join(words)}' ;;" for route, words in tree.items())
85
+ transitions = "|".join(f"'{route}'" for route in tree if route)
86
+ if shell in {"bash", "zsh"}:
87
+ if shell == "bash":
88
+ init = 'local -a tokens=("${COMP_WORDS[@]}")'
89
+ limit = "COMP_CWORD"
90
+ emit = 'COMPREPLY=( $(compgen -W "$candidates" -- "$cur") )'
91
+ register = "complete -F _bugx_complete bugx"
92
+ start = 1
93
+ else:
94
+ init = 'local -a tokens=("${words[@]}")'
95
+ limit = "CURRENT"
96
+ emit = 'compadd -- $=candidates'
97
+ register = "compdef _bugx_complete bugx"
98
+ start = 2
99
+ print(f"""_bugx_complete() {{
100
+ {init}
101
+ local i route='' candidates='' cur
102
+ for ((i={start}; i<{limit}; i++)); do
103
+ case "$route/${{tokens[i]}}" in
104
+ {transitions}) route="$route/${{tokens[i]}}" ;;
105
+ esac
106
+ done
107
+ cur="${{tokens[i]}}"
108
+ case "$route" in
109
+ {routes}
124
110
  esac
111
+ {emit}
125
112
  }}
126
- _bugx''')
113
+ {register}""")
127
114
  elif shell == "fish":
128
- print(f'''complete -c bugx -f -n '__fish_use_subcommand' -a '{words}'
129
- complete -c bugx -f -n '__fish_seen_subcommand_from auth' -a '{children['auth']}'
130
- complete -c bugx -f -n '__fish_seen_subcommand_from cloud' -a '{children['cloud']}'
131
- complete -c bugx -f -n '__fish_seen_subcommand_from completion' -a '{children['completion']}'
132
- complete -c bugx -f -n '__fish_seen_subcommand_from hosts' -a '{children['hosts']}'
133
- complete -c bugx -f -n '__fish_seen_subcommand_from install' -a '{children['install']}'
134
- complete -c bugx -f -n '__fish_seen_subcommand_from autonomous' -a '{children['autonomous']}'
135
- complete -c bugx -f -n '__fish_seen_subcommand_from skill' -a '{children['skill']}'
136
- complete -c bugx -f -n '__fish_seen_subcommand_from update' -a '{children['update']}' ''')
137
- else: # argparse choices make this unreachable; keep the handler safe for embedding.
115
+ print("""function __bugx_at
116
+ set -l route ''
117
+ set -l tokens (commandline -opc)
118
+ for token in $tokens[2..-1]
119
+ switch "$route/$token" """)
120
+ fish_routes = " ".join(f"'{route}'" for route in tree if route)
121
+ print(f" case {fish_routes}")
122
+ print(""" set route "$route/$token"
123
+ end
124
+ end
125
+ test "$route/" = "$argv[1]"
126
+ end""")
127
+ for route, words in tree.items():
128
+ for word in words:
129
+ if word.startswith("--"):
130
+ flag = f"-l '{word[2:]}'"
131
+ elif word.startswith("-"):
132
+ flag = f"-s '{word[1:]}'"
133
+ else:
134
+ flag = f"-a '{word}'"
135
+ print(f"complete -c bugx -f -n '__bugx_at {route + '/'}' {flag}")
136
+ else:
138
137
  raise CliError(f"不支持的 shell: {shell}")
139
138
  return 0
140
139
 
@@ -160,6 +159,38 @@ def _update_channel(args: argparse.Namespace) -> str:
160
159
  return "stable"
161
160
 
162
161
 
162
+ def _update_installation_kind() -> tuple[str, str]:
163
+ """Return (client_kind, artifact_kind) for the running installation.
164
+
165
+ The npm wrapper deliberately owns its Python path and bundled assets, so a
166
+ pip wheel installation is not a valid npm update. Source and editable
167
+ installs are reported explicitly and must not be overwritten by update.
168
+ """
169
+ if os.environ.get("BUGX_CLI_SOURCE", "").strip().lower() == "npm":
170
+ return "npm", "npm-tarball"
171
+ try:
172
+ distribution = importlib.metadata.distribution("bugx-cli")
173
+ except importlib.metadata.PackageNotFoundError:
174
+ return "source", "python-wheel"
175
+ try:
176
+ direct_url_text = distribution.read_text("direct_url.json")
177
+ if direct_url_text:
178
+ direct_url = json.loads(direct_url_text)
179
+ if isinstance(direct_url, dict):
180
+ dir_info = direct_url.get("dir_info")
181
+ if isinstance(dir_info, dict) and dir_info.get("editable") is True:
182
+ return "editable", "python-wheel"
183
+ except (OSError, UnicodeError, json.JSONDecodeError):
184
+ return "unknown", "python-wheel"
185
+ module_path = Path(__file__).resolve()
186
+ try:
187
+ if (module_path.parents[4] / ".git").exists():
188
+ return "source", "python-wheel"
189
+ except IndexError:
190
+ pass
191
+ return "pip", "python-wheel"
192
+
193
+
163
194
  def command_version_check(args: argparse.Namespace) -> int:
164
195
  """bugx update --check:向服务端查询最新版本,提示更新。
165
196
 
@@ -172,10 +203,6 @@ def command_version_check(args: argparse.Namespace) -> int:
172
203
  # 仅供内部复用;公共入口是 bugx update --check。
173
204
  print(f"BugX CLI v{__version__}")
174
205
  return 0
175
- if os.environ.get("BUGX_DISABLE_VERSION_CHECK", "").lower() in {"1", "true", "yes"}:
176
- print("[update] 版本检查已由 BUGX_DISABLE_VERSION_CHECK 禁用")
177
- return 0
178
-
179
206
  try:
180
207
  _ensure_core_importable()
181
208
  from core.cloud_sync.cloud_client import CloudClient
@@ -183,10 +210,16 @@ def command_version_check(args: argparse.Namespace) -> int:
183
210
  print(f"[update] 依赖加载失败: {exc}")
184
211
  return 2
185
212
 
213
+ client_kind, artifact_kind = _update_installation_kind()
186
214
  client = CloudClient()
187
215
  channel = _update_channel(args)
188
216
  try:
189
- result = client.check_version(current_version=__version__, channel=channel)
217
+ result = client.check_version(
218
+ current_version=__version__,
219
+ channel=channel,
220
+ client_kind=client_kind,
221
+ artifact_kind=artifact_kind,
222
+ )
190
223
  except Exception as exc: # noqa: BLE001
191
224
  print(f"[update] 版本检查失败: {exc}")
192
225
  _print_version_tls_hint(exc)
@@ -234,8 +267,14 @@ def command_version_check(args: argparse.Namespace) -> int:
234
267
  or (min_version is not None and current_version < min_version))
235
268
 
236
269
  if getattr(args, "json", False):
237
- print(json.dumps(info, ensure_ascii=False, indent=2))
238
- return 0
270
+ payload = dict(info)
271
+ payload["status"] = (
272
+ "UPDATE_REQUIRED" if update_required
273
+ else "UPDATE_AVAILABLE" if update_available
274
+ else "UP_TO_DATE"
275
+ )
276
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
277
+ return 1 if update_available or update_required else 0
239
278
 
240
279
  print(f"当前版本: {__version__}")
241
280
  if latest:
@@ -533,8 +572,8 @@ def _download_pypi_stable_wheel(
533
572
  response.close()
534
573
 
535
574
 
536
- def _prepare_cli_package(path: Path) -> Path:
537
- """Give a downloaded wheel/sdist the extension pip uses to identify it."""
575
+ def _prepare_cli_package(path: Path, *, expected_version: str | None = None) -> Path:
576
+ """Validate a downloaded Python package and give it a pip-safe suffix."""
538
577
  try:
539
578
  if zipfile.is_zipfile(path):
540
579
  with zipfile.ZipFile(path) as archive:
@@ -555,6 +594,14 @@ def _prepare_cli_package(path: Path) -> Path:
555
594
  version = str(metadata.get("Version") or "").strip()
556
595
  if not name or not version:
557
596
  raise CliError(_i18n_exc("system.wheel_name_version_missing", "wheel 包缺少 Name/Version 元数据"))
597
+ normalized_name = re.sub(r"[-_.]+", "-", name).lower()
598
+ if expected_version is not None and (
599
+ normalized_name != "bugx-cli" or version != expected_version
600
+ ):
601
+ raise CliError(
602
+ f"wheel 身份不匹配:期望 bugx-cli {expected_version},"
603
+ f"收到 {normalized_name or '未知包'} {version or '未知版本'}"
604
+ )
558
605
  tags: list[str] = []
559
606
  if wheel_names:
560
607
  for line in archive.read(wheel_names[0]).decode(
@@ -586,6 +633,38 @@ def _prepare_cli_package(path: Path) -> Path:
586
633
  )), None)
587
634
  if root is None:
588
635
  raise CliError(_i18n_exc("system.sdist_missing_top_dir", "源码包缺少合法的顶层项目目录"))
636
+ if expected_version is not None:
637
+ metadata_members = [
638
+ member for member in archive.getmembers()
639
+ if member.isfile()
640
+ and PurePosixPath(member.name).name == "PKG-INFO"
641
+ and member.size <= 1024 * 1024
642
+ ]
643
+ if not metadata_members:
644
+ raise CliError("源码包缺少 PKG-INFO 元数据")
645
+ metadata_file = archive.extractfile(metadata_members[0])
646
+ if metadata_file is None:
647
+ raise CliError("无法读取源码包 PKG-INFO 元数据")
648
+ metadata = Parser().parsestr(
649
+ metadata_file.read().decode("utf-8", errors="strict")
650
+ )
651
+ package_name = re.sub(
652
+ r"[-_.]+", "-", str(metadata.get("Name") or "")
653
+ ).lower()
654
+ package_version = str(metadata.get("Version") or "").strip()
655
+ if package_name != "bugx-cli" or package_version != expected_version:
656
+ raise CliError(
657
+ f"源码包身份不匹配:期望 bugx-cli {expected_version},"
658
+ f"收到 {package_name or '未知包'} {package_version or '未知版本'}"
659
+ )
660
+ expected_root = re.sub(
661
+ r"[-_.+]+", "-", f"bugx-cli-{expected_version}"
662
+ ).lower()
663
+ actual_root = re.sub(r"[-_.]+", "-", root).lower()
664
+ if actual_root != expected_root:
665
+ raise CliError(
666
+ f"源码包身份不匹配:期望 {expected_root},实际 {actual_root}"
667
+ )
589
668
  target = path.with_name(f"{root}.tar.gz")
590
669
  else:
591
670
  raise CliError(_i18n_exc("system.unrecognized_package_archive", "下载内容不是可识别的 wheel 或源码包"))
@@ -604,6 +683,62 @@ def _installed_cli_distribution_version() -> str | None:
604
683
  return None
605
684
 
606
685
 
686
+ def _prepare_npm_package(path: Path, *, expected_version: str) -> Path:
687
+ """Validate an npm tarball without extracting or executing its scripts."""
688
+ if path.suffix.lower() != ".tgz":
689
+ raise CliError("npm 自动更新只接受 .tgz 制品")
690
+ try:
691
+ with tarfile.open(path, "r:gz") as archive:
692
+ member = archive.getmember("package/package.json")
693
+ if not member.isfile() or member.size > 256 * 1024:
694
+ raise CliError("npm 制品缺少安全的 package/package.json")
695
+ raw = archive.extractfile(member)
696
+ if raw is None:
697
+ raise CliError("无法读取 npm package.json")
698
+ payload = json.loads(raw.read().decode("utf-8", errors="strict"))
699
+ except (OSError, UnicodeError, json.JSONDecodeError, tarfile.TarError, KeyError) as exc:
700
+ raise CliError(f"无法识别 npm 制品:{exc}") from exc
701
+ if not isinstance(payload, dict) or payload.get("name") != "bugx-cli":
702
+ raise CliError("npm 制品 package.name 必须是 bugx-cli")
703
+ actual_version = str(payload.get("version") or "").strip()
704
+ if not actual_version or actual_version != expected_version:
705
+ raise CliError(
706
+ f"npm 制品版本不匹配:期望 {expected_version},实际 {actual_version or '未知'}"
707
+ )
708
+ return path
709
+
710
+
711
+ def _write_update_receipt(payload: dict[str, object]) -> Path | None:
712
+ """Persist a bounded, non-secret update receipt outside project sources."""
713
+ try:
714
+ from core.report_engine.report_client import atomic_write_nofollow
715
+
716
+ root = Path.home() / ".bugx" / "update" / "receipts"
717
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
718
+ operation_id = str(payload.get("operation_id") or f"upd-{time.time_ns()}")
719
+ destination = root / f"{operation_id}.json"
720
+ atomic_write_nofollow(
721
+ destination,
722
+ (json.dumps(payload, ensure_ascii=False, sort_keys=True, indent=2) + "\n").encode("utf-8"),
723
+ mode=0o600,
724
+ )
725
+ return destination
726
+ except (OSError, ValueError, TypeError, ImportError):
727
+ return None
728
+
729
+
730
+ def _receipt_project_identity(root: Path) -> dict[str, str]:
731
+ """Return a stable project identity without persisting its absolute path."""
732
+ try:
733
+ normalized = str(root.resolve())
734
+ except (OSError, RuntimeError, ValueError):
735
+ normalized = str(root)
736
+ fingerprint = hashlib.sha256(
737
+ normalized.encode("utf-8", "surrogatepass")
738
+ ).hexdigest()[:16]
739
+ return {"project_root_fingerprint": f"sha256:{fingerprint}"}
740
+
741
+
607
742
  def _trusted_repair_cloud_client():
608
743
  """Load CloudClient only from a self-consistent installed global engine."""
609
744
  engine_root = global_engine_root()
@@ -1552,13 +1687,18 @@ def command_update(args: argparse.Namespace) -> int:
1552
1687
  1. GET /api/v1/agent/version 获取最新版本元数据
1553
1688
  2. 如果已是最新 → 提示并退出
1554
1689
  3. 下载 CLI 包到临时目录
1555
- 4. SHA-256 校验
1556
- 5. pip install --upgrade <下载的包路径>
1690
+ 4. SHA-256 校验并确认制品身份
1691
+ 5. 由当前安装类型所属的 pip 或 npm 安装器安装
1557
1692
  6. bugx install --agent <已登记宿主> --root . --force --non-interactive(刷新宿主入口)
1558
1693
  7. bugx doctor --installation-only 验证
1559
1694
  """
1560
1695
  root = getattr(args, "root", Path.cwd()).resolve()
1561
1696
  started = time.monotonic()
1697
+ started_epoch = time.time()
1698
+ operation_id = f"upd-{time.time_ns()}"
1699
+ client_kind, artifact_kind = _update_installation_kind()
1700
+ switched = False
1701
+ last_receipt: Path | None = None
1562
1702
 
1563
1703
  if getattr(args, "repair_assets", False):
1564
1704
  if getattr(args, "check", False):
@@ -1588,9 +1728,27 @@ def command_update(args: argparse.Namespace) -> int:
1588
1728
  restart_cli_after_asset_repair()
1589
1729
 
1590
1730
  def record_failure(message: str, *, phase: str, **fields: object) -> None:
1731
+ nonlocal last_receipt
1732
+ final_state = "RECOVERY_REQUIRED" if switched else "ABORTED"
1733
+ receipt_payload = {
1734
+ "schema_version": 1,
1735
+ "operation_id": operation_id,
1736
+ "started_at_epoch": started_epoch,
1737
+ "finished_at_epoch": time.time(),
1738
+ "current_version": __version__,
1739
+ "client_kind": client_kind,
1740
+ "artifact_kind": artifact_kind,
1741
+ "phase": phase,
1742
+ "final_state": final_state,
1743
+ "message": str(message)[:1000],
1744
+ **_receipt_project_identity(root),
1745
+ **{str(key): value for key, value in fields.items()},
1746
+ }
1747
+ last_receipt = _write_update_receipt(receipt_payload)
1591
1748
  _log_update_event(
1592
1749
  root, "update_check_failed", message,
1593
1750
  phase=phase, duration_ms=round((time.monotonic() - started) * 1000, 1),
1751
+ operation_id=operation_id, final_state=final_state, receipt_path=str(last_receipt or ""),
1594
1752
  **fields,
1595
1753
  )
1596
1754
 
@@ -1609,12 +1767,26 @@ def command_update(args: argparse.Namespace) -> int:
1609
1767
  if getattr(args, "check", False):
1610
1768
  return command_version_check(args)
1611
1769
 
1770
+ if client_kind in {"source", "editable", "unknown"}:
1771
+ message = (
1772
+ f"当前 CLI 安装方式为 {client_kind},拒绝自动覆盖源码或 editable 环境;"
1773
+ "请使用源码同步、构建 wheel 或宿主专用安装流程更新"
1774
+ )
1775
+ record_failure(message, phase="preflight", failure_kind="unsupported_install_mode")
1776
+ print(f"[update] {message}")
1777
+ return 2
1778
+
1612
1779
  client = CloudClient()
1613
1780
 
1614
1781
  # 1. 版本检查(支持指定发布通道)
1615
1782
  channel = _update_channel(args)
1616
1783
  try:
1617
- result = client.check_version(current_version=__version__, channel=channel)
1784
+ result = client.check_version(
1785
+ current_version=__version__,
1786
+ channel=channel,
1787
+ client_kind=client_kind,
1788
+ artifact_kind=artifact_kind,
1789
+ )
1618
1790
  except Exception as exc: # noqa: BLE001
1619
1791
  record_failure(str(exc), phase="version_check", failure_kind="exception")
1620
1792
  print(f"[update] 版本检查失败: {exc}")
@@ -1642,6 +1814,34 @@ def command_update(args: argparse.Namespace) -> int:
1642
1814
  min_client = str(info.get("min_client_version") or "").strip()
1643
1815
  checksum = str(info.get("checksum_sha256") or "").strip().lower()
1644
1816
  notes = str(info.get("release_notes") or "")
1817
+ release_id = str(info.get("release_id") or "").strip()
1818
+ remote_channel = str(info.get("channel") or "").strip()
1819
+ remote_artifact_kind = str(info.get("artifact_kind") or "").strip()
1820
+ artifact_version = str(info.get("artifact_version") or latest).strip()
1821
+ if remote_channel and remote_channel != channel:
1822
+ record_failure(
1823
+ "服务端返回了错误发布通道",
1824
+ phase="version_validation",
1825
+ failure_kind="channel_mismatch",
1826
+ requested_channel=channel,
1827
+ remote_channel=remote_channel,
1828
+ )
1829
+ print(
1830
+ f"[update] 服务端通道不一致:请求 {channel},收到 {remote_channel}"
1831
+ )
1832
+ return 2
1833
+ if remote_artifact_kind and remote_artifact_kind != artifact_kind:
1834
+ record_failure(
1835
+ "服务端返回了错误制品类型",
1836
+ phase="version_validation",
1837
+ failure_kind="artifact_kind_mismatch",
1838
+ expected_artifact_kind=artifact_kind,
1839
+ remote_artifact_kind=remote_artifact_kind,
1840
+ )
1841
+ print(
1842
+ f"[update] 服务端制品类型不一致:期望 {artifact_kind},收到 {remote_artifact_kind}"
1843
+ )
1844
+ return 2
1645
1845
  update_available = info.get("update_available") is True
1646
1846
  update_required = info.get("update_required") is True
1647
1847
  rollback_required = (info.get("rollback_required") is True
@@ -1698,6 +1898,15 @@ def command_update(args: argparse.Namespace) -> int:
1698
1898
  failure_kind="missing_checksum", latest_version=latest)
1699
1899
  print("[update] 服务端未提供有效 SHA-256 校验值,拒绝安装未校验的升级包")
1700
1900
  return 2
1901
+ if not release_id:
1902
+ record_failure(
1903
+ "服务端未提供 release_id,拒绝未绑定发布身份的升级包",
1904
+ phase="package_validation",
1905
+ failure_kind="missing_release_id",
1906
+ latest_version=latest,
1907
+ )
1908
+ print("[update] 服务端未提供 release_id,拒绝安装未绑定发布身份的升级包")
1909
+ return 2
1701
1910
 
1702
1911
  print(f"[update] 当前版本: {__version__}")
1703
1912
  print(f"[update] 目标版本: {latest}")
@@ -1708,10 +1917,16 @@ def command_update(args: argparse.Namespace) -> int:
1708
1917
  # /agent/download;服务端的 302 由下载器跟随,摘要校验始终在本地完成。
1709
1918
  tmpdir = Path(tempfile.mkdtemp(prefix="bugx-update-"))
1710
1919
  try:
1711
- dest = tmpdir / f"bugx-{latest}.package"
1920
+ suffix = ".tgz" if artifact_kind == "npm-tarball" else ".package"
1921
+ dest = tmpdir / f"bugx-{artifact_version}{suffix}"
1712
1922
  print(f"[update] 正在下载 CLI 包...")
1713
1923
  ok, msg = client.download_package(
1714
- dest, expected_sha256=checksum, expected_version=latest,
1924
+ dest,
1925
+ expected_sha256=checksum,
1926
+ expected_version=latest,
1927
+ release_id=release_id,
1928
+ channel=channel,
1929
+ artifact_kind=artifact_kind,
1715
1930
  )
1716
1931
  if not ok:
1717
1932
  record_failure(msg, phase="package_download", failure_kind="download")
@@ -1719,54 +1934,113 @@ def command_update(args: argparse.Namespace) -> int:
1719
1934
  return 1
1720
1935
  print(f"[update] {msg}")
1721
1936
  try:
1722
- package_target = str(_prepare_cli_package(dest))
1937
+ if artifact_kind == "npm-tarball":
1938
+ package_target = str(
1939
+ _prepare_npm_package(dest, expected_version=artifact_version)
1940
+ )
1941
+ else:
1942
+ package_target = str(
1943
+ _prepare_cli_package(dest, expected_version=artifact_version)
1944
+ )
1723
1945
  except (CliError, OSError) as exc:
1724
1946
  record_failure(str(exc), phase="package_validation", failure_kind="package_format")
1725
1947
  print(f"[update] {exc}")
1726
1948
  return 1
1727
1949
 
1728
- # 4. pip install --upgrade
1729
- print(f"[update] 执行 pip install --upgrade {package_target}...")
1730
- pip_cmd = [sys.executable, "-m", "pip", "install", "--upgrade",
1731
- "--no-input", package_target]
1732
- if is_rollback:
1733
- # 回退到更低版本:pip --upgrade 不会降级,改用 --force-reinstall
1734
- pip_cmd = [sys.executable, "-m", "pip", "install",
1735
- "--force-reinstall", "--no-input", package_target]
1950
+ # 4. Install through the package manager that owns the running CLI.
1951
+ if client_kind == "npm":
1952
+ npm = shutil.which("npm")
1953
+ if not npm:
1954
+ record_failure(
1955
+ "当前 npm CLI 找不到 npm 可执行文件",
1956
+ phase="package_install",
1957
+ failure_kind="npm_missing",
1958
+ )
1959
+ print("[update] 当前 npm CLI 找不到 npm 可执行文件")
1960
+ return 2
1961
+ install_cmd = [
1962
+ npm, "install", "--global", "--no-audit", "--no-fund",
1963
+ package_target,
1964
+ ]
1965
+ print(f"[update] 执行 npm install --global {package_target}...")
1966
+ else:
1967
+ install_cmd = [sys.executable, "-m", "pip", "install", "--upgrade",
1968
+ "--no-input", "--disable-pip-version-check", package_target]
1969
+ if is_rollback:
1970
+ # 回退到更低版本:pip --upgrade 不会降级,改用 --force-reinstall
1971
+ install_cmd = [sys.executable, "-m", "pip", "install",
1972
+ "--force-reinstall", "--no-input",
1973
+ "--disable-pip-version-check", package_target]
1974
+ print(f"[update] 执行 pip install --upgrade {package_target}...")
1736
1975
  try:
1737
- proc = subprocess.run(pip_cmd, capture_output=True, text=True, timeout=120)
1976
+ proc = subprocess.run(install_cmd, capture_output=True, text=True, timeout=180)
1738
1977
  except subprocess.TimeoutExpired:
1739
- record_failure("pip install 超时(120s)", phase="package_install", failure_kind="timeout")
1740
- print("[update] pip install 超时(120s)")
1978
+ record_failure(
1979
+ f"{client_kind} install 超时(180s)",
1980
+ phase="package_install",
1981
+ failure_kind="timeout",
1982
+ )
1983
+ print(f"[update] {client_kind} install 超时(180s)")
1741
1984
  return 1
1742
1985
  except OSError as exc:
1743
1986
  record_failure(str(exc), phase="package_install", failure_kind="exec")
1744
- print(f"[update] pip install 执行失败: {exc}")
1987
+ print(f"[update] {client_kind} install 执行失败: {exc}")
1745
1988
  return 1
1746
1989
 
1747
1990
  if proc.returncode != 0:
1748
1991
  record_failure(
1749
- f"pip install exit {proc.returncode}", phase="package_install",
1992
+ f"{client_kind} install exit {proc.returncode}", phase="package_install",
1750
1993
  failure_kind="nonzero_exit", exit_code=proc.returncode,
1751
1994
  )
1752
- print(f"[update] pip install 失败 (exit {proc.returncode})")
1995
+ print(f"[update] {client_kind} install 失败 (exit {proc.returncode})")
1753
1996
  if proc.stderr:
1754
1997
  print(proc.stderr[-500:])
1755
1998
  return 1
1756
1999
 
1757
- installed_version = _installed_cli_distribution_version()
1758
- if installed_version != latest:
1759
- record_failure(
1760
- "安装后版本校验失败", phase="package_install",
1761
- failure_kind="version_mismatch", expected_version=latest,
1762
- installed_version=installed_version,
1763
- )
1764
- print(
1765
- f"[update] 安装后版本校验失败:期望 {latest},"
1766
- f"实际 {installed_version or '未知'}"
2000
+ if client_kind == "npm":
2001
+ bugx_bin = shutil.which("bugx")
2002
+ if not bugx_bin:
2003
+ record_failure(
2004
+ "npm 安装成功但找不到 bugx wrapper",
2005
+ phase="package_install",
2006
+ failure_kind="wrapper_missing",
2007
+ )
2008
+ print("[update] npm 安装成功但找不到 bugx wrapper")
2009
+ return 1
2010
+ version_proc = subprocess.run(
2011
+ [bugx_bin, "--version"],
2012
+ capture_output=True,
2013
+ text=True,
2014
+ timeout=30,
1767
2015
  )
1768
- return 1
1769
- print(f"[update] pip install 成功,已安装版本 {installed_version}")
2016
+ if version_proc.returncode != 0 or latest not in (version_proc.stdout or ""):
2017
+ actual = (version_proc.stdout or version_proc.stderr or "").strip()[-300:]
2018
+ record_failure(
2019
+ "npm 安装后版本校验失败",
2020
+ phase="package_install",
2021
+ failure_kind="version_mismatch",
2022
+ expected_version=latest,
2023
+ observed_version=actual,
2024
+ )
2025
+ print(f"[update] npm 安装后版本校验失败:期望 {latest},实际 {actual or '未知'}")
2026
+ return 1
2027
+ installed_version = latest
2028
+ print(f"[update] npm install 成功,已验证 bugx --version ({latest})")
2029
+ else:
2030
+ installed_version = _installed_cli_distribution_version()
2031
+ if installed_version != latest:
2032
+ record_failure(
2033
+ "安装后版本校验失败", phase="package_install",
2034
+ failure_kind="version_mismatch", expected_version=latest,
2035
+ installed_version=installed_version,
2036
+ )
2037
+ print(
2038
+ f"[update] 安装后版本校验失败:期望 {latest},"
2039
+ f"实际 {installed_version or '未知'}"
2040
+ )
2041
+ return 1
2042
+ print(f"[update] pip install 成功,已安装版本 {installed_version}")
2043
+ switched = True
1770
2044
 
1771
2045
  # 更新全局运行时引擎与宿主登记独立;没有 hosts.json 也必须刷新并验证。
1772
2046
  try:
@@ -1846,7 +2120,34 @@ def command_update(args: argparse.Namespace) -> int:
1846
2120
  return 1
1847
2121
  print("[update] 安装验证通过")
1848
2122
 
2123
+ # 成功也必须留下与本次发布身份绑定的收据;模型文本、进程退出码
2124
+ # 和宿主文件刷新都不能替代这个最终状态证据。
2125
+ last_receipt = _write_update_receipt({
2126
+ "schema_version": 1,
2127
+ "operation_id": operation_id,
2128
+ "started_at_epoch": started_epoch,
2129
+ "finished_at_epoch": time.time(),
2130
+ "current_version": __version__,
2131
+ "installed_version": latest,
2132
+ "client_kind": client_kind,
2133
+ "artifact_kind": artifact_kind,
2134
+ "release_id": release_id,
2135
+ "channel": channel,
2136
+ "phase": "complete",
2137
+ "final_state": "COMPLETE",
2138
+ **_receipt_project_identity(root),
2139
+ })
2140
+ _log_update_event(
2141
+ root, "update_completed", "CLI update completed",
2142
+ phase="complete", duration_ms=round((time.monotonic() - started) * 1000, 1),
2143
+ operation_id=operation_id, final_state="COMPLETE",
2144
+ receipt_path=str(last_receipt or ""), release_id=release_id,
2145
+ target_version=latest,
2146
+ )
2147
+
1849
2148
  print(f"\n✓ BugX 已更新到 {latest}")
2149
+ if last_receipt:
2150
+ print(f"[update] 收据: {last_receipt}")
1850
2151
  print("请重新运行 bugx 命令以使用新版本。")
1851
2152
  return 0
1852
2153
  finally:
@@ -1884,6 +2185,74 @@ SUPERVISOR_PASSTHROUGH_ACTIONS = (
1884
2185
  + SUPERVISOR_REPAIR_ACTIONS
1885
2186
  + SUPERVISOR_DECISION_ACTIONS
1886
2187
  )
2188
+ SUPERVISOR_COMMANDS = ("install", "status", "rpc", *SUPERVISOR_PASSTHROUGH_ACTIONS)
2189
+
2190
+
2191
+ def forwarded_help(tokens: list[str]) -> bool:
2192
+ """Recognize help in a forwarded command's option segment."""
2193
+ for token in tokens:
2194
+ if token == "--":
2195
+ return False
2196
+ if token in {"-h", "--help"}:
2197
+ return True
2198
+ return bool(tokens and (tokens[0] == "help" or tokens[1:] == ["help"]))
2199
+
2200
+
2201
+ def _forwarded_root(root: Path | None, tokens: list[str]) -> tuple[Path | None, list[str]]:
2202
+ """Resolve one wrapper-owned root before any logging or dispatch."""
2203
+ remaining: list[str] = []
2204
+ tokens = list(tokens)
2205
+ if tokens[:1] == ["--"]:
2206
+ tokens.pop(0)
2207
+ index = 0
2208
+ while index < len(tokens):
2209
+ token = tokens[index]
2210
+ if token == "--":
2211
+ remaining.extend(tokens[index:])
2212
+ break
2213
+ if token == "--root" or token.startswith("--root="):
2214
+ if root is not None:
2215
+ raise CliError("重复指定 --root,请保留一个项目路径。")
2216
+ value = token.partition("=")[2]
2217
+ if token == "--root":
2218
+ index += 1
2219
+ value = tokens[index] if index < len(tokens) else ""
2220
+ if value.startswith("-"):
2221
+ value = ""
2222
+ if not value:
2223
+ raise CliError("--root 缺少项目路径。")
2224
+ root = Path(value)
2225
+ else:
2226
+ remaining.append(token)
2227
+ index += 1
2228
+ return root, remaining
2229
+
2230
+
2231
+ def normalize_engine_target(args: argparse.Namespace) -> None:
2232
+ args.root, args.engine_args = _forwarded_root(args.root, args.engine_args)
2233
+
2234
+
2235
+ def normalize_supervisor_target(args: argparse.Namespace) -> None:
2236
+ args.root, args.supervisor_args = _forwarded_root(args.root, args.supervisor_args)
2237
+ if args.supervisor_command in {"install", "status"} and args.supervisor_args:
2238
+ raise CliError(f"supervisor {args.supervisor_command} 只接受 --root;使用 --help 查看用法。")
2239
+
2240
+
2241
+ def supervisor_help(action: str) -> int:
2242
+ if action in {"install", "status"}:
2243
+ parser = argparse.ArgumentParser(
2244
+ prog=f"bugx supervisor {action}",
2245
+ description="写入 OpenCode 的 Supervisor MCP 配置。" if action == "install"
2246
+ else "查看 Supervisor 运行态和宿主配置。",
2247
+ )
2248
+ parser.add_argument("--root", metavar="ROOT", help="项目根目录(默认当前目录)")
2249
+ parser.print_help()
2250
+ return 0
2251
+ root = Path.cwd()
2252
+ return subprocess.call(
2253
+ [sys.executable, str(_script(root, Path("supervisor") / "cli.py")), action, "--help"],
2254
+ cwd=root, env=_python_environment(),
2255
+ )
1887
2256
 
1888
2257
 
1889
2258
  def _supervisor_recovery_action(root: Path, action: str, forwarded: list[str]) -> int:
@@ -1917,39 +2286,15 @@ def _supervisor_recovery_action(root: Path, action: str, forwarded: list[str]) -
1917
2286
  def command_supervisor(args: argparse.Namespace) -> int:
1918
2287
  """canonical supervisor MCP:install(部署/接线)/ status(部署状态)/ rpc(协议回退通道)。"""
1919
2288
  forwarded = list(getattr(args, "supervisor_args", []) or [])
1920
- # ``supervisor_args`` uses argparse.REMAINDER so rpc options can be passed
1921
- # through. That also captures ``--root`` when it appears after the action
1922
- # (for example ``supervisor status --root <project>``). Honor that root for
1923
- # all actions while leaving rpc's argv intact.
1924
- root = args.root
1925
- index = 0
1926
- while index < len(forwarded):
1927
- item = forwarded[index]
1928
- if item == "--root":
1929
- if index + 1 >= len(forwarded) or not forwarded[index + 1]:
1930
- print("[supervisor] --root 缺少路径", file=sys.stderr)
1931
- return 2
1932
- root = Path(forwarded[index + 1])
1933
- index += 2
1934
- continue
1935
- if item.startswith("--root="):
1936
- value = item.partition("=")[2]
1937
- if not value:
1938
- print("[supervisor] --root 缺少路径", file=sys.stderr)
1939
- return 2
1940
- root = Path(value)
1941
- index += 1
1942
- root = root.expanduser().resolve()
1943
2289
  act = args.supervisor_command
2290
+ if forwarded_help(forwarded):
2291
+ return supervisor_help(act)
2292
+ normalize_supervisor_target(args)
2293
+ forwarded = args.supervisor_args
2294
+ root = (args.root or Path.cwd()).expanduser().resolve()
1944
2295
  if act == "rpc":
1945
2296
  # PE-20261005-003 集成:worker 协议 CLI 回退通道,一问一答直连引擎
1946
- has_forwarded_root = any(
1947
- item == "--root" or item.startswith("--root=")
1948
- for item in forwarded
1949
- )
1950
- if not has_forwarded_root:
1951
- forwarded = ["--root", str(root), *forwarded]
1952
- return _run_script(root, Path("supervisor") / "cli.py", ["rpc", *forwarded])
2297
+ return _run_script(root, Path("supervisor") / "cli.py", ["rpc", "--root", str(root), *forwarded])
1953
2298
  if act == "install":
1954
2299
  return _supervisor_deploy(root)
1955
2300
  if act == "status":
@@ -1984,7 +2329,13 @@ def command_engine(args: argparse.Namespace) -> int:
1984
2329
  the engine so the same command works from Windows, Linux and macOS even
1985
2330
  when the global engine and project live on different volumes.
1986
2331
  """
1987
- root = resolve_project_root(args.root).resolve()
2332
+ normalize_engine_target(args)
2333
+ forwarded = args.engine_args or ["status"]
2334
+ help_requested = forwarded_help(forwarded)
2335
+ if help_requested and (forwarded[0] == "path" or forwarded == ["help", "path"]):
2336
+ print("用法:bugx engine --root <项目> path --name <引擎文件>")
2337
+ return 0
2338
+ root = Path.cwd() if help_requested else resolve_project_root(args.root).resolve()
1988
2339
  if not root.is_dir():
1989
2340
  # 宿主最容易犯的错是把 `--root` 指到拼错的路径 / 还没 clone 的目录。
1990
2341
  # 静默让 subprocess 以 cwd 缺失抛 FileNotFoundError 只会产出一条
@@ -1993,11 +2344,6 @@ def command_engine(args: argparse.Namespace) -> int:
1993
2344
  f"项目根目录不存在或不是目录:{root};"
1994
2345
  "请用 `--root` 指向已初始化的项目目录(或先在该目录执行 `bugx init`)。"
1995
2346
  )
1996
- forwarded = list(getattr(args, "engine_args", []) or [])
1997
- if forwarded and forwarded[0] == "--":
1998
- forwarded = forwarded[1:]
1999
- if not forwarded:
2000
- forwarded = ["status"]
2001
2347
  if forwarded[0] == "path":
2002
2348
  if len(forwarded) != 3 or forwarded[1] not in {"--name", "-n"}:
2003
2349
  raise CliError("用法:bugx engine --root <项目> path --name <引擎文件>")
@@ -2022,18 +2368,74 @@ def command_engine(args: argparse.Namespace) -> int:
2022
2368
  )
2023
2369
 
2024
2370
 
2371
+ def _parse_probe_timeout(raw: object) -> float:
2372
+ """Parse the bounded outer watchdog used by ``bugx probe``."""
2373
+ try:
2374
+ value = float(raw)
2375
+ except (TypeError, ValueError) as exc:
2376
+ raise argparse.ArgumentTypeError("--timeout-seconds 必须是数字") from exc
2377
+ if not math.isfinite(value) or value <= 0 or value > MAX_PROBE_TIMEOUT_SECONDS:
2378
+ raise argparse.ArgumentTypeError(
2379
+ f"--timeout-seconds 必须在 0 和 {MAX_PROBE_TIMEOUT_SECONDS:g} 秒之间"
2380
+ )
2381
+ return value
2382
+
2383
+
2384
+ def _extract_probe_timeout(
2385
+ args: argparse.Namespace, actual_extra: list[str],
2386
+ ) -> tuple[list[str], float]:
2387
+ """Extract the outer timeout without forwarding it to the probe script.
2388
+
2389
+ ``probe_args`` uses ``argparse.REMAINDER``, so users may put the option
2390
+ after the probe kind as well as before it. Keeping the extraction here
2391
+ makes both forms equivalent and prevents ``ui_audit.py`` from seeing a
2392
+ BugX wrapper option it does not own.
2393
+ """
2394
+ configured = getattr(args, "timeout_seconds", None)
2395
+ forwarded: list[str] = []
2396
+ forwarded_timeout: float | None = None
2397
+ index = 0
2398
+ while index < len(actual_extra):
2399
+ token = actual_extra[index]
2400
+ if token == "--timeout-seconds":
2401
+ if forwarded_timeout is not None or index + 1 >= len(actual_extra):
2402
+ raise CliError("--timeout-seconds 只能指定一次并且必须带值")
2403
+ try:
2404
+ forwarded_timeout = _parse_probe_timeout(actual_extra[index + 1])
2405
+ except argparse.ArgumentTypeError as exc:
2406
+ raise CliError(str(exc)) from exc
2407
+ index += 2
2408
+ continue
2409
+ if token.startswith("--timeout-seconds="):
2410
+ if forwarded_timeout is not None:
2411
+ raise CliError("--timeout-seconds 只能指定一次")
2412
+ try:
2413
+ forwarded_timeout = _parse_probe_timeout(token.split("=", 1)[1])
2414
+ except argparse.ArgumentTypeError as exc:
2415
+ raise CliError(str(exc)) from exc
2416
+ index += 1
2417
+ continue
2418
+ forwarded.append(token)
2419
+ index += 1
2420
+
2421
+ if configured is not None and forwarded_timeout is not None:
2422
+ raise CliError("--timeout-seconds 只能指定一次")
2423
+ timeout = configured if configured is not None else forwarded_timeout
2424
+ return forwarded, _parse_probe_timeout(
2425
+ DEFAULT_PROBE_TIMEOUT_SECONDS if timeout is None else timeout
2426
+ )
2427
+
2428
+
2025
2429
  def command_probe(args: argparse.Namespace, extra_args: list[str] | None = None) -> int:
2026
2430
  """运行探针包装命令,透传选定 probe 的参数。"""
2027
2431
  root = args.root.resolve()
2028
2432
  script_name = PROBE_SCRIPTS[args.probe_kind]
2029
- forward_args: list[str] = []
2030
2433
  actual_extra = extra_args if extra_args is not None else getattr(args, "probe_args", [])
2031
- if actual_extra:
2032
- forward_args.extend(actual_extra)
2434
+ forward_args, timeout = _extract_probe_timeout(args, list(actual_extra))
2033
2435
  if args.probe_kind not in PROBES_WITHOUT_ROOT_ARGUMENT \
2034
2436
  and "--root" not in forward_args and "-r" not in forward_args:
2035
2437
  forward_args.extend(["--root", str(root)])
2036
- return _run_script(root, script_name, forward_args, timeout=300)
2438
+ return _run_script(root, script_name, forward_args, timeout=timeout)
2037
2439
 
2038
2440
 
2039
2441
  def command_mcp_prune(args: argparse.Namespace) -> int:
@@ -2434,13 +2836,18 @@ def _parser_for_command_path(parser: argparse.ArgumentParser,
2434
2836
  command_path: list[str]) -> argparse.ArgumentParser:
2435
2837
  """Return the argparse parser for a top-level or nested command path."""
2436
2838
  current = parser
2437
- for command in command_path:
2839
+ for index, command in enumerate(command_path):
2438
2840
  subparsers = next(
2439
2841
  (action for action in current._actions
2440
2842
  if isinstance(action, argparse._SubParsersAction)),
2441
2843
  None,
2442
2844
  )
2443
2845
  if subparsers is None or command not in subparsers.choices:
2846
+ if subparsers is None and index + 1 == len(command_path) and any(
2847
+ not action.option_strings and action.choices and command in action.choices
2848
+ for action in current._actions
2849
+ ):
2850
+ return current
2444
2851
  path = " ".join(command_path)
2445
2852
  raise CliError(_i18n_exc("system.unknown_help_topic", f"未知的帮助主题:{path}", path=path))
2446
2853
  current = subparsers.choices[command]
@@ -2451,6 +2858,14 @@ def command_help(parser: argparse.ArgumentParser, args: argparse.Namespace) -> i
2451
2858
  """Print root or command-specific help without entering command dispatch."""
2452
2859
  command_path = list(getattr(args, "help_command", []))
2453
2860
  try:
2861
+ if command_path[:1] == ["engine"]:
2862
+ if len(command_path) > 2:
2863
+ parser.error("用法:bugx help engine [COMMAND]")
2864
+ if command_path[1:] == ["path"]:
2865
+ return command_engine(argparse.Namespace(root=None, engine_args=["path", "--help"]))
2866
+ return command_engine(argparse.Namespace(root=None, engine_args=["help", *command_path[1:]]))
2867
+ if len(command_path) == 2 and command_path[0] == "supervisor" and command_path[1] in SUPERVISOR_COMMANDS:
2868
+ return supervisor_help(command_path[1])
2454
2869
  target = _parser_for_command_path(parser, command_path)
2455
2870
  except CliError as exc:
2456
2871
  parser.error(str(exc))