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
@@ -1083,7 +1083,15 @@ class CloudClient:
1083
1083
 
1084
1084
  # ---- 版本检查与 CLI 包下载(Phase 2 自动更新)----
1085
1085
 
1086
- 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:
1087
1095
  """GET /api/v1/agent/version — 查询最新版本元数据。
1088
1096
 
1089
1097
  当传入 current_version 时,服务端额外返回 update_available 和
@@ -1095,6 +1103,12 @@ class CloudClient:
1095
1103
  params["current"] = current_version
1096
1104
  if channel and channel.strip():
1097
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()
1098
1112
  return self._request("GET", VERSION_CHECK_PATH, None,
1099
1113
  auth=False, retry_auth=False, params=params or None)
1100
1114
 
@@ -1113,8 +1127,16 @@ class CloudClient:
1113
1127
  return host in {"127.0.0.1", "::1", "localhost"}
1114
1128
  return False
1115
1129
 
1116
- def download_package(self, dest: Path, *, expected_sha256: str = "",
1117
- 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]:
1118
1140
  """GET /api/v1/agent/download — 下载 CLI 包到指定路径。
1119
1141
 
1120
1142
  返回 (success, message)。下载后做 SHA-256 校验(必须提供)。
@@ -1124,7 +1146,7 @@ class CloudClient:
1124
1146
 
1125
1147
  dest: 目标文件路径(含文件名)。
1126
1148
  expected_sha256: 下载后校验哈希(必填,缺失即拒绝下载)。
1127
- expected_version: 仅用于日志/提示,不影响逻辑。
1149
+ release_id/channel/artifact_kind: 锁定服务端返回的具体制品。
1128
1150
  """
1129
1151
  expected_sha256 = str(expected_sha256 or "").strip().lower()
1130
1152
  if not expected_sha256:
@@ -1132,10 +1154,23 @@ class CloudClient:
1132
1154
  if not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
1133
1155
  return False, "下载失败: expected_sha256 必须是 64 位 SHA-256 hex"
1134
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()
1135
1164
  url = self.base + DOWNLOAD_PATH
1165
+ if params:
1166
+ url += "?" + urllib.parse.urlencode(params)
1136
1167
  # 跟随重定向(版本检查端点可能配置了外部 PyPI 镜像地址)
1137
1168
  opener = _build_redirect_opener(self.base)
1138
- 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
+ }
1139
1174
  req = urllib.request.Request(url, headers=headers)
1140
1175
  try:
1141
1176
  resp = opener.open(req, timeout=self.timeout)
@@ -1151,6 +1186,22 @@ class CloudClient:
1151
1186
  f"下载失败: 最终 URL 非 HTTPS,拒绝下载: {final_url}"
1152
1187
  )
1153
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
+ )
1154
1205
  content_length = None
1155
1206
  if headers is not None:
1156
1207
  raw_length = headers.get("Content-Length")
@@ -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,14 +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 | None:
58
- # 单一真源:与 cloud_onboard.sync_layers / auto_sync 共用 consent 判定,
59
- # 禁止在这里另写一套读取逻辑(双轨实现会让撤销在两处产生不同结论)。
60
- # 必须保留三态:撤销(False)要压过 BUGX_ACCEPT_DATA_SHARING 预同意入口。
61
- from core.cloud_sync.consent import data_sharing_flag
62
- return data_sharing_flag()
63
-
64
-
65
71
  def _stored_base_url() -> str | None:
66
72
  path = Path(os.environ.get("BUGX_CLOUD_CONFIG", str(_bugx_root() / "cloud-config.json"))).expanduser()
67
73
  try:
@@ -88,6 +94,64 @@ def _stored_auth_token() -> str | None:
88
94
  return None
89
95
 
90
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
+
91
155
  def _canonical(value: Any) -> bytes:
92
156
  return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
93
157
 
@@ -407,18 +471,11 @@ class FlywheelUploader:
407
471
  self.audit_path = Path(audit_path or default_audit_path()).expanduser()
408
472
  self._urlopen = urlopen or urllib.request.urlopen
409
473
  self.auth_token = auth_token if auth_token is not None else _stored_auth_token()
410
- # F-024:撤销(显式 false)是硬闸门——BUGX_ACCEPT_DATA_SHARING 预同意
411
- # 入口只对「未表态」生效,不得越过用户显式撤销(与 sync_push/pull 的
412
- # require_sharing 硬闸门同策略)。
413
- if data_sharing is not None:
414
- self.data_sharing = data_sharing
415
- elif _stored_data_sharing() is False:
416
- self.data_sharing = False
417
- else:
418
- self.data_sharing = (
419
- os.environ.get("BUGX_ACCEPT_DATA_SHARING") == "1"
420
- or _stored_data_sharing() is True
421
- )
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()
422
479
  self.privacy_strict = (os.environ.get("BUGX_PRIVACY_STRICT") == "1") if privacy_strict is None else privacy_strict
423
480
  self.sleep = sleep
424
481
  self.timeout = timeout
@@ -427,6 +484,16 @@ class FlywheelUploader:
427
484
  self._circuit_until = 0.0
428
485
  self._redactor = SecretRedactor(test_context=bool(os.environ.get("BUGX_TEST_CONTEXT") == "1"))
429
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
+
430
497
  def close(self) -> None:
431
498
  if getattr(self, "_redactor", None):
432
499
  self._redactor.close()
@@ -441,6 +508,19 @@ class FlywheelUploader:
441
508
  clean = self._redactor.redact_records(dict(payload))
442
509
  if self.privacy_strict:
443
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
+ }
444
524
  clean = {
445
525
  "schema_version": 1,
446
526
  "event_type": clean.get("event_type", "flywheel") if isinstance(clean, dict) else "flywheel",
@@ -448,13 +528,18 @@ class FlywheelUploader:
448
528
  "topology_hash": clean.get("topology_hash") if isinstance(clean, dict) else None,
449
529
  "metrics": metrics if isinstance(metrics, dict) else {},
450
530
  "privacy": "strict",
531
+ **safe_context,
451
532
  }
452
533
  return clean
453
534
 
454
535
  def enqueue(self, payload: Mapping[str, Any], *, tier: str | int | None = None) -> int | None:
536
+ self.data_sharing = self._sharing_enabled()
455
537
  if not self.data_sharing:
456
538
  return None
457
- 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)
458
543
  return self.outbox.enqueue(clean, tier=tier or clean.get("quality_tier"))
459
544
 
460
545
  queue = enqueue
@@ -487,6 +572,26 @@ class FlywheelUploader:
487
572
  payload["dpo_preference"] = dpo_pair.as_dict() if isinstance(dpo_pair, DPOPreferencePair) else dict(dpo_pair)
488
573
  return self.enqueue(payload, tier=quality)
489
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
+
490
595
  def _url(self) -> str:
491
596
  return self._endpoint
492
597
 
@@ -584,6 +689,7 @@ class FlywheelUploader:
584
689
 
585
690
  def flush(self, *, limit: int = 100, batch_size: int = 1) -> dict[str, Any]:
586
691
  """Flush queued records to the telemetry flywheel (DES-06, DES-18)."""
692
+ self.data_sharing = self._sharing_enabled()
587
693
  if not self.data_sharing or time.monotonic() < self._circuit_until:
588
694
  return {"sent": 0, "remaining": self.outbox.count(), "circuit_open": True}
589
695
  sent = 0
@@ -729,6 +835,61 @@ class FlywheelUploader:
729
835
  return len([line for line in records if line.strip()])
730
836
 
731
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
+
732
893
  def _encrypt(data: bytes, passphrase: str) -> bytes:
733
894
  try:
734
895
  from cryptography.hazmat.primitives.ciphers.aead import AESGCM
@@ -763,7 +924,8 @@ def _decrypt(data: bytes, passphrase: str) -> bytes:
763
924
 
764
925
  __all__ = [
765
926
  "AUDIT_BACKUPS", "DPOPreferencePair", "FLYWHEEL_PATH", "FlywheelOutbox", "FlywheelUploader",
927
+ "INSTALLATION_HEARTBEAT_INTERVAL",
766
928
  "MAX_AUDIT_BYTES", "MAX_OUTBOX_BYTES", "MAX_OUTBOX_RECORDS", "OutboxFullError",
767
929
  "build_dpo_preference_pair", "default_audit_path", "default_outbox_path",
768
- "merkle_root", "quality_tier", "quality_tier_name",
930
+ "maybe_report_installation", "merkle_root", "quality_tier", "quality_tier_name",
769
931
  ]
@@ -1,6 +1,6 @@
1
1
  # BugX 智能体执行协议与交互契约子系统 (Agent Runtime Contracts & Protocols)
2
2
 
3
- > **版本契约**: `0.1.1` | **父系统**: `core/`
3
+ > **版本契约**: `0.1.2` | **父系统**: `core/`
4
4
  > **工程规范**: 参见 [`docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md`](../../docs/02_architecture/05_ARCH_NOMENCLATURE_GUIDE.md) 与 [`docs/02_architecture/06_MODULE_GOVERNANCE_SPEC.md`](../../docs/02_architecture/06_MODULE_GOVERNANCE_SPEC.md)
5
5
  > **守卫机制**: `scripts/verify_directory_indices.py` (100% 索引对齐防漂移)
6
6
 
@@ -1,4 +1,4 @@
1
- # BugX 运行时契约(0.1.1)
1
+ # BugX 运行时契约(0.1.2)
2
2
 
3
3
  这是部署到用户级全局引擎 `~/.bugx/core/` 的最小运行时契约。项目不再保存
4
4
  `.bugx/core` 可执行入口;需要定位本文件时使用 `bugx engine path --name bugx-runtime-contract.md`。
@@ -1,5 +1,5 @@
1
1
  ---
2
- # bugx_version: 0.1.1
2
+ # bugx_version: 0.1.2
3
3
  description: BugX 并发 worker。负责 Supervisor 分配的覆盖单元或亲和任务包(最多 5 单元):领取租约 → 确认真实启动 → 挖掘举证 → 提交 checkpoint。不写寿命、不结算、不生成最终报告。
4
4
  mode: subagent
5
5
  permissions: