dsh-bufeng 0.0.0-stage → 0.64.1

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 (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -2
  3. package/bufeng.patch.yml +3 -0
  4. package/client/build-client.mjs +159 -0
  5. package/client/client.js +4038 -0
  6. package/client/src/board.js +133 -0
  7. package/client/src/capabilities.js +787 -0
  8. package/client/src/cards.js +263 -0
  9. package/client/src/data.js +43 -0
  10. package/client/src/graph.js +558 -0
  11. package/client/src/icons.js +88 -0
  12. package/client/src/projects.js +467 -0
  13. package/client/src/prompt.js +55 -0
  14. package/client/src/react.js +7 -0
  15. package/client/src/settings.js +407 -0
  16. package/client/src/styles.js +611 -0
  17. package/client/src/taskboard.js +321 -0
  18. package/client/src/taskgraph.js +145 -0
  19. package/client/src/ui.js +72 -0
  20. package/lib/acceptance-subject.js +71 -0
  21. package/lib/board/server.js +546 -0
  22. package/lib/board/snapshot.js +133 -0
  23. package/lib/board/taskview.js +151 -0
  24. package/lib/bootstrap.js +77 -0
  25. package/lib/catalog.js +385 -0
  26. package/lib/core.js +478 -0
  27. package/lib/data/capability-alias-catalog.json +301 -0
  28. package/lib/data/capability-alias.json +25 -0
  29. package/lib/domain.js +1342 -0
  30. package/lib/host-probe.js +176 -0
  31. package/lib/identity-hook.js +490 -0
  32. package/lib/index.js +119 -0
  33. package/lib/lessons.js +134 -0
  34. package/lib/metering.js +109 -0
  35. package/lib/scope.js +389 -0
  36. package/lib/session/child-watch.js +86 -0
  37. package/lib/session/evidence.js +118 -0
  38. package/lib/session/node-session.js +335 -0
  39. package/lib/session/queue.js +307 -0
  40. package/lib/session/reconcile.js +500 -0
  41. package/lib/tools/capabilities.js +1461 -0
  42. package/lib/tools/governance.js +579 -0
  43. package/lib/tools/index.js +33 -0
  44. package/lib/tools/project.js +500 -0
  45. package/lib/tools/readonly.js +566 -0
  46. package/lib/tools/recover.js +402 -0
  47. package/lib/tools/run.js +1609 -0
  48. package/lib/tools/skills.js +162 -0
  49. package/lib/tools/trees.js +637 -0
  50. package/lib/workspace-rmw.js +365 -0
  51. package/package.json +42 -4
package/lib/catalog.js ADDED
@@ -0,0 +1,385 @@
1
+ /**
2
+ * lib/catalog.js — v0.60.0 S2a 官方 MCP 目录叶子模块。
3
+ * 设计:docs/设计/2026-10-29-能力面公网推荐与装备体验重设计-v2.md §二(目录抓取/缓存/归一化/离线降级三级;冻结 v2.1)。
4
+ * 叶子纪律:只 import node 内建(node:fs/node:path/node:http/node:https);禁 import lib/tools、lib/domain.js、lib/board、lib/core.js;
5
+ * fetch 注入契约保留(refreshOfficialCatalog 可由调用方传 fetchImpl);缺省=受控实现 createControlledFetch(v0.62.3:
6
+ * 宿主进程内 globalThis.fetch 被 dsh-http-proxy 启动器重定向到捆绑 userland undici 的全局 dispatcher,跨版本耦合下
7
+ * 连接可能长挂到 15s 超时 abort;受控实现走 node:https 直连绕开该全局槽,不依赖宿主进程网络面状态);缓存路径由调用方传入(BUFENG_DIR 口径归调用方)。
8
+ * 安全(§六):目录记录=元数据≠可执行≠安全审计(rawTrust 恒 'metadata-only');文本清洗去控制字符/折叠空白/截断;
9
+ * 本模块零安装 API、零自动启用——唯一写口=缓存快照文件(catalog 动作),suggest 只读。
10
+ * 离线降级三级:无缓存→no-cache 视图;fetchedAt>24h→stale=true 继续用;刷新失败→保留旧缓存+lastError(绝不抛给 suggest)。
11
+ */
12
+ import { readFileSync, writeFileSync, mkdirSync, renameSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import http from 'node:http';
15
+ import https from 'node:https';
16
+
17
+ /* ---------- 常量(设计 §二:源白名单硬编码,P1 唯一自动源) ---------- */
18
+ export const CATALOG_SOURCE = 'official-registry';
19
+ export const CATALOG_BASE_URL = 'https://registry.modelcontextprotocol.io/v0.1';
20
+ export const OFFICIAL_META_KEY = 'io.modelcontextprotocol.registry/official';
21
+ export const CATALOG_SCHEMA_VERSION = 1;
22
+ export const CATALOG_THROTTLE_MS = 60 * 60 * 1000; // 两次刷新尝试间隔 ≥60min(失败也记 lastAttemptAt 防打爆)
23
+ export const CATALOG_FULL_PERIOD_MS = 24 * 3600 * 1000; // 全量周期 24h,其余走增量
24
+ export const CATALOG_PAGE_LIMIT = 100;
25
+ export const CATALOG_MAX_PAGES = 20;
26
+ export const CATALOG_FETCH_TIMEOUT_MS = 15000; // HTTPS 15s 超时
27
+ export const CATALOG_MAX_BYTES = 5 * 1024 * 1024; // 单轮抓取累计响应体上限 5MB
28
+ export const CATALOG_MAX_SERVERS = 5000; // servers≤5000
29
+ export const CATALOG_DESC_MAX = 500; // description≤500
30
+
31
+ /* ---------- v0.63.x B截(ADR 2026-11-06-目录刷新限流韧性-页间缓冲与退避重试.md):全量翻页渐进限流韧性参数 ----------
32
+ * 缺陷实证:registry/CDN 对同源连续快速重页渐进限流(leaky-bucket,阈值≈连续 5-7 重页,冷却数十秒至数分钟),
33
+ * 客户实机 2026-11-06 21:42 全量刷新死于第 ~5 页 AbortError code=20(诊断出处=2026-11-03 ADR §7.2 第二因子)。
34
+ * 缺省仅对真实网络通道(未传 fetchImpl=缺省受控实现,或 createControlledFetch 产物——CONTROLLED_FETCH_MARK 标记面)生效;
35
+ * 注入替身(测试桩)通道全 0——外呼计数与套件耗时与旧码逐字节等价(既有判据零漂移);显式参数恒覆盖(判据注入 0 防真睡)。 */
36
+ export const CATALOG_PAGE_GAP_MS = 400; // 页间缓冲:第 2 页起请求前等待 400ms(数百 ms 级:registry 单页正常耗时 1-8s,400ms 只削峰不拖慢)
37
+ export const CATALOG_PAGE_RETRIES = 3; // 单页退避重试上限(总尝试=1+3;abort/超时/HTTP≥400/网络错/json 解析错皆重试)
38
+ export const CATALOG_RETRY_BASE_MS = 500; // 退避基数:第 n 次重试前等 base×2^(n-1) ms(500/1000/2000,单页总退避 ≤3.5s,总尝试时长有界)
39
+
40
+ const CONTROLLED_FETCH_MARK = Symbol('bufeng.catalog.controlledFetch'); // 受控实现标记面:createControlledFetch 产物唯一识别(注入替身不带标记→零时序副作用)
41
+
42
+ /** 目录缓存硬锚:<BUFENG_DIR>/catalog/official-registry.json(BUFENG_DIR 由调用方传入口径,本模块不 import core)。 */
43
+ export function officialCatalogPath(bufengDir) {
44
+ return join(String(bufengDir ?? ''), 'catalog', 'official-registry.json');
45
+ }
46
+
47
+ /** 展示文本清洗(安全 §六-②注入防护):去控制字符、折叠空白、截断。 */
48
+ function sanitizeText(value, max = CATALOG_DESC_MAX) {
49
+ const cap = Number.isInteger(max) && max > 0 ? max : CATALOG_DESC_MAX;
50
+ return String(value ?? '')
51
+ .replace(/[\u0000-\u001f\u007f]+/g, ' ')
52
+ .replace(/\s+/g, ' ')
53
+ .trim()
54
+ .slice(0, cap);
55
+ }
56
+
57
+ /**
58
+ * 归一化一条官方 Registry 条目(设计 §二归一化形状)。
59
+ * 缺 server.name→null(丢弃);status=deleted→{serverName,status:'deleted'}(全量=不入场,增量=剔除既有行);
60
+ * 缺 description 用 title 兜底;packages/remotes 皆空仍保留并标 notInstallable。
61
+ */
62
+ export function normalizeRegistryEntry(entry, fetchedAtIso) {
63
+ const srv = entry && typeof entry === 'object' ? entry.server : null;
64
+ if (!srv || typeof srv !== 'object') return null;
65
+ const meta = (entry._meta && typeof entry._meta === 'object' ? entry._meta[OFFICIAL_META_KEY] : null) ?? {};
66
+ const serverName = typeof srv.name === 'string' && srv.name.trim() ? srv.name.trim() : null;
67
+ if (!serverName) return null; // 缺 name 丢弃
68
+ const status = String(meta.status ?? 'active').trim().toLowerCase() || 'active';
69
+ if (status === 'deleted') return { serverName, status: 'deleted' };
70
+ const description = sanitizeText(srv.description) || sanitizeText(srv.title); // ≤500;缺 description 用 title 兜底
71
+ const packages = (Array.isArray(srv.packages) ? srv.packages : []).slice(0, 8).map((p) => ({
72
+ registryType: sanitizeText(p?.registryType, 40),
73
+ identifier: sanitizeText(p?.identifier, 200),
74
+ version: sanitizeText(p?.version, 40),
75
+ transport: { type: sanitizeText(p?.transport?.type, 40) }
76
+ })).filter((p) => p.identifier);
77
+ const remotes = (Array.isArray(srv.remotes) ? srv.remotes : []).slice(0, 8).map((r) => ({
78
+ type: sanitizeText(r?.type, 40),
79
+ url: sanitizeText(r?.url, 500)
80
+ })).filter((r) => r.url || r.type);
81
+ const title = sanitizeText(srv.title, 200) || serverName;
82
+ const version = sanitizeText(srv.version, 40) || (packages[0] ? packages[0].version : '');
83
+ return {
84
+ source: CATALOG_SOURCE,
85
+ serverName,
86
+ title,
87
+ description,
88
+ version,
89
+ status, // deprecated 保留标注;deleted 已在上行剔除
90
+ isLatest: meta.isLatest === true ? true : meta.isLatest === false ? false : null,
91
+ packages,
92
+ remotes,
93
+ homepage: sanitizeText(srv.websiteUrl, 500) || null,
94
+ repository: sanitizeText(srv.repository?.url, 500) || null,
95
+ notInstallable: !(packages.length > 0 || remotes.length > 0),
96
+ updatedAt: sanitizeText(meta.updatedAt, 40) || sanitizeText(meta.publishedAt, 40) || null,
97
+ fetchedAt: fetchedAtIso,
98
+ rawTrust: 'metadata-only' // 目录记录=元数据≠安全审计
99
+ };
100
+ }
101
+
102
+ /** 双 version 组取最新:isLatest===true 优先 → updatedAt ISO 字典序 → version。 */
103
+ export function registryEntryNewer(a, b) {
104
+ if (!b) return true;
105
+ if ((a.isLatest === true) !== (b.isLatest === true)) return a.isLatest === true;
106
+ const ua = String(a.updatedAt ?? '');
107
+ const ub = String(b.updatedAt ?? '');
108
+ if (ua !== ub) return ua > ub;
109
+ return String(a.version ?? '') > String(b.version ?? '');
110
+ }
111
+
112
+ function upsertServer(map, row) {
113
+ if (row.status === 'deleted') { map.delete(row.serverName); return; } // deleted 剔除
114
+ const old = map.get(row.serverName);
115
+ if (registryEntryNewer(row, old)) map.set(row.serverName, row);
116
+ }
117
+
118
+ /** 读缓存(只读)。ENOENT/ENOTDIR→no-cache;JSON 解析失败→缓存损坏;schemaVersion 不识别→按空缓存不炸(均带 reason 不抛错)。 */
119
+ export function readOfficialCatalog(cachePath) {
120
+ let raw;
121
+ try {
122
+ raw = readFileSync(cachePath, 'utf8');
123
+ } catch (err) {
124
+ if (err && (err.code === 'ENOENT' || err.code === 'ENOTDIR')) {
125
+ return { cache: null, reason: 'no-cache(尚无目录缓存)——先跑 action=catalog 刷新' };
126
+ }
127
+ return { cache: null, reason: '缓存读取失败——先跑 action=catalog 覆盖重建' };
128
+ }
129
+ let data = null;
130
+ try { data = JSON.parse(raw); } catch { return { cache: null, reason: '缓存损坏(JSON 解析失败)——重跑 action=catalog 覆盖重建' }; }
131
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { cache: null, reason: '缓存形状不识别——重跑 action=catalog 覆盖重建' };
132
+ if (data.schemaVersion !== CATALOG_SCHEMA_VERSION) {
133
+ return { cache: null, reason: '缓存 schemaVersion=' + JSON.stringify(data.schemaVersion) + ' 不识别——按空缓存处理(重跑 action=catalog)' };
134
+ }
135
+ return { cache: data };
136
+ }
137
+
138
+ /** 原子写(tmp+rename,同 saveLedger 先例):临时文件以 .tmp 结尾且 rename 后零残留(A10)。 */
139
+ export function writeOfficialCatalog(cachePath, cache) {
140
+ mkdirSync(dirname(cachePath), { recursive: true });
141
+ const tmp = cachePath + '.' + process.pid + '.' + Date.now().toString(36) + '.tmp';
142
+ writeFileSync(tmp, JSON.stringify(cache), 'utf8');
143
+ renameSync(tmp, cachePath);
144
+ }
145
+
146
+ /* ---------- 受控 fetch(v0.62.3 根因修复:目录拉取不走宿主进程内被替换的 undici 全局槽) ----------
147
+ * 证据链:宿主启动器(@deepseek-ai/dsh-http-proxy)在首个插件挂载前 setGlobalDispatcher(捆绑 userland undici Agent),
148
+ * 即便无代理策略也装 direct Agent;Node 内建 fetch(内建 undici)经 legacy 全局槽驱动跨版本 Agent——该耦合
149
+ * 「not a contract」(宿主 Dev Note 自认),实测宿主进程内对官方目录域连接 15s 不落定(ADR:2026-11-03-catalog拉取15s-abort)。
150
+ * 受控实现:node:https/http 直连;每请求新建连接(keepAlive:false,不复用任何进程级连接池状态);
151
+ * connect family:4(IPv4 优先,绕 AAAA 黑洞);servername=hostname 保 SNI;AbortSignal→req.destroy(文案同 undici)。 */
152
+
153
+ /** AbortError 形态(与 undici 内建 fetch 同文案/同 name):signal.reason 为 Error 时原样透传。 */
154
+ function abortErrorOf(signal) {
155
+ const r = signal && signal.reason;
156
+ if (r instanceof Error) return r;
157
+ const e = new Error('This operation was aborted');
158
+ e.name = 'AbortError';
159
+ e.code = 'ABORT_ERR';
160
+ return e;
161
+ }
162
+
163
+ /** 失败语义描述(R3 证据链增强):message + err.code + err.cause.{code,message} 拼串,≤300 字;
164
+ * 无 code/cause 时与旧文案(String(err.message||err).slice(0,300))逐字兼容。 */
165
+ export function describeFetchError(err) {
166
+ const parts = [String((err && err.message) || err)];
167
+ if (err && err.code) parts.push('code=' + err.code);
168
+ const cause = err && err.cause;
169
+ if (cause && typeof cause === 'object') {
170
+ if (cause.code) parts.push('cause.code=' + cause.code);
171
+ if (cause.message) parts.push('cause=' + String(cause.message).slice(0, 120));
172
+ }
173
+ return parts.join(' | ').slice(0, 300);
174
+ }
175
+
176
+ /** 构造受控 fetch 实现:返回 async (url, init) => {ok,status,statusText,headers,json(),text()},与 fetchOfficialEntries 消费面兼容。 */
177
+ export function createControlledFetch({ family = 4 } = {}) {
178
+ const controlledFetch = async function controlledFetch(url, init = {}) {
179
+ const u = new URL(String(url));
180
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
181
+ if (!lib) throw new Error('受控 fetch 仅支持 http(s)(收到 ' + u.protocol + ')');
182
+ const headers = {};
183
+ for (const [k, v] of Object.entries(init.headers ?? {})) headers[k] = String(v);
184
+ const signal = init.signal ?? null;
185
+ if (signal && signal.aborted) throw abortErrorOf(signal);
186
+ const agent = new lib.Agent({ keepAlive: false }); // 每请求新建连接:不共享任何连接池/全局状态
187
+ return await new Promise((resolve, reject) => {
188
+ let settled = false;
189
+ const req = lib.request({
190
+ hostname: u.hostname,
191
+ port: u.port || (u.protocol === 'https:' ? 443 : 80),
192
+ path: u.pathname + u.search,
193
+ method: init.method ?? 'GET',
194
+ headers,
195
+ agent,
196
+ family, // IPv4 优先
197
+ servername: u.hostname // 保 SNI(CDN/证书校验)
198
+ }, (res) => {
199
+ const chunks = [];
200
+ res.on('data', (c) => chunks.push(c));
201
+ res.on('error', (e) => { if (!settled) { settled = true; agent.destroy(); reject(e); } });
202
+ res.on('end', () => {
203
+ if (settled) return;
204
+ settled = true;
205
+ agent.destroy();
206
+ const body = Buffer.concat(chunks).toString('utf8');
207
+ const status = res.statusCode ?? 0;
208
+ resolve({
209
+ ok: status >= 200 && status < 300,
210
+ status,
211
+ statusText: res.statusMessage ?? '',
212
+ headers: res.headers,
213
+ json: async () => JSON.parse(body),
214
+ text: async () => body
215
+ });
216
+ });
217
+ });
218
+ req.on('error', (e) => { if (!settled) { settled = true; agent.destroy(); reject(e); } });
219
+ if (signal) {
220
+ const onAbort = () => {
221
+ const e = abortErrorOf(signal);
222
+ if (!settled) req.destroy(e); // 触发 req error → reject(同 undici AbortError 文案)
223
+ };
224
+ if (typeof signal.addEventListener === 'function') {
225
+ signal.addEventListener('abort', onAbort, { once: true });
226
+ req.on('close', () => signal.removeEventListener('abort', onAbort));
227
+ }
228
+ }
229
+ req.end();
230
+ });
231
+ };
232
+ controlledFetch[CONTROLLED_FETCH_MARK] = true; // 韧性缺省解析标记面(B截 ADR):catalog.js 自产受控实现唯一识别——带标记=真实网络通道→页间缓冲/退避重试缺省开
233
+ return controlledFetch;
234
+ }
235
+
236
+ /** 单页等待辅助:ms>0 真睡(setTimeout),0/负数立即放行(判据注入 0 防真睡)。 */
237
+ function catalogSleep(ms) {
238
+ return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
239
+ }
240
+
241
+ /** 抓取官方 Registry 条目(fetchImpl 注入优先,缺省=受控实现):全量=limit=100 游标翻页;增量=updated_since+version=latest;≤20 页、15s 超时、5MB 上限。
242
+ * 韧性(B截 ADR 2026-11-06-目录刷新限流韧性):①页间缓冲 pageGapMs——第 2 页起请求前隔 ≥gapMs,缓释同源连续重页渐进限流;
243
+ * ②单页失败(abort/超时/HTTP≥400/网络错/JSON 解析错)退避重试 pageRetries 次——退避 retryBaseMs×2^(n-1),重试复用同 URL(同 cursor),
244
+ * 单页超时 15 秒(常量定义见文件头)每次尝试独立计时不放宽为无界;重试耗尽抛原始错误(refreshOfficialCatalog catch 臂承接,形状不变)。
245
+ * 韧性缺省自动解析:真实网络通道(未传 fetchImpl,或传入 createControlledFetch 产物——CONTROLLED_FETCH_MARK 标记面)→ 生产参数;
246
+ * 注入替身(测试桩,无标记)→ 全 0(外呼计数/套件耗时与旧码逐字节等价);显式传有限数 ≥0 恒覆盖(Math.max(0,·) 钳制)。 */
247
+ export async function fetchOfficialEntries({ fetchImpl, baseUrl = CATALOG_BASE_URL, since = null, pageGapMs = null, pageRetries = null, retryBaseMs = null }) {
248
+ const injected = typeof fetchImpl === 'function' ? fetchImpl : null;
249
+ const doFetch = injected ?? createControlledFetch(); // v0.62.3:缺省受控,绕开宿主全局 fetch 槽
250
+ const resilient = injected === null || injected[CONTROLLED_FETCH_MARK] === true; // 真实网络通道才缺省开韧性
251
+ const gapMs = Number.isFinite(pageGapMs) ? Math.max(0, pageGapMs) : (resilient ? CATALOG_PAGE_GAP_MS : 0);
252
+ const retries = Number.isFinite(pageRetries) ? Math.max(0, Math.floor(pageRetries)) : (resilient ? CATALOG_PAGE_RETRIES : 0);
253
+ const backoffMs = Number.isFinite(retryBaseMs) ? Math.max(0, retryBaseMs) : CATALOG_RETRY_BASE_MS;
254
+ const entries = [];
255
+ let cursor = null;
256
+ let bytes = 0;
257
+ for (let page = 0; page < CATALOG_MAX_PAGES; page += 1) {
258
+ const params = new URLSearchParams({ limit: String(CATALOG_PAGE_LIMIT) });
259
+ if (since) { params.set('updated_since', since); params.set('version', 'latest'); }
260
+ if (cursor) params.set('cursor', cursor);
261
+ const url = baseUrl + '/servers?' + params.toString(); // 页内重试复用同 URL(同 cursor)
262
+ if (page > 0) await catalogSleep(gapMs); // 页间缓冲:第 2 页起请求前隔 ≥gapMs(渐进限流缓释)
263
+ let body = null;
264
+ for (let attempt = 0; ; attempt += 1) {
265
+ const ctl = new AbortController();
266
+ const timer = setTimeout(() => ctl.abort(), CATALOG_FETCH_TIMEOUT_MS); // 单页 15s 超时:每次尝试独立计时,不放宽为无界
267
+ try {
268
+ const res = await doFetch(url, { signal: ctl.signal, headers: { accept: 'application/json' } });
269
+ if (!res || res.ok === false || (typeof res.status === 'number' && res.status >= 400)) {
270
+ throw new Error('官方目录 HTTP ' + (res ? res.status : '无响应'));
271
+ }
272
+ body = typeof res.json === 'function' ? await res.json() : null;
273
+ break; // 本页成功:跳出尝试环
274
+ } catch (err) {
275
+ if (attempt >= retries) throw err; // 重试耗尽:抛原始错误(catch 臂 describeFetchError 形状不变)
276
+ await catalogSleep(backoffMs * 2 ** attempt); // 退避后重试同 URL(500/1000/2000…,单页总退避 ≤3.5s)
277
+ } finally { clearTimeout(timer); }
278
+ }
279
+ if (!body || typeof body !== 'object') throw new Error('官方目录响应形状不识别(非 JSON 对象)');
280
+ bytes += JSON.stringify(body).length;
281
+ if (bytes > CATALOG_MAX_BYTES) throw new Error('官方目录响应超上限(>5MB)');
282
+ for (const e of Array.isArray(body.servers) ? body.servers : []) entries.push(e);
283
+ cursor = body.metadata && typeof body.metadata.nextCursor === 'string' && body.metadata.nextCursor ? body.metadata.nextCursor : null;
284
+ if (!cursor) break;
285
+ }
286
+ return entries;
287
+ }
288
+
289
+ /** cache→视图(available/ageMs/stale;source 恒官方源)。 */
290
+ export function catalogView(cache, now = Date.now()) {
291
+ const fetchedAt = cache && typeof cache.fetchedAt === 'string' ? cache.fetchedAt : null;
292
+ const ageMs = fetchedAt ? now - Date.parse(fetchedAt) : null;
293
+ return {
294
+ source: CATALOG_SOURCE,
295
+ fetchedAt,
296
+ ageMs: Number.isFinite(ageMs) ? ageMs : null,
297
+ stale: Number.isFinite(ageMs) ? ageMs > CATALOG_FULL_PERIOD_MS : false,
298
+ available: true
299
+ };
300
+ }
301
+
302
+ /**
303
+ * 刷新官方目录缓存(catalog 动作唯一缓存写口)。限流模型(S1 判据推演锁定):
304
+ * 节流判据=lastAttemptAt 新鲜度(<60min 且 age≥0→throttled 纯读零写);全量成功写 lastAttemptAt=null(下次可立即增量);
305
+ * 增量成功/失败写 lastAttemptAt=now(60min 窗口);失败保留旧 servers/fetchedAt 只写 lastError+lastAttemptAt。
306
+ * mode 判定:无缓存或 fetchedAt 距今 ≥24h→full,否则 incremental。
307
+ */
308
+ export async function refreshOfficialCatalog({ cachePath, fetchImpl, now = Date.now(), baseUrl = CATALOG_BASE_URL }) {
309
+ const nowIso = new Date(now).toISOString();
310
+ const read = readOfficialCatalog(cachePath);
311
+ const cache = read.cache;
312
+ const prevView = cache ? catalogView(cache, now) : { source: CATALOG_SOURCE, fetchedAt: null, ageMs: null, stale: false, available: false };
313
+ const prevServers = cache && Array.isArray(cache.servers) ? cache.servers : [];
314
+ if (cache && typeof cache.lastAttemptAt === 'string' && cache.lastAttemptAt) {
315
+ const sinceAttempt = now - Date.parse(cache.lastAttemptAt);
316
+ if (Number.isFinite(sinceAttempt) && sinceAttempt >= 0 && sinceAttempt < CATALOG_THROTTLE_MS) {
317
+ return {
318
+ mode: 'throttled', refreshed: false,
319
+ fetchedAt: prevView.fetchedAt, ageMs: prevView.ageMs, stale: prevView.stale, available: prevView.available,
320
+ serverCount: prevServers.length, lastError: cache.lastError ?? null,
321
+ reason: '限流窗口内(上次尝试 ' + Math.round(sinceAttempt / 60000) + ' 分钟前 <60min)——复用缓存零外呼;需强制刷新先删缓存文件'
322
+ };
323
+ }
324
+ }
325
+ const fetchedAge = prevView.fetchedAt ? now - Date.parse(prevView.fetchedAt) : null;
326
+ const fullDue = !prevView.fetchedAt || !Number.isFinite(fetchedAge) || fetchedAge >= CATALOG_FULL_PERIOD_MS;
327
+ const mode = fullDue ? 'full' : 'incremental';
328
+ try {
329
+ const since = mode === 'incremental' ? (cache.lastIncrementalAt ?? cache.fetchedAt ?? null) : null;
330
+ const entries = await fetchOfficialEntries({ fetchImpl, baseUrl, since });
331
+ const map = new Map();
332
+ if (mode === 'incremental') for (const s of prevServers) if (s && s.serverName) map.set(s.serverName, s);
333
+ for (const e of entries) {
334
+ const row = normalizeRegistryEntry(e, nowIso);
335
+ if (!row) continue; // 缺 name 丢弃
336
+ upsertServer(map, row); // deleted 剔除;双 version 取最新
337
+ }
338
+ const servers = [...map.values()].slice(0, CATALOG_MAX_SERVERS);
339
+ const next = {
340
+ schemaVersion: CATALOG_SCHEMA_VERSION,
341
+ source: CATALOG_SOURCE,
342
+ baseUrl,
343
+ fetchedAt: mode === 'incremental' ? prevView.fetchedAt : nowIso, // fetchedAt=最近一次全量时间(24h 全量周期依据)
344
+ lastIncrementalAt: nowIso,
345
+ lastAttemptAt: mode === 'incremental' ? nowIso : null, // 全量成功重置限流戳;增量成功落 now
346
+ lastError: null,
347
+ servers
348
+ };
349
+ writeOfficialCatalog(cachePath, next);
350
+ return {
351
+ mode, refreshed: true, fetchedAt: next.fetchedAt, ageMs: now - Date.parse(next.fetchedAt), stale: false,
352
+ available: true, serverCount: servers.length, lastError: null, reason: null
353
+ };
354
+ } catch (err) {
355
+ const failed = {
356
+ schemaVersion: CATALOG_SCHEMA_VERSION,
357
+ source: CATALOG_SOURCE,
358
+ baseUrl,
359
+ fetchedAt: prevView.fetchedAt,
360
+ lastIncrementalAt: cache && typeof cache.lastIncrementalAt === 'string' ? cache.lastIncrementalAt : null,
361
+ lastAttemptAt: nowIso, // 失败也记 lastAttemptAt(防打爆)
362
+ lastError: describeFetchError(err), // v0.62.3 R3:带 err.code/err.cause(证据链可观测),无 cause 时与旧文案逐字兼容
363
+ servers: prevServers // 保留旧缓存不丢
364
+ };
365
+ try { writeOfficialCatalog(cachePath, failed); } catch { /* 盘故障:只披露不抛给调用方 */ }
366
+ return {
367
+ mode, refreshed: false, fetchedAt: prevView.fetchedAt, ageMs: prevView.ageMs, stale: prevServers.length > 0,
368
+ available: prevServers.length > 0, serverCount: prevServers.length,
369
+ lastError: failed.lastError, reason: '刷新失败:' + failed.lastError
370
+ };
371
+ }
372
+ }
373
+
374
+ /** suggest 侧只读快照:{view:{source,fetchedAt,ageMs,stale,available,reason?},servers[]}(无缓存/损坏/不识别→available=false+reason,零外呼零写)。 */
375
+ export function catalogSnapshotFor(cachePath, now = Date.now()) {
376
+ const read = readOfficialCatalog(cachePath);
377
+ if (!read.cache) {
378
+ return {
379
+ view: { source: CATALOG_SOURCE, fetchedAt: null, ageMs: null, stale: false, available: false, reason: read.reason },
380
+ servers: []
381
+ };
382
+ }
383
+ const view = catalogView(read.cache, now);
384
+ return { view, servers: Array.isArray(read.cache.servers) ? read.cache.servers : [] };
385
+ }