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
@@ -0,0 +1,545 @@
1
+ #!/usr/bin/env python3
2
+ """core/launch_phases/semantic_recon.py — Recon 阶段轻量语义侦察叠加层(P2 / T-006)。
3
+
4
+ 在确定性静态图谱之上叠加三类高价值语义资产,严格遵守零外部依赖与非受信输入隔离:
5
+ 1. ``implicit_routes``:动态分发、插件注册表、RPC/装饰器工厂等隐式入口路由;
6
+ 2. ``auth_boundaries``:自定义鉴权中间件、装饰器、租户隔离与信任域切换点;
7
+ 3. ``business_invariants``:状态机合法迁移、金额/库存守恒、幂等键等业务不变量。
8
+
9
+ 核心门禁:
10
+ - 物理锚点核验:拒绝不存在文件、越界路径(``..``)、符号链接穿越及超界行号;
11
+ - 反提示词注入净化:剥离控制字符、截断 ≤200 字符、拦截典型 prompt-injection 载荷;
12
+ - 文件级 SHA-256 哈希绑定:目标源码一旦修改,该文件的过期语义自动过滤失效。
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import ast
18
+ import hashlib
19
+ import json
20
+ import os
21
+ import re
22
+ import tempfile
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Mapping, Sequence
26
+
27
+ OVERLAY_SCHEMA_VERSION = 1
28
+ MAX_FIELD_CHARS = 200
29
+ MAX_CONTEXT_FILES = 24
30
+ MAX_CONTEXT_CHARS = 12000
31
+
32
+ _SKIP_DIRS = frozenset({
33
+ ".git", ".bugx", "node_modules", "__pycache__", ".venv", "venv",
34
+ "dist", "build", ".next", "target", ".pytest_cache",
35
+ })
36
+ _CODE_SUFFIXES = frozenset({".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".kt"})
37
+ _PRIORITY_KEYWORDS = (
38
+ "route", "router", "dispatch", "handler", "middleware", "auth", "guard",
39
+ "permission", "rbac", "tenant", "order", "payment", "billing", "balance",
40
+ "state", "workflow", "webhook", "rpc", "plugin",
41
+ )
42
+
43
+ _INJECTION_PATTERNS: tuple[re.Pattern[str], ...] = (
44
+ re.compile(r"(?i)ignore\s+(?:all\s+)?(?:previous|above|prior)\s+instructions?"),
45
+ re.compile(r"(?i)disregard\s+(?:all\s+)?(?:previous|prior)\s+instructions?"),
46
+ re.compile(r"(?i)you\s+are\s+now\s+(?:a|an|in)\s+"),
47
+ re.compile(r"(?i)</?(?:system|assistant|user|instruction|prompt)\b[^>]*>"),
48
+ re.compile(r"(?i)^\s*system\s*:"),
49
+ re.compile(r"(?i)mark\s+all\s+(?:findings|vulnerabilities|issues)\s+(?:as\s+)?safe"),
50
+ )
51
+
52
+
53
+ def overlay_path(root: Path) -> Path:
54
+ return Path(root).resolve() / ".bugx" / "state" / "semantic-recon-overlay.json"
55
+
56
+
57
+ def _sha256_bytes(data: bytes) -> str:
58
+ return hashlib.sha256(data).hexdigest()
59
+
60
+
61
+ def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
62
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
63
+ raw = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
64
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
65
+ try:
66
+ os.fchmod(fd, 0o600)
67
+ with os.fdopen(fd, "wb") as handle:
68
+ handle.write(raw)
69
+ handle.flush()
70
+ os.fsync(handle.fileno())
71
+ os.replace(tmp_name, path)
72
+ except BaseException:
73
+ try:
74
+ os.close(fd)
75
+ except OSError:
76
+ pass
77
+ try:
78
+ os.unlink(tmp_name)
79
+ except OSError:
80
+ pass
81
+ raise
82
+
83
+
84
+ def _sanitize_text(value: object, *, max_len: int = MAX_FIELD_CHARS) -> tuple[str, bool]:
85
+ """Strip control chars, bound length, and neutralize prompt-injection payloads."""
86
+ raw = re.sub(r"[\x00-\x1f\x7f]+", " ", str(value or "")).strip()
87
+ injected = False
88
+ for pattern in _INJECTION_PATTERNS:
89
+ if pattern.search(raw):
90
+ raw = pattern.sub("[REDACTED_INJECTION]", raw)
91
+ injected = True
92
+ if len(raw) > max_len:
93
+ raw = raw[:max_len].rstrip()
94
+ return raw, injected
95
+
96
+
97
+ def _resolve_anchor(root: Path, rel_file: object, line: object) -> tuple[str, int, str] | None:
98
+ """Physically verify file exists inside root (no traversal/symlink) and line is in bounds."""
99
+ if not isinstance(rel_file, str) or not rel_file.strip():
100
+ return None
101
+ if isinstance(line, bool) or not isinstance(line, int) or line < 1:
102
+ return None
103
+ candidate = Path(rel_file.replace("\\", "/").strip())
104
+ if candidate.is_absolute() or ".." in candidate.parts:
105
+ return None
106
+ resolved_root = Path(root).resolve()
107
+ cursor = resolved_root
108
+ for part in candidate.parts:
109
+ if part in {"", "."}:
110
+ continue
111
+ cursor = cursor / part
112
+ if cursor.is_symlink():
113
+ return None
114
+ try:
115
+ abs_path = (resolved_root / candidate).resolve()
116
+ rel_norm = abs_path.relative_to(resolved_root).as_posix()
117
+ except (OSError, ValueError):
118
+ return None
119
+ if not abs_path.is_file() or abs_path.is_symlink():
120
+ return None
121
+ try:
122
+ raw_bytes = abs_path.read_bytes()
123
+ except OSError:
124
+ return None
125
+ line_count = max(1, len(raw_bytes.decode("utf-8", errors="replace").splitlines()))
126
+ if line > line_count:
127
+ return None
128
+ return rel_norm, line, _sha256_bytes(raw_bytes)
129
+
130
+
131
+ def _iter_candidate_files(root: Path, *, max_files: int = MAX_CONTEXT_FILES) -> list[Path]:
132
+ resolved_root = Path(root).resolve()
133
+ scored: list[tuple[int, str, Path]] = []
134
+ for dirpath, dirnames, filenames in os.walk(resolved_root):
135
+ dirnames[:] = sorted(d for d in dirnames if d not in _SKIP_DIRS and not d.startswith("."))
136
+ for fname in sorted(filenames):
137
+ fpath = Path(dirpath) / fname
138
+ if fpath.is_symlink() or fpath.suffix.lower() not in _CODE_SUFFIXES:
139
+ continue
140
+ rel = fpath.relative_to(resolved_root).as_posix()
141
+ rel_lower = rel.lower()
142
+ score = sum(2 for kw in _PRIORITY_KEYWORDS if kw in rel_lower)
143
+ scored.append((score, rel, fpath))
144
+ scored.sort(key=lambda item: (-item[0], item[1]))
145
+ return [item[2] for item in scored[:max_files]]
146
+
147
+
148
+ def collect_semantic_context_pack(
149
+ root: Path,
150
+ *,
151
+ max_files: int = MAX_CONTEXT_FILES,
152
+ max_chars: int = MAX_CONTEXT_CHARS,
153
+ ) -> dict[str, Any]:
154
+ """Build a bounded context pack for lightweight LLM semantic recon."""
155
+ resolved_root = Path(root).resolve()
156
+ files_payload: list[dict[str, Any]] = []
157
+ used = 0
158
+ for fpath in _iter_candidate_files(resolved_root, max_files=max_files):
159
+ rel = fpath.relative_to(resolved_root).as_posix()
160
+ try:
161
+ text = fpath.read_text(encoding="utf-8", errors="replace")
162
+ except OSError:
163
+ continue
164
+ remaining = max_chars - used
165
+ if remaining <= 128:
166
+ break
167
+ excerpt = text[: min(len(text), 2000, remaining)]
168
+ files_payload.append({
169
+ "file": rel,
170
+ "line_count": len(text.splitlines()),
171
+ "excerpt": excerpt,
172
+ })
173
+ used += len(excerpt)
174
+ return {
175
+ "schema_version": OVERLAY_SCHEMA_VERSION,
176
+ "root_name": resolved_root.name,
177
+ "file_count": len(files_payload),
178
+ "files": files_payload,
179
+ }
180
+
181
+
182
+ def _heuristic_extract_python(root: Path, fpath: Path) -> dict[str, list[dict[str, Any]]]:
183
+ """Zero-dependency Python AST heuristic extractor for implicit routes, auth boundaries & invariants."""
184
+ rel = fpath.resolve().relative_to(Path(root).resolve()).as_posix()
185
+ routes: list[dict[str, Any]] = []
186
+ auths: list[dict[str, Any]] = []
187
+ invariants: list[dict[str, Any]] = []
188
+ try:
189
+ src = fpath.read_text(encoding="utf-8", errors="replace")
190
+ tree = ast.parse(src, filename=rel)
191
+ except (OSError, SyntaxError):
192
+ return {"implicit_routes": routes, "auth_boundaries": auths, "business_invariants": invariants}
193
+
194
+ for node in ast.walk(tree):
195
+ # 1. Implicit dispatch: getattr(..., action/method/handler) or HANDLERS/ROUTES dict registry
196
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "getattr":
197
+ routes.append({
198
+ "file": rel,
199
+ "line": getattr(node, "lineno", 1),
200
+ "endpoint_or_dispatch": "dynamic getattr() dispatch",
201
+ "handler": "dynamic_target",
202
+ "auth_required": "unknown",
203
+ "confidence": "medium",
204
+ "source": "heuristic_ast",
205
+ })
206
+ elif isinstance(node, ast.Assign):
207
+ for target in node.targets:
208
+ if isinstance(target, ast.Name) and any(
209
+ tok in target.id.upper() for tok in ("ROUTE", "HANDLER", "DISPATCH", "RPC_METHOD")
210
+ ) and isinstance(node.value, ast.Dict):
211
+ routes.append({
212
+ "file": rel,
213
+ "line": getattr(node, "lineno", 1),
214
+ "endpoint_or_dispatch": f"registry table {target.id}",
215
+ "handler": target.id,
216
+ "auth_required": "unknown",
217
+ "confidence": "medium",
218
+ "source": "heuristic_ast",
219
+ })
220
+ elif isinstance(target, ast.Name) and any(
221
+ tok in target.id.upper() for tok in ("TRANSITION", "ALLOWED_STATE", "VALID_STATUS")
222
+ ):
223
+ invariants.append({
224
+ "file": rel,
225
+ "line": getattr(node, "lineno", 1),
226
+ "entity": target.id,
227
+ "invariant_rule": f"explicit state transition table {target.id}",
228
+ "violation_impact": "state machine bypass if transition check is skipped",
229
+ "confidence": "medium",
230
+ "source": "heuristic_ast",
231
+ })
232
+
233
+ # 2. Custom auth middleware / guard functions
234
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
235
+ lname = node.name.lower()
236
+ if any(tok in lname for tok in ("require_auth", "check_auth", "verify_token", "auth_middleware", "require_role", "tenant_guard")):
237
+ auths.append({
238
+ "file": rel,
239
+ "line": getattr(node, "lineno", 1),
240
+ "mechanism": f"custom guard `{node.name}`",
241
+ "scope": rel,
242
+ "trust_transition": "untrusted request -> authenticated principal",
243
+ "confidence": "high",
244
+ "source": "heuristic_ast",
245
+ })
246
+ elif any(tok in lname for tok in ("transfer", "refund", "checkout", "withdraw", "transition_state", "approve_order")):
247
+ invariants.append({
248
+ "file": rel,
249
+ "line": getattr(node, "lineno", 1),
250
+ "entity": node.name,
251
+ "invariant_rule": f"business operation `{node.name}` requires non-negative conservation & valid state check",
252
+ "violation_impact": "financial/state integrity violation",
253
+ "confidence": "medium",
254
+ "source": "heuristic_ast",
255
+ })
256
+
257
+ return {
258
+ "implicit_routes": routes,
259
+ "auth_boundaries": auths,
260
+ "business_invariants": invariants,
261
+ }
262
+
263
+
264
+ def heuristic_semantic_recon(root: Path, *, max_files: int = MAX_CONTEXT_FILES) -> dict[str, list[dict[str, Any]]]:
265
+ """Offline zero-dependency semantic clue extractor across candidate files."""
266
+ combined: dict[str, list[dict[str, Any]]] = {
267
+ "implicit_routes": [],
268
+ "auth_boundaries": [],
269
+ "business_invariants": [],
270
+ }
271
+ for fpath in _iter_candidate_files(root, max_files=max_files):
272
+ if fpath.suffix.lower() == ".py":
273
+ part = _heuristic_extract_python(root, fpath)
274
+ for key in combined:
275
+ combined[key].extend(part[key])
276
+ return combined
277
+
278
+
279
+ def validate_and_anchor_overlay(
280
+ root: Path,
281
+ raw_overlay: Mapping[str, Any],
282
+ ) -> tuple[dict[str, Any], dict[str, str]]:
283
+ """Physically verify file/line anchors & sanitize prompt-injection payloads (P2-D02)."""
284
+ watched_hashes: dict[str, str] = {}
285
+ rejected_hallucinations = 0
286
+ sanitized_injections = 0
287
+
288
+ def _clean_items(
289
+ items: object,
290
+ spec_fields: tuple[str, ...],
291
+ dedup_keys: tuple[str, ...],
292
+ ) -> list[dict[str, Any]]:
293
+ nonlocal rejected_hallucinations, sanitized_injections
294
+ if not isinstance(items, Sequence) or isinstance(items, (str, bytes)):
295
+ return []
296
+ cleaned: list[dict[str, Any]] = []
297
+ seen: set[tuple[str, ...]] = set()
298
+ for entry in items:
299
+ if not isinstance(entry, Mapping):
300
+ rejected_hallucinations += 1
301
+ continue
302
+ anchor = _resolve_anchor(root, entry.get("file"), entry.get("line"))
303
+ if anchor is None:
304
+ rejected_hallucinations += 1
305
+ continue
306
+ rel_norm, line_no, file_hash = anchor
307
+ watched_hashes[rel_norm] = file_hash
308
+ record: dict[str, Any] = {"file": rel_norm, "line": line_no}
309
+ for field in spec_fields:
310
+ text, inj = _sanitize_text(entry.get(field, ""))
311
+ if inj:
312
+ sanitized_injections += 1
313
+ record[field] = text
314
+ conf = str(entry.get("confidence") or "medium").strip().lower()
315
+ record["confidence"] = conf if conf in {"high", "medium", "low"} else "medium"
316
+ src_tag, _ = _sanitize_text(entry.get("source") or "llm_semantic", max_len=48)
317
+ record["source"] = src_tag or "llm_semantic"
318
+ sig = tuple(str(record.get(k, "")) for k in dedup_keys)
319
+ if sig in seen:
320
+ continue
321
+ seen.add(sig)
322
+ cleaned.append(record)
323
+ return cleaned
324
+
325
+ routes = _clean_items(
326
+ raw_overlay.get("implicit_routes"),
327
+ ("endpoint_or_dispatch", "handler", "auth_required"),
328
+ ("file", "line", "endpoint_or_dispatch"),
329
+ )
330
+ auths = _clean_items(
331
+ raw_overlay.get("auth_boundaries"),
332
+ ("mechanism", "scope", "trust_transition"),
333
+ ("file", "line", "mechanism"),
334
+ )
335
+ invariants = _clean_items(
336
+ raw_overlay.get("business_invariants"),
337
+ ("entity", "invariant_rule", "violation_impact"),
338
+ ("file", "line", "entity", "invariant_rule"),
339
+ )
340
+
341
+ validated = {
342
+ "schema_version": OVERLAY_SCHEMA_VERSION,
343
+ "implicit_routes": routes,
344
+ "auth_boundaries": auths,
345
+ "business_invariants": invariants,
346
+ "audit_stats": {
347
+ "rejected_hallucinations": rejected_hallucinations,
348
+ "sanitized_injections": sanitized_injections,
349
+ "anchored_files": len(watched_hashes),
350
+ },
351
+ }
352
+ return validated, watched_hashes
353
+
354
+
355
+ def run_semantic_recon_overlay(
356
+ root: Path,
357
+ *,
358
+ llm_analyzer: Callable[[Mapping[str, Any]], Mapping[str, Any]] | None = None,
359
+ max_files: int = MAX_CONTEXT_FILES,
360
+ max_chars: int = MAX_CONTEXT_CHARS,
361
+ persist: bool = True,
362
+ ) -> dict[str, Any]:
363
+ """Run dual-channel semantic recon (optional LLM + heuristic baseline), anchor-verify & persist."""
364
+ resolved_root = Path(root).resolve()
365
+ merged: dict[str, list[dict[str, Any]]] = {
366
+ "implicit_routes": [],
367
+ "auth_boundaries": [],
368
+ "business_invariants": [],
369
+ }
370
+ mode = "heuristic_fallback"
371
+
372
+ if llm_analyzer is not None:
373
+ context_pack = collect_semantic_context_pack(
374
+ resolved_root, max_files=max_files, max_chars=max_chars,
375
+ )
376
+ try:
377
+ llm_out = llm_analyzer(context_pack)
378
+ if isinstance(llm_out, Mapping):
379
+ for key in merged:
380
+ raw_list = llm_out.get(key)
381
+ if isinstance(raw_list, list):
382
+ for item in raw_list:
383
+ if isinstance(item, Mapping):
384
+ merged[key].append({"source": "llm_semantic", **dict(item)})
385
+ mode = "llm_plus_heuristic"
386
+ except Exception:
387
+ mode = "heuristic_fallback_after_llm_error"
388
+
389
+ heur = heuristic_semantic_recon(resolved_root, max_files=max_files)
390
+ for key in merged:
391
+ merged[key].extend(heur[key])
392
+
393
+ validated, watched_hashes = validate_and_anchor_overlay(resolved_root, merged)
394
+ payload = {
395
+ **validated,
396
+ "mode": mode,
397
+ "watched_file_hashes": watched_hashes,
398
+ "created_at": time.time(),
399
+ }
400
+ if persist:
401
+ _atomic_write_json(overlay_path(resolved_root), payload)
402
+ return payload
403
+
404
+
405
+ def load_semantic_overlay(
406
+ root: Path,
407
+ *,
408
+ allow_stale: bool = False,
409
+ ) -> dict[str, Any]:
410
+ """Load persisted semantic overlay and drop entries whose anchored file hash drifted (P2-D03)."""
411
+ resolved_root = Path(root).resolve()
412
+ path = overlay_path(resolved_root)
413
+ if not path.is_file():
414
+ return {
415
+ "schema_version": OVERLAY_SCHEMA_VERSION,
416
+ "implicit_routes": [],
417
+ "auth_boundaries": [],
418
+ "business_invariants": [],
419
+ "stale_files": [],
420
+ }
421
+ try:
422
+ data = json.loads(path.read_text(encoding="utf-8"))
423
+ except (OSError, ValueError):
424
+ return {
425
+ "schema_version": OVERLAY_SCHEMA_VERSION,
426
+ "implicit_routes": [],
427
+ "auth_boundaries": [],
428
+ "business_invariants": [],
429
+ "stale_files": [],
430
+ }
431
+ if not isinstance(data, dict):
432
+ return {
433
+ "schema_version": OVERLAY_SCHEMA_VERSION,
434
+ "implicit_routes": [],
435
+ "auth_boundaries": [],
436
+ "business_invariants": [],
437
+ "stale_files": [],
438
+ }
439
+
440
+ watched = data.get("watched_file_hashes") if isinstance(data.get("watched_file_hashes"), dict) else {}
441
+ stale_files: set[str] = set()
442
+ for rel, expected_hash in watched.items():
443
+ if not isinstance(rel, str) or not isinstance(expected_hash, str):
444
+ continue
445
+ target = resolved_root / rel
446
+ if not target.is_file() or target.is_symlink():
447
+ stale_files.add(rel)
448
+ continue
449
+ try:
450
+ actual = _sha256_bytes(target.read_bytes())
451
+ except OSError:
452
+ stale_files.add(rel)
453
+ continue
454
+ if actual != expected_hash:
455
+ stale_files.add(rel)
456
+
457
+ def _filter_list(key: str) -> list[dict[str, Any]]:
458
+ raw = data.get(key)
459
+ if not isinstance(raw, list):
460
+ return []
461
+ out: list[dict[str, Any]] = []
462
+ for item in raw:
463
+ if not isinstance(item, dict):
464
+ continue
465
+ rel = str(item.get("file") or "")
466
+ is_stale = rel in stale_files
467
+ if is_stale and not allow_stale:
468
+ continue
469
+ copied = dict(item)
470
+ if is_stale:
471
+ copied["stale"] = True
472
+ out.append(copied)
473
+ return out
474
+
475
+ return {
476
+ "schema_version": int(data.get("schema_version") or OVERLAY_SCHEMA_VERSION),
477
+ "mode": data.get("mode", ""),
478
+ "implicit_routes": _filter_list("implicit_routes"),
479
+ "auth_boundaries": _filter_list("auth_boundaries"),
480
+ "business_invariants": _filter_list("business_invariants"),
481
+ "audit_stats": data.get("audit_stats") or {},
482
+ "stale_files": sorted(stale_files),
483
+ }
484
+
485
+
486
+ def render_semantic_overlay_guidance(
487
+ overlay: Mapping[str, Any],
488
+ *,
489
+ target_files: Sequence[str] = (),
490
+ char_budget: int = 900,
491
+ ) -> str:
492
+ """Render target-filtered, budget-capped semantic recon guidance for Worker prompts."""
493
+ if char_budget <= 0 or not isinstance(overlay, Mapping):
494
+ return ""
495
+ wanted = {f.replace("\\", "/").strip() for f in target_files if isinstance(f, str) and f.strip()}
496
+
497
+ def _match(items: object) -> list[dict[str, Any]]:
498
+ if not isinstance(items, Sequence) or isinstance(items, (str, bytes)):
499
+ return []
500
+ res = [it for it in items if isinstance(it, dict)]
501
+ if wanted:
502
+ res = [it for it in res if str(it.get("file") or "") in wanted]
503
+ return res
504
+
505
+ routes = _match(overlay.get("implicit_routes"))
506
+ auths = _match(overlay.get("auth_boundaries"))
507
+ invs = _match(overlay.get("business_invariants"))
508
+ if not (routes or auths or invs):
509
+ return ""
510
+
511
+ lines = ["[语义侦察叠加层 (Semantic Recon Overlay)]"]
512
+ used = len(lines[0]) + 1
513
+ candidates: list[str] = []
514
+ for r in routes:
515
+ candidates.append(
516
+ f"- [隐式路由] {r.get('file')}:{r.get('line')} | {r.get('endpoint_or_dispatch')} -> "
517
+ f"{r.get('handler')} (auth={r.get('auth_required')})"
518
+ )
519
+ for a in auths:
520
+ candidates.append(
521
+ f"- [鉴权边界] {a.get('file')}:{a.get('line')} | {a.get('mechanism')} ({a.get('trust_transition')})"
522
+ )
523
+ for inv in invs:
524
+ candidates.append(
525
+ f"- [业务不变量] {inv.get('file')}:{inv.get('line')} | {inv.get('entity')}: {inv.get('invariant_rule')}"
526
+ )
527
+
528
+ for line in candidates:
529
+ if used + len(line) + 1 > char_budget:
530
+ break
531
+ lines.append(line)
532
+ used += len(line) + 1
533
+ return "\n".join(lines) if len(lines) > 1 else ""
534
+
535
+
536
+ __all__ = [
537
+ "OVERLAY_SCHEMA_VERSION",
538
+ "overlay_path",
539
+ "collect_semantic_context_pack",
540
+ "heuristic_semantic_recon",
541
+ "validate_and_anchor_overlay",
542
+ "run_semantic_recon_overlay",
543
+ "load_semantic_overlay",
544
+ "render_semantic_overlay_guidance",
545
+ ]
@@ -240,8 +240,8 @@ def version_marker(path: Path) -> str | None:
240
240
  if not match:
241
241
  return None
242
242
  value = match.group(1)
243
- if value == "0.1.1":
244
- value = os.environ.get("BUGX_VERSION", "0.1.1")
243
+ if value == "0.1.3":
244
+ value = os.environ.get("BUGX_VERSION", "0.1.3")
245
245
  return value
246
246
 
247
247
  def startup_release_version(value: object) -> tuple[int, int, int] | None:
@@ -732,9 +732,13 @@ def startup_remote_version_check(*, stream=None) -> None:
732
732
  cli_ver = cloud_client.__version__
733
733
  if cli_ver == "unknown":
734
734
  cli_ver = ""
735
+ client_kind = "npm" if os.environ.get("BUGX_CLI_SOURCE", "").strip().lower() == "npm" else "pip"
736
+ artifact_kind = "npm-tarball" if client_kind == "npm" else "python-wheel"
735
737
  result = client.check_version(
736
738
  current_version=cli_ver,
737
739
  channel=client_metadata.release_channel(),
740
+ client_kind=client_kind,
741
+ artifact_kind=artifact_kind,
738
742
  )
739
743
  if not result.ok:
740
744
  _record_remote_version_result(
@@ -1056,8 +1056,6 @@ def supervisor_mcp_gate(*, review_mode: str | None,
1056
1056
  * ``"restart_required"`` —— 配置已写入/已存在但当前宿主未加载 ⇒ 必须重启宿主;
1057
1057
  * ``"blocked"`` —— 需要用户/宿主决策或安装未完成。
1058
1058
  """
1059
- if review_mode != "mcp-auto":
1060
- return "ok"
1061
1059
  # [BEGIN DEV_ONLY: FAST_VERIFICATION_MCP_GATE]
1062
1060
  try:
1063
1061
  from core.runtime.interaction import try_get_preset_runtime_config
@@ -1071,27 +1069,20 @@ def supervisor_mcp_gate(*, review_mode: str | None,
1071
1069
  if preset_cfg.get("supervisor_mcp") in {"manual", "skip"}:
1072
1070
  return "ok"
1073
1071
  # [END DEV_ONLY: FAST_VERIFICATION_MCP_GATE]
1072
+
1074
1073
  status = _supervisor_mcp_status()
1075
- if status is None:
1074
+ # 强制重启门禁:若项目已配置 Supervisor MCP 但当前宿主会话未加载该工具链(stale),
1075
+ # 宿主进程无法动态感知新配置,探活绝不能替代重启,必须阻断并强制要求重启宿主。
1076
+ if status is not None and _mcp_session_is_stale(status):
1077
+ host = str(status.get("host") or "当前宿主")
1078
+ print(f"[launch_bugx] ✗ 必须强制重启宿主:{host} 已配置 Supervisor MCP,但当前会话尚未加载该 MCP 工具链。")
1079
+ print(" 宿主进程(IDE/终端)不支持动态热重载配置,必须【重载窗口 / 重启宿主会话】后再启动 BugX。")
1080
+ return "restart_required"
1081
+
1082
+ if review_mode != "mcp-auto":
1076
1083
  return "ok"
1077
- # A configured-but-not-loaded session is handled by the final
1078
- # ``startup_action`` gate below. Do not present the older install/manual
1079
- # gate here, otherwise the host can silently choose manual review and move
1080
- # on to the polling question (the bug this gate is meant to prevent).
1081
- if _mcp_session_is_stale(status):
1082
- # 尝试快速 stdio 活体探活(A1 自愈机制)
1083
- try:
1084
- from core.supervisor import supervisor_host
1085
- probe_result = supervisor_host.probe_builtin_mcp_session(resolve_project_root(), deadline=None)
1086
- if not probe_result.get("error"):
1087
- os.environ[supervisor_host.MCP_SESSION_PROOF_ENV] = json.dumps(probe_result, ensure_ascii=False)
1088
- return "ok"
1089
- except Exception:
1090
- pass
1091
- if autonomous:
1092
- print("[launch_bugx] ✗ 需要重启宿主:Supervisor MCP 已配置但当前宿主未加载且探活未通过;"
1093
- "支持使用 stdio JSON-RPC 等效通道驱动,或重启宿主会话后重试。")
1094
- return "restart_required"
1084
+
1085
+ if status is None:
1095
1086
  return "ok"
1096
1087
  if autonomous:
1097
1088
  # The installer is already constrained to the BugX-managed host
@@ -1100,7 +1091,7 @@ def supervisor_mcp_gate(*, review_mode: str | None,
1100
1091
  if not _install_supervisor_mcp(status):
1101
1092
  print("[launch_bugx] 自治模式已停止:Supervisor MCP 安装失败(需宿主重启后重试)。")
1102
1093
  return "restart_required"
1103
- print("[launch_bugx] Supervisor MCP 配置已写入;需要宿主重新启动后才能加载。")
1094
+ print("[launch_bugx] ✗ 必须强制重启宿主:Supervisor MCP 配置已写入;宿主重新启动后才能加载。")
1104
1095
  return "restart_required"
1105
1096
  choice = _prompt_supervisor_mcp(status, allow_manual=False)
1106
1097
  if choice is None:
@@ -1133,7 +1124,7 @@ def supervisor_mcp_gate(*, review_mode: str | None,
1133
1124
  return "blocked"
1134
1125
  if choice == "install":
1135
1126
  _install_supervisor_mcp(status)
1136
- print("[launch_bugx] Supervisor MCP 配置已写入;需要宿主重新启动后才能加载。")
1127
+ print("[launch_bugx] ✗ 必须强制重启宿主:Supervisor MCP 配置已写入;宿主重新启动后才能加载。")
1137
1128
  return "restart_required"
1138
1129
  if choice == "later":
1139
1130
  print("[launch_bugx] Supervisor MCP 安装已延后,本轮启动停止。")