bugx-cli 0.1.1 → 0.1.2
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.
- package/README.md +13 -9
- package/core/README.md +1 -1
- package/core/assets/README.md +3 -2
- package/core/assets/bugx-social-preview.svg +71 -0
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/audit_packs/README.md +2 -0
- package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
- package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
- package/core/audit_packs/pitfalls/go_backend.json +66 -0
- package/core/audit_packs/pitfalls/java_spring.json +64 -0
- package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
- package/core/audit_packs/pitfalls/python_web.json +82 -0
- package/core/bugx.md +1 -1
- package/core/bugx_paths.py +2 -2
- package/core/cloud_sync/cloud_client.py +56 -5
- package/core/cloud_sync/consent.py +33 -3
- package/core/cloud_sync/flywheel_client.py +186 -24
- package/core/contracts/README.md +1 -1
- package/core/contracts/bugx-runtime-contract.md +1 -1
- package/core/contracts/bugx-worker.md +1 -1
- package/core/engine-integrity.json +122 -66
- package/core/infra/README.md +1 -1
- package/core/infra/build_info.py +2 -2
- package/core/launch_phases/README.md +6 -3
- package/core/launch_phases/finding_confirm_phase.py +168 -7
- package/core/launch_phases/post_phase.py +5 -5
- package/core/launch_phases/pre_recon_scout.py +13 -0
- package/core/launch_phases/report_sharing.py +3 -7
- package/core/launch_phases/round_orchestrator.py +114 -26
- package/core/launch_phases/semantic_recon.py +545 -0
- package/core/launch_phases/startup_version_gate.py +6 -2
- package/core/launch_phases/verify_loop.py +767 -0
- package/core/launch_phases/worker_prior.py +115 -0
- package/core/ledger/README.md +2 -1
- package/core/ledger/finding_verification.py +511 -2
- package/core/ledger/fp_ledger.py +255 -0
- package/core/metadata.txt +2 -2
- package/core/planning/README.md +2 -1
- package/core/planning/prompt_harness.py +50 -10
- package/core/planning/prompt_policy_engine.py +386 -0
- package/core/prompts/README.md +4 -2
- package/core/prompts/policies/prompt_policies.json +101 -0
- package/core/prompts/stages/stage_verify.defensive.md +42 -0
- package/core/prompts/stages/stage_verify.md +44 -0
- package/core/report_engine/report_share.py +0 -8
- package/core/retrieval/README.md +2 -1
- package/core/retrieval/pitfall_packs.py +277 -0
- package/core/runtime/README.md +1 -1
- package/core/runtime/global_telemetry.py +20 -0
- package/core/runtime/scenario_eval.py +1 -1
- package/core/supervisor/README.md +1 -1
- package/docs/07_distribution/01_README_NPM.md +13 -9
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/qoder/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
- package/interfaces/bin/bugx.js +7 -7
- package/interfaces/cli/bugx_cli/__init__.py +2 -2
- package/interfaces/cli/bugx_cli/cli.py +163 -67
- package/interfaces/cli/bugx_cli/commands/agent.py +122 -61
- package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
- package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
- package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
- package/interfaces/cli/bugx_cli/commands/plugin.py +3 -3
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
- package/interfaces/cli/bugx_cli/commands/project.py +6 -13
- package/interfaces/cli/bugx_cli/commands/system.py +513 -158
- package/interfaces/cli/bugx_cli/common.py +6 -8
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
- package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
- package/package.json +29 -15
- package/pyproject.toml +40 -1
- package/scripts/sync-version.mjs +1 -1
- package/core/assets/bugx-hero-cn.png +0 -0
- 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.
|
|
244
|
-
value = os.environ.get("BUGX_VERSION", "0.1.
|
|
243
|
+
if value == "0.1.2":
|
|
244
|
+
value = os.environ.get("BUGX_VERSION", "0.1.2")
|
|
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(
|