bugx-cli 0.1.0 → 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 (338) hide show
  1. package/README.md +193 -185
  2. package/core/README.md +2 -2
  3. package/core/agent/README.md +2 -1
  4. package/core/agent/agent_artifacts.py +8 -6
  5. package/core/agent/agent_eval.py +136 -54
  6. package/core/agent/agent_execution.py +218 -52
  7. package/core/agent/agent_orchestrator.py +14 -8
  8. package/core/agent/agent_targets.py +8 -2
  9. package/core/agent/feature_baseline.py +150 -0
  10. package/core/assets/README.md +3 -2
  11. package/core/assets/axe-core/LICENSE-3RD-PARTY.txt +66 -0
  12. package/core/assets/axe-core/LICENSE.txt +362 -0
  13. package/core/assets/axe-core/UPSTREAM.md +10 -0
  14. package/core/assets/axe-core/axe.min.js +12 -0
  15. package/core/assets/bugx-hero-en.svg +74 -0
  16. package/core/assets/bugx-hero-zh.svg +74 -0
  17. package/core/assets/bugx-social-preview.svg +71 -0
  18. package/core/assets/bugx-wechat-group.png +0 -0
  19. package/core/assets/codex.png +0 -0
  20. package/core/assets/dsh.png +0 -0
  21. package/core/assets/webui-chatgpt.jpg +0 -0
  22. package/core/assets/webui-session.jpg +0 -0
  23. package/core/assets/webui-skills.jpg +0 -0
  24. package/core/assets/webui-studio.jpg +0 -0
  25. package/core/assets/webui-zcode.jpg +0 -0
  26. package/core/assets/zcode.png +0 -0
  27. package/core/audit_packs/README.md +2 -0
  28. package/core/audit_packs/pitfalls/auth_crypto.json +64 -0
  29. package/core/audit_packs/pitfalls/file_ssrf_cmd.json +64 -0
  30. package/core/audit_packs/pitfalls/go_backend.json +66 -0
  31. package/core/audit_packs/pitfalls/java_spring.json +64 -0
  32. package/core/audit_packs/pitfalls/js_ts_web.json +67 -0
  33. package/core/audit_packs/pitfalls/python_web.json +82 -0
  34. package/core/autonomous_cve/SPEC.md +1 -1
  35. package/core/autonomous_cve/attack_graph_store.py +152 -106
  36. package/core/autonomous_cve/behavior_graph.py +8 -2
  37. package/core/autonomous_cve/verifier.py +4 -1
  38. package/core/bugx.md +1 -1
  39. package/core/bugx_paths.py +43 -8
  40. package/core/cli-help.txt +66 -0
  41. package/core/cloud_sync/SPEC.md +1 -1
  42. package/core/cloud_sync/cloud_client.py +81 -11
  43. package/core/cloud_sync/cloud_onboard.py +42 -1
  44. package/core/cloud_sync/consent.py +33 -3
  45. package/core/cloud_sync/flywheel_client.py +186 -15
  46. package/core/cloud_sync/network_transport.py +24 -3
  47. package/core/cloud_sync/sensitive_filter.py +2 -2
  48. package/core/cloud_sync/sync_push.py +12 -10
  49. package/core/contracts/AGENT_GUIDE.md +6 -9
  50. package/core/contracts/README.md +2 -2
  51. package/core/contracts/bugx-runtime-contract.md +1 -1
  52. package/core/contracts/bugx-worker.md +1 -1
  53. package/core/contracts/engine_gap_contracts.py +86 -3
  54. package/core/coverage/coverage_discovery.py +599 -29
  55. package/core/coverage/coverage_evidence.py +47 -0
  56. package/core/coverage/coverage_forensics.py +9 -0
  57. package/core/coverage/coverage_validate.py +6 -1
  58. package/core/dev_harness/SPEC.md +1 -1
  59. package/core/engine-integrity.json +670 -442
  60. package/core/fuzzing/concurrency_fuzzer.py +53 -0
  61. package/core/fuzzing/differential_oracle.py +562 -27
  62. package/core/fuzzing/fuzz_input.py +109 -6
  63. package/core/fuzzing/stateful_fuzzer.py +72 -0
  64. package/core/governance/secret_redactor.py +22 -10
  65. package/core/host_acp/SPEC.md +1 -1
  66. package/core/host_acp/__init__.py +4 -4
  67. package/core/host_acp/claude.py +59 -1
  68. package/core/host_acp/cline.py +64 -1
  69. package/core/host_acp/codex.py +56 -1
  70. package/core/host_acp/dsh.py +59 -1
  71. package/core/host_acp/opencode.py +56 -1
  72. package/core/host_acp/pi.py +59 -1
  73. package/core/host_acp/zcode.py +59 -1
  74. package/core/host_runtime/SPEC.md +1 -1
  75. package/core/host_runtime/adapters.py +1 -1
  76. package/core/host_runtime/cline.py +13 -0
  77. package/core/host_runtime/host_evaluators.py +44 -4
  78. package/core/host_runtime/host_probe.py +1 -1
  79. package/core/host_runtime/host_provider_arbitrator.py +116 -62
  80. package/core/host_runtime/host_registry.py +15 -8
  81. package/core/host_runtime/mcp_registry_gate.py +12 -1
  82. package/core/host_runtime/pi.py +102 -0
  83. package/core/host_runtime/provider_facts.py +66 -0
  84. package/core/hosts/SPEC.md +1 -1
  85. package/core/hosts/__init__.py +6 -2
  86. package/core/hosts/_dsh_usage.py +1 -1
  87. package/core/hosts/base.py +32 -4
  88. package/core/hosts/claude.py +55 -0
  89. package/core/hosts/cline.py +6 -2
  90. package/core/hosts/codex.py +58 -0
  91. package/core/hosts/dsh.py +9 -1
  92. package/core/hosts/opencode.py +6 -6
  93. package/core/hosts/pi.py +159 -2
  94. package/core/infra/README.md +4 -2
  95. package/core/infra/__init__.py +2 -0
  96. package/core/infra/build_info.py +22 -3
  97. package/core/infra/client_metadata.py +1 -1
  98. package/core/infra/json_utils.py +22 -0
  99. package/core/launch_phases/README.md +6 -3
  100. package/core/launch_phases/SPEC.md +1 -1
  101. package/core/launch_phases/common.py +21 -2
  102. package/core/launch_phases/finding_confirm_phase.py +170 -5
  103. package/core/launch_phases/finding_settlement.py +188 -1
  104. package/core/launch_phases/judge_phase.py +69 -12
  105. package/core/launch_phases/orchestrator_controls.py +11 -7
  106. package/core/launch_phases/post_coverage_sync.py +9 -2
  107. package/core/launch_phases/post_phase.py +144 -8
  108. package/core/launch_phases/post_receipt.py +12 -1
  109. package/core/launch_phases/pre_phase.py +3 -3
  110. package/core/launch_phases/pre_recon_scout.py +66 -36
  111. package/core/launch_phases/pre_state_builder.py +23 -176
  112. package/core/launch_phases/report_sharing.py +3 -7
  113. package/core/launch_phases/round_orchestrator.py +129 -58
  114. package/core/launch_phases/semantic_recon.py +545 -0
  115. package/core/launch_phases/session_runtime.py +56 -9
  116. package/core/launch_phases/startup_gates.py +36 -8
  117. package/core/launch_phases/startup_interaction.py +68 -12
  118. package/core/launch_phases/startup_version_gate.py +13 -3
  119. package/core/launch_phases/supervisor_bridge.py +46 -17
  120. package/core/launch_phases/supervisor_coverage.py +8 -2
  121. package/core/launch_phases/supervisor_degraded.py +1 -9
  122. package/core/launch_phases/verify_loop.py +767 -0
  123. package/core/launch_phases/worker_barriers.py +15 -5
  124. package/core/launch_phases/worker_orchestrator.py +105 -25
  125. package/core/launch_phases/worker_prior.py +115 -0
  126. package/core/ledger/README.md +2 -1
  127. package/core/ledger/SPEC.md +1 -1
  128. package/core/ledger/_facade.py +2 -1
  129. package/core/ledger/archive_ops.py +60 -2
  130. package/core/ledger/cli.py +6 -1
  131. package/core/ledger/export_ops.py +6 -1
  132. package/core/ledger/finding_confirmation.py +48 -6
  133. package/core/ledger/finding_lifecycle.py +428 -5
  134. package/core/ledger/finding_verification.py +555 -10
  135. package/core/ledger/fp_ledger.py +255 -0
  136. package/core/ledger/incidents.py +10 -4
  137. package/core/ledger/patterns.py +10 -7
  138. package/core/ledger/receipt_contract.py +17 -1
  139. package/core/ledger/sync_ops.py +21 -16
  140. package/core/ledger/tool_experience.py +2 -1
  141. package/core/ledger/verify_life.py +88 -17
  142. package/core/locales/en-US.json +2 -2
  143. package/core/locales/zh-CN.json +2 -2
  144. package/core/mcp_handlers/SPEC.md +1 -1
  145. package/core/mcp_handlers/base.py +23 -3
  146. package/core/mcp_handlers/channel_lifecycle.py +85 -30
  147. package/core/mcp_handlers/retrieval_handlers.py +11 -1
  148. package/core/mcp_handlers/rpc_server.py +6 -1
  149. package/core/mcp_handlers/supervisor_handlers.py +32 -6
  150. package/core/mcp_handlers/tool_table.py +15 -0
  151. package/core/mcp_runtime_support/environment.py +0 -38
  152. package/core/mcp_runtime_support/verifier.py +0 -52
  153. package/core/metadata.txt +2 -3
  154. package/core/planning/README.md +2 -1
  155. package/core/planning/domain_router.py +4 -2
  156. package/core/planning/dynamic_flow_analyzer.py +219 -14
  157. package/core/planning/judge_pipeline.py +87 -4
  158. package/core/planning/prompt_harness.py +57 -15
  159. package/core/planning/prompt_policy_engine.py +386 -0
  160. package/core/planning/spec_harvester.py +4 -4
  161. package/core/probes/INTERFACE.md +11 -1
  162. package/core/probes/SPEC.md +11 -1
  163. package/core/probes/__init__.py +46 -40
  164. package/core/probes/android_probe.py +177 -9
  165. package/core/probes/codebase_memory_probe.py +57 -0
  166. package/core/probes/desktop_probe.py +104 -0
  167. package/core/probes/differential_probe.py +99 -21
  168. package/core/probes/efficiency_probe.py +64 -0
  169. package/core/probes/ios_binary_probe.py +105 -1
  170. package/core/probes/memory_probe.py +66 -0
  171. package/core/probes/miniprogram_probe.py +75 -13
  172. package/core/probes/mobile_probe.py +215 -30
  173. package/core/probes/native_probe.py +88 -0
  174. package/core/probes/openwiki_probe.py +70 -0
  175. package/core/probes/pattern_probe.py +106 -0
  176. package/core/probes/platform_probe.py +81 -0
  177. package/core/probes/probe_registry.py +108 -7
  178. package/core/probes/sast_fixture_corpus.py +340 -0
  179. package/core/probes/sast_probe.py +553 -52
  180. package/core/probes/sast_rules.py +668 -28
  181. package/core/probes/sca_scanner.py +48 -0
  182. package/core/probes/ui_accessibility.py +149 -0
  183. package/core/probes/ui_audit.py +513 -0
  184. package/core/probes/ui_contract.py +273 -0
  185. package/core/probes/ui_evidence.py +212 -0
  186. package/core/probes/ui_measurements.py +314 -0
  187. package/core/probes/ui_repair.py +250 -0
  188. package/core/probes/ui_review.py +133 -0
  189. package/core/probes/ui_storybook.py +107 -0
  190. package/core/probes/ui_tokens.py +185 -0
  191. package/core/probes/ui_visual_diff.py +131 -0
  192. package/core/probes/web_probe.py +373 -18
  193. package/core/project_profiler/SPEC.md +1 -1
  194. package/core/project_profiler/arbitrator.py +6 -1
  195. package/core/project_profiler/detector.py +8 -1
  196. package/core/project_profiler/strategy.py +51 -15
  197. package/core/prompts/README.md +4 -2
  198. package/core/prompts/command_routing_en.md +2 -2
  199. package/core/prompts/command_routing_zh.md +2 -2
  200. package/core/prompts/policies/prompt_policies.json +101 -0
  201. package/core/prompts/stages/stage_repair.md +1 -1
  202. package/core/prompts/stages/stage_verify.defensive.md +42 -0
  203. package/core/prompts/stages/stage_verify.md +44 -0
  204. package/core/repair/README.md +1 -1
  205. package/core/repair/l7_repair_loop.py +1 -4
  206. package/core/repair/rsi_fixer.py +4 -4
  207. package/core/repair/rsi_loop.py +1 -3
  208. package/core/repair/rsi_repair.py +7 -7
  209. package/core/repair/rsi_scope.py +27 -8
  210. package/core/report_engine/SPEC.md +1 -1
  211. package/core/report_engine/attestation.py +8 -4
  212. package/core/report_engine/finding_report.py +2 -1
  213. package/core/report_engine/models.py +7 -9
  214. package/core/report_engine/report_share.py +0 -8
  215. package/core/report_engine/sast_bridge.py +2 -2
  216. package/core/report_engine/server.py +18 -8
  217. package/core/report_engine/web-conformance.md +123 -18
  218. package/core/report_engine/web_conformance.py +21 -52
  219. package/core/retrieval/README.md +2 -1
  220. package/core/retrieval/SPEC.md +1 -1
  221. package/core/retrieval/code_analyzer.py +50 -14
  222. package/core/retrieval/context_assembler.py +7 -1
  223. package/core/retrieval/knowledge_sync.py +108 -14
  224. package/core/retrieval/pitfall_packs.py +277 -0
  225. package/core/retrieval/symbol_index.py +25 -6
  226. package/core/retrieval/universal_code_matcher.py +234 -49
  227. package/core/runtime/README.md +1 -1
  228. package/core/runtime/bugx_logging.py +78 -7
  229. package/core/runtime/fixture_solidify.py +5 -10
  230. package/core/runtime/global_telemetry.py +20 -0
  231. package/core/runtime/incident_eval.py +1 -1
  232. package/core/runtime/model_runner.py +4 -41
  233. package/core/runtime/platform_adapter.py +2 -2
  234. package/core/runtime/prep_validate.py +4 -2
  235. package/core/runtime/project_settings.py +2 -1
  236. package/core/runtime/scenario_eval.py +50 -8
  237. package/core/skills/bugx_docs_mcp_server.py +3 -1
  238. package/core/skills/bugx_mcp_server.py +29 -2
  239. package/core/skills/tools_kb.py +1 -1
  240. package/core/supervisor/README.md +1 -1
  241. package/core/supervisor/SPEC.md +1 -1
  242. package/core/supervisor/budget_governor.py +503 -9
  243. package/core/supervisor/checkpoint_pipeline.py +248 -6
  244. package/core/supervisor/checkpoint_sync.py +13 -0
  245. package/core/supervisor/claim_events.py +1 -1
  246. package/core/supervisor/finding_workflow.py +22 -5
  247. package/core/supervisor/lease_manager.py +1 -1
  248. package/core/supervisor/lifecycle_blocks.py +6 -1
  249. package/core/supervisor/rejection_remedies.py +52 -5
  250. package/core/supervisor/serial_authorization.py +48 -4
  251. package/core/supervisor/task_scheduler.py +2 -2
  252. package/core/supervisor/worker_checkpoint.py +8 -1
  253. package/core/supervisor/worker_runtime.py +8 -2
  254. package/core/supervisor_types/worker_claim.py +9 -0
  255. package/core/webui/README.md +1 -1
  256. package/core/webui/SPEC.md +2 -1
  257. package/core/webui/adapters/claude.py +5 -1
  258. package/core/webui/adapters/cline.py +10 -2
  259. package/core/webui/adapters/codex.py +5 -1
  260. package/core/webui/adapters/dsh.py +5 -1
  261. package/core/webui/docs_session_service.py +2 -2
  262. package/core/webui/mcp_inspector.py +11 -7
  263. package/core/webui/static/00-base.css +1060 -0
  264. package/core/webui/static/01-monitoring.css +802 -0
  265. package/core/webui/static/02-header-actions.css +321 -0
  266. package/core/webui/static/03-trigger-popover.css +697 -0
  267. package/core/webui/static/04-composer.css +628 -0
  268. package/core/webui/static/05-skills-center.css +878 -0
  269. package/core/webui/static/06-mcp-center.css +623 -0
  270. package/core/webui/static/07-skill-detail.css +265 -0
  271. package/core/webui/static/08-files-management.css +167 -0
  272. package/core/webui/static/09-files-center.css +386 -0
  273. package/core/webui/static/10-icons.css +105 -0
  274. package/core/webui/static/11-project-options.css +185 -0
  275. package/core/webui/static/12-profile-tab.css +383 -0
  276. package/core/webui/static/design-tokens.css +113 -0
  277. package/core/webui/static/index.html +14 -1
  278. package/core/webui/workspace_service.py +1 -1
  279. package/docs/07_distribution/01_README_NPM.md +193 -185
  280. package/ecosystem/integrations/README.md +1 -1
  281. package/ecosystem/integrations/dsh/mcp/package.json +1 -1
  282. package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
  283. package/ecosystem/integrations/dsh/ui/package.json +1 -1
  284. package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +4 -4
  285. package/ecosystem/integrations/opencode/mcp-lock.json +14 -6
  286. package/ecosystem/integrations/opencode/opencode.json +23 -12
  287. package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
  288. package/ecosystem/integrations/qoder/connector-meta.json +1 -1
  289. package/ecosystem/integrations/workbuddy/connector-meta.json +1 -1
  290. package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +1 -1
  291. package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +1 -1
  292. package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +1 -1
  293. package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +1 -1
  294. package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +2 -2
  295. package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
  296. package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
  297. package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +1 -1
  298. package/interfaces/bin/bugx.js +37 -0
  299. package/interfaces/cli/bugx_cli/__init__.py +4 -2
  300. package/interfaces/cli/bugx_cli/cli.py +172 -69
  301. package/interfaces/cli/bugx_cli/commands/advisory.py +1 -1
  302. package/interfaces/cli/bugx_cli/commands/agent.py +461 -134
  303. package/interfaces/cli/bugx_cli/commands/audit.py +10 -9
  304. package/interfaces/cli/bugx_cli/commands/autonomous.py +1 -1
  305. package/interfaces/cli/bugx_cli/commands/cloud.py +31 -22
  306. package/interfaces/cli/bugx_cli/commands/doctor.py +449 -204
  307. package/interfaces/cli/bugx_cli/commands/interaction.py +5 -1
  308. package/interfaces/cli/bugx_cli/commands/knowledge.py +5 -4
  309. package/interfaces/cli/bugx_cli/commands/lifecycle.py +3 -3
  310. package/interfaces/cli/bugx_cli/commands/plugin.py +58 -23
  311. package/interfaces/cli/bugx_cli/commands/plugin_claude.py +7 -7
  312. package/interfaces/cli/bugx_cli/commands/plugin_funide.py +2 -1
  313. package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +1 -1
  314. package/interfaces/cli/bugx_cli/commands/project.py +6 -13
  315. package/interfaces/cli/bugx_cli/commands/report.py +2 -6
  316. package/interfaces/cli/bugx_cli/commands/system.py +524 -169
  317. package/interfaces/cli/bugx_cli/common.py +21 -15
  318. package/interfaces/cli/bugx_cli/host_adapters.py +29 -54
  319. package/interfaces/cli/bugx_cli/hosts/registry.py +8 -6
  320. package/interfaces/cli/bugx_cli/infra/ai_advisor.py +157 -27
  321. package/interfaces/cli/bugx_cli/infra/engine_installer.py +35 -16
  322. package/interfaces/cli/bugx_cli/infra/host_sync.py +11 -8
  323. package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +76 -5
  324. package/interfaces/cli/bugx_cli/infra/security.py +13 -6
  325. package/package.json +30 -15
  326. package/pyproject.toml +60 -9
  327. package/scripts/ensure-python.mjs +7 -7
  328. package/scripts/sync-version.mjs +10 -21
  329. package/scripts/test-npm-wrapper.mjs +1 -1
  330. package/core/assets/bugx-hero-cn.png +0 -0
  331. package/core/assets/bugx-hero-en.png +0 -0
  332. package/core/webui/static/project-settings.css +0 -6458
  333. package/docs/07_distribution/README.md +0 -16
  334. package/docs/README.md +0 -121
  335. package/interfaces/README.md +0 -143
  336. package/interfaces/bin/README.md +0 -35
  337. package/interfaces/cli/README.md +0 -90
  338. package/scripts/README.md +0 -118
@@ -278,6 +278,19 @@ class CloudClient:
278
278
  key = self.cred.api_key or self.cred.token
279
279
  return f"Bearer {key}" if key else None
280
280
 
281
+ @staticmethod
282
+ def _unauthenticated(method: str, path: str) -> ReportResult:
283
+ """Fail closed before egress when no account credential exists."""
284
+ message = (
285
+ f"unauthenticated: {method} {path} 必须携带账号 Bearer token;"
286
+ "project_key 只是幂等标识,不是鉴权凭据"
287
+ )
288
+ return ReportResult(
289
+ ok=False, status=401,
290
+ data={"code": "SYNC_UNAUTHENTICATED", "message": message},
291
+ error=message,
292
+ )
293
+
281
294
  def _mark_auth_expired(self) -> None:
282
295
  """Keep a server-confirmed 401 visible to the next CLI process."""
283
296
  self.cred.auth_state_override = "expired"
@@ -323,8 +336,12 @@ class CloudClient:
323
336
  if expires_in is not None and expires_in <= 2 * 86400:
324
337
  self._refresh()
325
338
  header = self._auth_header()
326
- if header:
327
- headers["Authorization"] = header
339
+ if header is None:
340
+ # F-RSI-20261115-145:账号 Bearer token 是云端操作唯一的鉴权凭据,
341
+ # project_key 只是同账号内的幂等标识。缺失账号凭据时不得发出任何
342
+ # 请求(此前会静默省略 Authorization,仅凭 body 里的 project_key 出网)。
343
+ return self._unauthenticated(method, path)
344
+ headers["Authorization"] = header
328
345
  body = None
329
346
  if payload is not None:
330
347
  # V2-only:pull 一律 query 参数(DOC-008 §5.2),GET 禁止携带 body。
@@ -445,8 +462,10 @@ class CloudClient:
445
462
  headers = {"Accept": "application/json", **client_headers(),
446
463
  "Content-Type": content_type, "Content-Length": str(len(body))}
447
464
  auth = self._auth_header()
448
- if auth:
449
- headers["Authorization"] = auth
465
+ if auth is None:
466
+ # 同 _request:补丁包上传同样必须带账号凭据,缺失即零 egress 拒绝。
467
+ return self._unauthenticated(method, path)
468
+ headers["Authorization"] = auth
450
469
  req = urllib.request.Request(url, data=body, headers=headers, method=method)
451
470
  try:
452
471
  resp = self._open_request(req)
@@ -757,7 +776,7 @@ class CloudClient:
757
776
  operation_id: str | None = None,
758
777
  base_version: int | None = None,
759
778
  device_id: str | None = None,
760
- sensitive_policy: str = "allow") -> ReportResult:
779
+ sensitive_policy: str = "redact") -> ReportResult:
761
780
  """V2 push:完整 envelope(records 四数组恒在,无 legacy 顶层字段)。
762
781
 
763
782
  DOC-211:sensitive_policy=allow 跳过出网敏感扫描(策略应用已在构建侧
@@ -818,7 +837,7 @@ class CloudClient:
818
837
  return self._request("POST", self.scope_path(scope, project_id), container)
819
838
 
820
839
  def import_knowledge_bundle(self, bundle: dict[str, Any], *, mode: str = "merge",
821
- sensitive_policy: str = "allow") -> ReportResult:
840
+ sensitive_policy: str = "redact") -> ReportResult:
822
841
  """Import one validated V2 JSON bundle through the explicit import API.
823
842
 
824
843
  DOC-211:upload 与 sync 同吃一档策略——block 补凭据形状扫描(堵旧
@@ -1064,7 +1083,15 @@ class CloudClient:
1064
1083
 
1065
1084
  # ---- 版本检查与 CLI 包下载(Phase 2 自动更新)----
1066
1085
 
1067
- def check_version(self, current_version: str = "", channel: str = "") -> ReportResult:
1086
+ def check_version(
1087
+ self,
1088
+ current_version: str = "",
1089
+ channel: str = "",
1090
+ *,
1091
+ client_kind: str = "pip",
1092
+ artifact_kind: str = "python-wheel",
1093
+ release_id: str = "",
1094
+ ) -> ReportResult:
1068
1095
  """GET /api/v1/agent/version — 查询最新版本元数据。
1069
1096
 
1070
1097
  当传入 current_version 时,服务端额外返回 update_available 和
@@ -1076,6 +1103,12 @@ class CloudClient:
1076
1103
  params["current"] = current_version
1077
1104
  if channel and channel.strip():
1078
1105
  params["channel"] = channel.strip()
1106
+ if client_kind and client_kind.strip():
1107
+ params["client_kind"] = client_kind.strip()
1108
+ if artifact_kind and artifact_kind.strip():
1109
+ params["artifact_kind"] = artifact_kind.strip()
1110
+ if release_id and release_id.strip():
1111
+ params["release_id"] = release_id.strip()
1079
1112
  return self._request("GET", VERSION_CHECK_PATH, None,
1080
1113
  auth=False, retry_auth=False, params=params or None)
1081
1114
 
@@ -1094,8 +1127,16 @@ class CloudClient:
1094
1127
  return host in {"127.0.0.1", "::1", "localhost"}
1095
1128
  return False
1096
1129
 
1097
- def download_package(self, dest: Path, *, expected_sha256: str = "",
1098
- expected_version: str = "") -> tuple[bool, str]:
1130
+ def download_package(
1131
+ self,
1132
+ dest: Path,
1133
+ *,
1134
+ expected_sha256: str = "",
1135
+ expected_version: str = "",
1136
+ release_id: str = "",
1137
+ channel: str = "",
1138
+ artifact_kind: str = "python-wheel",
1139
+ ) -> tuple[bool, str]:
1099
1140
  """GET /api/v1/agent/download — 下载 CLI 包到指定路径。
1100
1141
 
1101
1142
  返回 (success, message)。下载后做 SHA-256 校验(必须提供)。
@@ -1105,7 +1146,7 @@ class CloudClient:
1105
1146
 
1106
1147
  dest: 目标文件路径(含文件名)。
1107
1148
  expected_sha256: 下载后校验哈希(必填,缺失即拒绝下载)。
1108
- expected_version: 仅用于日志/提示,不影响逻辑。
1149
+ release_id/channel/artifact_kind: 锁定服务端返回的具体制品。
1109
1150
  """
1110
1151
  expected_sha256 = str(expected_sha256 or "").strip().lower()
1111
1152
  if not expected_sha256:
@@ -1113,10 +1154,23 @@ class CloudClient:
1113
1154
  if not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
1114
1155
  return False, "下载失败: expected_sha256 必须是 64 位 SHA-256 hex"
1115
1156
 
1157
+ params: dict[str, str] = {}
1158
+ if channel and channel.strip():
1159
+ params["channel"] = channel.strip()
1160
+ if artifact_kind and artifact_kind.strip():
1161
+ params["artifact_kind"] = artifact_kind.strip()
1162
+ if release_id and release_id.strip():
1163
+ params["release_id"] = release_id.strip()
1116
1164
  url = self.base + DOWNLOAD_PATH
1165
+ if params:
1166
+ url += "?" + urllib.parse.urlencode(params)
1117
1167
  # 跟随重定向(版本检查端点可能配置了外部 PyPI 镜像地址)
1118
1168
  opener = _build_redirect_opener(self.base)
1119
- headers = {"Accept": "application/octet-stream", **client_headers()}
1169
+ headers = {
1170
+ "Accept": "application/octet-stream",
1171
+ "X-BugX-Artifact-Kind": artifact_kind,
1172
+ **client_headers(),
1173
+ }
1120
1174
  req = urllib.request.Request(url, headers=headers)
1121
1175
  try:
1122
1176
  resp = opener.open(req, timeout=self.timeout)
@@ -1132,6 +1186,22 @@ class CloudClient:
1132
1186
  f"下载失败: 最终 URL 非 HTTPS,拒绝下载: {final_url}"
1133
1187
  )
1134
1188
  headers = getattr(resp, "headers", None)
1189
+ if headers is not None:
1190
+ remote_release_id = str(headers.get("X-BugX-Release-ID") or "").strip()
1191
+ remote_version = str(headers.get("X-BugX-Version") or "").strip()
1192
+ remote_checksum = str(headers.get("X-Checksum-SHA256") or "").strip().lower()
1193
+ if remote_release_id and release_id and remote_release_id != release_id:
1194
+ return False, (
1195
+ "下载失败: 服务端 release_id 与版本检查结果不一致"
1196
+ )
1197
+ if remote_version and expected_version and remote_version != expected_version:
1198
+ return False, (
1199
+ "下载失败: 服务端版本与版本检查结果不一致"
1200
+ )
1201
+ if remote_checksum and remote_checksum != expected_sha256:
1202
+ return False, (
1203
+ "下载失败: 服务端响应校验值与版本元数据不一致"
1204
+ )
1135
1205
  content_length = None
1136
1206
  if headers is not None:
1137
1207
  raw_length = headers.get("Content-Length")
@@ -10,6 +10,15 @@
10
10
  tombstone/冲突过滤 → Supervisor 原子导入 → 「inbox imported + cursor 推进」
11
11
  原子提交 → quarantine 落地仅作诊断。
12
12
 
13
+ 威胁模型边界(F-RSI-20261115-145 实测证实):
14
+ - ``project_key`` 是公开可推断的标识符(sha256(origin URL + root commit)),
15
+ **不是秘密**;任何能读取该仓库的人均可重算同一 key。
16
+ - ``project_key`` 在客户端只承担**幂等标识**(同一账号内 upsert 去重),不是
17
+ 鉴权凭据:账号 Bearer token 是唯一授权依据,缺失即由 ``CloudClient._request``
18
+ 与 ``sync_layers`` 的 F2 闸门 fail-closed 拒绝,零 egress、零本地身份写入。
19
+ - 服务端必须按账号隔离 project_key 并在 upsert 前校验项目归属——该防线是外部
20
+ 契约,本仓只有客户端实现,不得以「防线在服务端」为由证伪客户端可推断风险。
21
+
13
22
  不变量:显式 quarantine 导入只能为 candidate;私有多设备同步按远端治理状态恢复
14
23
  active/candidate;committed cursor 只随成功导入推进;
15
24
  任一页失败时 Ledger、旧 snapshot 与 committed cursor 均不变化(AD-008-02/03)。
@@ -205,6 +214,25 @@ def derive_project_key(root: Path) -> str:
205
214
  任何设备首次运行时得到同一 ``project_key``,服务端解析到既有项目而
206
215
  不是新建一个重复项。已存在的 binding/committed 身份始终优先,绝不
207
216
  因本函数而改写既有项目。
217
+
218
+ 威胁模型边界(F-RSI-20261115-145,探针实测 CONFIRMED):
219
+ - ``project_key`` 是**幂等标识符,不是鉴权凭据**:sha256(origin URL
220
+ + root commit) 的两个输入对任何能读取该仓库的人(含克隆者)完全可见,
221
+ 可完整重算同一 key(探针验证:公开输入重算与实际派生逐字节一致);
222
+ 已提交的 ``.bugx-project.json``(0o644)本身也随仓库公开。该 key 只用于
223
+ 同一账号内的 upsert 去重,禁止把它当作授权依据或访问控制手段。
224
+ - 鉴权边界在传输与账号层:所有云端 upsert/pull/push 必须携带账号
225
+ Bearer token,缺失即由 ``CloudClient._request``/``_request_raw`` 与
226
+ ``sync_layers`` 的 F2 闸门 fail-closed 拒绝(零 egress、零本地身份写入),
227
+ 不存在「仅凭 project_key 即可操作」的客户端路径。
228
+ - 提高熵源不可行:机器本地随机盐会破坏跨设备确定性(本函数存在的唯一
229
+ 目的),且 committed 身份文件本来随仓库公开——可推断性是共享仓库
230
+ 项目身份的固有属性,不是可修复缺陷。
231
+ - 服务端归属校验是**必需的外部契约**(本仓无服务端实现,无法自证):
232
+ 服务端必须按账号隔离 ``project_key``,并在 upsert 前校验请求者对该
233
+ 项目的归属;缺失该校验时,可推断 key 允许任何克隆者以自身 token
234
+ 覆盖/冒用同账号可见的项目身份数据。禁止以「防线在服务端」为由将
235
+ 此风险标记为已证伪——部署/交付侧必须显式确认服务端已实现。
208
236
  """
209
237
  identity = _git_repo_identity(root)
210
238
  if identity:
@@ -562,6 +590,19 @@ def sync_layers(client, root: Path, project_slug: str | None = None,
562
590
  from core.cloud_sync.consent import revoked_summary, sharing_revoked
563
591
  if sharing_revoked():
564
592
  return revoked_summary(scopes)
593
+ # F2 硬闸门(F-RSI-20261115-145):账号 Bearer token 是唯一的鉴权凭据。
594
+ # project_key 由公开的 origin URL + 首 commit 确定性派生,任何克隆者都能重算,
595
+ # 它只是同账号内的幂等标识;缺失账号凭据时不得写本地身份,也不得发出任何请求。
596
+ cred = getattr(client, "cred", None)
597
+ if cred is None or not cred.is_authenticated():
598
+ return {
599
+ "ok": False,
600
+ "error": ("unauthenticated: 云端同步必须携带账号 Bearer token;"
601
+ "project_key 只是幂等标识,不是鉴权凭据"),
602
+ "code": "SYNC_UNAUTHENTICATED",
603
+ "skipped": "unauthenticated",
604
+ "scopes": sorted(scopes or {"global", "project"}),
605
+ }
565
606
  from core.cloud_sync.onboard_wizard import (
566
607
  ask_project_identity_decision,
567
608
  ensure_project_identity,
@@ -579,7 +620,7 @@ def sync_layers(client, root: Path, project_slug: str | None = None,
579
620
  sync_cfg = _load_cloud_config()
580
621
  except Exception: # noqa: BLE001 - 配置缺失/非法不改变同步入口行为(非法值由闸报错)
581
622
  sync_cfg = {}
582
- selected_policy = sensitive_policy or sync_cfg.get("sensitive_policy") or "allow"
623
+ selected_policy = sensitive_policy or sync_cfg.get("sensitive_policy") or "redact"
583
624
  selected_detail_mode = ns["resolve_detail_mode"](
584
625
  detail_mode or sync_cfg.get("sync_detail_mode"))
585
626
  out: dict = {}
@@ -1,13 +1,14 @@
1
- """cloud_sync/consent.py - 云端数据共享同意的唯一真源(L2 F1 修复)。
1
+ """cloud_sync/consent.py - 云端数据共享与遥测开关的唯一真源。
2
2
 
3
3
  语义(三态,禁止双轨实现):
4
4
 
5
5
  - ``True`` —— 用户显式同意共享;云端 push/pull 仍需项目 onboarding 完成。
6
6
  - ``False`` —— 用户显式撤销;任何云端 egress(push 或 pull)一律拒绝,
7
7
  且不得写项目侧状态(撤销是用户级决定,不改写 ``.bugx/cloud-onboard.json``)。
8
- - ``None`` —— 用户尚未表态;沿用既有 onboarding 状态判定,保持旧行为不变。
8
+ - ``None`` —— 用户尚未表态;云同步仍按既有 onboarding 状态判定,
9
+ 遥测则按产品默认值开启。
9
10
 
10
- 历史缺陷(F1):``bugx cloud telemetry-config telemetry.data_sharing false`` 只清空
11
+ 历史缺陷(F1):``bugx config set telemetry.data_sharing false`` 只清空
11
12
  飞轮 outbox 并写 ``~/.bugx/cloud-config.json``,但 ``sync_layers`` / ``auto_sync``
12
13
  只看 ``.bugx/cloud-onboard.json`` 的 ``state == "done"``,于是「已撤销共享」的项目
13
14
  仍会继续上传 ledger/report。修复方式是把撤销做成读取期硬闸门(本模块),而不是
@@ -20,8 +21,12 @@ import os
20
21
  from pathlib import Path
21
22
 
22
23
  CONFIG_ENV = "BUGX_CLOUD_CONFIG"
24
+ TELEMETRY_ENABLED_ENV = "BUGX_TELEMETRY_ENABLED"
25
+ DEFAULT_TELEMETRY_ENABLED = True
23
26
  REVOKED_ERROR = "data_sharing_revoked"
24
27
  REVOKED_DETAIL = "用户已撤销 telemetry.data_sharing,云端同步被拒绝"
28
+ _TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
29
+ _FALSE_VALUES = frozenset({"0", "false", "no", "off"})
25
30
 
26
31
 
27
32
  class CloudConsentRevoked(RuntimeError):
@@ -69,6 +74,31 @@ def sharing_allowed() -> bool:
69
74
  return data_sharing_flag() is True
70
75
 
71
76
 
77
+ def telemetry_enabled() -> bool:
78
+ """返回统一遥测门禁状态。
79
+
80
+ ``telemetry.data_sharing`` 是用户持久化开关,缺失时按产品契约默认开启。
81
+ ``BUGX_TELEMETRY_ENABLED`` 是未撤销状态下的进程级覆盖;持久化 ``False``
82
+ 优先级最高,非法值按关闭处理,避免把不明确的环境配置误当成允许出网。
83
+ 所有本地统计、飞轮入队、飞轮 flush 和安装心跳都必须调用这个函数,禁止在
84
+ 调用方自行解释三态值。
85
+ """
86
+ # 用户显式持久化的 false 是硬撤销,不能通过环境变量 true 绕过。
87
+ # 环境变量仍可在未撤销时关闭当前进程,或在没有持久化决定时临时开启。
88
+ stored = data_sharing_flag()
89
+ if stored is False:
90
+ return False
91
+ raw = os.environ.get(TELEMETRY_ENABLED_ENV)
92
+ if raw is not None:
93
+ normalized = raw.strip().lower()
94
+ if normalized in _TRUE_VALUES:
95
+ return True
96
+ if normalized in _FALSE_VALUES:
97
+ return False
98
+ return False
99
+ return DEFAULT_TELEMETRY_ENABLED if stored is None else stored
100
+
101
+
72
102
  def revoked_summary(scopes: set[str] | list[str] | None) -> dict:
73
103
  """与 ``sync_layers`` 返回结构对齐的拒绝汇总(零 egress、零状态变更)。"""
74
104
  scope_list = sorted(scopes) if scopes else ["global", "project"]
@@ -13,6 +13,7 @@ import gzip
13
13
  import hashlib
14
14
  import json
15
15
  import os
16
+ import platform
16
17
  import shutil
17
18
  import sqlite3
18
19
  import tarfile
@@ -28,17 +29,30 @@ from typing import Any, Callable, Iterable, Mapping
28
29
  from core.governance.secret_redactor import SecretRedactor
29
30
 
30
31
  try:
31
- from core.infra.client_metadata import client_headers, tls_context
32
+ from core.infra.client_metadata import (
33
+ client_headers,
34
+ client_marker,
35
+ client_version,
36
+ release_channel,
37
+ tls_context,
38
+ )
32
39
  except ImportError:
33
40
  import sys
34
41
  sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
35
- from core.infra.client_metadata import client_headers, tls_context
42
+ from core.infra.client_metadata import (
43
+ client_headers,
44
+ client_marker,
45
+ client_version,
46
+ release_channel,
47
+ tls_context,
48
+ )
36
49
 
37
50
  MAX_OUTBOX_RECORDS = 1000
38
51
  MAX_OUTBOX_BYTES = 50 * 1024 * 1024
39
52
  MAX_AUDIT_BYTES = 10 * 1024 * 1024
40
53
  AUDIT_BACKUPS = 3
41
54
  FLYWHEEL_PATH = "/api/v1/agent/telemetry/flywheel"
55
+ INSTALLATION_HEARTBEAT_INTERVAL = 24 * 60 * 60
42
56
  QUALITY_TIERS = {"tier-1": 3, "tier-2": 2, "tier-3": 1, "TIER-1": 3, "TIER-2": 2, "TIER-3": 1}
43
57
 
44
58
 
@@ -54,13 +68,6 @@ def default_audit_path() -> Path:
54
68
  return Path(os.environ.get("BUGX_FLYWHEEL_AUDIT", str(_bugx_root() / "telemetry" / "egress_audit.log"))).expanduser()
55
69
 
56
70
 
57
- def _stored_data_sharing() -> bool:
58
- # 单一真源:与 cloud_onboard.sync_layers / auto_sync 共用 consent 判定,
59
- # 禁止在这里另写一套读取逻辑(双轨实现会让撤销在两处产生不同结论)。
60
- from core.cloud_sync.consent import sharing_allowed
61
- return sharing_allowed()
62
-
63
-
64
71
  def _stored_base_url() -> str | None:
65
72
  path = Path(os.environ.get("BUGX_CLOUD_CONFIG", str(_bugx_root() / "cloud-config.json"))).expanduser()
66
73
  try:
@@ -87,6 +94,64 @@ def _stored_auth_token() -> str | None:
87
94
  return None
88
95
 
89
96
 
97
+ def _client_kind() -> str:
98
+ value = str(os.environ.get("BUGX_CLIENT_KIND") or os.environ.get("BUGX_CLI_SOURCE") or "pip").strip().lower()
99
+ return value if value in {"pip", "npm", "source", "editable", "unknown"} else "unknown"
100
+
101
+
102
+ def _artifact_kind() -> str:
103
+ return "npm-package" if _client_kind() == "npm" else "python-wheel"
104
+
105
+
106
+ def _telemetry_context(base_url: str) -> dict[str, Any]:
107
+ """Build only stable, scoped client metadata for remote attribution.
108
+
109
+ The installation identity is an HMAC of the local installation secret and
110
+ server origin. No hostname, username, project path, credential, or secret
111
+ value is included in the payload.
112
+ """
113
+ from core.cloud_sync.device_identity import get_device_id
114
+ from core.report_engine.report_client import installation_identity
115
+
116
+ return {
117
+ "installation_id": installation_identity(base_url, account_id=""),
118
+ "device_id": get_device_id(),
119
+ "client_version": client_version(),
120
+ "client_marker": client_marker(),
121
+ "release_channel": release_channel(),
122
+ "client_kind": _client_kind(),
123
+ "artifact_kind": _artifact_kind(),
124
+ "platform": platform.system().lower() or "unknown",
125
+ }
126
+
127
+
128
+ def _installation_state_path() -> Path:
129
+ return _bugx_root() / "telemetry" / "installation-state.json"
130
+
131
+
132
+ def _load_installation_state() -> dict[str, Any]:
133
+ path = _installation_state_path()
134
+ try:
135
+ if path.is_symlink() or not path.is_file():
136
+ return {}
137
+ value = json.loads(path.read_text(encoding="utf-8"))
138
+ return value if isinstance(value, dict) else {}
139
+ except (OSError, UnicodeError, json.JSONDecodeError):
140
+ return {}
141
+
142
+
143
+ def _save_installation_state(state: Mapping[str, Any]) -> None:
144
+ path = _installation_state_path()
145
+ from core.report_engine.report_client import atomic_write_nofollow
146
+
147
+ atomic_write_nofollow(
148
+ path,
149
+ _canonical(dict(state)),
150
+ mode=0o600,
151
+ parent_mode=0o700,
152
+ )
153
+
154
+
90
155
  def _canonical(value: Any) -> bytes:
91
156
  return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
92
157
 
@@ -406,10 +471,11 @@ class FlywheelUploader:
406
471
  self.audit_path = Path(audit_path or default_audit_path()).expanduser()
407
472
  self._urlopen = urlopen or urllib.request.urlopen
408
473
  self.auth_token = auth_token if auth_token is not None else _stored_auth_token()
409
- self.data_sharing = (
410
- os.environ.get("BUGX_ACCEPT_DATA_SHARING") == "1" or _stored_data_sharing()
411
- if data_sharing is None else data_sharing
412
- )
474
+ # 统一门禁:显式 false 只能进一步关闭,不能用显式 true 绕过用户
475
+ # 配置或 BUGX_TELEMETRY_ENABLED=0。未配置时由 consent.py 的产品默认值
476
+ # 开启远程遥测,满足“默认开启、可关闭”的契约。
477
+ self._requested_data_sharing = data_sharing
478
+ self.data_sharing = self._sharing_enabled()
413
479
  self.privacy_strict = (os.environ.get("BUGX_PRIVACY_STRICT") == "1") if privacy_strict is None else privacy_strict
414
480
  self.sleep = sleep
415
481
  self.timeout = timeout
@@ -418,6 +484,16 @@ class FlywheelUploader:
418
484
  self._circuit_until = 0.0
419
485
  self._redactor = SecretRedactor(test_context=bool(os.environ.get("BUGX_TEST_CONTEXT") == "1"))
420
486
 
487
+ def _sharing_enabled(self) -> bool:
488
+ if self._requested_data_sharing is False:
489
+ return False
490
+ try:
491
+ from core.cloud_sync.consent import telemetry_enabled
492
+
493
+ return bool(telemetry_enabled())
494
+ except Exception: # noqa: BLE001 - privacy gate fails closed
495
+ return False
496
+
421
497
  def close(self) -> None:
422
498
  if getattr(self, "_redactor", None):
423
499
  self._redactor.close()
@@ -432,6 +508,19 @@ class FlywheelUploader:
432
508
  clean = self._redactor.redact_records(dict(payload))
433
509
  if self.privacy_strict:
434
510
  metrics = clean.get("metrics") if isinstance(clean, dict) else None
511
+ safe_context = {
512
+ key: clean.get(key)
513
+ for key in (
514
+ "installation_id",
515
+ "client_version",
516
+ "release_channel",
517
+ "client_kind",
518
+ "artifact_kind",
519
+ "platform",
520
+ "installation_event",
521
+ )
522
+ if isinstance(clean, dict) and isinstance(clean.get(key), str) and clean.get(key)
523
+ }
435
524
  clean = {
436
525
  "schema_version": 1,
437
526
  "event_type": clean.get("event_type", "flywheel") if isinstance(clean, dict) else "flywheel",
@@ -439,13 +528,18 @@ class FlywheelUploader:
439
528
  "topology_hash": clean.get("topology_hash") if isinstance(clean, dict) else None,
440
529
  "metrics": metrics if isinstance(metrics, dict) else {},
441
530
  "privacy": "strict",
531
+ **safe_context,
442
532
  }
443
533
  return clean
444
534
 
445
535
  def enqueue(self, payload: Mapping[str, Any], *, tier: str | int | None = None) -> int | None:
536
+ self.data_sharing = self._sharing_enabled()
446
537
  if not self.data_sharing:
447
538
  return None
448
- clean = self._redact(payload)
539
+ enriched = dict(payload)
540
+ for key, value in _telemetry_context(self.base_url).items():
541
+ enriched.setdefault(key, value)
542
+ clean = self._redact(enriched)
449
543
  return self.outbox.enqueue(clean, tier=tier or clean.get("quality_tier"))
450
544
 
451
545
  queue = enqueue
@@ -478,6 +572,26 @@ class FlywheelUploader:
478
572
  payload["dpo_preference"] = dpo_pair.as_dict() if isinstance(dpo_pair, DPOPreferencePair) else dict(dpo_pair)
479
573
  return self.enqueue(payload, tier=quality)
480
574
 
575
+ def enqueue_installation(self, event: str = "heartbeat") -> int | None:
576
+ """Queue an install/heartbeat identity event in the existing outbox.
577
+
578
+ The server treats this event as an upsert into its installation table,
579
+ while retaining the normal Flywheel event receipt for auditability.
580
+ """
581
+ normalized = str(event or "heartbeat").strip().lower()
582
+ if normalized not in {"installed", "heartbeat"}:
583
+ raise ValueError("installation event must be installed or heartbeat")
584
+ return self.enqueue(
585
+ {
586
+ "schema_version": 2,
587
+ "event_type": "installation",
588
+ "installation_event": normalized,
589
+ "quality_tier": "tier-3",
590
+ "metrics": {},
591
+ },
592
+ tier="tier-3",
593
+ )
594
+
481
595
  def _url(self) -> str:
482
596
  return self._endpoint
483
597
 
@@ -575,6 +689,7 @@ class FlywheelUploader:
575
689
 
576
690
  def flush(self, *, limit: int = 100, batch_size: int = 1) -> dict[str, Any]:
577
691
  """Flush queued records to the telemetry flywheel (DES-06, DES-18)."""
692
+ self.data_sharing = self._sharing_enabled()
578
693
  if not self.data_sharing or time.monotonic() < self._circuit_until:
579
694
  return {"sent": 0, "remaining": self.outbox.count(), "circuit_open": True}
580
695
  sent = 0
@@ -720,6 +835,61 @@ class FlywheelUploader:
720
835
  return len([line for line in records if line.strip()])
721
836
 
722
837
 
838
+ def maybe_report_installation(*, force: bool = False) -> dict[str, Any]:
839
+ """Queue and opportunistically flush one install/heartbeat event.
840
+
841
+ The CLI calls this at most once per day. It is deliberately best effort:
842
+ a network failure leaves the normal bounded outbox intact and cannot block
843
+ the requested local command. ``force`` is reserved for an explicit
844
+ diagnostic/verification caller and still cannot bypass the privacy gate.
845
+ """
846
+ try:
847
+ from core.cloud_sync.consent import telemetry_enabled
848
+
849
+ if not telemetry_enabled():
850
+ return {"enabled": False, "status": "disabled", "sent": 0}
851
+ state = _load_installation_state()
852
+ now = time.time()
853
+ last_attempt = float(state.get("last_attempt_at") or 0.0)
854
+ if not force and last_attempt > 0 and now - last_attempt < INSTALLATION_HEARTBEAT_INTERVAL:
855
+ return {"enabled": True, "status": "not_due", "sent": 0}
856
+
857
+ event = "installed" if not bool(state.get("installed_reported")) else "heartbeat"
858
+ with FlywheelUploader() as uploader:
859
+ if not uploader.data_sharing:
860
+ return {"enabled": False, "status": "disabled", "sent": 0}
861
+ record_id = uploader.enqueue_installation(event)
862
+ if record_id is None:
863
+ return {"enabled": False, "status": "disabled", "sent": 0}
864
+ flushed = uploader.flush(limit=20, batch_size=20)
865
+ remaining_ids = {
866
+ int(item["id"])
867
+ for item in uploader.outbox.items(limit=uploader.outbox.max_records)
868
+ }
869
+ delivered = record_id not in remaining_ids
870
+
871
+ state.update({
872
+ "schema_version": 1,
873
+ "last_attempt_at": now,
874
+ "last_event": event,
875
+ "installed_reported": bool(state.get("installed_reported")) or delivered,
876
+ })
877
+ try:
878
+ _save_installation_state(state)
879
+ except (OSError, ValueError):
880
+ # The telemetry event itself has already been queued/sent. State
881
+ # persistence failure only causes a bounded duplicate next time.
882
+ pass
883
+ return {
884
+ "enabled": True,
885
+ "status": "sent" if delivered else "queued",
886
+ "event": event,
887
+ "sent": int(flushed.get("sent", 0)) if isinstance(flushed, dict) else 0,
888
+ }
889
+ except Exception as exc: # noqa: BLE001 - telemetry must not block CLI work
890
+ return {"enabled": True, "status": "error", "error": str(exc), "sent": 0}
891
+
892
+
723
893
  def _encrypt(data: bytes, passphrase: str) -> bytes:
724
894
  try:
725
895
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
@@ -754,7 +924,8 @@ def _decrypt(data: bytes, passphrase: str) -> bytes:
754
924
 
755
925
  __all__ = [
756
926
  "AUDIT_BACKUPS", "DPOPreferencePair", "FLYWHEEL_PATH", "FlywheelOutbox", "FlywheelUploader",
927
+ "INSTALLATION_HEARTBEAT_INTERVAL",
757
928
  "MAX_AUDIT_BYTES", "MAX_OUTBOX_BYTES", "MAX_OUTBOX_RECORDS", "OutboxFullError",
758
929
  "build_dpo_preference_pair", "default_audit_path", "default_outbox_path",
759
- "merkle_root", "quality_tier", "quality_tier_name",
930
+ "maybe_report_installation", "merkle_root", "quality_tier", "quality_tier_name",
760
931
  ]
@@ -24,6 +24,23 @@ from core.infra.client_metadata import tls_context as client_tls_context
24
24
 
25
25
  logger = logging.getLogger(__name__)
26
26
 
27
+ # F-133:curl 子进程不得继承任何能改写 TLS 信任根的 env。
28
+ # 这些变量会让攻击者用自有 CA 覆盖代码构造的信任上下文(--ca-native/--cacert
29
+ # 或 --insecure 的显式决策),使 CA 固定被旁路。白名单只放行与此无关的 env;
30
+ # 命中即被剔除,信任只来自本函数据 context/BUGX_CA_BUNDLE 构造的参数,绝不
31
+ # 以“信任系统默认 + 残留 env”了事。
32
+ _TLS_TRUST_ENV_VARS = frozenset({
33
+ "CURL_CA_BUNDLE", # curl 读取的 CA bundle
34
+ "CURL_CA_PATH", # curl 读取的 CA 目录
35
+ "SSL_CERT_FILE", # OpenSSL/curl 默认 CA 文件
36
+ "SSL_CERT_DIR", # OpenSSL/curl 默认 CA 目录
37
+ "REQUESTS_CA_BUNDLE", # requests 信任根(同进程其他 HTTP 栈)
38
+ "NODE_EXTRA_CA_CERTS", # Node 追加信任根
39
+ "GIT_SSL_CAINFO", # git/curl 信任根
40
+ "GIT_SSL_CAPATH", # git/curl 信任目录
41
+ })
42
+
43
+
27
44
  def is_private_target_host(host: str) -> bool:
28
45
  """Check if host is a local/private network target (excluding loopback)."""
29
46
  if not host or host in {"localhost", "localhost.localdomain"}:
@@ -240,9 +257,13 @@ def trusted_curl_request(req: urllib.request.Request, timeout: float) -> CurlRes
240
257
  command.extend(("--request", req.get_method(), "--dump-header", "/dev/stderr",
241
258
  "--output", "-", req.full_url))
242
259
 
243
- environment = {key: value for key, value in os.environ.items()
244
- if not key.startswith("DYLD_")}
245
- environment.pop("CURL_CA_BUNDLE", None)
260
+ # 剔除注入向量:DYLD_*(动态库劫持)与全部 TLS 信任根 env(F-133)。
261
+ # 保留 BUGX_CA_BUNDLE:它是本函数上面显式读取并转成 --cacert 的代码构造锚,
262
+ # 不属于被污染的系统信任根注入面。
263
+ environment = {
264
+ key: value for key, value in os.environ.items()
265
+ if not key.startswith("DYLD_") and key not in _TLS_TRUST_ENV_VARS
266
+ }
246
267
  try:
247
268
  result = subprocess.run(
248
269
  command, input=req.data, capture_output=True, timeout=timeout,
@@ -232,8 +232,8 @@ def emit_policy_audit(policy: str, categories: list[str], redacted_count: int) -
232
232
 
233
233
 
234
234
  def prepare_records_for_sync(records: Mapping[str, list], *,
235
- policy: str = "allow") -> dict[str, Any]:
236
- """DOC-211:push/upload 发网前的敏感策略统一入口。
235
+ policy: str = "redact") -> dict[str, Any]:
236
+ """DOC-211:push/upload 发网前的敏感策略统一入口(默认档安全默认 redact,F-025)。
237
237
 
238
238
  必须在 manifest_hash/envelope 构建之前调用(redact 会改内容,幂等键在
239
239
  manifest 之后派生会错位)。block=三正则+凭据形状双扫描,命中即拒(原语义