bugx-cli 0.1.2 → 0.1.4
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 +26 -29
- package/core/README.md +5 -3
- package/core/agent/agent_orchestrator.py +3 -0
- package/core/agent/agent_workspace.py +14 -2
- package/core/assets/bugx-wechat-group.png +0 -0
- package/core/assets/twitter_promo_art.jpg +0 -0
- package/core/assets/twitter_promo_card.svg +166 -0
- package/core/assets/twitter_promo_clean.jpg +0 -0
- package/core/assets/twitter_terminal_real.png +0 -0
- package/core/bugx.md +3 -3
- package/core/bugx_paths.py +10 -2
- package/core/bundled_docs/OVERVIEW.md +310 -0
- package/core/bundled_docs/README.md +10 -0
- package/core/bundled_docs/README_EN.md +278 -0
- package/core/bundled_docs/ai/01_AI_REFERENCE.md +833 -0
- package/core/bundled_docs/ai/02_AI_USAGE.md +161 -0
- package/core/bundled_docs/ai/03_AI_COMMANDS.md +322 -0
- package/core/bundled_docs/guides/01_USER_GUIDE.md +887 -0
- package/core/bundled_docs/guides/02_COMMANDS.md +935 -0
- package/core/bundled_docs/guides/03_TROUBLESHOOTING.md +763 -0
- package/core/bundled_docs/guides/04_CLOUD_AUTH_AND_SYNC_COOKBOOK.md +48 -0
- package/core/bundled_docs/guides/05_HOST_MATRIX_AND_DISPATCH.md +23 -0
- package/core/bundled_docs/guides/06_PROBES_AND_POC_COOKBOOK.md +49 -0
- package/core/bundled_docs/guides/07_LIFECYCLE_AND_RECOVERY_STATES.md +46 -0
- package/core/bundled_docs/guides/08_LESSONS_AND_PRIVACY_BOUNDARY.md +35 -0
- package/core/bundled_docs/hosts/bugx-claude_SKILL.md +326 -0
- package/core/bundled_docs/hosts/bugx-dsh_SKILL.md +229 -0
- package/core/bundled_docs/hosts/bugx-opencode_SKILL.md +129 -0
- package/core/bundled_docs/hosts/bugx-zcode_SKILL.md +459 -0
- package/core/bundled_docs/hosts/bugx_SKILL.md +118 -0
- package/core/bundled_docs/hosts/cline_bugx_SKILL.md +69 -0
- package/core/bundled_docs/hosts/platform_bugx_SKILL.md +50 -0
- package/core/bundled_docs/manifest.json +140 -0
- package/core/bundled_docs/reference/01_ENVIRONMENT_VARIABLES.md +421 -0
- package/core/bundled_docs/reference/04_REPOSITORY_TOPOLOGY.md +180 -0
- package/core/cli-help.txt +7 -3
- package/core/cloud_sync/cloud_client.py +81 -2
- package/core/cloud_sync/endpoint_router.py +22 -9
- package/core/cloud_sync/issue_uploader.py +297 -0
- package/core/cloud_sync/sensitive_filter.py +77 -7
- package/core/contracts/AGENT_GUIDE.md +3 -9
- package/core/contracts/README.md +1 -1
- package/core/contracts/bugx-opencode.md +1 -1
- package/core/contracts/bugx-runtime-contract.md +10 -20
- package/core/contracts/bugx-worker.md +1 -1
- package/core/engine-integrity.json +267 -111
- package/core/host_acp/antigravity.py +153 -0
- package/core/host_acp/kimi.py +175 -0
- package/core/host_acp/minimax.py +28 -0
- package/core/host_runtime/adapters.py +5 -1
- package/core/host_runtime/antigravity.py +162 -0
- package/core/host_runtime/host_bootstrap.py +18 -7
- package/core/host_runtime/host_evaluators.py +4 -4
- package/core/host_runtime/host_registry.py +25 -4
- package/core/host_runtime/mcp_process_tracker.py +30 -3
- package/core/host_runtime/mcp_registry_gate.py +34 -11
- package/core/hosts/antigravity.py +115 -0
- package/core/hosts/codex.py +3 -0
- package/core/hosts/dsh.py +43 -24
- package/core/hosts/kimi.py +293 -0
- package/core/hosts/minimax.py +249 -0
- package/core/hosts/zcode.py +5 -0
- package/core/i18n.py +94 -5
- package/core/infra/README.md +1 -1
- package/core/infra/build_info.py +30 -5
- package/core/launch_phases/README.md +2 -2
- package/core/launch_phases/startup_version_gate.py +2 -2
- package/core/launch_phases/supervisor_bridge.py +16 -23
- package/core/launch_phases/supervisor_degraded.py +7 -5
- package/core/ledger/README.md +1 -1
- package/core/locales/en-US.json +3 -3
- package/core/locales/zh-CN.json +3 -3
- package/core/mcp_runtime_support/environment.py +6 -1
- package/core/metadata.txt +2 -2
- package/core/planning/README.md +1 -1
- package/core/planning/prompt_harness.py +2 -2
- package/core/probes/codebase_memory_probe.py +43 -24
- package/core/probes/probe_registry.py +10 -7
- package/core/prompts/command_routing_en.md +6 -5
- package/core/prompts/command_routing_zh.md +6 -5
- package/core/repair/rsi_rounds.py +3 -0
- package/core/repair/self_heal.py +160 -6
- package/core/retrieval/README.md +1 -1
- package/core/runtime/README.md +1 -1
- package/core/runtime/scenario_eval.py +5 -1
- package/core/runtime/setup_ui_env.py +4 -7
- package/core/runtime/tool_install_targets.py +12 -2
- package/core/skills/README.md +4 -2
- package/core/skills/bugx_docs_cloud_sync.py +658 -0
- package/core/skills/bugx_docs_mcp_server.py +966 -140
- package/core/supervisor/README.md +1 -1
- package/core/supervisor/cli.py +2 -2
- package/core/supervisor/worker_execution.py +16 -3
- package/core/webui/docs_session_service.py +40 -2
- package/core/webui/mcp_inspector.py +12 -6
- package/core/webui/static/index.html +51 -3
- package/core/webui/static/manifest.webmanifest +1 -1
- package/core/webui/static/project-settings.js +18 -3
- package/core/webui/static/robots.txt +36 -0
- package/core/webui/static/sitemap.xml +15 -0
- package/docs/07_distribution/01_README_NPM.md +26 -29
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +46 -46
- package/ecosystem/integrations/dsh/agents/bugx.md +2 -1
- package/ecosystem/integrations/dsh/dsh-patch.yml +2 -2
- package/ecosystem/integrations/dsh/mcp/package.json +1 -1
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +6 -6
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/integrations/dsh/ui/package.json +1 -1
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +2 -2
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +1 -1
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +6 -6
- package/ecosystem/integrations/qoder/CONNECTORS.md +11 -23
- package/ecosystem/integrations/qoder/connector-meta.json +9 -9
- package/ecosystem/integrations/workbuddy/connector-meta.json +9 -9
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +8 -7
- package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +2 -2
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +2 -2
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +4 -4
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +2 -2
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +14 -18
- package/ecosystem/plugins/bugx/agents/bugx.md +45 -49
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +8 -8
- package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +1 -1
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +3 -3
- package/interfaces/bin/bugx.js +2 -0
- package/interfaces/cli/bugx_cli/__init__.py +2 -2
- package/interfaces/cli/bugx_cli/cli.py +153 -8
- package/interfaces/cli/bugx_cli/commands/agent.py +568 -136
- package/interfaces/cli/bugx_cli/commands/cloud.py +42 -1
- package/interfaces/cli/bugx_cli/commands/doctor.py +668 -223
- package/interfaces/cli/bugx_cli/commands/guide.py +143 -0
- package/interfaces/cli/bugx_cli/commands/issue.py +262 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +99 -62
- package/interfaces/cli/bugx_cli/commands/plugin.py +301 -60
- package/interfaces/cli/bugx_cli/commands/plugin_antigravity.py +350 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +27 -13
- package/interfaces/cli/bugx_cli/commands/plugin_kimi.py +440 -0
- package/interfaces/cli/bugx_cli/commands/plugin_minimax.py +522 -0
- package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +3 -4
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +4 -5
- package/interfaces/cli/bugx_cli/commands/system.py +75 -5
- package/interfaces/cli/bugx_cli/common.py +135 -15
- package/interfaces/cli/bugx_cli/host_adapters.py +190 -7
- package/interfaces/cli/bugx_cli/hosts/registry.py +6 -3
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +31 -11
- package/interfaces/cli/bugx_cli/infra/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +14 -12
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +76 -10
- package/interfaces/cli/bugx_cli/infra/host_sync.py +66 -1
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +242 -52
- package/package.json +38 -13
- package/pyproject.toml +57 -13
- package/scripts/sync-version.mjs +1 -1
- package/skills/README.md +24 -0
- package/skills/platform/bugx/SKILL.md +50 -0
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""BugX 官方文档云端热同步与不可变内容寻址缓存管理器 (DOC-006)。
|
|
3
|
+
|
|
4
|
+
提供:
|
|
5
|
+
1. 按 ``contract_version`` 分桶的只读官方文档清单探测 (ETag / 304 < 1.5s);
|
|
6
|
+
2. 不可变快照缓存 ``~/.bugx/cache/docs/<contract_version>/<sha256>.sqlite3`` 与
|
|
7
|
+
``current.json`` 原子指针切换;
|
|
8
|
+
3. 校验门禁:HTTPS/本机测试地址白名单 + 无重定向下载 + 字节上限 (32 MiB gz / 64 MiB SQLite)
|
|
9
|
+
+ SHA-256 强校 + ``PRAGMA quick_check``;
|
|
10
|
+
4. 单飞并发锁 ``sync.lock``(防 6 Worker 并发拉起时踩踏雪崩)与旧快照安全清扫(兼容 Windows WinError 32);
|
|
11
|
+
5. 严格断网与隐私边界:``BUGX_DOCS_OFFLINE=1`` 或 ``docs_remote_enabled=false`` 零出网;
|
|
12
|
+
远程请求不附带任何本地项目路径、代码片段或敏感凭据。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from contextlib import contextmanager
|
|
18
|
+
import gzip
|
|
19
|
+
import hashlib
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import sqlite3
|
|
24
|
+
import time
|
|
25
|
+
import urllib.error
|
|
26
|
+
import urllib.parse
|
|
27
|
+
import urllib.request
|
|
28
|
+
import uuid
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Callable, Iterator
|
|
31
|
+
|
|
32
|
+
from core.cloud_sync.endpoint_router import (
|
|
33
|
+
configured_base_url,
|
|
34
|
+
load_cloud_config,
|
|
35
|
+
validate_base_url,
|
|
36
|
+
)
|
|
37
|
+
from core.cloud_sync.network_transport import (
|
|
38
|
+
build_no_redirect_open,
|
|
39
|
+
diagnose_network_error,
|
|
40
|
+
trusted_curl_request,
|
|
41
|
+
)
|
|
42
|
+
from core.infra.build_info import BASE_VERSION
|
|
43
|
+
from core.infra.client_metadata import client_headers
|
|
44
|
+
from core.report_engine.report_client import atomic_write_nofollow
|
|
45
|
+
from core.secure_atomic import AtomicWriteError, reject_symlink_components
|
|
46
|
+
|
|
47
|
+
DOCS_SCHEMA_VERSION = "v2-trigram-section-hybrid"
|
|
48
|
+
DOCS_MANIFEST_PATH = "/api/v1/agent/docs/manifest"
|
|
49
|
+
DOCS_BUNDLE_PATH = "/api/v1/agent/docs/bundle"
|
|
50
|
+
DOCS_SEARCH_PATH = "/api/v1/agent/docs/search"
|
|
51
|
+
DOCS_FETCH_PATH = "/api/v1/agent/docs/fetch"
|
|
52
|
+
|
|
53
|
+
MAX_MANIFEST_BYTES = 256 * 1024
|
|
54
|
+
MAX_BUNDLE_GZ_BYTES = 32 * 1024 * 1024
|
|
55
|
+
MAX_BUNDLE_SQLITE_BYTES = 64 * 1024 * 1024
|
|
56
|
+
MAX_REMOTE_JSON_BYTES = 256 * 1024
|
|
57
|
+
|
|
58
|
+
DEFAULT_MANIFEST_TIMEOUT = 1.5
|
|
59
|
+
DEFAULT_BUNDLE_TIMEOUT = 5.0
|
|
60
|
+
DEFAULT_SEARCH_TIMEOUT = 2.0
|
|
61
|
+
DEFAULT_TTL_SECONDS = 3600
|
|
62
|
+
DEFAULT_FAILURE_BACKOFF_SECONDS = 120
|
|
63
|
+
|
|
64
|
+
_CONTRACT_RE = re.compile(r"^\d+\.\d+\.\d+$")
|
|
65
|
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
|
66
|
+
_TRUTHY = frozenset({"1", "true", "yes", "on"})
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DocsSyncError(ValueError):
|
|
70
|
+
"""受控文档同步或验证失败。"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def contract_version_of(value: str | None = None) -> str:
|
|
74
|
+
"""提取 X.Y.Z 契约版本号(剥离 +build / prerelease)。"""
|
|
75
|
+
raw = str(value or BASE_VERSION or "0.1.3").strip()
|
|
76
|
+
m = re.match(r"^v?(\d+\.\d+\.\d+)", raw)
|
|
77
|
+
ver = m.group(1) if m else "0.1.3"
|
|
78
|
+
if not _CONTRACT_RE.fullmatch(ver):
|
|
79
|
+
raise DocsSyncError(f"非法的契约版本号: {value!r}")
|
|
80
|
+
return ver
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def docs_offline_disabled() -> bool:
|
|
84
|
+
"""检查是否因空气隔离环境变量或配置而禁用文档远端连接。"""
|
|
85
|
+
env_flag = os.environ.get("BUGX_DOCS_OFFLINE", "").strip().lower()
|
|
86
|
+
if env_flag in _TRUTHY:
|
|
87
|
+
return True
|
|
88
|
+
try:
|
|
89
|
+
cfg = load_cloud_config()
|
|
90
|
+
except ValueError:
|
|
91
|
+
return False
|
|
92
|
+
return cfg.get("docs_remote_enabled") is False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def resolve_remote_base_url(explicit_url: str | None = None) -> str:
|
|
96
|
+
"""解析并严格校验服务端基地址(HTTPS 或本机测试回环)。"""
|
|
97
|
+
candidate = (
|
|
98
|
+
str(explicit_url or "").strip()
|
|
99
|
+
or os.environ.get("BUGX_DOCS_REMOTE_URL", "").strip()
|
|
100
|
+
or configured_base_url()
|
|
101
|
+
)
|
|
102
|
+
try:
|
|
103
|
+
return validate_base_url(candidate)
|
|
104
|
+
except ValueError as exc:
|
|
105
|
+
raise DocsSyncError(str(exc)) from exc
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def docs_cache_dir(contract_version: str | None = None) -> Path:
|
|
109
|
+
"""返回全局不可变官方文档缓存目录。"""
|
|
110
|
+
ver = contract_version_of(contract_version)
|
|
111
|
+
override = os.environ.get("BUGX_DOCS_CACHE_DIR", "").strip()
|
|
112
|
+
if override:
|
|
113
|
+
base = Path(override).expanduser()
|
|
114
|
+
else:
|
|
115
|
+
bugx_home = os.environ.get("BUGX_HOME", "").strip()
|
|
116
|
+
home_root = Path(bugx_home).expanduser() if bugx_home else (Path.home() / ".bugx")
|
|
117
|
+
base = home_root / "cache" / "docs"
|
|
118
|
+
target = base / ver
|
|
119
|
+
try:
|
|
120
|
+
reject_symlink_components(target)
|
|
121
|
+
except AtomicWriteError as exc:
|
|
122
|
+
raise DocsSyncError(f"文档缓存路径不安全: {target}") from exc
|
|
123
|
+
return target
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _read_current_state(cache_root: Path) -> dict[str, Any]:
|
|
127
|
+
pointer = cache_root / "current.json"
|
|
128
|
+
if not pointer.exists():
|
|
129
|
+
return {}
|
|
130
|
+
try:
|
|
131
|
+
reject_symlink_components(pointer)
|
|
132
|
+
if pointer.is_symlink() or not pointer.is_file():
|
|
133
|
+
return {}
|
|
134
|
+
data = json.loads(pointer.read_text(encoding="utf-8"))
|
|
135
|
+
return data if isinstance(data, dict) else {}
|
|
136
|
+
except (OSError, UnicodeError, ValueError, AtomicWriteError):
|
|
137
|
+
return {}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _write_current_state(cache_root: Path, state: dict[str, Any]) -> None:
|
|
141
|
+
pointer = cache_root / "current.json"
|
|
142
|
+
cache_root.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
143
|
+
atomic_write_nofollow(
|
|
144
|
+
pointer,
|
|
145
|
+
json.dumps(state, ensure_ascii=False, indent=2).encode("utf-8"),
|
|
146
|
+
parent_mode=0o700,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def verify_sqlite_snapshot(db_path: Path, expected_contract: str | None = None) -> bool:
|
|
151
|
+
"""只读校验证明:文件非软链、PRAGMA quick_check 通过且包含双域 trigram 表。"""
|
|
152
|
+
if db_path.is_symlink() or not db_path.is_file():
|
|
153
|
+
return False
|
|
154
|
+
try:
|
|
155
|
+
reject_symlink_components(db_path)
|
|
156
|
+
conn = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True)
|
|
157
|
+
except (sqlite3.Error, OSError, AtomicWriteError):
|
|
158
|
+
return False
|
|
159
|
+
try:
|
|
160
|
+
qc = conn.execute("PRAGMA quick_check").fetchone()
|
|
161
|
+
if not qc or str(qc[0]).lower() != "ok":
|
|
162
|
+
return False
|
|
163
|
+
tables = {
|
|
164
|
+
str(r[0])
|
|
165
|
+
for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
|
166
|
+
}
|
|
167
|
+
if not {"documents_meta", "documents", "document_sections", "sections_fts"}.issubset(tables):
|
|
168
|
+
return False
|
|
169
|
+
meta = dict(conn.execute("SELECT key, value FROM documents_meta").fetchall())
|
|
170
|
+
if meta.get("schema_version") != DOCS_SCHEMA_VERSION:
|
|
171
|
+
return False
|
|
172
|
+
if expected_contract and meta.get("contract_version") not in {None, expected_contract}:
|
|
173
|
+
return False
|
|
174
|
+
return True
|
|
175
|
+
except sqlite3.Error:
|
|
176
|
+
return False
|
|
177
|
+
finally:
|
|
178
|
+
conn.close()
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def current_cached_db(contract_version: str | None = None) -> Path | None:
|
|
182
|
+
"""获取当前通过校验的不可变全局官方文档数据库路径(不触发网络)。"""
|
|
183
|
+
ver = contract_version_of(contract_version)
|
|
184
|
+
try:
|
|
185
|
+
cache_root = docs_cache_dir(ver)
|
|
186
|
+
except DocsSyncError:
|
|
187
|
+
return None
|
|
188
|
+
state = _read_current_state(cache_root)
|
|
189
|
+
db_name = str(state.get("db_file") or "").strip()
|
|
190
|
+
if not db_name or "/" in db_name or "\\" in db_name:
|
|
191
|
+
return None
|
|
192
|
+
db_path = cache_root / db_name
|
|
193
|
+
if verify_sqlite_snapshot(db_path, ver):
|
|
194
|
+
return db_path
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@contextmanager
|
|
199
|
+
def _single_flight_lock(lock_path: Path) -> Iterator[bool]:
|
|
200
|
+
"""非阻塞文件单飞锁,避免并发 Worker 拉起同步踩踏。"""
|
|
201
|
+
lock_path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
202
|
+
if os.name == "nt":
|
|
203
|
+
# Windows 排他创建锁文件,若已存在则判定竞争跳过
|
|
204
|
+
try:
|
|
205
|
+
fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
|
|
206
|
+
except FileExistsError:
|
|
207
|
+
try:
|
|
208
|
+
if time.time() - lock_path.stat().st_mtime > 30:
|
|
209
|
+
lock_path.unlink(missing_ok=True)
|
|
210
|
+
except OSError:
|
|
211
|
+
pass
|
|
212
|
+
yield False
|
|
213
|
+
return
|
|
214
|
+
except OSError:
|
|
215
|
+
yield False
|
|
216
|
+
return
|
|
217
|
+
try:
|
|
218
|
+
os.write(fd, str(os.getpid()).encode("ascii"))
|
|
219
|
+
yield True
|
|
220
|
+
finally:
|
|
221
|
+
try:
|
|
222
|
+
os.close(fd)
|
|
223
|
+
finally:
|
|
224
|
+
try:
|
|
225
|
+
lock_path.unlink(missing_ok=True)
|
|
226
|
+
except OSError:
|
|
227
|
+
pass
|
|
228
|
+
return
|
|
229
|
+
|
|
230
|
+
import fcntl
|
|
231
|
+
fd = -1
|
|
232
|
+
try:
|
|
233
|
+
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o600)
|
|
234
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
235
|
+
except OSError:
|
|
236
|
+
if fd >= 0:
|
|
237
|
+
try:
|
|
238
|
+
os.close(fd)
|
|
239
|
+
except OSError:
|
|
240
|
+
pass
|
|
241
|
+
yield False
|
|
242
|
+
return
|
|
243
|
+
try:
|
|
244
|
+
yield True
|
|
245
|
+
finally:
|
|
246
|
+
try:
|
|
247
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
248
|
+
except OSError:
|
|
249
|
+
pass
|
|
250
|
+
try:
|
|
251
|
+
os.close(fd)
|
|
252
|
+
except OSError:
|
|
253
|
+
pass
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _gc_stale_files(cache_root: Path, keep_names: set[str], pending: list[str] | None = None) -> list[str]:
|
|
257
|
+
"""物理清理历史版本 SQLite 快照;Windows 句柄占用时记录延迟回收。"""
|
|
258
|
+
remaining: list[str] = []
|
|
259
|
+
targets: set[str] = set(pending or [])
|
|
260
|
+
if cache_root.is_dir():
|
|
261
|
+
for entry in cache_root.iterdir():
|
|
262
|
+
if entry.is_file() and entry.suffix == ".sqlite3" and entry.name not in keep_names:
|
|
263
|
+
targets.add(entry.name)
|
|
264
|
+
for name in sorted(targets):
|
|
265
|
+
if name in keep_names:
|
|
266
|
+
continue
|
|
267
|
+
candidate = cache_root / name
|
|
268
|
+
if not candidate.exists():
|
|
269
|
+
continue
|
|
270
|
+
try:
|
|
271
|
+
if not candidate.is_symlink():
|
|
272
|
+
candidate.unlink()
|
|
273
|
+
except OSError:
|
|
274
|
+
remaining.append(name)
|
|
275
|
+
return remaining
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _http_request(
|
|
279
|
+
method: str,
|
|
280
|
+
url: str,
|
|
281
|
+
*,
|
|
282
|
+
timeout: float,
|
|
283
|
+
headers: dict[str, str] | None = None,
|
|
284
|
+
body: bytes | None = None,
|
|
285
|
+
max_bytes: int = MAX_BUNDLE_GZ_BYTES,
|
|
286
|
+
urlopen: Callable[..., Any] | None = None,
|
|
287
|
+
) -> tuple[int, dict[str, str], bytes]:
|
|
288
|
+
req_headers = {"Accept": "application/json", **client_headers()}
|
|
289
|
+
if headers:
|
|
290
|
+
req_headers.update(headers)
|
|
291
|
+
if body is not None and "Content-Type" not in req_headers:
|
|
292
|
+
req_headers["Content-Type"] = "application/json"
|
|
293
|
+
req = urllib.request.Request(url, data=body, method=method, headers=req_headers)
|
|
294
|
+
opener = urlopen or build_no_redirect_open(url)
|
|
295
|
+
try:
|
|
296
|
+
resp = opener(req, timeout=timeout)
|
|
297
|
+
except urllib.error.HTTPError as err:
|
|
298
|
+
err_body = err.read(MAX_REMOTE_JSON_BYTES)
|
|
299
|
+
err_headers = {str(k).lower(): str(v) for k, v in dict(getattr(err, "headers", {}) or {}).items()}
|
|
300
|
+
return int(err.code), err_headers, err_body
|
|
301
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
|
|
302
|
+
if urlopen is not None or not diagnose_network_error(exc, url).get("is_local_network_blocked"):
|
|
303
|
+
raise DocsSyncError(f"文档服务请求失败: {exc}") from exc
|
|
304
|
+
resp = trusted_curl_request(req, timeout)
|
|
305
|
+
|
|
306
|
+
status = int(getattr(resp, "status", 200) or 200)
|
|
307
|
+
resp_headers = {str(k).lower(): str(v) for k, v in dict(getattr(resp, "headers", {}) or {}).items()}
|
|
308
|
+
chunks: list[bytes] = []
|
|
309
|
+
total = 0
|
|
310
|
+
while True:
|
|
311
|
+
chunk = resp.read(65536)
|
|
312
|
+
if not chunk:
|
|
313
|
+
break
|
|
314
|
+
total += len(chunk)
|
|
315
|
+
if total > max_bytes:
|
|
316
|
+
raise DocsSyncError(f"远端响应体超过最大安全限制 ({max_bytes} bytes)")
|
|
317
|
+
chunks.append(chunk)
|
|
318
|
+
return status, resp_headers, b"".join(chunks)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _decompress_gzip_bounded(raw_gz: bytes, *, max_bytes: int = MAX_BUNDLE_SQLITE_BYTES) -> bytes:
|
|
322
|
+
"""防 Zip Bomb 流式限额解压,或在直接传未压缩 SQLite 时透传校验。"""
|
|
323
|
+
import io
|
|
324
|
+
if raw_gz.startswith(b"SQLite format 3\x00"):
|
|
325
|
+
if len(raw_gz) > max_bytes:
|
|
326
|
+
raise DocsSyncError("文档库体积超过安全限制")
|
|
327
|
+
return raw_gz
|
|
328
|
+
out = bytearray()
|
|
329
|
+
with gzip.GzipFile(fileobj=io.BytesIO(raw_gz), mode="rb") as gz:
|
|
330
|
+
while True:
|
|
331
|
+
chunk = gz.read(65536)
|
|
332
|
+
if not chunk:
|
|
333
|
+
break
|
|
334
|
+
if len(out) + len(chunk) > max_bytes:
|
|
335
|
+
raise DocsSyncError(f"解压后的文档库超过最大限制 ({max_bytes} bytes)")
|
|
336
|
+
out.extend(chunk)
|
|
337
|
+
return bytes(out)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _resolve_same_origin_url(base_url: str, target_url: str) -> str:
|
|
341
|
+
"""严防重定向或 manifest URL 指向非受控第三方域。"""
|
|
342
|
+
raw = str(target_url or "").strip()
|
|
343
|
+
if not raw:
|
|
344
|
+
raise DocsSyncError("manifest 缺少 bundle_url")
|
|
345
|
+
if raw.startswith("/"):
|
|
346
|
+
return f"{base_url}{raw}"
|
|
347
|
+
resolved = validate_base_url(raw) if "://" not in raw else raw
|
|
348
|
+
base_parts = urllib.parse.urlsplit(base_url)
|
|
349
|
+
target_parts = urllib.parse.urlsplit(resolved)
|
|
350
|
+
if target_parts.scheme not in {"http", "https"}:
|
|
351
|
+
raise DocsSyncError("拒绝非 http(s) bundle_url")
|
|
352
|
+
if target_parts.scheme == "http" and (target_parts.hostname or "").lower() not in {"127.0.0.1", "localhost", "::1"}:
|
|
353
|
+
raise DocsSyncError("拒绝非本地回环的明文 HTTP bundle_url")
|
|
354
|
+
if target_parts.netloc.lower() != base_parts.netloc.lower():
|
|
355
|
+
raise DocsSyncError(f"拒绝跨源下载文档包: {target_parts.netloc} != {base_parts.netloc}")
|
|
356
|
+
return resolved
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def sync_official_docs(
|
|
360
|
+
*,
|
|
361
|
+
contract_version: str | None = None,
|
|
362
|
+
force: bool = False,
|
|
363
|
+
offline: bool = False,
|
|
364
|
+
remote_url: str | None = None,
|
|
365
|
+
manifest_timeout: float = DEFAULT_MANIFEST_TIMEOUT,
|
|
366
|
+
bundle_timeout: float = DEFAULT_BUNDLE_TIMEOUT,
|
|
367
|
+
urlopen: Callable[..., Any] | None = None,
|
|
368
|
+
) -> dict[str, Any]:
|
|
369
|
+
"""同步 BugX 服务端官方文档快照至全局不可变缓存。"""
|
|
370
|
+
ver = contract_version_of(contract_version)
|
|
371
|
+
cache_root = docs_cache_dir(ver)
|
|
372
|
+
state = _read_current_state(cache_root)
|
|
373
|
+
existing_db = current_cached_db(ver)
|
|
374
|
+
|
|
375
|
+
if offline or docs_offline_disabled():
|
|
376
|
+
return {
|
|
377
|
+
"ok": True,
|
|
378
|
+
"status": "offline",
|
|
379
|
+
"contract_version": ver,
|
|
380
|
+
"db": str(existing_db) if existing_db else None,
|
|
381
|
+
"revision": state.get("revision"),
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
now = time.time()
|
|
385
|
+
if not force:
|
|
386
|
+
backoff_until = float(state.get("backoff_until") or 0)
|
|
387
|
+
if backoff_until > now:
|
|
388
|
+
return {
|
|
389
|
+
"ok": True,
|
|
390
|
+
"status": "backoff_cached",
|
|
391
|
+
"contract_version": ver,
|
|
392
|
+
"db": str(existing_db) if existing_db else None,
|
|
393
|
+
"revision": state.get("revision"),
|
|
394
|
+
}
|
|
395
|
+
ttl = max(60, int(state.get("ttl_seconds") or DEFAULT_TTL_SECONDS))
|
|
396
|
+
checked_at = float(state.get("checked_at") or 0)
|
|
397
|
+
if existing_db and checked_at > 0 and (checked_at + ttl) > now:
|
|
398
|
+
return {
|
|
399
|
+
"ok": True,
|
|
400
|
+
"status": "fresh_cached",
|
|
401
|
+
"contract_version": ver,
|
|
402
|
+
"db": str(existing_db),
|
|
403
|
+
"revision": state.get("revision"),
|
|
404
|
+
"sha256": state.get("sha256"),
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
try:
|
|
408
|
+
base_url = resolve_remote_base_url(remote_url)
|
|
409
|
+
except DocsSyncError as exc:
|
|
410
|
+
return {
|
|
411
|
+
"ok": False,
|
|
412
|
+
"status": "invalid_remote",
|
|
413
|
+
"error": str(exc),
|
|
414
|
+
"db": str(existing_db) if existing_db else None,
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
with _single_flight_lock(cache_root / "sync.lock") as acquired:
|
|
418
|
+
if not acquired:
|
|
419
|
+
return {
|
|
420
|
+
"ok": True,
|
|
421
|
+
"status": "locked_skip",
|
|
422
|
+
"contract_version": ver,
|
|
423
|
+
"db": str(existing_db) if existing_db else None,
|
|
424
|
+
"revision": state.get("revision"),
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
headers: dict[str, str] = {}
|
|
428
|
+
current_sha = str(state.get("sha256") or "")
|
|
429
|
+
if existing_db and _SHA256_RE.fullmatch(current_sha) and not force:
|
|
430
|
+
headers["If-None-Match"] = f'"{current_sha}"'
|
|
431
|
+
|
|
432
|
+
manifest_url = f"{base_url}{DOCS_MANIFEST_PATH}?contract_version={urllib.parse.quote(ver)}"
|
|
433
|
+
try:
|
|
434
|
+
status, _, body = _http_request(
|
|
435
|
+
"GET", manifest_url, timeout=manifest_timeout, headers=headers,
|
|
436
|
+
max_bytes=MAX_MANIFEST_BYTES, urlopen=urlopen,
|
|
437
|
+
)
|
|
438
|
+
except DocsSyncError as exc:
|
|
439
|
+
new_state = {**state, "backoff_until": now + DEFAULT_FAILURE_BACKOFF_SECONDS, "last_error": str(exc)}
|
|
440
|
+
try:
|
|
441
|
+
_write_current_state(cache_root, new_state)
|
|
442
|
+
except (OSError, AtomicWriteError):
|
|
443
|
+
pass
|
|
444
|
+
return {
|
|
445
|
+
"ok": False,
|
|
446
|
+
"status": "degraded_fallback",
|
|
447
|
+
"error": str(exc),
|
|
448
|
+
"db": str(existing_db) if existing_db else None,
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if status == 304 and existing_db:
|
|
452
|
+
gc_pending = _gc_stale_files(cache_root, {existing_db.name}, state.get("gc_pending"))
|
|
453
|
+
_write_current_state(cache_root, {
|
|
454
|
+
**state, "checked_at": now, "backoff_until": 0, "last_error": None, "gc_pending": gc_pending,
|
|
455
|
+
})
|
|
456
|
+
return {
|
|
457
|
+
"ok": True,
|
|
458
|
+
"status": "not_modified",
|
|
459
|
+
"contract_version": ver,
|
|
460
|
+
"db": str(existing_db),
|
|
461
|
+
"revision": state.get("revision"),
|
|
462
|
+
"sha256": current_sha,
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
if status != 200:
|
|
466
|
+
new_state = {
|
|
467
|
+
**state,
|
|
468
|
+
"backoff_until": now + DEFAULT_FAILURE_BACKOFF_SECONDS,
|
|
469
|
+
"last_error": f"HTTP {status}",
|
|
470
|
+
}
|
|
471
|
+
try:
|
|
472
|
+
_write_current_state(cache_root, new_state)
|
|
473
|
+
except (OSError, AtomicWriteError):
|
|
474
|
+
pass
|
|
475
|
+
return {
|
|
476
|
+
"ok": False,
|
|
477
|
+
"status": "degraded_fallback",
|
|
478
|
+
"http_status": status,
|
|
479
|
+
"error": f"manifest HTTP {status}",
|
|
480
|
+
"db": str(existing_db) if existing_db else None,
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
try:
|
|
484
|
+
envelope = json.loads(body.decode("utf-8"))
|
|
485
|
+
data = envelope.get("data") if isinstance(envelope, dict) and isinstance(envelope.get("data"), dict) else envelope
|
|
486
|
+
if not isinstance(data, dict):
|
|
487
|
+
raise DocsSyncError("manifest 响应结构非法")
|
|
488
|
+
remote_ver = str(data.get("contract_version") or "").strip()
|
|
489
|
+
if remote_ver != ver:
|
|
490
|
+
raise DocsSyncError(f"跨版本拒绝接收: 请求 {ver}, 服务端返回 {remote_ver!r}")
|
|
491
|
+
bundle_sha = str(data.get("bundle_sha256") or "").strip().lower()
|
|
492
|
+
if not _SHA256_RE.fullmatch(bundle_sha):
|
|
493
|
+
raise DocsSyncError("manifest bundle_sha256 格式非法")
|
|
494
|
+
schema_tag = str(data.get("schema") or DOCS_SCHEMA_VERSION).strip()
|
|
495
|
+
if schema_tag != DOCS_SCHEMA_VERSION:
|
|
496
|
+
raise DocsSyncError(f"不兼容的文档库 schema: {schema_tag}")
|
|
497
|
+
revision = int(data.get("revision") or 0)
|
|
498
|
+
ttl_sec = max(60, min(86400, int(data.get("ttl_seconds") or DEFAULT_TTL_SECONDS)))
|
|
499
|
+
except (ValueError, UnicodeDecodeError, TypeError, DocsSyncError) as exc:
|
|
500
|
+
return {
|
|
501
|
+
"ok": False,
|
|
502
|
+
"status": "rejected",
|
|
503
|
+
"error": str(exc),
|
|
504
|
+
"db": str(existing_db) if existing_db else None,
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if existing_db and current_sha == bundle_sha:
|
|
508
|
+
gc_pending = _gc_stale_files(cache_root, {existing_db.name}, state.get("gc_pending"))
|
|
509
|
+
_write_current_state(cache_root, {
|
|
510
|
+
**state, "revision": revision, "ttl_seconds": ttl_sec,
|
|
511
|
+
"checked_at": now, "backoff_until": 0, "last_error": None, "gc_pending": gc_pending,
|
|
512
|
+
})
|
|
513
|
+
return {
|
|
514
|
+
"ok": True,
|
|
515
|
+
"status": "up_to_date",
|
|
516
|
+
"contract_version": ver,
|
|
517
|
+
"db": str(existing_db),
|
|
518
|
+
"revision": revision,
|
|
519
|
+
"sha256": bundle_sha,
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
bundle_url = _resolve_same_origin_url(
|
|
523
|
+
base_url,
|
|
524
|
+
str(data.get("bundle_url") or f"{DOCS_BUNDLE_PATH}?contract_version={urllib.parse.quote(ver)}&sha256={bundle_sha}"),
|
|
525
|
+
)
|
|
526
|
+
try:
|
|
527
|
+
b_status, _, raw_wire = _http_request(
|
|
528
|
+
"GET", bundle_url, timeout=bundle_timeout, max_bytes=MAX_BUNDLE_GZ_BYTES, urlopen=urlopen,
|
|
529
|
+
)
|
|
530
|
+
if b_status != 200:
|
|
531
|
+
raise DocsSyncError(f"bundle 下载失败: HTTP {b_status}")
|
|
532
|
+
wire_digest = hashlib.sha256(raw_wire).hexdigest()
|
|
533
|
+
sqlite_bytes = _decompress_gzip_bounded(raw_wire, max_bytes=MAX_BUNDLE_SQLITE_BYTES)
|
|
534
|
+
sqlite_digest = hashlib.sha256(sqlite_bytes).hexdigest()
|
|
535
|
+
expected_sqlite_sha = str(data.get("sqlite_sha256") or "").strip().lower()
|
|
536
|
+
if expected_sqlite_sha:
|
|
537
|
+
if wire_digest != bundle_sha or sqlite_digest != expected_sqlite_sha:
|
|
538
|
+
raise DocsSyncError("文档包 SHA-256 校验失败,已拒绝写入")
|
|
539
|
+
elif bundle_sha not in {wire_digest, sqlite_digest}:
|
|
540
|
+
raise DocsSyncError("文档包 SHA-256 校验失败,已拒绝写入")
|
|
541
|
+
except DocsSyncError as exc:
|
|
542
|
+
return {
|
|
543
|
+
"ok": False,
|
|
544
|
+
"status": "rejected",
|
|
545
|
+
"error": str(exc),
|
|
546
|
+
"db": str(existing_db) if existing_db else None,
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
cache_root.mkdir(parents=True, mode=0o700, exist_ok=True)
|
|
550
|
+
tmp_db = cache_root / f".tmp-{os.getpid()}-{uuid.uuid4().hex[:8]}.sqlite3"
|
|
551
|
+
final_name = f"{sqlite_digest}.sqlite3"
|
|
552
|
+
final_db = cache_root / final_name
|
|
553
|
+
try:
|
|
554
|
+
tmp_db.write_bytes(sqlite_bytes)
|
|
555
|
+
if os.name != "nt":
|
|
556
|
+
tmp_db.chmod(0o600)
|
|
557
|
+
if not verify_sqlite_snapshot(tmp_db, ver):
|
|
558
|
+
raise DocsSyncError("文档库完整性或 schema 校验未通过")
|
|
559
|
+
os.replace(tmp_db, final_db)
|
|
560
|
+
except Exception as exc: # noqa: BLE001
|
|
561
|
+
try:
|
|
562
|
+
tmp_db.unlink(missing_ok=True)
|
|
563
|
+
except OSError:
|
|
564
|
+
pass
|
|
565
|
+
return {
|
|
566
|
+
"ok": False,
|
|
567
|
+
"status": "rejected",
|
|
568
|
+
"error": f"落盘校验失败: {exc}",
|
|
569
|
+
"db": str(existing_db) if existing_db else None,
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
gc_pending = _gc_stale_files(cache_root, {final_name}, state.get("gc_pending"))
|
|
573
|
+
_write_current_state(cache_root, {
|
|
574
|
+
"contract_version": ver,
|
|
575
|
+
"revision": revision,
|
|
576
|
+
"sha256": bundle_sha,
|
|
577
|
+
"sqlite_sha256": sqlite_digest,
|
|
578
|
+
"db_file": final_name,
|
|
579
|
+
"ttl_seconds": ttl_sec,
|
|
580
|
+
"checked_at": now,
|
|
581
|
+
"backoff_until": 0,
|
|
582
|
+
"last_error": None,
|
|
583
|
+
"source": "cloud",
|
|
584
|
+
"gc_pending": gc_pending,
|
|
585
|
+
})
|
|
586
|
+
return {
|
|
587
|
+
"ok": True,
|
|
588
|
+
"status": "updated",
|
|
589
|
+
"contract_version": ver,
|
|
590
|
+
"db": str(final_db),
|
|
591
|
+
"revision": revision,
|
|
592
|
+
"sha256": bundle_sha,
|
|
593
|
+
"gc_pending": gc_pending,
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def remote_search_docs(
|
|
598
|
+
query: str,
|
|
599
|
+
*,
|
|
600
|
+
contract_version: str | None = None,
|
|
601
|
+
limit: int = 5,
|
|
602
|
+
remote_url: str | None = None,
|
|
603
|
+
timeout: float = DEFAULT_SEARCH_TIMEOUT,
|
|
604
|
+
urlopen: Callable[..., Any] | None = None,
|
|
605
|
+
) -> dict[str, Any]:
|
|
606
|
+
"""透传官方公开文档检索请求(严格剥离本地 project_id 与业务上下文)。"""
|
|
607
|
+
if docs_offline_disabled():
|
|
608
|
+
raise DocsSyncError("已启用离线隔离模式,禁止远端文档检索")
|
|
609
|
+
ver = contract_version_of(contract_version)
|
|
610
|
+
base_url = resolve_remote_base_url(remote_url)
|
|
611
|
+
payload = json.dumps({
|
|
612
|
+
"contract_version": ver,
|
|
613
|
+
"query": str(query or "")[:512],
|
|
614
|
+
"limit": max(1, min(int(limit), 20)),
|
|
615
|
+
}, ensure_ascii=False).encode("utf-8")
|
|
616
|
+
status, _, body = _http_request(
|
|
617
|
+
"POST", f"{base_url}{DOCS_SEARCH_PATH}",
|
|
618
|
+
timeout=timeout, body=payload, max_bytes=MAX_REMOTE_JSON_BYTES, urlopen=urlopen,
|
|
619
|
+
)
|
|
620
|
+
if status != 200:
|
|
621
|
+
raise DocsSyncError(f"远端文档检索失败: HTTP {status}")
|
|
622
|
+
parsed = json.loads(body.decode("utf-8"))
|
|
623
|
+
data = parsed.get("data") if isinstance(parsed, dict) and isinstance(parsed.get("data"), dict) else parsed
|
|
624
|
+
if not isinstance(data, dict) or not isinstance(data.get("results"), list):
|
|
625
|
+
raise DocsSyncError("远端文档检索响应格式非法")
|
|
626
|
+
return data
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def remote_fetch_doc(
|
|
630
|
+
document_id: str,
|
|
631
|
+
*,
|
|
632
|
+
contract_version: str | None = None,
|
|
633
|
+
section: str = "",
|
|
634
|
+
remote_url: str | None = None,
|
|
635
|
+
timeout: float = DEFAULT_SEARCH_TIMEOUT,
|
|
636
|
+
urlopen: Callable[..., Any] | None = None,
|
|
637
|
+
) -> dict[str, Any]:
|
|
638
|
+
"""透传官方公开文档分段读取请求。"""
|
|
639
|
+
if docs_offline_disabled():
|
|
640
|
+
raise DocsSyncError("已启用离线隔离模式,禁止远端文档读取")
|
|
641
|
+
ver = contract_version_of(contract_version)
|
|
642
|
+
base_url = resolve_remote_base_url(remote_url)
|
|
643
|
+
payload = json.dumps({
|
|
644
|
+
"contract_version": ver,
|
|
645
|
+
"document_id": str(document_id or "")[:256],
|
|
646
|
+
"section": str(section or "")[:256],
|
|
647
|
+
}, ensure_ascii=False).encode("utf-8")
|
|
648
|
+
status, _, body = _http_request(
|
|
649
|
+
"POST", f"{base_url}{DOCS_FETCH_PATH}",
|
|
650
|
+
timeout=timeout, body=payload, max_bytes=MAX_REMOTE_JSON_BYTES, urlopen=urlopen,
|
|
651
|
+
)
|
|
652
|
+
if status != 200:
|
|
653
|
+
raise DocsSyncError(f"远端文档读取失败: HTTP {status}")
|
|
654
|
+
parsed = json.loads(body.decode("utf-8"))
|
|
655
|
+
data = parsed.get("data") if isinstance(parsed, dict) and isinstance(parsed.get("data"), dict) else parsed
|
|
656
|
+
if not isinstance(data, dict):
|
|
657
|
+
raise DocsSyncError("远端文档读取响应格式非法")
|
|
658
|
+
return data
|