@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.
@@ -0,0 +1,716 @@
1
+ // Memory Runtime 运维诊断(MCP CLI / supervisor 侧)。
2
+ //
3
+ // 只读取 sidecar 自己写入的脱敏 JSONL 与 outbox 元数据;不读取 host/capability token,
4
+ // 不返回正文、prompt、真实 home 或绝对路径。CLI `memory-runtime logs|doctor|outbox`
5
+ // 与 supervisor 的崩溃/重启记录共用这里的格式与轮转规则。
6
+
7
+ import { chmod, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
8
+ import { appendFileSync, chmodSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs';
9
+ import { join, resolve, basename, sep } from 'node:path';
10
+
11
+ const DEFAULT_MAX_BYTES = 512 * 1024;
12
+ const DEFAULT_MAX_FILES = 3;
13
+ const MAX_LINE_BYTES = 8 * 1024;
14
+ const MAX_STRING = 512;
15
+ const MAX_DEPTH = 4;
16
+ const OUTBOX_ITEM_RE = /^[A-Za-z0-9._:-]{1,128}$/;
17
+ const OUTBOX_MAX_QUEUE_MS = 30 * 24 * 60 * 60 * 1000;
18
+ const SENSITIVE_KEY_RE = /^(?:authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|token|secret|password|passwd|credential|private[-_]?key|keyref|cookie)$/i;
19
+ const BODY_KEY_RE = /^(?:body|content|contents|text|prompt|prompts|response|responses|messages|message|chunks?|items?|payload|raw|detailtext)$/i;
20
+ const PATH_RE = /(?:\b[A-Za-z]:[\\/](?:[^\\/\s"'<>|]+[\\/])*[^\\/\s"'<>|]*|\\\\[^\\/\s"'<>|]+\\[^\s"'<>|]*|\/(?:[A-Za-z0-9._-]+\/)+[A-Za-z0-9._-]*|\/(?:opt|root)(?=$|[\s"',;:]))/g;
21
+ const SECRET_SHAPE_RE = /\b(?:sk-[A-Za-z0-9_-]{12,}|Bearer\s+[A-Za-z0-9._~+/=-]{12,}|meb_[A-Za-z0-9]{16,})\b/g;
22
+
23
+ function isObject(value) {
24
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
25
+ }
26
+
27
+ function sanitizeString(value) {
28
+ return String(value)
29
+ .replace(SECRET_SHAPE_RE, '[redacted]')
30
+ .replace(PATH_RE, '[path]')
31
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '')
32
+ .slice(0, MAX_STRING);
33
+ }
34
+
35
+ function sanitizeValue(value, key, depth) {
36
+ if (key && SENSITIVE_KEY_RE.test(key)) return '[redacted]';
37
+ if (key && BODY_KEY_RE.test(key)) return '[omitted]';
38
+ if (typeof value === 'string') return sanitizeString(value);
39
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
40
+ if (typeof value === 'boolean' || value === null || value === undefined) return value;
41
+ if (depth >= MAX_DEPTH) return '[truncated]';
42
+ if (Array.isArray(value)) return value.slice(0, 20).map((entry) => sanitizeValue(entry, undefined, depth + 1));
43
+ if (isObject(value)) {
44
+ const out = {};
45
+ let count = 0;
46
+ for (const [entryKey, entryValue] of Object.entries(value)) {
47
+ if (entryValue === undefined) continue;
48
+ out[entryKey] = sanitizeValue(entryValue, entryKey, depth + 1);
49
+ count += 1;
50
+ if (count >= 40) break;
51
+ }
52
+ return out;
53
+ }
54
+ return '[truncated]';
55
+ }
56
+
57
+ export function sanitizeMemoryRuntimeEvent(event) {
58
+ const source = isObject(event) ? event : {};
59
+ const out = {
60
+ ts: Number.isFinite(source.ts) ? Math.floor(source.ts) : Date.now(),
61
+ level: source.level === 'warn' || source.level === 'error' ? source.level : 'info',
62
+ event: sanitizeString(source.event ?? 'unknown'),
63
+ };
64
+ for (const [key, value] of Object.entries(source)) {
65
+ if (key === 'ts' || key === 'level' || key === 'event') continue;
66
+ out[key] = sanitizeValue(value, key, 0);
67
+ }
68
+ return out;
69
+ }
70
+
71
+ function logFiles(dataDir) {
72
+ const dir = join(dataDir, 'logs');
73
+ const current = join(dir, 'runtime.jsonl');
74
+ return {
75
+ dir,
76
+ current,
77
+ rotated: (index) => `${current}.${index}`,
78
+ all: [current, `${current}.1`, `${current}.2`],
79
+ };
80
+ }
81
+
82
+ async function rotateLogUnlocked(paths, extraBytes, maxBytes, maxFiles) {
83
+ let size = 0;
84
+ try {
85
+ size = (await stat(paths.current)).size;
86
+ } catch {
87
+ size = 0;
88
+ }
89
+ if (size === 0 || size + extraBytes <= maxBytes) return;
90
+ if (maxFiles === 1) {
91
+ await rm(paths.current, { force: true }).catch(() => undefined);
92
+ return;
93
+ }
94
+ for (let index = maxFiles - 1; index >= 1; index -= 1) {
95
+ const source = index === 1 ? paths.current : paths.rotated(index - 1);
96
+ const target = paths.rotated(index);
97
+ if (index === maxFiles - 1) await rm(target, { force: true }).catch(() => undefined);
98
+ try {
99
+ await rename(source, target);
100
+ } catch (error) {
101
+ if (error?.code !== 'ENOENT') throw error;
102
+ }
103
+ }
104
+ }
105
+
106
+ export async function appendMemoryRuntimeLog(dataDir, event, {
107
+ now = Date.now,
108
+ maxBytes = DEFAULT_MAX_BYTES,
109
+ maxFiles = DEFAULT_MAX_FILES,
110
+ } = {}) {
111
+ if (typeof dataDir !== 'string' || dataDir.length === 0) return null;
112
+ const paths = logFiles(dataDir);
113
+ const sanitized = sanitizeMemoryRuntimeEvent({ ts: now(), ...event });
114
+ let line = `${JSON.stringify(sanitized)}\n`;
115
+ if (Buffer.byteLength(line, 'utf8') > MAX_LINE_BYTES) {
116
+ line = `${JSON.stringify({
117
+ ts: sanitized.ts,
118
+ level: sanitized.level,
119
+ event: sanitized.event,
120
+ truncated: true,
121
+ })}\n`;
122
+ }
123
+ try {
124
+ await mkdir(paths.dir, { recursive: true, mode: 0o700 });
125
+ await chmod(paths.dir, 0o700).catch(() => undefined);
126
+ await rotateLogUnlocked(paths, Buffer.byteLength(line, 'utf8'), Math.max(256, maxBytes), Math.max(1, maxFiles));
127
+ const handle = await open(paths.current, 'a', 0o600);
128
+ try {
129
+ await handle.write(line, null, 'utf8');
130
+ await handle.chmod(0o600).catch(() => undefined);
131
+ } finally {
132
+ await handle.close().catch(() => undefined);
133
+ }
134
+ return sanitized;
135
+ } catch {
136
+ // 诊断日志失败不得影响主流程。
137
+ return null;
138
+ }
139
+ }
140
+
141
+ /** 同步版本:用于 child exit 等不能在异步写日志期间被测试清理打断的生命周期回调。 */
142
+ export function appendMemoryRuntimeLogSync(dataDir, event, {
143
+ now = Date.now,
144
+ maxBytes = DEFAULT_MAX_BYTES,
145
+ maxFiles = DEFAULT_MAX_FILES,
146
+ } = {}) {
147
+ if (typeof dataDir !== 'string' || dataDir.length === 0) return null;
148
+ const paths = logFiles(dataDir);
149
+ const sanitized = sanitizeMemoryRuntimeEvent({ ts: now(), ...event });
150
+ let line = `${JSON.stringify(sanitized)}\n`;
151
+ if (Buffer.byteLength(line, 'utf8') > MAX_LINE_BYTES) {
152
+ line = `${JSON.stringify({
153
+ ts: sanitized.ts,
154
+ level: sanitized.level,
155
+ event: sanitized.event,
156
+ truncated: true,
157
+ })}\n`;
158
+ }
159
+ try {
160
+ mkdirSync(paths.dir, { recursive: true, mode: 0o700 });
161
+ chmodSync(paths.dir, 0o700);
162
+ let size = 0;
163
+ try {
164
+ size = statSync(paths.current).size;
165
+ } catch {
166
+ size = 0;
167
+ }
168
+ const limit = Math.max(256, maxBytes);
169
+ const files = Math.max(1, maxFiles);
170
+ if (size > 0 && size + Buffer.byteLength(line, 'utf8') > limit) {
171
+ if (files === 1) {
172
+ try { rmSync(paths.current, { force: true }); } catch { /* ignore */ }
173
+ } else {
174
+ for (let index = files - 1; index >= 1; index -= 1) {
175
+ const source = index === 1 ? paths.current : paths.rotated(index - 1);
176
+ const target = paths.rotated(index);
177
+ if (index === files - 1) {
178
+ try { rmSync(target, { force: true }); } catch { /* ignore */ }
179
+ }
180
+ try { renameSync(source, target); } catch { /* ENOENT */ }
181
+ }
182
+ }
183
+ }
184
+ appendFileSync(paths.current, line, { mode: 0o600 });
185
+ chmodSync(paths.current, 0o600);
186
+ return sanitized;
187
+ } catch {
188
+ return null;
189
+ }
190
+ }
191
+
192
+ export async function readMemoryRuntimeLogs(dataDir, { limit = 50, maxFiles = DEFAULT_MAX_FILES } = {}) {
193
+ if (typeof dataDir !== 'string' || dataDir.length === 0) return [];
194
+ const paths = logFiles(dataDir);
195
+ const files = [paths.current];
196
+ for (let index = 1; index < Math.max(1, maxFiles); index += 1) files.push(paths.rotated(index));
197
+ const events = [];
198
+ for (const file of files) {
199
+ let text;
200
+ try {
201
+ text = await readFile(file, 'utf8');
202
+ } catch {
203
+ continue;
204
+ }
205
+ for (const line of text.split('\n')) {
206
+ if (line.trim().length === 0) continue;
207
+ try {
208
+ const parsed = JSON.parse(line);
209
+ if (isObject(parsed) && typeof parsed.event === 'string') {
210
+ events.push(sanitizeMemoryRuntimeEvent(parsed));
211
+ }
212
+ } catch {
213
+ // 损坏行忽略。
214
+ }
215
+ }
216
+ }
217
+ events.sort((a, b) => (a.ts ?? 0) - (b.ts ?? 0));
218
+ return events.slice(-Math.max(1, Math.min(500, Math.floor(limit))));
219
+ }
220
+
221
+ export async function memoryRuntimeLogStatus(dataDir) {
222
+ const paths = logFiles(dataDir);
223
+ let files = 0;
224
+ let bytes = 0;
225
+ for (const file of paths.all) {
226
+ try {
227
+ const info = await stat(file);
228
+ if (!info.isFile() || info.size === 0) continue;
229
+ files += 1;
230
+ bytes += info.size;
231
+ } catch {
232
+ // ignore
233
+ }
234
+ }
235
+ const recent = await readMemoryRuntimeLogs(dataDir, { limit: 1 });
236
+ return {
237
+ files,
238
+ bytes,
239
+ latestAt: recent.length > 0 && typeof recent[0].ts === 'number' ? recent[0].ts : null,
240
+ };
241
+ }
242
+
243
+ async function readJson(path, fallback = null) {
244
+ try {
245
+ return JSON.parse(await readFile(path, 'utf8'));
246
+ } catch {
247
+ return fallback;
248
+ }
249
+ }
250
+
251
+ async function writeJsonAtomic(path, value) {
252
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
253
+ await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 0o600 });
254
+ await rename(temporary, path);
255
+ await chmod(path, 0o600).catch(() => undefined);
256
+ }
257
+
258
+ function operationOf(item) {
259
+ const kind = item?.meta?.kind;
260
+ if (kind === 'detail' || item?.endpoint === '/detail') return 'detail';
261
+ if (kind === 'record' || item?.endpoint === '/write') return 'record';
262
+ if (item?.endpoint === '/internal-object') {
263
+ const bodyKind = isObject(item.body) && typeof item.body.kind === 'string' ? item.body.kind : '';
264
+ if (bodyKind === 'compact') return 'compact';
265
+ if (bodyKind === 'context_checkpoint') return 'checkpoint';
266
+ if (bodyKind === 'self_record') return 'self';
267
+ }
268
+ return 'other';
269
+ }
270
+
271
+ function failureOf(item) {
272
+ const failure = isObject(item?.lastFailure) ? item.lastFailure : null;
273
+ if (failure && typeof failure.code === 'string') {
274
+ return {
275
+ code: failure.code,
276
+ at: typeof failure.at === 'number' ? failure.at : (item.lastAttemptAt ?? item.createdAt ?? 0),
277
+ ...(typeof failure.status === 'number' ? { status: failure.status } : {}),
278
+ ...(typeof failure.stage === 'string' ? { stage: failure.stage } : {}),
279
+ ...(typeof failure.disposition === 'string' ? { disposition: failure.disposition } : {}),
280
+ ...(isObject(failure.details) ? { details: sanitizeValue(failure.details, undefined, 0) } : {}),
281
+ ...(failure.possibleCommit === true ? { possibleCommit: true } : {}),
282
+ };
283
+ }
284
+ const code = typeof item?.error === 'string' ? item.error : (typeof item?.lastError === 'string' ? item.lastError : null);
285
+ if (!code) return null;
286
+ return {
287
+ code,
288
+ at: item.lastAttemptAt ?? item.createdAt ?? 0,
289
+ ...(typeof item.failureStage === 'string' ? { stage: item.failureStage } : {}),
290
+ };
291
+ }
292
+
293
+ function outboxMetadata(item, { dead = false } = {}) {
294
+ const body = isObject(item?.body) ? item.body : {};
295
+ const failure = failureOf(item);
296
+ const committed = isObject(item?.committed) ? item.committed : null;
297
+ const committedObjects = committed
298
+ ? {
299
+ records: Array.isArray(committed.records) ? committed.records.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
300
+ details: Array.isArray(committed.details) ? committed.details.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
301
+ objects: Array.isArray(committed.objects) ? committed.objects.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
302
+ }
303
+ : null;
304
+ return {
305
+ id: item.id,
306
+ requestId: item.requestId,
307
+ endpoint: item.endpoint,
308
+ operation: operationOf(item),
309
+ createdAt: item.createdAt,
310
+ attempts: item.attempts,
311
+ lastAttemptAt: item.lastAttemptAt ?? null,
312
+ revision: typeof body.expectedRevision === 'number' ? body.expectedRevision : null,
313
+ ...(typeof item.failureStage === 'string' ? { failureStage: item.failureStage } : {}),
314
+ ...(dead && typeof item.deadAt === 'number' ? { deadAt: item.deadAt } : {}),
315
+ ...(dead && typeof item.error === 'string' ? { reason: item.error } : {}),
316
+ ...(failure ? { lastFailure: failure } : {}),
317
+ ...(committedObjects ? { committedObjects } : {}),
318
+ };
319
+ }
320
+
321
+ async function readOutboxDir(root) {
322
+ const items = [];
323
+ let entries;
324
+ try {
325
+ entries = await readdir(root, { withFileTypes: true });
326
+ } catch {
327
+ return items;
328
+ }
329
+ for (const entry of entries) {
330
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
331
+ const item = await readJson(join(root, entry.name));
332
+ if (isObject(item) && item.version === 1 && typeof item.id === 'string') items.push(item);
333
+ }
334
+ items.sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || String(a.id).localeCompare(String(b.id)));
335
+ return items;
336
+ }
337
+
338
+ function aggregate(items, dead, now) {
339
+ const rows = new Map();
340
+ const reasons = new Map();
341
+ const apply = (item, isDead, keyOf) => {
342
+ const key = keyOf(item);
343
+ const row = rows.get(key) ?? {
344
+ operation: operationOf(item),
345
+ endpoint: item.endpoint,
346
+ active: 0,
347
+ dead: 0,
348
+ oldestAt: null,
349
+ deadOldestAt: null,
350
+ lastFailure: null,
351
+ };
352
+ if (isDead) {
353
+ row.dead += 1;
354
+ const at = typeof item.deadAt === 'number' ? item.deadAt : item.createdAt;
355
+ row.deadOldestAt = row.deadOldestAt === null ? at : Math.min(row.deadOldestAt, at);
356
+ } else {
357
+ row.active += 1;
358
+ row.oldestAt = row.oldestAt === null ? item.createdAt : Math.min(row.oldestAt, item.createdAt);
359
+ }
360
+ const failure = failureOf(item);
361
+ if (failure && (!row.lastFailure || failure.at >= row.lastFailure.at)) row.lastFailure = failure;
362
+ rows.set(key, row);
363
+ };
364
+ for (const item of items) apply(item, false, (entry) => operationOf(entry));
365
+ for (const item of dead) apply(item, true, (entry) => operationOf(entry));
366
+ const byOperation = [...rows.values()].map((row) => ({
367
+ operation: row.operation,
368
+ endpoint: row.endpoint,
369
+ active: row.active,
370
+ dead: row.dead,
371
+ oldestAgeMs: row.oldestAt === null ? null : Math.max(0, now - row.oldestAt),
372
+ deadOldestAgeMs: row.deadOldestAt === null ? null : Math.max(0, now - row.deadOldestAt),
373
+ lastFailure: row.lastFailure
374
+ ? {
375
+ code: row.lastFailure.code,
376
+ at: row.lastFailure.at,
377
+ ...(row.lastFailure.stage ? { stage: row.lastFailure.stage } : {}),
378
+ ...(row.lastFailure.disposition ? { disposition: row.lastFailure.disposition } : {}),
379
+ }
380
+ : null,
381
+ })).sort((a, b) => a.operation.localeCompare(b.operation));
382
+ const endpoints = new Map();
383
+ for (const item of items) {
384
+ const row = endpoints.get(item.endpoint) ?? { endpoint: item.endpoint, active: 0, dead: 0 };
385
+ row.active += 1;
386
+ endpoints.set(item.endpoint, row);
387
+ }
388
+ for (const item of dead) {
389
+ const row = endpoints.get(item.endpoint) ?? { endpoint: item.endpoint, active: 0, dead: 0 };
390
+ row.dead += 1;
391
+ endpoints.set(item.endpoint, row);
392
+ }
393
+ const byEndpoint = [...endpoints.values()].sort((a, b) => a.endpoint.localeCompare(b.endpoint));
394
+ for (const item of dead) {
395
+ const reason = typeof item.error === 'string' && item.error.length > 0
396
+ ? item.error
397
+ : (item.lastFailure?.code ?? 'unknown');
398
+ reasons.set(reason, (reasons.get(reason) ?? 0) + 1);
399
+ }
400
+ const all = [...items.map((item) => ({ item, failure: failureOf(item) })),
401
+ ...dead.map((item) => ({ item, failure: failureOf(item) }))];
402
+ const conflicts = all
403
+ .filter((entry) => entry.failure && (entry.failure.disposition === 'conflict'
404
+ || entry.failure.code === 'revision_mismatch'
405
+ || entry.failure.code === 'checkpoint_lease_held'))
406
+ .sort((a, b) => b.failure.at - a.failure.at);
407
+ const latest = conflicts[0];
408
+ const ambiguous = all
409
+ .filter((entry) => entry.failure && (entry.failure.possibleCommit === true
410
+ || entry.failure.code === 'timeout'
411
+ || entry.failure.code === 'network_error'
412
+ || entry.failure.code === 'partial_failure'))
413
+ .map(({ item, failure }) => ({
414
+ requestId: item.requestId,
415
+ endpoint: item.endpoint,
416
+ operation: operationOf(item),
417
+ ...(failure.stage ? { stage: failure.stage } : {}),
418
+ reason: failure.code,
419
+ at: failure.at,
420
+ ageMs: Math.max(0, now - failure.at),
421
+ possiblyCommitted: true,
422
+ hint: 'may_have_been_committed',
423
+ reconciliation: 'read_authoritative_objects',
424
+ ...(isObject(item.committed) ? {
425
+ committedObjects: {
426
+ records: Array.isArray(item.committed.records) ? item.committed.records.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
427
+ details: Array.isArray(item.committed.details) ? item.committed.details.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
428
+ objects: Array.isArray(item.committed.objects) ? item.committed.objects.map((entry) => entry?.id).filter((id) => typeof id === 'string') : [],
429
+ },
430
+ } : {}),
431
+ }))
432
+ .sort((a, b) => b.at - a.at);
433
+ return {
434
+ active: items.length,
435
+ dead: dead.length,
436
+ byOperation,
437
+ byEndpoint,
438
+ deadReasons: [...reasons.entries()].map(([reason, count]) => ({ reason, count }))
439
+ .sort((a, b) => b.count - a.count || a.reason.localeCompare(b.reason)),
440
+ lastConflict: latest
441
+ ? {
442
+ code: latest.failure.code,
443
+ at: latest.failure.at,
444
+ endpoint: latest.item.endpoint,
445
+ operation: operationOf(latest.item),
446
+ requestId: latest.item.requestId,
447
+ ...(typeof latest.failure.status === 'number' ? { status: latest.failure.status } : {}),
448
+ ...(typeof latest.failure.details?.currentRevision === 'number'
449
+ ? { currentRevision: latest.failure.details.currentRevision } : {}),
450
+ ...(typeof latest.failure.details?.expectedRevision === 'number'
451
+ ? { expectedRevision: latest.failure.details.expectedRevision }
452
+ : isObject(latest.item.body) && typeof latest.item.body.expectedRevision === 'number'
453
+ ? { expectedRevision: latest.item.body.expectedRevision } : {}),
454
+ ...(typeof latest.failure.details?.hostId === 'string'
455
+ ? { hostId: latest.failure.details.hostId } : {}),
456
+ ...(typeof latest.failure.details?.until === 'number'
457
+ ? { until: latest.failure.details.until } : {}),
458
+ ...(latest.failure.stage ? { stage: latest.failure.stage } : {}),
459
+ }
460
+ : null,
461
+ ambiguous,
462
+ };
463
+ }
464
+
465
+ export async function inspectMemoryRuntimeOutbox(dataDir, { now = Date.now(), includeItems = false } = {}) {
466
+ const active = await readOutboxDir(join(dataDir, 'outbox'));
467
+ const dead = await readOutboxDir(join(dataDir, 'outbox', 'dead'));
468
+ const summary = aggregate(active, dead, now);
469
+ const oldestAt = active.reduce((oldest, item) => oldest === null ? item.createdAt : Math.min(oldest, item.createdAt), null);
470
+ const deadOldestAt = dead.reduce((oldest, item) => {
471
+ const at = typeof item.deadAt === 'number' ? item.deadAt : item.createdAt;
472
+ return oldest === null ? at : Math.min(oldest, at);
473
+ }, null);
474
+ return {
475
+ ...summary,
476
+ oldestAgeMs: oldestAt === null ? null : Math.max(0, now - oldestAt),
477
+ deadOldestAgeMs: deadOldestAt === null ? null : Math.max(0, now - deadOldestAt),
478
+ ...(includeItems ? {
479
+ items: [
480
+ ...active.map((item) => outboxMetadata(item)),
481
+ ...dead.map((item) => outboxMetadata(item, { dead: true })),
482
+ ],
483
+ } : {}),
484
+ };
485
+ }
486
+
487
+ function diagnosticError(code, message) {
488
+ const error = new Error(message);
489
+ error.code = code;
490
+ return error;
491
+ }
492
+
493
+ /** 与 sidecar `assertSafeDataDir` 同一规则:不得写 MCP daemon 的 runtime 安装根。 */
494
+ export function assertSafeMemoryRuntimeDataDir(dataDir, home) {
495
+ const resolvedHome = resolve(home ?? process.env.MEBULAR_HOME ?? process.cwd());
496
+ const resolvedData = resolve(dataDir);
497
+ const homeRuntime = join(resolvedHome, 'runtime');
498
+ const underHomeRuntime = resolvedData === homeRuntime || resolvedData.startsWith(`${homeRuntime}${sep}`);
499
+ const normalized = resolvedData.split(sep).join('/');
500
+ const underCloudRuntime = /\/runtime\/\d+\.\d+\.\d+(?:[-+][^/]*)?(?:\/|$)/.test(normalized);
501
+ const isRuntimeDir = basename(resolvedData) === 'runtime';
502
+ if (underHomeRuntime || underCloudRuntime || isRuntimeDir) {
503
+ throw diagnosticError('data_dir_forbidden', 'sidecar 数据目录不能指向 MCP daemon 的 runtime 安装根');
504
+ }
505
+ return resolvedData;
506
+ }
507
+
508
+ function pidAliveDefault(pid) {
509
+ if (!Number.isInteger(pid) || pid <= 0) return false;
510
+ try {
511
+ process.kill(pid, 0);
512
+ return true;
513
+ } catch (error) {
514
+ return error?.code === 'EPERM';
515
+ }
516
+ }
517
+
518
+ async function assertOutboxMutable(dataDir, id, {
519
+ now = Date.now(),
520
+ pidAlive = pidAliveDefault,
521
+ } = {}) {
522
+ const lock = await readJson(join(dataDir, 'start.lock'));
523
+ if (isObject(lock) && Number.isInteger(lock.pid) && pidAlive(lock.pid)) {
524
+ throw diagnosticError('sidecar_running', 'sidecar 正在运行:拒绝修改 outbox');
525
+ }
526
+ const active = await readJson(join(dataDir, 'outbox', `${id}.json`));
527
+ if (isObject(active)
528
+ && typeof active.replayLeaseUntil === 'number'
529
+ && active.replayLeaseUntil > now) {
530
+ throw diagnosticError('outbox_in_flight', 'outbox 项正在重放:拒绝重建或清理');
531
+ }
532
+ }
533
+
534
+ export async function rebuildMemoryRuntimeOutboxItem(dataDir, id, {
535
+ expectedRevision,
536
+ now = Date.now(),
537
+ pidAlive = pidAliveDefault,
538
+ } = {}) {
539
+ if (typeof id !== 'string' || !OUTBOX_ITEM_RE.test(id)) {
540
+ throw diagnosticError('invalid_outbox_item', 'outbox id 格式非法');
541
+ }
542
+ await assertOutboxMutable(dataDir, id, { now, pidAlive });
543
+ const activePath = join(dataDir, 'outbox', `${id}.json`);
544
+ const deadPath = join(dataDir, 'outbox', 'dead', `${id}.json`);
545
+ const reconcilePath = join(dataDir, 'outbox', 'reconcile', `${id}.json`);
546
+ const active = await readJson(activePath);
547
+ const dead = await readJson(deadPath);
548
+ const source = isObject(active) && active.version === 1 ? active : (isObject(dead) && dead.version === 1 ? dead : null);
549
+ if (!source) {
550
+ throw diagnosticError('outbox_not_found', 'outbox 项不存在');
551
+ }
552
+ const body = isObject(source.body) ? JSON.parse(JSON.stringify(source.body)) : {};
553
+ if (expectedRevision !== undefined) {
554
+ if (typeof expectedRevision !== 'number'
555
+ || !Number.isSafeInteger(expectedRevision)
556
+ || expectedRevision < 0) {
557
+ throw diagnosticError('usage', '--expected-revision 必须是非负安全整数');
558
+ }
559
+ body.expectedRevision = expectedRevision;
560
+ }
561
+ const originalExpiresAt = typeof source.expiresAt === 'number'
562
+ && Number.isFinite(source.expiresAt)
563
+ && source.expiresAt > 0
564
+ ? source.expiresAt
565
+ : null;
566
+ const rebuiltExpiresAt = originalExpiresAt === null
567
+ ? now + OUTBOX_MAX_QUEUE_MS
568
+ : Math.min(now + OUTBOX_MAX_QUEUE_MS, originalExpiresAt);
569
+ const meta = { ...(isObject(source.meta) ? source.meta : {}) };
570
+ delete meta.needsFinalize;
571
+ delete meta.finalizeOutcome;
572
+ const rebuilt = {
573
+ ...source,
574
+ body,
575
+ createdAt: now,
576
+ expiresAt: rebuiltExpiresAt,
577
+ attempts: 0,
578
+ lastAttemptAt: null,
579
+ lastError: null,
580
+ nextAttemptAt: undefined,
581
+ replayLeaseUntil: undefined,
582
+ replayLeaseOwner: undefined,
583
+ replayLeaseMs: undefined,
584
+ replayLeaseGeneration: undefined,
585
+ meta: {
586
+ ...meta,
587
+ manualRebuild: true,
588
+ rebuiltAt: now,
589
+ ...(expectedRevision !== undefined ? { manualExpectedRevision: expectedRevision } : {}),
590
+ },
591
+ };
592
+ delete rebuilt.deadAt;
593
+ delete rebuilt.error;
594
+ delete rebuilt.lastFailure;
595
+ delete rebuilt.failureStage;
596
+ await mkdir(join(dataDir, 'outbox'), { recursive: true, mode: 0o700 });
597
+ await writeJsonAtomic(activePath, rebuilt);
598
+ await rm(deadPath, { force: true });
599
+ await rm(reconcilePath, { force: true });
600
+ return outboxMetadata(rebuilt);
601
+ }
602
+
603
+ export async function purgeMemoryRuntimeOutboxItem(dataDir, id, {
604
+ now = Date.now(),
605
+ pidAlive = pidAliveDefault,
606
+ } = {}) {
607
+ if (typeof id !== 'string' || !OUTBOX_ITEM_RE.test(id)) {
608
+ throw diagnosticError('invalid_outbox_item', 'outbox id 格式非法');
609
+ }
610
+ await assertOutboxMutable(dataDir, id, { now, pidAlive });
611
+ const paths = [
612
+ join(dataDir, 'outbox', `${id}.json`),
613
+ join(dataDir, 'outbox', 'dead', `${id}.json`),
614
+ join(dataDir, 'outbox', 'reconcile', `${id}.json`),
615
+ ];
616
+ let removed = 0;
617
+ for (const path of paths) {
618
+ try {
619
+ const info = await stat(path);
620
+ if (!info.isFile()) continue;
621
+ await rm(path);
622
+ removed += 1;
623
+ } catch {
624
+ // 不存在即未删除。
625
+ }
626
+ }
627
+ return { id, removed };
628
+ }
629
+
630
+ async function directoryBytes(root) {
631
+ let total = 0;
632
+ let entries;
633
+ try {
634
+ entries = await readdir(root, { withFileTypes: true });
635
+ } catch {
636
+ return 0;
637
+ }
638
+ for (const entry of entries) {
639
+ const path = join(root, entry.name);
640
+ if (entry.isDirectory()) {
641
+ total += await directoryBytes(path);
642
+ continue;
643
+ }
644
+ if (!entry.isFile()) continue;
645
+ try {
646
+ total += (await stat(path)).size;
647
+ } catch {
648
+ // ignore
649
+ }
650
+ }
651
+ return total;
652
+ }
653
+
654
+ export async function memoryRuntimeDiskUsage(dataDir) {
655
+ const [staging, cache, outbox, logs, models] = await Promise.all([
656
+ directoryBytes(join(dataDir, 'staging')),
657
+ directoryBytes(join(dataDir, 'cache')),
658
+ directoryBytes(join(dataDir, 'outbox')),
659
+ directoryBytes(join(dataDir, 'logs')),
660
+ directoryBytes(join(dataDir, 'models')),
661
+ ]);
662
+ const traceBytes = await stat(join(dataDir, 'traces.jsonl')).then((info) => info.size).catch(() => 0);
663
+ return {
664
+ stagingBytes: staging,
665
+ traceBytes,
666
+ cacheBytes: cache,
667
+ outboxBytes: outbox,
668
+ logsBytes: logs,
669
+ modelsBytes: models,
670
+ totalBytes: staging + traceBytes + cache + outbox + logs + models,
671
+ };
672
+ }
673
+
674
+ async function countJsonFiles(root) {
675
+ let entries;
676
+ try {
677
+ entries = await readdir(root, { withFileTypes: true });
678
+ } catch {
679
+ return 0;
680
+ }
681
+ let count = 0;
682
+ for (const entry of entries) {
683
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
684
+ count += 1;
685
+ }
686
+ return count;
687
+ }
688
+
689
+ async function countJsonlLines(file) {
690
+ try {
691
+ const text = await readFile(file, 'utf8');
692
+ return text.split('\n').filter((line) => line.trim().length > 0).length;
693
+ } catch {
694
+ return 0;
695
+ }
696
+ }
697
+
698
+ export async function inspectMemoryRuntimeLocalCounts(dataDir) {
699
+ const [stagingChunks, traces, cacheEntries, detailCacheEntries, outbox, dead] = await Promise.all([
700
+ countJsonlLines(join(dataDir, 'staging', 'chunks.jsonl')),
701
+ countJsonlLines(join(dataDir, 'traces.jsonl')),
702
+ countJsonFiles(join(dataDir, 'cache')),
703
+ countJsonFiles(join(dataDir, 'cache', 'details')),
704
+ countJsonFiles(join(dataDir, 'outbox')),
705
+ countJsonFiles(join(dataDir, 'outbox', 'dead')),
706
+ ]);
707
+ return {
708
+ stagingChunks,
709
+ traces,
710
+ cacheEntries,
711
+ detailCacheEntries,
712
+ outboxItems: outbox,
713
+ deadItems: dead,
714
+ };
715
+ }
716
+