bugx-cli 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/core/README.md +1 -1
  2. package/core/agent/agent_execution.py +7 -0
  3. package/core/bugx.md +1 -1
  4. package/core/bugx_paths.py +2 -2
  5. package/core/bundled_docs/OVERVIEW.md +3 -2
  6. package/core/bundled_docs/README.md +2 -2
  7. package/core/bundled_docs/ai/01_AI_REFERENCE.md +11 -6
  8. package/core/bundled_docs/ai/02_AI_USAGE.md +1 -1
  9. package/core/bundled_docs/ai/03_AI_COMMANDS.md +1 -1
  10. package/core/bundled_docs/guides/01_USER_GUIDE.md +5 -5
  11. package/core/bundled_docs/guides/02_COMMANDS.md +3 -3
  12. package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +4 -4
  13. package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +4 -2
  14. package/core/bundled_docs/hosts/bugx_SKILL.md +2 -2
  15. package/core/bundled_docs/hosts/platform_bugx_SKILL.md +2 -2
  16. package/core/bundled_docs/manifest.json +20 -20
  17. package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +1 -0
  18. package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +1 -1
  19. package/core/contracts/README.md +1 -1
  20. package/core/contracts/bugx-runtime-contract.md +1 -1
  21. package/core/contracts/bugx-worker.md +1 -1
  22. package/core/coverage/coverage_ai_review.py +15 -11
  23. package/core/coverage/coverage_bootstrap.py +18 -13
  24. package/core/coverage/coverage_discovery.py +1 -1
  25. package/core/dev_harness/interaction_preset.py +1 -1
  26. package/core/engine-integrity.json +119 -111
  27. package/core/host_acp/README.md +4 -0
  28. package/core/host_acp/agnescode.py +128 -0
  29. package/core/host_runtime/README.md +3 -0
  30. package/core/host_runtime/host_registry.py +1 -0
  31. package/core/hosts/README.md +4 -0
  32. package/core/hosts/agnescode.py +415 -0
  33. package/core/hosts/opencode.py +11 -3
  34. package/core/infra/README.md +1 -1
  35. package/core/infra/build_info.py +2 -2
  36. package/core/infra/python_runtime.py +4 -1
  37. package/core/launch_phases/README.md +2 -2
  38. package/core/launch_phases/finding_confirm_phase.py +1 -1
  39. package/core/launch_phases/semantic_recon.py +3 -19
  40. package/core/launch_phases/startup_version_gate.py +2 -2
  41. package/core/launch_phases/verify_loop.py +3 -19
  42. package/core/ledger/README.md +1 -1
  43. package/core/ledger/finding_confirmation.py +1 -1
  44. package/core/ledger/finding_verification.py +2 -20
  45. package/core/ledger/fp_ledger.py +3 -19
  46. package/core/ledger/life_ledger.py +7 -33
  47. package/core/ledger/schema.py +1 -1
  48. package/core/mcp_handlers/supervisor_handlers.py +1 -1
  49. package/core/mcp_runtime_support/common.py +6 -0
  50. package/core/mcp_runtime_support/environment.py +82 -23
  51. package/core/metadata.txt +1 -1
  52. package/core/planning/README.md +1 -1
  53. package/core/planning/target_sandbox_manager.py +2 -0
  54. package/core/probes/mobile_probe.py +1 -0
  55. package/core/probes/sast_probe.py +1 -1
  56. package/core/probes/sca_scanner.py +1 -1
  57. package/core/project_profiler/constants.py +1 -1
  58. package/core/retrieval/README.md +1 -1
  59. package/core/retrieval/symbol_index.py +227 -52
  60. package/core/runtime/README.md +1 -1
  61. package/core/runtime/daemon_runner.py +3 -2
  62. package/core/runtime/project_init.py +1 -1
  63. package/core/runtime/scenario_eval.py +1 -1
  64. package/core/skills/bugx_mcp_server.py +9 -0
  65. package/core/skills/mcp_session_proof.py +3 -31
  66. package/core/supervisor/README.md +1 -1
  67. package/core/supervisor/finding_commit.py +3 -24
  68. package/core/supervisor/task_scheduler.py +5 -2
  69. package/core/supervisor/worker_handoff.py +2 -2
  70. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  71. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  72. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +3 -3
  73. package/ecosystem/integrations/opencode/mcp-lock.json +1 -1
  74. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  75. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  76. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  77. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  78. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  79. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  80. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  81. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  82. package/interfaces/cli/bugx_cli/__init__.py +1 -1
  83. package/interfaces/cli/bugx_cli/cli.py +15 -0
  84. package/interfaces/cli/bugx_cli/commands/audit.py +2 -1
  85. package/interfaces/cli/bugx_cli/commands/lifecycle.py +1 -1
  86. package/interfaces/cli/bugx_cli/commands/patch.py +5 -1
  87. package/interfaces/cli/bugx_cli/commands/plugin.py +11 -2
  88. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  89. package/interfaces/cli/bugx_cli/host_adapters.py +6 -0
  90. package/interfaces/cli/bugx_cli/hosts/registry.py +1 -1
  91. package/interfaces/cli/bugx_cli/infra/engine_installer.py +4 -4
  92. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  93. package/package.json +1 -1
  94. package/scripts/sync-version.mjs +1 -1
  95. package/skills/platform/bugx/SKILL.md +2 -2
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env python3
2
+ """core/host_acp/agnescode.py - Agnes Code 的 ACP 适配插件。
3
+
4
+ 实机口径:
5
+ * ACP 入口为 ``agnescode acp``(或 ``agnes acp``),工作区绑定由探针 cwd 提供;
6
+ * 探活服务器绑定到探活项目的 ``agnescode.json``(v2 ``mcp.servers`` 形状)。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import shutil
15
+ from typing import Any
16
+
17
+ from .base import AcpPlugin
18
+
19
+ __all__ = ["AgnesCodeAcpPlugin", "PLUGIN", "is_available", "run_static_degraded"]
20
+
21
+
22
+ def _resolve_executable() -> str:
23
+ for cmd in ("agnescode", "agnes"):
24
+ found = shutil.which(cmd)
25
+ if found:
26
+ return found
27
+ return "agnescode"
28
+
29
+
30
+ class AgnesCodeAcpPlugin(AcpPlugin):
31
+ """Agnes Code ACP 插件。"""
32
+
33
+ name = "agnescode"
34
+ executable = "agnescode"
35
+ status = "ready"
36
+ supports_project_permissions = True
37
+
38
+ def acp_argv(
39
+ self,
40
+ *,
41
+ model: str | None = None,
42
+ data_dir: Path | str | None = None,
43
+ ) -> list[str]:
44
+ del model, data_dir
45
+ return [_resolve_executable(), "acp"]
46
+
47
+ def ensure_probe_servers(
48
+ self,
49
+ project_root: Path,
50
+ config_paths: tuple[Path, ...],
51
+ servers: dict[str, dict[str, Any]],
52
+ ) -> list[str]:
53
+ """把 BugX 通道绑定到探活项目的 ``agnescode.json``(v2 ``mcp.servers`` 形状)。"""
54
+ updated: list[str] = []
55
+ root_resolved = project_root.resolve()
56
+ for path in config_paths:
57
+ try:
58
+ resolved = path.resolve()
59
+ except OSError:
60
+ continue
61
+ if root_resolved not in resolved.parents and resolved.parent != root_resolved:
62
+ continue
63
+ try:
64
+ if resolved.is_symlink() or not resolved.is_file():
65
+ continue
66
+ payload = json.loads(resolved.read_text(encoding="utf-8"))
67
+ except (OSError, UnicodeError, ValueError):
68
+ continue
69
+ if not isinstance(payload, dict):
70
+ continue
71
+ if "mcp" not in payload:
72
+ payload["mcp"] = {}
73
+ block = payload["mcp"]
74
+ if not isinstance(block, dict):
75
+ raise ValueError(f"AgnesCode v2 mcp 配置必须是对象: {resolved}")
76
+ entries = block.get("servers")
77
+ if "servers" not in block:
78
+ entries = {}
79
+ block["servers"] = entries
80
+ if not isinstance(entries, dict):
81
+ raise ValueError(f"AgnesCode v2 mcp.servers 必须是对象: {resolved}")
82
+
83
+ changed = False
84
+ for server_name, server_def in servers.items():
85
+ target_def = {
86
+ "type": "local",
87
+ "command": [server_def.get("command", "bugx"), *server_def.get("args", [])],
88
+ "disabled": False,
89
+ }
90
+ if entries.get(server_name) != target_def:
91
+ entries[server_name] = target_def
92
+ changed = True
93
+
94
+ if changed:
95
+ resolved.write_text(
96
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
97
+ encoding="utf-8",
98
+ )
99
+ updated.append(str(resolved))
100
+ return updated
101
+
102
+
103
+ PLUGIN = AgnesCodeAcpPlugin
104
+
105
+
106
+ def is_available() -> tuple[bool, str]:
107
+ for cmd in ("agnescode", "agnes"):
108
+ found = shutil.which(cmd)
109
+ if found:
110
+ return True, found
111
+ return False, "agnescode 可执行文件未安装;ACP 通道不可用"
112
+
113
+
114
+ def run_static_degraded(root: Path | None = None) -> dict[str, Any]:
115
+ available, detail = is_available()
116
+ return {
117
+ "plugin": "agnescode",
118
+ "schema_version": 1,
119
+ "success": available,
120
+ "status": "degraded",
121
+ "degraded": True,
122
+ "degraded_reason": "static_facts_only" if available else "agnescode_not_installed",
123
+ "probe_mode": "static_degraded",
124
+ "evidence": {
125
+ "availability_detail": detail,
126
+ "project_root": str(root) if root else None,
127
+ },
128
+ }
@@ -38,6 +38,7 @@ flowchart TD
38
38
  | :--- | :--- | :--- |
39
39
  | `__init__.py` | Python 包初始化与核心模块符号导出 | `__all__` |
40
40
  | `adapters.py` | 宿主运行时适配器转接层,抹平不同宿主在 CLI / API 交互上的协议差异 | `RuntimeAdapterFactory` |
41
+ | `antigravity.py` | Google Antigravity 宿主专用运行时适配 | `AntigravityRuntimeAdapter` |
41
42
  | `autonomous_runner.py` | 自主攻防运行器主干,驱动无头环境下的全自动循环(Pre $\rightarrow$ Run $\rightarrow$ Post) | `AutonomousRunner` |
42
43
  | `cline.py` | Cline / Roo Code 运行时特定扩展,处理专用会话注入与命令执行 | `ClineRuntimeAdapter` |
43
44
  | `common.py` | 运行时共享工具函数,包括超时保护、跨平台管道封装与环境变量清洗 | `run_with_timeout`, `sanitize_env` |
@@ -51,6 +52,8 @@ flowchart TD
51
52
  | `INTERFACE.md` | 运行时模块间协议接口规范 | 运行时状态与生命周期契约 |
52
53
  | `mcp_process_tracker.py` | MCP 守护进程追踪器,记录每个拉起的 MCP Server PID,防止孤儿进程泄漏 | `MCPProcessTracker` |
53
54
  | `mcp_registry_gate.py` | MCP 注册表门禁校验器,确保 MCP 服务配置完整有效,防止假死启动 | `verify_mcp_registry` |
55
+ | `pi.py` | Pi 宿主专用运行时适配与超时预算透传 | `PiRuntimeAdapter` |
56
+ | `provider_facts.py` | 宿主模型事实与提供商元数据表 | `ProviderFacts` |
54
57
  | `SPEC.md` | 运行时技术设计规范文档 | 子进程模型与信号传播规则 |
55
58
 
56
59
  ---
@@ -41,6 +41,7 @@ SUPPORTED_HOSTS: tuple[str, ...] = (
41
41
  "kimi",
42
42
  "minimax",
43
43
  "antigravity",
44
+ "agnescode",
44
45
  "chatgpt",
45
46
  "workbuddy",
46
47
  "qoder",
@@ -47,12 +47,16 @@ flowchart TD
47
47
  | `_dsh_usage.py` | DSH 环境专有调用链耗时与交互次数统计实现 | `DshUsageTracker` |
48
48
  | `_mcp_toml.py` | MCP 客户端配置注入器,安全写入或更新 `.codex/mcp.toml` / `.vscode/cline_mcp.json` | `inject_mcp_toml_config` |
49
49
  | `_zcode_usage.py` | ZCode 平台专有资源配额与请求频率追踪器 | `ZCodeUsageTracker` |
50
+ | `agnescode.py` | Agnes Code 宿主接入适配器,生成 MCP 配置与智能体入口 | `PLUGIN` |
51
+ | `antigravity.py` | Google Antigravity 宿主接入适配器,生成 Plugin 插件与工作区 MCP | `PLUGIN` |
50
52
  | `base.py` | 宿主插件核心契约定义,提供探针注入、MCP 服务拉起与生命周期钩子 | `BaseHostPlugin` |
51
53
  | `claude.py` | Claude Desktop / Claude Code 宿主接入适配器,生成 MCP 配置与技能包 | `ClaudeHostPlugin` |
52
54
  | `cline.py` | Cline 插件适配器,实现 Roo Code / Cline 的 MCP 注入与规则提示词联动 | `ClineHostPlugin` |
53
55
  | `codex.py` | OpenAI Codex 适配器,管理 Codex CLI 交互式与无头会话 | `CodexHostPlugin` |
54
56
  | `dsh.py` | DSH (Deep Shell) 适配器,支持终端交互代理与工作流联动 | `DshHostPlugin` |
55
57
  | `INTERFACE.md` | 宿主插件公共接口设计与契约规范文档 | 宿主生命周期协议说明 |
58
+ | `kimi.py` | Kimi Code CLI 宿主接入适配器,生成 subagent 入口与 MCP 配置 | `PLUGIN` |
59
+ | `minimax.py` | MiniMax Code 桌面端插件适配器,管理 Plugin V1 入口与规范 | `PLUGIN` |
56
60
  | `opencode.py` | OpenCode 智能体适配器,提供标准 JSON-RPC MCP 挂载与环境发现 | `OpenCodeHostPlugin` |
57
61
  | `pi.py` | Pi 智能体平台接入适配器,实现扩展注册与事件桥接 | `PiHostPlugin` |
58
62
  | `SPEC.md` | 多宿主架构设计规格书,阐述各宿主环境差异与统一语义模型 | 规范与技术考量 |
@@ -0,0 +1,415 @@
1
+ #!/usr/bin/env python3
2
+ """core/hosts/agnescode.py - Agnes Code 宿主插件及自治配置环境。
3
+
4
+ 事实来源(Agnes AI / Agnes Code):
5
+ * identity ← 可执行程序 ``agnescode``(别名 ``agnes``);项目标记 ``agnescode.json`` / ``.agnescode``
6
+ * install ← ``subagent`` / ``agent`` 入口:``.agnescode/agents/bugx.md``
7
+ * engine_run ← ``agnescode run --standalone --agent <agent> --format json --auto <prompt>``
8
+ * mcp_write ← ``mcp.servers`` 容器键,配置文件 ``agnescode.json`` 与镜像 ``.agnescode/agnescode.json``
9
+ * acp ← ``core/host_acp/agnescode.py``(``agnescode acp``)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from contextlib import contextmanager
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ import shutil
19
+ from typing import Iterator
20
+
21
+ from core.infra.json_utils import unique_json_object
22
+
23
+ from .base import (
24
+ AcpFacet,
25
+ EngineRunFacet,
26
+ HostPlugin,
27
+ IdentityFacet,
28
+ InstallFacet,
29
+ McpWriteFacet,
30
+ RunContext,
31
+ STATUS_READY,
32
+ WorkerRuntimeFacet,
33
+ )
34
+
35
+ __all__ = ["PLUGIN", "is_available", "run_static_degraded"]
36
+
37
+ _NAME = "agnescode"
38
+
39
+
40
+ def _resolve_executable() -> str | None:
41
+ for cmd in ("agnescode", "agnes"):
42
+ found = shutil.which(cmd)
43
+ if found:
44
+ return found
45
+ app_agnesd = Path("/Applications/AgnesCode.app/Contents/Resources/bin/agnesd")
46
+ if app_agnesd.is_file():
47
+ return str(app_agnesd)
48
+ return None
49
+
50
+
51
+ def _agnes_app_markers() -> tuple[Path, ...]:
52
+ home = Path.home()
53
+ return (
54
+ Path("/Applications/AgnesCode.app"),
55
+ home / "Applications" / "AgnesCode.app",
56
+ home / "Library" / "Application Support" / "AgnesCode",
57
+ home / ".agnes",
58
+ )
59
+
60
+
61
+ def _configured_model(root: Path) -> str:
62
+ """Read the project model without making it part of BugX state."""
63
+ configured = os.environ.get("BUGX_AGNESCODE_MODEL", "").strip()
64
+ if configured:
65
+ return configured
66
+ for candidate in (root / "agnescode.json", root / ".agnescode" / "agnescode.json"):
67
+ if candidate.is_file():
68
+ try:
69
+ payload = json.loads(candidate.read_text(encoding="utf-8"))
70
+ except (OSError, json.JSONDecodeError):
71
+ continue
72
+ model = payload.get("model") if isinstance(payload, dict) else ""
73
+ if isinstance(model, str) and model.strip():
74
+ return model.strip()
75
+ return ""
76
+
77
+
78
+ def _strip_jsonc_comments_and_trailing_commas(source: str) -> str:
79
+ """Remove JSONC comments and trailing commas without touching string data."""
80
+ clean: list[str] = []
81
+ in_string = False
82
+ escaped = False
83
+ line_comment = False
84
+ block_comment = False
85
+ index = 0
86
+ while index < len(source):
87
+ char = source[index]
88
+ next_char = source[index + 1] if index + 1 < len(source) else ""
89
+ if line_comment:
90
+ if char in "\r\n":
91
+ line_comment = False
92
+ clean.append(char)
93
+ else:
94
+ clean.append(" ")
95
+ elif block_comment:
96
+ if char == "*" and next_char == "/":
97
+ clean.extend((" ", " "))
98
+ index += 1
99
+ block_comment = False
100
+ else:
101
+ clean.append(char if char in "\r\n" else " ")
102
+ elif in_string:
103
+ clean.append(char)
104
+ if escaped:
105
+ escaped = False
106
+ elif char == "\\":
107
+ escaped = True
108
+ elif char == '"':
109
+ in_string = False
110
+ elif char == '"':
111
+ in_string = True
112
+ clean.append(char)
113
+ elif char == "/" and next_char == "/":
114
+ clean.extend((" ", " "))
115
+ index += 1
116
+ line_comment = True
117
+ elif char == "/" and next_char == "*":
118
+ clean.extend((" ", " "))
119
+ index += 1
120
+ block_comment = True
121
+ else:
122
+ clean.append(char)
123
+ index += 1
124
+
125
+ if block_comment:
126
+ raise ValueError("unterminated block comment")
127
+
128
+ without_comments = "".join(clean).lstrip("\ufeff")
129
+ clean = []
130
+ in_string = False
131
+ escaped = False
132
+ index = 0
133
+ while index < len(without_comments):
134
+ char = without_comments[index]
135
+ if in_string:
136
+ clean.append(char)
137
+ if escaped:
138
+ escaped = False
139
+ elif char == "\\":
140
+ escaped = True
141
+ elif char == '"':
142
+ in_string = False
143
+ elif char == '"':
144
+ in_string = True
145
+ clean.append(char)
146
+ elif char == ",":
147
+ lookahead = index + 1
148
+ while lookahead < len(without_comments) and without_comments[lookahead].isspace():
149
+ lookahead += 1
150
+ if lookahead >= len(without_comments) or without_comments[lookahead] not in "]}":
151
+ clean.append(char)
152
+ else:
153
+ clean.append(char)
154
+ index += 1
155
+ return "".join(clean)
156
+
157
+
158
+ def _unique_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
159
+ return unique_json_object(
160
+ pairs,
161
+ error_factory=lambda key: ValueError(f"duplicate key: {key}"),
162
+ )
163
+
164
+
165
+ def _read_agnescode_config(path: Path) -> dict[str, object]:
166
+ try:
167
+ parsed = json.loads(
168
+ _strip_jsonc_comments_and_trailing_commas(path.read_text(encoding="utf-8")),
169
+ object_pairs_hook=_unique_object,
170
+ )
171
+ except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc:
172
+ raise RuntimeError(
173
+ f"AgnesCode 自治配置无法安全隔离: {path.name} ({type(exc).__name__})"
174
+ ) from exc
175
+ if not isinstance(parsed, dict):
176
+ raise RuntimeError(f"AgnesCode 自治配置必须是对象: {path.name}")
177
+ return parsed
178
+
179
+
180
+ def _child_path(value: str, root: Path) -> Path:
181
+ path = Path(value).expanduser()
182
+ return (path if path.is_absolute() else root / path).resolve()
183
+
184
+
185
+ def _agnescode_global_config_dir(root: Path) -> Path:
186
+ configured = os.environ.get("AGNESCODE_CONFIG_DIR")
187
+ if "AGNESCODE_CONFIG_DIR" in os.environ:
188
+ if not configured:
189
+ raise RuntimeError("AGNESCODE_CONFIG_DIR 为空,无法隔离 AgnesCode 用户配置")
190
+ return _child_path(configured, root)
191
+ xdg = os.environ.get("XDG_CONFIG_HOME")
192
+ base = _child_path(xdg, root) if xdg else Path.home() / ".config"
193
+ return (base / "agnescode").resolve()
194
+
195
+
196
+ @contextmanager
197
+ def _autonomous_environment(root: Path) -> Iterator[dict[str, str | None]]:
198
+ """Hide user-global plugin/MCP sources while preserving AgnesCode's project config."""
199
+ for name in ("AGNESCODE_CONFIG", "AGNESCODE_CONFIG_CONTENT"):
200
+ if os.environ.get(name):
201
+ raise RuntimeError(
202
+ f"AgnesCode 自治配置隔离不接受额外覆盖 {name};请先移除该覆盖再运行"
203
+ )
204
+ for name in ("AGNESCODE_CONFIG_PROJECT_DISABLE", "AGNESCODE_DISABLE_PROJECT_CONFIG"):
205
+ value = os.environ.get(name, "")
206
+ if value == "1" or value.lower() == "true":
207
+ raise RuntimeError(f"{name} 禁用了项目配置,BugX MCP 无法加载")
208
+
209
+ import tempfile
210
+
211
+ source_dir = _agnescode_global_config_dir(root)
212
+ parent = source_dir.parent if source_dir.parent.is_dir() else Path(tempfile.gettempdir())
213
+ with tempfile.TemporaryDirectory(prefix="bugx-agnescode-config-", dir=parent) as private_name:
214
+ private_dir = Path(private_name).resolve()
215
+ project_root = root.resolve()
216
+ if private_dir == project_root or project_root in private_dir.parents:
217
+ raise RuntimeError("AgnesCode 自治私有配置目录落在被测项目内,已阻断")
218
+ private_dir.chmod(0o700)
219
+
220
+ if source_dir.exists():
221
+ if not source_dir.is_dir():
222
+ raise RuntimeError("AGNESCODE_CONFIG_DIR 不是目录,无法安全隔离")
223
+ try:
224
+ for entry in source_dir.iterdir():
225
+ if entry.name in {"agnescode.json", "agnescode.jsonc", "plugin", "plugins"}:
226
+ continue
227
+ dest = private_dir / entry.name
228
+ try:
229
+ dest.symlink_to(entry, target_is_directory=entry.is_dir())
230
+ except OSError:
231
+ if os.name != "nt":
232
+ raise
233
+ if entry.is_dir():
234
+ shutil.copytree(entry, dest, dirs_exist_ok=True)
235
+ else:
236
+ shutil.copy2(entry, dest)
237
+ except OSError as exc:
238
+ raise RuntimeError(
239
+ f"AgnesCode 自治配置资产无法隔离 ({type(exc).__name__})"
240
+ ) from exc
241
+
242
+ for name in ("agnescode.json", "agnescode.jsonc"):
243
+ source_file = source_dir / name
244
+ if not source_file.exists() and not source_file.is_symlink():
245
+ continue
246
+ if not source_file.is_file():
247
+ raise RuntimeError(f"AgnesCode 用户配置不是文件: {name}")
248
+ payload = _read_agnescode_config(source_file)
249
+ for key in ("mcp", "plugin", "plugins"):
250
+ payload.pop(key, None)
251
+ target = private_dir / name
252
+ target.write_text(
253
+ json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
254
+ encoding="utf-8",
255
+ )
256
+ target.chmod(0o600)
257
+
258
+ yield {
259
+ "AGNESCODE_CONFIG_DIR": str(private_dir),
260
+ "AGNESCODE_CONFIG": None,
261
+ "AGNESCODE_CONFIG_CONTENT": None,
262
+ }
263
+
264
+
265
+ def _argv(ctx: RunContext, *, auto: bool) -> list[str]:
266
+ exe = _resolve_executable() or "agnescode"
267
+ cmd = [exe, "run"]
268
+ if auto:
269
+ cmd.append("--standalone")
270
+ cmd += ["--agent", ctx.agent, "--format", "json"]
271
+ model = _configured_model(ctx.root)
272
+ if model:
273
+ cmd += ["--model", model]
274
+ if auto:
275
+ cmd.append("--auto")
276
+ if ctx.session:
277
+ cmd += ["-s", ctx.session]
278
+ cmd.append(ctx.prompt)
279
+ return cmd
280
+
281
+
282
+ def _headless_argv(ctx: RunContext) -> list[str]:
283
+ return _argv(ctx, auto=False)
284
+
285
+
286
+ def _autonomous_argv(ctx: RunContext) -> list[str]:
287
+ return _argv(ctx, auto=True)
288
+
289
+
290
+ def _recon_scout_argv(
291
+ root: Path, prompt_text: str, prompt_file: Path, inventory: object | None = None,
292
+ ) -> list[str]:
293
+ del root
294
+ exe = _resolve_executable() or "agnescode"
295
+ cmd = [exe, "run", "--standalone", "--format", "json", "--auto"]
296
+ scout_model = (
297
+ os.environ.get("BUGX_SCOUT_MODEL")
298
+ or os.environ.get("BUGX_AGNESCODE_MODEL")
299
+ or os.environ.get("AGNESCODE_MODEL")
300
+ )
301
+ if scout_model:
302
+ cmd.extend(["-m", scout_model])
303
+ cmd.extend(["-f", str(prompt_file), "Execute BugX Recon Scout review"])
304
+ return cmd
305
+
306
+
307
+ def _mcp_config_paths(root: Path) -> tuple[Path, ...]:
308
+ return (root / "agnescode.json", root / ".agnescode" / "agnescode.json")
309
+
310
+
311
+ def _agent_config_path(root: Path) -> Path:
312
+ return root / ".agnescode" / "agents" / "bugx.md"
313
+
314
+
315
+ def _mcp_health(name: str, cfg: dict, root: Path | None = None) -> bool:
316
+ del name, cfg, root
317
+ return True
318
+
319
+
320
+ PLUGIN = HostPlugin(
321
+ identity=IdentityFacet(
322
+ name=_NAME,
323
+ label="Agnes Code",
324
+ order=20,
325
+ executable="agnescode",
326
+ markers=("agnescode.json", ".agnescode/agnescode.json", ".agnescode", ".agnes"),
327
+ aliases=("agnes",),
328
+ app_markers=_agnes_app_markers,
329
+ native_question=True,
330
+ ),
331
+ status=STATUS_READY,
332
+ install=InstallFacet(
333
+ kind="agent",
334
+ path=".agnescode/agents/bugx.md",
335
+ marker=".agnescode",
336
+ entry_mode="rendered",
337
+ required_paths=(),
338
+ legacy_paths=(),
339
+ capabilities=frozenset({"native-mcp-config", "global-agent-link"}),
340
+ interaction={
341
+ "tool": "question",
342
+ "single_select": "multiple=false",
343
+ },
344
+ mcp_relpaths=("agnescode.json", ".agnescode/agnescode.json"),
345
+ worker_subagent=False,
346
+ ),
347
+ engine_run=EngineRunFacet(
348
+ supports_headless=True,
349
+ headless_argv=_headless_argv,
350
+ autonomous_argv=_autonomous_argv,
351
+ mcp_config_paths=_mcp_config_paths,
352
+ agent_config_path=_agent_config_path,
353
+ mcp_health=_mcp_health,
354
+ host_surface="tui",
355
+ recon_scout_argv=_recon_scout_argv,
356
+ native_task=True,
357
+ autonomous_environment=_autonomous_environment,
358
+ ),
359
+ worker_runtime=WorkerRuntimeFacet(
360
+ mode="multi",
361
+ max_concurrency=None,
362
+ requires_process_mode=False,
363
+ sandbox_sync=(),
364
+ ),
365
+ mcp_write=McpWriteFacet(
366
+ container_key="mcp.servers",
367
+ writer_key=_NAME,
368
+ project_relpath="agnescode.json",
369
+ global_scope=None,
370
+ mirror_relpaths=(".agnescode/agnescode.json",),
371
+ requires_absolutize=True,
372
+ custom_writer=False,
373
+ ),
374
+ acp=AcpFacet(plugin=_NAME),
375
+ )
376
+
377
+
378
+ def is_available() -> tuple[bool, str]:
379
+ path = _resolve_executable()
380
+ if path is None:
381
+ return False, "agnescode 未安装;headless 与 ACP 通道不可用"
382
+ return True, path
383
+
384
+
385
+ def run_static_degraded(root: Path | None = None) -> dict:
386
+ available, availability_detail = is_available()
387
+ return {
388
+ "plugin": _NAME,
389
+ "schema_version": 1,
390
+ "success": available,
391
+ "status": "degraded",
392
+ "degraded": True,
393
+ "degraded_reason": "static_facts_only" if available else "agnescode_not_installed",
394
+ "probe_mode": "static_degraded",
395
+ "headless_available": available,
396
+ "native_task_available": bool(available and PLUGIN.engine_run.native_task),
397
+ "identity": {
398
+ "executable": PLUGIN.identity.executable,
399
+ "aliases": list(PLUGIN.identity.aliases),
400
+ "markers": list(PLUGIN.identity.markers),
401
+ },
402
+ "agent_entry": PLUGIN.install.path,
403
+ "mcp_project_relpath": PLUGIN.mcp_write.project_relpath,
404
+ "mcp_global_scope": PLUGIN.mcp_write.global_scope,
405
+ "findings": [],
406
+ "evidence": {
407
+ "availability_detail": availability_detail,
408
+ "project_root": str(root) if root else None,
409
+ },
410
+ "metadata": {
411
+ "degraded_mode": "static_plugin_facts_only",
412
+ "acp": "ready(agnescode acp 原生支持标准 ACP,见 core/host_acp/agnescode.py)",
413
+ "fallback": "宿主 CLI 缺失时由外层宿主/用户决策接管;BugX 不代装宿主 CLI",
414
+ },
415
+ }
@@ -18,6 +18,7 @@ from contextlib import contextmanager
18
18
  import json
19
19
  import os
20
20
  from pathlib import Path
21
+ import shutil
21
22
  from typing import Iterator
22
23
 
23
24
  from core.infra.json_utils import unique_json_object
@@ -208,9 +209,16 @@ def _autonomous_environment(root: Path) -> Iterator[dict[str, str | None]]:
208
209
  for entry in source_dir.iterdir():
209
210
  if entry.name in {"opencode.json", "opencode.jsonc", "plugin", "plugins"}:
210
211
  continue
211
- (private_dir / entry.name).symlink_to(
212
- entry, target_is_directory=entry.is_dir(),
213
- )
212
+ dest = private_dir / entry.name
213
+ try:
214
+ dest.symlink_to(entry, target_is_directory=entry.is_dir())
215
+ except OSError:
216
+ if os.name != "nt":
217
+ raise
218
+ if entry.is_dir():
219
+ shutil.copytree(entry, dest, dirs_exist_ok=True)
220
+ else:
221
+ shutil.copy2(entry, dest)
214
222
  except OSError as exc:
215
223
  raise RuntimeError(
216
224
  f"OpenCode 自治配置资产无法隔离 ({type(exc).__name__})"
@@ -1,6 +1,6 @@
1
1
  # BugX Core Infrastructure & Primitives (核心基础设施与底层操作系统原语子系统)
2
2
 
3
- > **版本契约**: `0.1.4` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
3
+ > **版本契约**: `0.1.5` | **所属分层**: `Layer 0: 基础设施与操作系统抽象`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md) 与 [`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
 
@@ -12,8 +12,8 @@ import re
12
12
  from pathlib import Path
13
13
 
14
14
  VERSION_ENV = "BUGX_VERSION"
15
- VERSION_TOKEN = "0.1.4"
16
- _DEFAULT_VERSION = "0.1.4"
15
+ VERSION_TOKEN = "0.1.5"
16
+ _DEFAULT_VERSION = "0.1.5"
17
17
  _VERSION_RE = re.compile(r"^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$")
18
18
 
19
19
 
@@ -47,6 +47,8 @@ def parse_python_version(executable_path):
47
47
  stdout=subprocess.PIPE,
48
48
  stderr=subprocess.PIPE,
49
49
  text=True,
50
+ encoding="utf-8",
51
+ errors="replace",
50
52
  timeout=2.0,
51
53
  check=False,
52
54
  )
@@ -131,7 +133,8 @@ def find_python_candidates(extra_paths=None):
131
133
  try:
132
134
  res = subprocess.run(
133
135
  [py_launcher, ver_flag, "-c", "import sys; print(sys.executable)"],
134
- stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=2.0, check=False,
136
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
137
+ encoding="utf-8", errors="replace", timeout=2.0, check=False,
135
138
  )
136
139
  if res.returncode == 0 and res.stdout.strip():
137
140
  add_candidate(res.stdout.strip())
@@ -91,7 +91,7 @@ flowchart TD
91
91
  | `startup_gates.py` | 启动前置安全门禁(文件树白名单、脏工作区检查、权限拦截) | `verify_startup_gates` |
92
92
  | `startup_interaction.py` | 交互式问答决策引擎,根据终端能力与配置解析交互模式 | `resolve_startup_interaction` |
93
93
  | `verify_loop.py` | 独立验证员盲审输入包构造、Anti-Gaming 校验与报错驱动 PoC 自纠错闭环 | `build_verify_bundle`, `execute_verify_attempt`, `run_verification_loop` |
94
- | `startup_version_gate.py` | 版本硬门禁校验器,确保运行时版本严格等于 `0.1.4` 绝不漂移 | `assert_version_integrity` |
94
+ | `startup_version_gate.py` | 版本硬门禁校验器,确保运行时版本严格等于 `0.1.5` 绝不漂移 | `assert_version_integrity` |
95
95
  | `supervisor_bridge.py` | Supervisor 模块间解耦桥接层,提供轻量化调用门面 | `SupervisorBridge` |
96
96
  | `supervisor_coverage.py` | 覆盖率生命周期继承器,支持空闲历史会话继承与动态分发 | `SupervisorCoverageSync` |
97
97
  | `supervisor_degraded.py` | 降级容灾与探针就地自愈控制器,无损处理缺失依赖与环境 | `SupervisorDegradedCoordinator` |
@@ -103,7 +103,7 @@ flowchart TD
103
103
 
104
104
  ## 3. 核心设计契约与公理 (Design Axioms)
105
105
 
106
- 1. **版本绝对固化公理**:`startup_version_gate.py` 必须在任何业务逻辑启动前执行,基线版本严格锁定在 `0.1.4`,杜绝任何环境版本漂移。
106
+ 1. **版本绝对固化公理**:`startup_version_gate.py` 必须在任何业务逻辑启动前执行,基线版本严格锁定在 `0.1.5`,杜绝任何环境版本漂移。
107
107
  2. **状态机单向流转与幂等性**:生命周期从 `Pre` $\rightarrow$ `Round` $\rightarrow$ `Worker` $\rightarrow$ `Judge` $\rightarrow$ `Settlement` $\rightarrow$ `Post` 严格单向流动,禁止逆流操作;重试必须走显式的轮次迭代(`advance_round_lifecycle`)。
108
108
  3. **证据零伪造公理**:在 `findings_adjudication.py` 与 `candidate_revalidation.py` 中,所有缺陷判定必须有可执行的反事实测试证据,严禁仅凭模型推理文本定性。
109
109
  4. **工作树物理安全红线**:`post_dry_run.py` 与 `post_commit.py` 严格遵守工作树保护宪法,未授权时绝对禁止覆盖用户未暂存的修改。