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.
Files changed (82) hide show
  1. package/README.md +13 -9
  2. package/core/README.md +1 -1
  3. package/core/assets/README.md +3 -2
  4. package/core/assets/bugx-social-preview.svg +71 -0
  5. package/core/assets/bugx-wechat-group.png +0 -0
  6. package/core/audit_packs/README.md +2 -0
  7. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  8. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  9. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  10. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  11. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  12. package/core/audit_packs/pitfalls/python_web.json +82 -0
  13. package/core/bugx.md +1 -1
  14. package/core/bugx_paths.py +2 -2
  15. package/core/cloud_sync/cloud_client.py +56 -5
  16. package/core/cloud_sync/consent.py +33 -3
  17. package/core/cloud_sync/flywheel_client.py +186 -24
  18. package/core/contracts/README.md +1 -1
  19. package/core/contracts/bugx-runtime-contract.md +1 -1
  20. package/core/contracts/bugx-worker.md +1 -1
  21. package/core/engine-integrity.json +122 -66
  22. package/core/infra/README.md +1 -1
  23. package/core/infra/build_info.py +2 -2
  24. package/core/launch_phases/README.md +6 -3
  25. package/core/launch_phases/finding_confirm_phase.py +168 -7
  26. package/core/launch_phases/post_phase.py +5 -5
  27. package/core/launch_phases/pre_recon_scout.py +13 -0
  28. package/core/launch_phases/report_sharing.py +3 -7
  29. package/core/launch_phases/round_orchestrator.py +114 -26
  30. package/core/launch_phases/semantic_recon.py +545 -0
  31. package/core/launch_phases/startup_version_gate.py +6 -2
  32. package/core/launch_phases/verify_loop.py +767 -0
  33. package/core/launch_phases/worker_prior.py +115 -0
  34. package/core/ledger/README.md +2 -1
  35. package/core/ledger/finding_verification.py +511 -2
  36. package/core/ledger/fp_ledger.py +255 -0
  37. package/core/metadata.txt +2 -2
  38. package/core/planning/README.md +2 -1
  39. package/core/planning/prompt_harness.py +50 -10
  40. package/core/planning/prompt_policy_engine.py +386 -0
  41. package/core/prompts/README.md +4 -2
  42. package/core/prompts/policies/prompt_policies.json +101 -0
  43. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  44. package/core/prompts/stages/stage_verify.md +44 -0
  45. package/core/report_engine/report_share.py +0 -8
  46. package/core/retrieval/README.md +2 -1
  47. package/core/retrieval/pitfall_packs.py +277 -0
  48. package/core/runtime/README.md +1 -1
  49. package/core/runtime/global_telemetry.py +20 -0
  50. package/core/runtime/scenario_eval.py +1 -1
  51. package/core/supervisor/README.md +1 -1
  52. package/docs/07_distribution/01_README_NPM.md +13 -9
  53. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  54. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  55. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +1 -1
  56. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  57. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  58. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  59. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  60. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  61. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  62. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  63. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  64. package/interfaces/bin/bugx.js +7 -7
  65. package/interfaces/cli/bugx_cli/__init__.py +2 -2
  66. package/interfaces/cli/bugx_cli/cli.py +163 -67
  67. package/interfaces/cli/bugx_cli/commands/agent.py +122 -61
  68. package/interfaces/cli/bugx_cli/commands/audit.py +8 -7
  69. package/interfaces/cli/bugx_cli/commands/cloud.py +27 -19
  70. package/interfaces/cli/bugx_cli/commands/knowledge.py +3 -4
  71. package/interfaces/cli/bugx_cli/commands/plugin.py +3 -3
  72. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +2 -2
  73. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  74. package/interfaces/cli/bugx_cli/commands/system.py +513 -158
  75. package/interfaces/cli/bugx_cli/common.py +6 -8
  76. package/interfaces/cli/bugx_cli/infra/engine_installer.py +21 -10
  77. package/interfaces/cli/bugx_cli/infra/host_sync.py +1 -1
  78. package/package.json +29 -15
  79. package/pyproject.toml +40 -1
  80. package/scripts/sync-version.mjs +1 -1
  81. package/core/assets/bugx-hero-cn.png +0 -0
  82. package/core/assets/bugx-hero-en.png +0 -0
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env python3
2
+ """core/ledger/fp_ledger.py — 负样本误报账本与源码哈希防误杀护栏(P1 / T-005)。
3
+
4
+ 核心安全边界:
5
+ 1. 仅沉淀经引擎确认驳回的误报(允许 ``not_reproducible`` / ``false_positive`` / ``wont_fix``),
6
+ 严禁把 ``timeout`` / ``env_blocked`` / ``source_tampered`` 误记为“代码安全”;
7
+ 2. 每条负样本必须绑定目标文件的 ``source_sha256``;
8
+ 3. 查询时实时重算目标文件 SHA-256:
9
+ - 哈希一致 → ``active_guard``(有效降噪护栏);
10
+ - 哈希漂移或文件消失 → 自动降级为 ``stale_guard`` 并失效,严防修改代码引入新漏洞后被旧误报掩盖!
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Mapping, Sequence
22
+
23
+ LEDGER_SCHEMA_VERSION = 1
24
+ ALLOWED_FP_REJECTION_CLASSES = frozenset({
25
+ "not_reproducible",
26
+ "false_positive",
27
+ "wont_fix",
28
+ })
29
+
30
+
31
+ class FalsePositiveLedgerError(ValueError):
32
+ """Raised on invalid false-positive ledger path or payload."""
33
+
34
+
35
+ def _sha256_bytes(data: bytes) -> str:
36
+ return hashlib.sha256(data).hexdigest()
37
+
38
+
39
+ def _confined_file(root: Path, rel_path: str) -> tuple[str, Path]:
40
+ if not isinstance(rel_path, str) or not rel_path.strip():
41
+ raise FalsePositiveLedgerError("file_path 必须是非空相对路径")
42
+ candidate = Path(rel_path.replace("\\", "/"))
43
+ if candidate.is_absolute() or ".." in candidate.parts:
44
+ raise FalsePositiveLedgerError(f"file_path 越界或非相对路径: {rel_path}")
45
+ resolved_root = Path(root).resolve()
46
+ cursor = resolved_root
47
+ for part in candidate.parts:
48
+ if part in {"", "."}:
49
+ continue
50
+ cursor = cursor / part
51
+ if cursor.is_symlink():
52
+ raise FalsePositiveLedgerError(f"file_path 禁止穿过符号链接: {rel_path}")
53
+ resolved = (resolved_root / candidate).resolve()
54
+ try:
55
+ rel_norm = resolved.relative_to(resolved_root).as_posix()
56
+ except ValueError as exc:
57
+ raise FalsePositiveLedgerError(f"file_path 越界: {rel_path}") from exc
58
+ return rel_norm, resolved
59
+
60
+
61
+ def _file_sha256(path: Path) -> str | None:
62
+ if not path.is_file() or path.is_symlink():
63
+ return None
64
+ try:
65
+ return _sha256_bytes(path.read_bytes())
66
+ except OSError:
67
+ return None
68
+
69
+
70
+ def ledger_path(root: Path) -> Path:
71
+ return Path(root).resolve() / ".bugx" / "knowledge" / "fp-ledger.json"
72
+
73
+
74
+ def _atomic_write_json(path: Path, payload: Mapping[str, Any]) -> None:
75
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
76
+ raw = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
77
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
78
+ try:
79
+ os.fchmod(fd, 0o600)
80
+ with os.fdopen(fd, "wb") as handle:
81
+ handle.write(raw)
82
+ handle.flush()
83
+ os.fsync(handle.fileno())
84
+ os.replace(tmp_name, path)
85
+ except BaseException:
86
+ try:
87
+ os.close(fd)
88
+ except OSError:
89
+ pass
90
+ try:
91
+ os.unlink(tmp_name)
92
+ except OSError:
93
+ pass
94
+ raise
95
+
96
+
97
+ def load_fp_ledger(root: Path) -> dict[str, Any]:
98
+ path = ledger_path(root)
99
+ if not path.is_file():
100
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
101
+ try:
102
+ data = json.loads(path.read_text(encoding="utf-8"))
103
+ except (OSError, ValueError):
104
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
105
+ if not isinstance(data, dict) or not isinstance(data.get("entries"), list):
106
+ return {"schema_version": LEDGER_SCHEMA_VERSION, "entries": []}
107
+ return data
108
+
109
+
110
+ def record_false_positive(
111
+ root: Path,
112
+ *,
113
+ file_path: str,
114
+ rejection_class: str,
115
+ guard_evidence: str,
116
+ category: str = "",
117
+ cwe: str = "",
118
+ symbol: str = "",
119
+ fingerprint: str = "",
120
+ languages: Sequence[str] = (),
121
+ frameworks: Sequence[str] = (),
122
+ ) -> dict[str, Any]:
123
+ """Persist a source-hash-bound false-positive guard into .bugx/knowledge/fp-ledger.json."""
124
+ if rejection_class not in ALLOWED_FP_REJECTION_CLASSES:
125
+ raise FalsePositiveLedgerError(
126
+ f"不允许将 rejection_class={rejection_class!r} 写入负样本误报账本(仅允许 {sorted(ALLOWED_FP_REJECTION_CLASSES)})"
127
+ )
128
+ evidence_text = (guard_evidence or "").strip()
129
+ if not evidence_text:
130
+ raise FalsePositiveLedgerError("guard_evidence 不能为空")
131
+
132
+ rel_norm, abs_path = _confined_file(root, file_path)
133
+ src_hash = _file_sha256(abs_path)
134
+ if src_hash is None:
135
+ raise FalsePositiveLedgerError(f"目标文件不存在或不可读,拒绝写入无哈希绑定的误报记录: {rel_norm}")
136
+
137
+ dedup_key = _sha256_bytes(
138
+ f"{rel_norm}|{category.strip().lower()}|{cwe.strip().upper()}|{symbol.strip()}|{src_hash}".encode("utf-8")
139
+ )[:16]
140
+ fp_id = f"FP-{dedup_key}"
141
+ now = time.time()
142
+
143
+ data = load_fp_ledger(root)
144
+ entries: list[dict[str, Any]] = [e for e in data.get("entries", []) if isinstance(e, dict)]
145
+
146
+ existing = next((e for e in entries if e.get("fp_id") == fp_id), None)
147
+ if existing is not None:
148
+ existing["hit_count"] = int(existing.get("hit_count") or 1) + 1
149
+ existing["guard_evidence"] = evidence_text[:500]
150
+ existing["updated_at"] = now
151
+ record = existing
152
+ else:
153
+ record = {
154
+ "fp_id": fp_id,
155
+ "file_path": rel_norm,
156
+ "source_sha256": src_hash,
157
+ "category": category.strip().lower(),
158
+ "cwe": cwe.strip().upper(),
159
+ "symbol": symbol.strip(),
160
+ "fingerprint": fingerprint.strip(),
161
+ "rejection_class": rejection_class,
162
+ "guard_evidence": evidence_text[:500],
163
+ "languages": sorted({s.strip().lower() for s in languages if isinstance(s, str) and s.strip()}),
164
+ "frameworks": sorted({s.strip().lower() for s in frameworks if isinstance(s, str) and s.strip()}),
165
+ "hit_count": 1,
166
+ "created_at": now,
167
+ "updated_at": now,
168
+ }
169
+ entries.append(record)
170
+
171
+ payload = {
172
+ "schema_version": LEDGER_SCHEMA_VERSION,
173
+ "updated_at": now,
174
+ "entries": entries,
175
+ }
176
+ _atomic_write_json(ledger_path(root), payload)
177
+ return record
178
+
179
+
180
+ def match_false_positive_guards(
181
+ root: Path,
182
+ *,
183
+ file_path: str,
184
+ category: str = "",
185
+ cwe: str = "",
186
+ symbol: str = "",
187
+ include_stale: bool = False,
188
+ ) -> list[dict[str, Any]]:
189
+ """Return active (hash-verified) false-positive guards for a file; stale entries auto-invalidate."""
190
+ try:
191
+ rel_norm, abs_path = _confined_file(root, file_path)
192
+ except FalsePositiveLedgerError:
193
+ return []
194
+ current_hash = _file_sha256(abs_path)
195
+ data = load_fp_ledger(root)
196
+ cat_norm = category.strip().lower()
197
+ cwe_norm = cwe.strip().upper()
198
+ sym_norm = symbol.strip()
199
+
200
+ matched: list[dict[str, Any]] = []
201
+ for entry in data.get("entries", []):
202
+ if not isinstance(entry, dict):
203
+ continue
204
+ if entry.get("file_path") != rel_norm:
205
+ continue
206
+ if cat_norm and entry.get("category") and entry.get("category") != cat_norm:
207
+ continue
208
+ if cwe_norm and entry.get("cwe") and entry.get("cwe") != cwe_norm:
209
+ continue
210
+ if sym_norm and entry.get("symbol") and entry.get("symbol") != sym_norm:
211
+ continue
212
+
213
+ is_active = bool(current_hash and entry.get("source_sha256") == current_hash)
214
+ guard_status = "active_guard" if is_active else "stale_guard"
215
+ if not is_active and not include_stale:
216
+ continue
217
+ item = dict(entry)
218
+ item["guard_status"] = guard_status
219
+ matched.append(item)
220
+ return matched
221
+
222
+
223
+ def render_fp_guard_guidance(
224
+ guards: Sequence[Mapping[str, Any]],
225
+ *,
226
+ char_budget: int = 600,
227
+ ) -> str:
228
+ """Render compact active false-positive guard hints for Worker noise reduction."""
229
+ active = [g for g in guards if g.get("guard_status") == "active_guard"]
230
+ if not active or char_budget <= 0:
231
+ return ""
232
+ lines = ["[历史已证伪误报护栏 (Active FP Guards — 源码未变更,避免重复无效验证)]"]
233
+ used = len(lines[0]) + 1
234
+ for g in active:
235
+ block = (
236
+ f"- [{g.get('fp_id')} | {g.get('file_path')} | {g.get('rejection_class')}] "
237
+ f"{g.get('guard_evidence')}"
238
+ )
239
+ if used + len(block) + 1 > char_budget:
240
+ break
241
+ lines.append(block)
242
+ used += len(block) + 1
243
+ return "\n".join(lines) if len(lines) > 1 else ""
244
+
245
+
246
+ __all__ = [
247
+ "LEDGER_SCHEMA_VERSION",
248
+ "ALLOWED_FP_REJECTION_CLASSES",
249
+ "FalsePositiveLedgerError",
250
+ "ledger_path",
251
+ "load_fp_ledger",
252
+ "record_false_positive",
253
+ "match_false_positive_guards",
254
+ "render_fp_guard_guidance",
255
+ ]
package/core/metadata.txt CHANGED
@@ -1,4 +1,4 @@
1
- bugx_version: "0.1.1"
1
+ bugx_version: "0.1.2"
2
2
  bugx_channel: "stable"
3
3
  bugx_marker: "stable"
4
- build_id: 9
4
+ build_id: 11
@@ -1,6 +1,6 @@
1
1
  # BugX Planning & Slicing Engine (能力规划、领域路由、代码切片与仲裁流水线)
2
2
 
3
- > **版本契约**: `0.1.1` | **所属分层**: `Layer 2: 分析、切片与探测引擎`
3
+ > **版本契约**: `0.1.2` | **所属分层**: `Layer 2: 分析、切片与探测引擎`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 物理条目索引覆盖)
6
6
 
@@ -22,6 +22,7 @@ core/planning/
22
22
  ├── 2. 源码探测、切片与提示词脚手架 (Slicing & Prompt Harness)
23
23
  │ ├── source_inspector.py # 轻量级源码结构化探测与上下文精准切片提取器
24
24
  │ ├── prompt_harness.py # 动态组合审计目标、代码切片与规则的 Prompt 2.0 组装器
25
+ │ ├── prompt_policy_engine.py # 声明式可配置提示词策略引擎(按模型路由、风控动态降级、代码块保护)
25
26
  │ ├── dynamic_flow_analyzer.py # 跨函数污点传递与动态数据流追踪器
26
27
  │ └── impact_pruner.py # 结合 Git Diff 与依赖图的精准剪枝引擎
27
28
  │
@@ -123,6 +123,7 @@ _STAGE_MAP = {
123
123
  "l0": "l0_router.md",
124
124
  "gate": "stages/stage_gate.md",
125
125
  "explore": "stages/stage_explore.md",
126
+ "verify": "stages/stage_verify.md",
126
127
  "mutate": "stages/stage_mutate.md",
127
128
  "repair": "stages/stage_repair.md",
128
129
  }
@@ -520,7 +521,11 @@ def load_stage(stage: str, root: Path | None = None) -> str:
520
521
  prompts_dir = get_prompts_dir(root)
521
522
  file_path = prompts_dir / _STAGE_MAP[key]
522
523
  if not file_path.is_file():
523
- raise FileNotFoundError(f"阶段提示词文件缺失: {file_path}")
524
+ local_fallback = Path(__file__).resolve().parents[1] / "prompts" / _STAGE_MAP[key]
525
+ if local_fallback.is_file():
526
+ file_path = local_fallback
527
+ else:
528
+ raise FileNotFoundError(f"阶段提示词文件缺失: {file_path}")
524
529
  content = file_path.read_text(encoding="utf-8").strip()
525
530
  # P1:附加 bugx.md 权威章节指针,消除"阶段卡 vs 全文"双源竞争。
526
531
  content += _stage_section_pointers(key, root)
@@ -558,15 +563,46 @@ def get_stage_prompt(
558
563
  context: Mapping[str, object] | None = None,
559
564
  root: Path | None = None,
560
565
  locale: str | None = None,
566
+ *,
567
+ host: str | None = None,
568
+ provider: str | None = None,
569
+ model: str | None = None,
570
+ policy: str | None = None,
571
+ last_error: str | None = None,
561
572
  ) -> str:
562
- """组装阶段提示词,注入动态上下文事实 (DOC-043, DOC-067, DOC-139)。"""
573
+ """组装阶段提示词,注入动态上下文事实,并按可配置策略引擎适配模型风控边界 (DOC-043, DOC-067, DOC-139)。"""
574
+ from core.planning import prompt_policy_engine
575
+
563
576
  key = stage.strip().lower()
564
- base_prompt = load_stage(key, root=root)
577
+ resolved_policy = prompt_policy_engine.resolve_policy(
578
+ host=host,
579
+ provider=provider,
580
+ model=model,
581
+ last_error=last_error,
582
+ explicit_policy=policy,
583
+ root=root,
584
+ )
585
+ override_rel = prompt_policy_engine.resolve_stage_override_relpath(resolved_policy, key)
586
+ if override_rel:
587
+ override_path = prompt_policy_engine.PROMPTS_ROOT / override_rel
588
+ if override_path.is_file():
589
+ base_prompt = override_path.read_text(encoding="utf-8")
590
+ else:
591
+ base_prompt = load_stage(key, root=root)
592
+ else:
593
+ base_prompt = load_stage(key, root=root)
594
+
595
+ def _finalize(rendered: str) -> str:
596
+ return prompt_policy_engine.apply_policy(
597
+ rendered,
598
+ resolved_policy,
599
+ include_preamble=True,
600
+ include_safe_repro=(key in {"verify", "mutate"}),
601
+ )
602
+
565
603
  if not context:
566
604
  # L0 是常驻入口,也必须经过和其他注入段相同的硬预算出口。
567
- if key == "l0":
568
- return base_prompt
569
- return base_prompt
605
+ return _finalize(base_prompt)
570
606
 
571
607
  title = "## 动态运行时事实(Dynamic Context)"
572
608
  if i18n is not None:
@@ -604,11 +640,15 @@ def get_stage_prompt(
604
640
  "dynamic_context": "Dynamic Context 事实注入",
605
641
  },
606
642
  )
607
- return sections["l0_router"] + sections["dynamic_context"] + _record_budget_degradations(
608
- context_degradations + degradations, stage="l0",
643
+ return _finalize(
644
+ sections["l0_router"] + sections["dynamic_context"] + _record_budget_degradations(
645
+ context_degradations + degradations, stage="l0",
646
+ )
647
+ )
648
+ return _finalize(
649
+ base_prompt + context_text + _record_budget_degradations(
650
+ context_degradations, stage=key,
609
651
  )
610
- return base_prompt + context_text + _record_budget_degradations(
611
- context_degradations, stage=key,
612
652
  )
613
653
 
614
654