@mebular/mcp 0.2.4 → 0.3.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.
@@ -12,10 +12,12 @@
12
12
  // 全部外部交互(健康探针 / 重启通道 / 时钟)可注入,便于 hermetic 测试;零 core 依赖。
13
13
 
14
14
  import { spawn } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
15
16
  import { existsSync } from 'node:fs';
16
17
  import { copyFile, readFile, rename, rm, writeFile } from 'node:fs/promises';
17
18
  import { join } from 'node:path';
18
19
  import { CONFIG_SCHEMA_BY_PATH } from './config-schema.mjs';
20
+ import { acquireConfigFileLock } from './config-lock.mjs';
19
21
 
20
22
  export const APPLY_RESULT_FILE = 'config-apply.result.json';
21
23
  export const APPLY_PENDING_FILE = 'config-apply.pending.json';
@@ -161,10 +163,197 @@ export function spawnSupervisor({ supervisorPath, args, env = process.env, spawn
161
163
  export const readJoinError = (home) => readJson(joinErrorPath(home));
162
164
 
163
165
  /** 还原备份(config.json ← config.json.bak)。返回是否真的还原了。 */
164
- export async function restoreBackup({ configFile, backupFile = `${configFile}.bak`, copyFileImpl = copyFile }) {
165
- if (!existsSync(backupFile)) return false;
166
- await copyFileImpl(backupFile, configFile);
167
- return true;
166
+ export async function restoreBackup({
167
+ configFile,
168
+ backupFile = `${configFile}.bak`,
169
+ copyFileImpl = copyFile,
170
+ expectedConfigHash = null,
171
+ }) {
172
+ const releaseConfigLock = await acquireConfigFileLock(configFile);
173
+ if (!releaseConfigLock) {
174
+ const error = new Error(`配置文件正在被其他进程写入:${configFile}`);
175
+ error.code = 'CONFIG_BUSY';
176
+ throw error;
177
+ }
178
+ try {
179
+ if (expectedConfigHash) {
180
+ const actual = await configFileHash(configFile);
181
+ if (actual !== expectedConfigHash) {
182
+ const error = new Error('当前配置文件已变化:拒绝恢复备份');
183
+ error.code = 'CONFIG_CHANGED';
184
+ throw error;
185
+ }
186
+ }
187
+ if (!existsSync(backupFile)) return false;
188
+ await copyFileImpl(backupFile, configFile);
189
+ return true;
190
+ } finally {
191
+ await releaseConfigLock();
192
+ }
193
+ }
194
+
195
+ /** pending 的完整身份:attempt/applyId/at/fields 任一变化都视为另一条 apply。 */
196
+ function pendingIdentity(pending) {
197
+ const record = pending && typeof pending === 'object' ? pending : {};
198
+ return {
199
+ attempt: record.attempt ?? null,
200
+ applyId: typeof record.applyId === 'string' ? record.applyId : null,
201
+ at: typeof record.at === 'string' ? record.at : null,
202
+ fields: Array.isArray(record.fields) ? record.fields.map(String) : [],
203
+ };
204
+ }
205
+
206
+ function samePendingIdentity(left, right) {
207
+ return left.attempt === right.attempt
208
+ && left.applyId === right.applyId
209
+ && left.at === right.at
210
+ && left.fields.length === right.fields.length
211
+ && left.fields.every((value, index) => value === right.fields[index]);
212
+ }
213
+
214
+ async function configFileHash(configFile) {
215
+ try {
216
+ return createHash('sha256').update(await readFile(configFile)).digest('hex');
217
+ } catch {
218
+ return null;
219
+ }
220
+ }
221
+
222
+ function rollbackSkippedRecord({
223
+ pending,
224
+ backupFile,
225
+ reason,
226
+ skipReason,
227
+ expectedConfigHash = null,
228
+ actualConfigHash = null,
229
+ configChanged = false,
230
+ }) {
231
+ return {
232
+ status: 'rollback-skipped',
233
+ attempt: pending.attempt ?? null,
234
+ applyId: pending.applyId ?? null,
235
+ at: new Date().toISOString(),
236
+ fields: Array.isArray(pending.fields) ? pending.fields : [],
237
+ reason,
238
+ skipReason,
239
+ ...(configChanged ? { configChanged: true } : {}),
240
+ restored: false,
241
+ backup: backupFile,
242
+ expectedConfigHash,
243
+ actualConfigHash,
244
+ recovered: false,
245
+ retries: Number(pending.attempts ?? 1),
246
+ };
247
+ }
248
+
249
+ async function recordAndClearMatchingPending({ home, pending, record }) {
250
+ await writeApplyResult(home, record);
251
+ // 恢复期间可能已有新的 apply 写入 pending:只有同一完整身份才允许清理。
252
+ const current = await readApplyPending(home);
253
+ if (current
254
+ && current.rollingBack === true
255
+ && samePendingIdentity(pendingIdentity(current), pendingIdentity(pending))) {
256
+ await clearApplyPending(home);
257
+ }
258
+ return record;
259
+ }
260
+
261
+ /** 生产启动/下次 apply:有界重试 rollingBack 的 restore;成功清理 pending,失败保留可重试状态。 */
262
+ export async function recoverPendingRollback({
263
+ home,
264
+ configFile = join(home, 'config.json'),
265
+ backupFile = `${configFile}.bak`,
266
+ log = () => {},
267
+ restoreImpl = restoreBackup,
268
+ } = {}) {
269
+ const pending = await readApplyPending(home);
270
+ if (!pending || pending.rollingBack !== true) return { status: 'not_pending' };
271
+ const fields = Array.isArray(pending.fields) ? pending.fields : [];
272
+ const expectedConfigHash = typeof pending.failedConfigHash === 'string' ? pending.failedConfigHash : null;
273
+ const actualConfigHash = await configFileHash(configFile);
274
+ if (!expectedConfigHash) {
275
+ const record = rollbackSkippedRecord({
276
+ pending,
277
+ backupFile,
278
+ reason: '缺少失败配置指纹:无法证明当前配置仍是失败 apply 的产物,拒绝覆盖',
279
+ skipReason: 'missing_config_hash',
280
+ actualConfigHash,
281
+ });
282
+ log('apply: rollingBack pending 缺少配置指纹,跳过自动恢复');
283
+ return recordAndClearMatchingPending({ home, pending, record });
284
+ }
285
+ if (actualConfigHash !== expectedConfigHash) {
286
+ const record = rollbackSkippedRecord({
287
+ pending,
288
+ backupFile,
289
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
290
+ skipReason: 'config_changed',
291
+ expectedConfigHash,
292
+ actualConfigHash,
293
+ configChanged: true,
294
+ });
295
+ log('apply: 当前配置已变化,跳过 rollingBack pending');
296
+ return recordAndClearMatchingPending({ home, pending, record });
297
+ }
298
+ try {
299
+ const restored = await restoreImpl({ configFile, backupFile, expectedConfigHash });
300
+ if (!restored) {
301
+ const error = new Error('回滚备份不存在');
302
+ error.code = 'BACKUP_MISSING';
303
+ throw error;
304
+ }
305
+ const record = {
306
+ status: 'rolled-back',
307
+ attempt: pending.attempt ?? null,
308
+ applyId: pending.applyId ?? null,
309
+ at: new Date().toISOString(),
310
+ fields,
311
+ reason: pending.reason ?? null,
312
+ restored: true,
313
+ backup: backupFile,
314
+ expectedConfigHash,
315
+ actualConfigHash,
316
+ recovered: true,
317
+ retries: Number(pending.attempts ?? 1),
318
+ };
319
+ log('apply: rollingBack pending 已自动恢复');
320
+ return recordAndClearMatchingPending({ home, pending, record });
321
+ } catch (error) {
322
+ if (error?.code === 'CONFIG_CHANGED') {
323
+ const record = rollbackSkippedRecord({
324
+ pending,
325
+ backupFile,
326
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
327
+ skipReason: 'config_changed',
328
+ expectedConfigHash,
329
+ actualConfigHash: await configFileHash(configFile),
330
+ configChanged: true,
331
+ });
332
+ log('apply: 恢复前配置已变化,跳过 rollingBack pending');
333
+ return recordAndClearMatchingPending({ home, pending, record });
334
+ }
335
+ const record = {
336
+ status: 'rollback-failed',
337
+ attempt: pending.attempt ?? null,
338
+ applyId: pending.applyId ?? null,
339
+ at: new Date().toISOString(),
340
+ fields,
341
+ reason: pending.reason ?? null,
342
+ restored: false,
343
+ backup: backupFile,
344
+ expectedConfigHash,
345
+ actualConfigHash,
346
+ restoreError: {
347
+ code: error?.code ?? 'RESTORE_FAILED',
348
+ message: String(error?.message ?? error),
349
+ },
350
+ recovered: false,
351
+ retries: Number(pending.attempts ?? 1),
352
+ };
353
+ await writeApplyResult(home, record);
354
+ // 保留 pending,允许下一次启动/apply 或人工重试。
355
+ return record;
356
+ }
168
357
  }
169
358
 
170
359
  /**
@@ -188,6 +377,9 @@ export async function runApplySupervisor({
188
377
  } = {}) {
189
378
  const now = () => Date.now();
190
379
  const pending = (await readApplyPending(home)) ?? { fields, at: new Date(since).toISOString(), attempts: 1 };
380
+ if (pending.rollingBack === true && configFile) {
381
+ return recoverPendingRollback({ home, configFile, backupFile, log });
382
+ }
191
383
  const attempts = Number(pending.attempts ?? 1);
192
384
  log(`apply: 等待新实例健康(fields=${fields.join(',')} timeout=${timeoutMs}ms)`);
193
385
  const outcome = await health({ home, port, oldPid, since, timeoutMs, now });
@@ -217,8 +409,64 @@ export async function runApplySupervisor({
217
409
  : `新实例在 ${timeoutMs}ms 内未健康(心跳/端口无响应)`;
218
410
  log(`apply: 新实例未健康(${reason})→ 回滚`);
219
411
  // 打标记:回滚实例启动时不得写 applied(否则会短暂谎报「已生效」)
220
- await writeApplyPending(home, { ...pending, rollingBack: true, reason }).catch(() => undefined);
221
- const restored = backupFile ? await restoreBackup({ configFile, backupFile }) : false;
412
+ const failedConfigHash = configFile ? await configFileHash(configFile) : null;
413
+ await writeApplyPending(home, {
414
+ ...pending,
415
+ rollingBack: true,
416
+ reason,
417
+ ...(failedConfigHash ? { failedConfigHash } : {}),
418
+ }).catch(() => undefined);
419
+ let restored = false;
420
+ let restoreError = null;
421
+ try {
422
+ restored = backupFile
423
+ ? await restoreBackup({
424
+ configFile,
425
+ backupFile,
426
+ ...(failedConfigHash ? { expectedConfigHash: failedConfigHash } : {}),
427
+ })
428
+ : false;
429
+ } catch (error) {
430
+ restoreError = error;
431
+ }
432
+ if (restoreError?.code === 'CONFIG_CHANGED') {
433
+ const record = {
434
+ status: 'rollback-skipped',
435
+ attempt: pending.attempt ?? null,
436
+ applyId: pending.applyId ?? null,
437
+ at: new Date(now()).toISOString(),
438
+ fields,
439
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
440
+ skipReason: 'config_changed',
441
+ configChanged: true,
442
+ restored: false,
443
+ backup: backupFile,
444
+ expectedConfigHash: failedConfigHash,
445
+ actualConfigHash: await configFileHash(configFile),
446
+ retries: attempts,
447
+ };
448
+ await recordAndClearMatchingPending({ home, pending, record });
449
+ return record;
450
+ }
451
+ if (restoreError) {
452
+ const record = {
453
+ status: 'rollback-failed',
454
+ attempt: pending.attempt ?? null,
455
+ at: new Date(now()).toISOString(),
456
+ fields,
457
+ reason,
458
+ restored: false,
459
+ backup: backupFile,
460
+ restoreError: {
461
+ code: restoreError?.code ?? 'RESTORE_FAILED',
462
+ message: String(restoreError?.message ?? restoreError),
463
+ },
464
+ retries: attempts,
465
+ };
466
+ await writeApplyResult(home, record);
467
+ // 保留 pending(rollingBack=true):锁释放/人工处理后仍可恢复,不假装回滚完成。
468
+ return record;
469
+ }
222
470
  if (restored) {
223
471
  await restart({ home, kind, env: process.env });
224
472
  const after = await health({ home, port, oldPid, since: now(), timeoutMs, now });
@@ -0,0 +1,167 @@
1
+ // 跨进程配置文件写锁。
2
+ //
3
+ // 配置 writer 必须在读取 → 修改 → rename/rollback 全程持有 `<config>.write-lock`。
4
+ // 锁文件包含 pid/at/owner:owner 用于 release 只删自己的锁。
5
+ // 锁内容优先通过临时文件 + link 原子创建;不支持硬链接的文件系统回退到 open('wx')。
6
+ // 持锁进程会周期性续租 mtime;活 PID 的锁在超过 staleMs 未续租后也可被接管(防 PID 复用)。
7
+ // 无法解析的锁只有在 mtime 超过 staleMs 后才可接管;读锁/stat 的非 ENOENT 瞬态错误一律按 busy 处理。
8
+
9
+ import { randomBytes } from 'node:crypto';
10
+ import { link, open, readFile, stat, unlink, utimes, writeFile } from 'node:fs/promises';
11
+
12
+ export const CONFIG_LOCK_STALE_MS = 30_000;
13
+ const LINK_UNSUPPORTED = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'EXDEV', 'ENOSYS', 'EACCES', 'EINVAL', 'EMLINK']);
14
+
15
+ function pidAlive(pid) {
16
+ if (!Number.isInteger(pid) || pid <= 0) return false;
17
+ try {
18
+ process.kill(pid, 0);
19
+ return true;
20
+ } catch (error) {
21
+ return error?.code === 'EPERM';
22
+ }
23
+ }
24
+
25
+ export async function acquireConfigFileLock(configFile, {
26
+ timeoutMs = null,
27
+ staleMs = CONFIG_LOCK_STALE_MS,
28
+ linkImpl = link,
29
+ openImpl = open,
30
+ now = Date.now,
31
+ } = {}) {
32
+ const lockPath = `${configFile}.write-lock`;
33
+ const configured = Number(process.env.MEBULAR_CONFIG_LOCK_TIMEOUT_MS ?? '');
34
+ const effectiveTimeout = Number.isFinite(timeoutMs) && timeoutMs !== null
35
+ ? Math.max(0, timeoutMs)
36
+ : (Number.isFinite(configured) && configured >= 0 ? configured : 5000);
37
+ const deadline = now() + effectiveTimeout;
38
+ const owner = randomBytes(12).toString('hex');
39
+
40
+ const snapshot = async () => {
41
+ let raw;
42
+ try {
43
+ raw = await readFile(lockPath, 'utf-8');
44
+ } catch (error) {
45
+ if (error?.code === 'ENOENT') {
46
+ return { exists: false, unreadable: false, raw: null, parsed: null, mtimeMs: null };
47
+ }
48
+ // EACCES/EMFILE 等瞬态错误:不能当作锁不存在,更不能 unlink。
49
+ return {
50
+ exists: true,
51
+ unreadable: true,
52
+ error: error?.code ?? 'read_failed',
53
+ raw: null,
54
+ parsed: null,
55
+ mtimeMs: null,
56
+ };
57
+ }
58
+ let info;
59
+ try {
60
+ info = await stat(lockPath);
61
+ } catch (error) {
62
+ if (error?.code === 'ENOENT') {
63
+ return { exists: false, unreadable: false, raw: null, parsed: null, mtimeMs: null };
64
+ }
65
+ return {
66
+ exists: true,
67
+ unreadable: true,
68
+ error: error?.code ?? 'stat_failed',
69
+ raw,
70
+ parsed: null,
71
+ mtimeMs: null,
72
+ };
73
+ }
74
+ let parsed = null;
75
+ try {
76
+ parsed = JSON.parse(raw);
77
+ } catch {
78
+ parsed = null;
79
+ }
80
+ return { exists: true, unreadable: false, raw, parsed, mtimeMs: info.mtimeMs };
81
+ };
82
+
83
+ const startHeartbeat = () => {
84
+ const period = Math.max(1, Math.min(Math.max(10, Math.floor(staleMs / 3)), Math.max(1, staleMs - 1)));
85
+ const timer = setInterval(() => {
86
+ void (async () => {
87
+ const current = await snapshot();
88
+ if (current.unreadable || current.parsed?.owner !== owner) return;
89
+ const at = new Date(now());
90
+ await utimes(lockPath, at, at).catch(() => undefined);
91
+ })();
92
+ }, period);
93
+ timer.unref?.();
94
+ return timer;
95
+ };
96
+
97
+ const createOnce = async () => {
98
+ const payload = JSON.stringify({ pid: process.pid, at: now(), owner });
99
+ const tmp = `${lockPath}.${owner}.tmp`;
100
+ try {
101
+ await writeFile(tmp, payload, { mode: 0o600 });
102
+ try {
103
+ await linkImpl(tmp, lockPath);
104
+ } catch (error) {
105
+ if (LINK_UNSUPPORTED.has(error?.code)) {
106
+ // 文件系统不支持硬链接:回退到 O_EXCL 原子创建;写入失败必须清理半截锁。
107
+ const handle = await openImpl(lockPath, 'wx', 0o600);
108
+ try {
109
+ await handle.writeFile(payload, 'utf-8');
110
+ } catch (writeError) {
111
+ await handle.close().catch(() => undefined);
112
+ await unlink(lockPath).catch(() => undefined);
113
+ throw writeError;
114
+ }
115
+ await handle.close().catch(() => undefined);
116
+ } else {
117
+ throw error;
118
+ }
119
+ }
120
+ } finally {
121
+ await unlink(tmp).catch(() => undefined);
122
+ }
123
+ };
124
+
125
+ for (;;) {
126
+ try {
127
+ await createOnce();
128
+ const heartbeat = startHeartbeat();
129
+ return async () => {
130
+ clearInterval(heartbeat);
131
+ // release 只删除自己的锁;已被 stale 接管或替换的锁不得误删。
132
+ const current = await snapshot();
133
+ if (!current.unreadable && current.parsed?.owner === owner) {
134
+ await unlink(lockPath).catch(() => undefined);
135
+ }
136
+ };
137
+ } catch (error) {
138
+ if (error?.code !== 'EEXIST') throw error;
139
+
140
+ const held = await snapshot();
141
+ let stale = false;
142
+ if (held.unreadable) {
143
+ stale = false;
144
+ } else if (held.exists && held.parsed && Number.isInteger(held.parsed.pid)) {
145
+ // 活 PID 也可能来自复用的旧进程:只有死 PID 或超时未续租才可接管。
146
+ stale = !pidAlive(held.parsed.pid)
147
+ || (typeof held.mtimeMs === 'number' && now() - held.mtimeMs > staleMs);
148
+ } else {
149
+ stale = !held.exists
150
+ || (typeof held.mtimeMs === 'number' && now() - held.mtimeMs > staleMs);
151
+ }
152
+ if (stale) {
153
+ // 重新读取确认仍是同一个锁,再接管,避免删除刚创建的新锁。
154
+ const confirmed = await snapshot();
155
+ if (!confirmed.unreadable
156
+ && confirmed.exists === held.exists
157
+ && confirmed.raw === held.raw
158
+ && confirmed.mtimeMs === held.mtimeMs) {
159
+ await unlink(lockPath).catch(() => undefined);
160
+ continue;
161
+ }
162
+ }
163
+ if (now() >= deadline) return null;
164
+ await new Promise((resolve) => setTimeout(resolve, 25));
165
+ }
166
+ }
167
+ }
@@ -587,6 +587,13 @@ export const CONFIG_SCHEMA = [
587
587
  effective: (s) => (s?.mcp?.tls === true ? 'on' : 'off'),
588
588
  reason: (ctx) => (ctx.settings?.mcp?.tls ? '已生效:TLS 实际启用' : '未启用:明文 HTTP(仅回环安全)'),
589
589
  },
590
+ // ------------------------------------------------------------------ Memory Runtime(device-local;0.3 默认关闭 = 轻量 MCP)
591
+ // 只承载 MCP 侧生命周期开关;sidecar 自己的设置放 <home>/memory-runtime/config.json。
592
+ // 热生效(requiresRestart:false):切换会动态生成/撤销 capability token。
593
+ { path: 'memoryRuntime.enabled', read: (c) => c?.memoryRuntime?.enabled === true, kind: 'bool', exposure: 'internal', writable: true, requiresRestart: false, default: false, ui: { group: '记忆运行时', type: 'bool', label: '启用记忆运行时(sidecar)' }, effective: (s) => s?.memoryRuntime?.enabled === true },
594
+ { path: 'memoryRuntime.command', read: (c) => c?.memoryRuntime?.command ?? null, kind: 'string', spec: { nonEmpty: true, empty: 'delete' }, exposure: 'internal', writable: true, requiresRestart: false, default: null, ui: { group: '记忆运行时', type: 'text', label: 'sidecar 可执行文件' }, effective: (s) => s?.memoryRuntime?.command ?? null },
595
+ { path: 'memoryRuntime.startTimeoutMs', read: (c) => c?.memoryRuntime?.startTimeoutMs ?? 5000, kind: 'int', spec: { min: 100, nullable: true }, exposure: 'internal', writable: true, requiresRestart: false, default: 5000, ui: { group: '记忆运行时', type: 'number', label: 'sidecar 启动超时(ms)' }, effective: (s) => s?.memoryRuntime?.startTimeoutMs ?? 5000 },
596
+
590
597
  // ------------------------------------------------------------------ internal(GUI 不渲染;API 仍可写)
591
598
  { path: 'network.libp2p.relayUnlimited', read: (c) => c?.network?.libp2p?.relayUnlimited === true, kind: 'bool', exposure: 'internal', writable: true, requiresRestart: true, default: false, ui: { type: 'bool', label: 'Relay 不做限额' } },
592
599
  { path: 'network.libp2p.relayServer', kind: 'bool', exposure: 'internal', requiresRestart: true, default: false, ui: { type: 'bool', label: '本机充当 relay 服务端' } },
package/src/config.mjs CHANGED
@@ -72,6 +72,22 @@ export async function loadConfigFile(home) {
72
72
  }
73
73
  }
74
74
 
75
+ /** fleet 任务面所需的额外同步域(能力卡/Agent 目录)。 */
76
+ export const FLEET_AGENT_NAMESPACE = 'agents';
77
+
78
+ /**
79
+ * CR-002/B4:旧 daemon 配置只订阅 `tasks` 时,启动期幂等补齐 `agents`。
80
+ * - 空数组/缺省 = 订阅全部,保持原语义(不强行收窄);
81
+ * - 已有非空 namespaces → 追加 agents(去重、保持原顺序)。
82
+ */
83
+ export function ensureFleetSyncNamespaces(config) {
84
+ const namespaces = config?.sync?.namespaces;
85
+ if (!Array.isArray(namespaces) || namespaces.length === 0) return config;
86
+ const merged = [...new Set([...namespaces, FLEET_AGENT_NAMESPACE])];
87
+ if (merged.length === namespaces.length) return config;
88
+ return { ...config, sync: { ...config.sync, namespaces: merged } };
89
+ }
90
+
75
91
  function truthy(value, fallback) {
76
92
  if (value === undefined) return fallback;
77
93
  return value === true || value === 'true' || value === '1';
@@ -185,7 +201,7 @@ export async function resolveMasterPublicKey(home, config) {
185
201
  /** 依配置构建并初始化 Mebular 门面 */
186
202
  export async function createMebular() {
187
203
  const home = homeDir();
188
- const config = await loadConfigFile(home);
204
+ const config = ensureFleetSyncNamespaces(await loadConfigFile(home));
189
205
  const storageAdapter = config.storageAdapter ?? 'json';
190
206
  const storagePath = storagePathForHome(home, config, process.env);
191
207
  // F-IDENT-1:身份文件是 deviceId/deviceName 的唯一权威;env/config 只在身份缺失时作为 bootstrap。
@@ -0,0 +1,150 @@
1
+ // 0.3 详情保留维护:MCP daemon 启动后扫描过期 DetailRecord。
2
+ //
3
+ // - 启动即跑一次,此后每 24h 一次;timer.unref,不拖住宿主退出。
4
+ // - 只调用 MemoryService.pruneExpiredDetails():复用图 + 事件日志,不做第二套存储/同步。
5
+ // - 失败只记录到 status 并打一行日志;绝不阻断 MCP READY 或后续定时任务。
6
+ // - 同一进程内热切换 service 时复用同一个 timer/状态;当天已成功跑过则跳过重复扫描。
7
+
8
+ const DAY_MS = 24 * 60 * 60 * 1000;
9
+
10
+ function dayKey(at) {
11
+ const date = new Date(at);
12
+ return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
13
+ }
14
+
15
+ function errorCode(error) {
16
+ return typeof error?.code === 'string' && error.code.length > 0 ? error.code : 'ERROR';
17
+ }
18
+
19
+ function safeErrorMessage(error) {
20
+ return String(error?.message ?? error ?? 'detail maintenance failed')
21
+ .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[redacted]')
22
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi, 'Bearer [redacted]')
23
+ .replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
24
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}\b/g, '[redacted]')
25
+ .replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, '[redacted]')
26
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted]')
27
+ .replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g, '[redacted]')
28
+ .replace(/\b(api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|passwd|authorization)\b(\s*[:=]\s*)(["']?)[^\s"',;]{4,}\3/gi, '$1$2$3[redacted]$3')
29
+ .slice(0, 512);
30
+ }
31
+
32
+ /**
33
+ * @param {{
34
+ * getService: () => ({ pruneExpiredDetails?: (options?: { now?: number }) => Promise<string[]> } | null),
35
+ * intervalMs?: number,
36
+ * now?: () => number,
37
+ * setIntervalFn?: typeof setInterval,
38
+ * clearIntervalFn?: typeof clearInterval,
39
+ * logger?: Pick<Console, 'error'>,
40
+ * }} options
41
+ */
42
+ export function createDetailMaintenance({
43
+ getService,
44
+ intervalMs = DAY_MS,
45
+ now = Date.now,
46
+ setIntervalFn = setInterval,
47
+ clearIntervalFn = clearInterval,
48
+ logger = console,
49
+ } = {}) {
50
+ let timer = null;
51
+ let stopped = false;
52
+ let activeRun = null;
53
+ let lastAttemptAt = null;
54
+ let lastSuccessAt = null;
55
+ let lastSuccessDay = null;
56
+ let lastResult = null;
57
+ let lastError = null;
58
+
59
+ const status = () => ({
60
+ running: timer !== null,
61
+ intervalMs,
62
+ lastAttemptAt,
63
+ lastSuccessAt,
64
+ lastSuccessDay,
65
+ lastResult,
66
+ lastError,
67
+ });
68
+
69
+ const serviceReady = () => {
70
+ const service = typeof getService === 'function' ? getService() : null;
71
+ return Boolean(service) && typeof service.pruneExpiredDetails === 'function';
72
+ };
73
+
74
+ const runOnce = ({ reason = 'startup', force = false } = {}) => {
75
+ if (stopped) return Promise.resolve(null);
76
+ if (activeRun) return activeRun;
77
+ if (!serviceReady()) return Promise.resolve(null);
78
+ const service = getService();
79
+ const at = now();
80
+ const day = dayKey(at);
81
+ if (!force && lastSuccessDay === day) {
82
+ return Promise.resolve({ skipped: true, reason: 'already_ran_today', day });
83
+ }
84
+ lastAttemptAt = at;
85
+ activeRun = (async () => {
86
+ try {
87
+ const pruned = await service.pruneExpiredDetails({ now: at });
88
+ lastSuccessAt = at;
89
+ lastSuccessDay = day;
90
+ lastResult = {
91
+ reason,
92
+ pruned: Array.isArray(pruned) ? pruned.length : 0,
93
+ // 现有 MemoryService 维护结果不含正文统计;明确未知,不伪造零值。
94
+ bytes: null,
95
+ oldestAgeMs: null,
96
+ at,
97
+ };
98
+ lastError = null;
99
+ return lastResult;
100
+ } catch (error) {
101
+ lastError = {
102
+ reason,
103
+ code: errorCode(error),
104
+ message: safeErrorMessage(error),
105
+ at,
106
+ };
107
+ logger?.error?.(`DETAIL_MAINTENANCE_FAILED ${lastError.code} ${lastError.message}`);
108
+ return lastError;
109
+ } finally {
110
+ activeRun = null;
111
+ }
112
+ })();
113
+ return activeRun;
114
+ };
115
+
116
+ const start = () => {
117
+ if (stopped) return status();
118
+ if (timer === null && serviceReady()) {
119
+ timer = setIntervalFn(() => {
120
+ void runOnce({ reason: 'interval' });
121
+ }, intervalMs);
122
+ timer?.unref?.();
123
+ }
124
+ // 启动/热切换都尝试一次;当天已成功跑过时会直接跳过。
125
+ void runOnce({ reason: timer === null ? 'service_pending' : 'startup' });
126
+ return status();
127
+ };
128
+
129
+ const stop = () => {
130
+ stopped = true;
131
+ if (timer !== null) {
132
+ clearIntervalFn(timer);
133
+ timer = null;
134
+ }
135
+ return status();
136
+ };
137
+
138
+ const idle = () => activeRun ?? Promise.resolve(null);
139
+
140
+ return {
141
+ start,
142
+ stop,
143
+ runOnce,
144
+ idle,
145
+ status,
146
+ serviceReady,
147
+ };
148
+ }
149
+
150
+ export const DETAIL_MAINTENANCE_INTERVAL_MS = DAY_MS;
@@ -9,7 +9,7 @@
9
9
  import { readFile } from 'node:fs/promises';
10
10
  import { join } from 'node:path';
11
11
 
12
- /** 任务事件节点的类型(`MebularTaskEventStore` 默认值)。 */
12
+ /** 任务事件节点的类型(fleet 任务事件存储的默认值)。 */
13
13
  export const TASK_EVENT_NODE_TYPE = 'task_event';
14
14
 
15
15
  /** 任务域默认 namespace(`fleet.config.json` 缺省 / 缺文件)。 */