@mebular/mcp 0.3.0 → 0.3.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.
@@ -98,6 +98,7 @@ const IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1000;
98
98
  const IDEMPOTENCY_MAX_ENTRIES = 5000;
99
99
  const IDEMPOTENCY_LEDGER_VERSION = 1;
100
100
  const IDEMPOTENCY_LEDGER_FILE = 'capability-idempotency.json';
101
+ const IDEMPOTENCY_MAINTENANCE_INTERVAL_MS = 60_000;
101
102
  const MAX_SYNC_WAIT_MS = 30_000;
102
103
 
103
104
  const AGENT_ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -112,6 +113,7 @@ const DEFAULT_TYPES = ['fact', 'preference', 'episode', 'observation', 'skill',
112
113
  const WRITE_ENDPOINTS = new Set(['write', 'update', 'delete', 'archive', 'internal-object', 'sync']);
113
114
  const INTERNAL_OBJECT_KINDS = ['compact', 'self_record', 'context_checkpoint'];
114
115
  const WRITE_KINDS = new Set(['fact', 'preference', 'episode', 'observation', 'skill', 'entity']);
116
+ const RECORD_NODE_TYPES = new Set(['fact', 'preference', 'episode', 'observation', 'skill', 'entity', 'meta']);
115
117
  const EPISODE_KINDS = new Set(['conversation', 'task', 'decision', 'error', 'observation', 'other']);
116
118
  const ENTITY_KINDS = new Set(['user', 'project', 'tool', 'concept', 'organization', 'location', 'other']);
117
119
  const SOURCE_VALUES = new Set(['mcp', 'runtime', 'host', 'import', 'legacy']);
@@ -915,10 +917,14 @@ function checkpointRevisionKey(node) {
915
917
  return `default:${checkpointAgentId(node) ?? ''}:${checkpointThreadId(node) ?? ''}`;
916
918
  }
917
919
 
918
- async function currentCheckpoint(app, { agentId, threadId, domain = null } = {}) {
920
+ async function checkpointRevisions(app, { agentId, threadId, domain = null } = {}) {
919
921
  const nodes = await listNodesOfType(app, 'context_checkpoint');
920
- const matches = nodes
921
- .filter((node) => !node.deletedAt && checkpointMatches(node, agentId, threadId, domain));
922
+ // 包含墓碑:revision high-water 不得因过期维护删除最新 revision 而回退。
923
+ return nodes.filter((node) => checkpointMatches(node, agentId, threadId, domain));
924
+ }
925
+
926
+ async function currentCheckpoint(app, { agentId, threadId, domain = null } = {}) {
927
+ const matches = await checkpointRevisions(app, { agentId, threadId, domain });
922
928
  if (matches.length === 0) return null;
923
929
  const keyed = new Map();
924
930
  for (const node of matches) {
@@ -929,10 +935,20 @@ async function currentCheckpoint(app, { agentId, threadId, domain = null } = {})
929
935
  return [...keyed.values()].sort(compareInternalObjectNodes)[0] ?? null;
930
936
  }
931
937
 
932
- async function allCheckpoints(app, agentId, threadId = null) {
938
+ async function highestCheckpointRevision(app, { agentId, threadId, domain = null } = {}) {
939
+ const matches = await checkpointRevisions(app, { agentId, threadId, domain });
940
+ let highest = 0;
941
+ for (const node of matches) {
942
+ const revision = internalObjectRevision(node);
943
+ if (typeof revision === 'number' && revision > highest) highest = revision;
944
+ }
945
+ return highest;
946
+ }
947
+
948
+ async function allCheckpoints(app, agentId, threadId = null, { includeDeleted = false } = {}) {
933
949
  const nodes = await listNodesOfType(app, 'context_checkpoint');
934
950
  return nodes.filter((node) => {
935
- if (node.deletedAt || !isV2CheckpointNode(node)) return false;
951
+ if ((!includeDeleted && node.deletedAt) || !isV2CheckpointNode(node)) return false;
936
952
  const domain = domainOfNamespace(node.namespace);
937
953
  if (domain.startsWith('task:')) {
938
954
  if (threadId !== null && checkpointThreadId(node) !== threadId) return false;
@@ -967,6 +983,91 @@ async function isCompactStale(app, node) {
967
983
  return false;
968
984
  }
969
985
 
986
+ /** capability 侧确定性摘要:用于离线 deferred compact 恢复,禁止占位摘要落图。 */
987
+ function compactSourceText(node) {
988
+ const content = isObject(node?.content) ? node.content : {};
989
+ switch (node?.type) {
990
+ case 'fact':
991
+ case 'preference': {
992
+ const subject = typeof content.subject === 'string' ? content.subject : '';
993
+ const predicate = typeof content.predicate === 'string' ? content.predicate : '';
994
+ const object = typeof content.object === 'string' ? content.object : '';
995
+ if (subject && predicate && object) return `${subject} ${predicate} ${object}`.trim();
996
+ break;
997
+ }
998
+ case 'episode':
999
+ if (typeof content.title === 'string' && content.title.trim()) return content.title.trim();
1000
+ break;
1001
+ case 'skill':
1002
+ case 'entity':
1003
+ if (typeof content.name === 'string' && content.name.trim()) {
1004
+ const description = typeof content.description === 'string' ? content.description.trim() : '';
1005
+ return description ? `${content.name.trim()}:${description}` : content.name.trim();
1006
+ }
1007
+ break;
1008
+ default:
1009
+ break;
1010
+ }
1011
+ if (typeof content.content === 'string' && content.content.trim()) return content.content.trim();
1012
+ if (typeof content.description === 'string' && content.description.trim()) return content.description.trim();
1013
+ if (typeof content.summary === 'string' && content.summary.trim()) return content.summary.trim();
1014
+ if (Object.keys(content).length === 0) return '';
1015
+ try {
1016
+ const serialized = JSON.stringify(content);
1017
+ return serialized === '{}' ? '' : serialized;
1018
+ } catch {
1019
+ return '';
1020
+ }
1021
+ }
1022
+
1023
+ function truncateUtf8(value, maxBytes) {
1024
+ const text = String(value ?? '');
1025
+ if (Buffer.byteLength(text, 'utf8') <= maxBytes) return { text, truncated: false };
1026
+ let low = 0;
1027
+ let high = text.length;
1028
+ while (low < high) {
1029
+ const mid = Math.ceil((low + high) / 2);
1030
+ if (Buffer.byteLength(text.slice(0, mid), 'utf8') <= maxBytes) low = mid;
1031
+ else high = mid - 1;
1032
+ }
1033
+ let cut = Math.max(0, low);
1034
+ // 避免把代理对切成半个字符。
1035
+ if (cut > 0 && /[\uD800-\uDBFF]/.test(text[cut - 1])) cut -= 1;
1036
+ const suffix = cut > 0 ? '…' : '';
1037
+ while (cut > 0 && Buffer.byteLength(`${text.slice(0, cut)}${suffix}`, 'utf8') > maxBytes) cut -= 1;
1038
+ return { text: `${text.slice(0, cut)}${suffix}`, truncated: true };
1039
+ }
1040
+
1041
+ function buildCompactSummaryFromNodes(nodes, strategy = 'summary') {
1042
+ const sorted = [...nodes].sort((a, b) => String(a.id ?? '').localeCompare(String(b.id ?? '')));
1043
+ const lines = [];
1044
+ const seen = new Set();
1045
+ const kinds = new Map();
1046
+ for (const node of sorted) {
1047
+ const type = typeof node.type === 'string' ? node.type : 'record';
1048
+ kinds.set(type, (kinds.get(type) ?? 0) + 1);
1049
+ const text = compactSourceText(node).replace(/\s+/g, ' ').trim().slice(0, 240);
1050
+ if (!text) continue;
1051
+ if (strategy === 'dedupe') {
1052
+ const key = text.toLocaleLowerCase();
1053
+ if (seen.has(key)) continue;
1054
+ seen.add(key);
1055
+ }
1056
+ lines.push(`- [${type}] ${text}`);
1057
+ }
1058
+ const kindSummary = [...kinds.entries()]
1059
+ .sort(([a], [b]) => a.localeCompare(b))
1060
+ .map(([kind, count]) => `${kind}:${count}`)
1061
+ .join(' ');
1062
+ const header = `Compact · ${sorted.length} records${kindSummary ? ` · ${kindSummary}` : ''}`;
1063
+ const rawSummary = lines.length > 0 ? `${header}\n${lines.join('\n')}` : header;
1064
+ const summary = truncateUtf8(rawSummary, MAX_COMPACT_SUMMARY_BYTES).text;
1065
+ return {
1066
+ summary,
1067
+ tokenCount: Math.max(1, Math.ceil([...summary].length / 4)),
1068
+ };
1069
+ }
1070
+
970
1071
  export function requestIdOf(req) {
971
1072
  const incoming = req?.headers?.['x-request-id'];
972
1073
  return typeof incoming === 'string' && REQUEST_ID_RE.test(incoming) ? incoming : `req_${randomUUID()}`;
@@ -1823,6 +1924,9 @@ function versionPayload() {
1823
1924
  * env?: NodeJS.ProcessEnv,
1824
1925
  * now?: () => number,
1825
1926
  * ttlMs?: number,
1927
+ * idempotencyMaintenanceIntervalMs?: number,
1928
+ * setIntervalFn?: typeof setInterval,
1929
+ * clearIntervalFn?: typeof clearInterval,
1826
1930
  * }} options
1827
1931
  */
1828
1932
  export function createMemoryCapabilityHandler({
@@ -1834,19 +1938,119 @@ export function createMemoryCapabilityHandler({
1834
1938
  env = process.env,
1835
1939
  now = () => Date.now(),
1836
1940
  ttlMs,
1941
+ idempotencyMaintenanceIntervalMs = IDEMPOTENCY_MAINTENANCE_INTERVAL_MS,
1942
+ setIntervalFn = setInterval,
1943
+ clearIntervalFn = clearInterval,
1837
1944
  } = {}) {
1838
1945
  let tokenRecord = null;
1839
1946
  let tokenPromise = null;
1840
1947
  let tokenError = null;
1841
1948
  let disposed = false;
1949
+ let idempotencyTimer = null;
1950
+ let idempotencyMaintenanceRun = null;
1951
+ let idempotencyMaintenanceStatus = {
1952
+ running: false,
1953
+ intervalMs: Math.max(10, Math.floor(idempotencyMaintenanceIntervalMs)),
1954
+ lastAttemptAt: null,
1955
+ lastSuccessAt: null,
1956
+ lastError: null,
1957
+ lastResult: null,
1958
+ };
1959
+ let checkpointMaintenanceRun = null;
1960
+ const checkpointMaintenanceStatus = {
1961
+ running: false,
1962
+ batchSize: 50,
1963
+ lastAttemptAt: null,
1964
+ lastSuccessAt: null,
1965
+ lastError: null,
1966
+ lastResult: null,
1967
+ };
1968
+ let revoked = false;
1969
+ let tokenGeneration = 0;
1970
+ let activeRequests = 0;
1971
+ // 同一 composite key 的在途单飞:并发同键请求共享一次 execute,避免超时重试
1972
+ // 与原请求各写一份。条目随主请求 promise 结算在 finally 清理。
1973
+ const idempotencyInFlight = new Map();
1974
+ const activeWaiters = new Set();
1975
+ let draining = false;
1976
+ let closePromise = null;
1842
1977
  const hostId = hostIdForHome(home);
1843
1978
 
1979
+ function finishActiveRequest() {
1980
+ activeRequests = Math.max(0, activeRequests - 1);
1981
+ if (activeRequests === 0) {
1982
+ for (const resolve of [...activeWaiters]) resolve();
1983
+ }
1984
+ }
1985
+
1986
+ /** 有界等待已认证的在途请求退出;false 表示仍有请求未结算(调用方必须报告 incomplete)。 */
1987
+ async function drain({ timeoutMs = 2000 } = {}) {
1988
+ if (activeRequests === 0) return true;
1989
+ await new Promise((resolve) => {
1990
+ const finish = () => {
1991
+ clearTimeout(timer);
1992
+ activeWaiters.delete(finish);
1993
+ resolve();
1994
+ };
1995
+ const timer = setTimeout(finish, Math.max(1, timeoutMs));
1996
+ timer.unref?.();
1997
+ activeWaiters.add(finish);
1998
+ });
1999
+ return activeRequests === 0;
2000
+ }
2001
+
2002
+ /**
2003
+ * 关闭能力面:先进入不可准入 draining,等待已认证请求(含真实图写)完成,
2004
+ * 再撤销 token。drain 超时则报告 incomplete 且不撤销 token,调用方不得声明 clean。
2005
+ */
2006
+ async function close({ timeoutMs = 5000 } = {}) {
2007
+ if (closePromise) return closePromise;
2008
+ draining = true;
2009
+ closePromise = (async () => {
2010
+ const clean = await drain({ timeoutMs });
2011
+ if (clean) await revoke();
2012
+ return { clean, active: activeRequests };
2013
+ })();
2014
+ return closePromise;
2015
+ }
2016
+
2017
+ /** drain 失败时放弃新请求,但不撤销 token / 不声明已撤销。 */
2018
+ function abandon() {
2019
+ draining = true;
2020
+ disposed = true;
2021
+ }
2022
+
2023
+ function beginDrain() {
2024
+ draining = true;
2025
+ }
2026
+
2027
+ function assertRequestGeneration(generation, operation = 'write') {
2028
+ if (disposed || revoked || draining || generation !== tokenGeneration) {
2029
+ throw new CapabilityError(409, 'mode_mismatch', '能力接口已撤销/关闭,写入未提交', {
2030
+ operation,
2031
+ }, false);
2032
+ }
2033
+ }
2034
+
2035
+ function isLifecycleError(error) {
2036
+ return error instanceof CapabilityError
2037
+ && error.status === 409
2038
+ && error.code === 'mode_mismatch';
2039
+ }
2040
+
1844
2041
  async function ensureToken() {
2042
+ if (disposed) {
2043
+ throw new CapabilityError(503, 'capability_unavailable', '能力接口已关闭', undefined, true);
2044
+ }
2045
+ if (revoked) {
2046
+ throw new CapabilityError(401, 'capability_token_invalid', 'capability token 已撤销');
2047
+ }
1845
2048
  const current = tokenRecord;
1846
2049
  if (current && !(typeof current.expiresAt === 'number' && current.expiresAt > 0 && now() >= current.expiresAt)) {
1847
2050
  return current;
1848
2051
  }
1849
2052
  if (!tokenPromise) {
2053
+ const generation = tokenGeneration;
1850
2054
  tokenPromise = ensureCapabilityToken({
1851
2055
  home,
1852
2056
  env,
@@ -1854,7 +2058,12 @@ export function createMemoryCapabilityHandler({
1854
2058
  mcpPid: process.pid,
1855
2059
  ...(ttlMs !== undefined ? { ttlMs } : {}),
1856
2060
  })
1857
- .then((record) => {
2061
+ .then(async (record) => {
2062
+ if (disposed || revoked || generation !== tokenGeneration) {
2063
+ // 撤销与生成竞态:晚到的生成不得复活 token 文件。
2064
+ await removeCapabilityToken({ home }).catch(() => undefined);
2065
+ throw new CapabilityError(401, 'capability_token_invalid', 'capability token 已撤销');
2066
+ }
1858
2067
  tokenRecord = record;
1859
2068
  tokenError = null;
1860
2069
  return record;
@@ -1871,9 +2080,19 @@ export function createMemoryCapabilityHandler({
1871
2080
  return tokenPromise;
1872
2081
  }
1873
2082
 
1874
- /** daemon 启动时调用(仅 enabled):提前生成 token 文件,sidecar 才能发现。 */
2083
+ /** daemon 启动时/显式恢复时调用(仅 enabled):准备 token 文件,sidecar 才能发现。 */
1875
2084
  async function prepare() {
2085
+ if (disposed) return { enabled: false, tokenId: null };
1876
2086
  if (!isMemoryRuntimeEnabled(getConfig())) return { enabled: false, tokenId: null };
2087
+ startIdempotencyMaintenance();
2088
+ // 先让上一代 token 生成收敛,再解除 revoke/draining 门闩;只有显式 prepare 能换发。
2089
+ const pending = tokenPromise;
2090
+ if (pending) await pending.catch(() => undefined);
2091
+ revoked = false;
2092
+ draining = false;
2093
+ closePromise = null;
2094
+ tokenError = null;
2095
+ tokenGeneration += 1;
1877
2096
  try {
1878
2097
  const record = await ensureToken();
1879
2098
  return { enabled: true, tokenId: record.tokenId };
@@ -1884,14 +2103,24 @@ export function createMemoryCapabilityHandler({
1884
2103
 
1885
2104
  /** 停用/关闭:撤销进程内 token 并删除 token 文件(旧 sidecar 下一次请求 401)。 */
1886
2105
  async function revoke() {
2106
+ revoked = true;
2107
+ draining = true;
2108
+ tokenGeneration += 1;
1887
2109
  tokenRecord = null;
1888
2110
  tokenError = null;
2111
+ const pending = tokenPromise;
2112
+ if (pending) await pending.catch(() => undefined);
1889
2113
  await removeCapabilityToken({ home });
1890
2114
  }
1891
2115
 
1892
2116
  async function dispose() {
1893
2117
  disposed = true;
2118
+ stopIdempotencyMaintenance();
2119
+ checkpointMaintenanceStatus.running = false;
2120
+ await idempotencyMaintenanceRun?.catch(() => undefined);
2121
+ await checkpointMaintenanceRun?.catch(() => undefined);
1894
2122
  await revoke();
2123
+ await drain({ timeoutMs: 2000 });
1895
2124
  }
1896
2125
 
1897
2126
  function identitySnapshot() {
@@ -1911,6 +2140,233 @@ export function createMemoryCapabilityHandler({
1911
2140
  };
1912
2141
  }
1913
2142
 
2143
+ // ---------- 写路径:幂等账本(24h,本地过渡数据,不进入图/同步) ----------
2144
+
2145
+ const ledgerDir = typeof home === 'string' && home.length > 0 ? join(home, 'memory-runtime') : null;
2146
+ const ledgerFile = ledgerDir ? join(ledgerDir, IDEMPOTENCY_LEDGER_FILE) : null;
2147
+ let ledger = null;
2148
+ let ledgerLoading = null;
2149
+ let ledgerLastPersisted = null;
2150
+ let ledgerWriteTail = Promise.resolve();
2151
+
2152
+ function sanitizeLedgerValue(value, key = '') {
2153
+ if (typeof value === 'string') {
2154
+ if (/^(?:authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|token|secret|password|passwd|credential|private[-_]?key)$/i.test(key)) {
2155
+ return '[redacted]';
2156
+ }
2157
+ return value
2158
+ .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[redacted]')
2159
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi, 'Bearer [redacted]')
2160
+ .replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
2161
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}\b/g, '[redacted]')
2162
+ .replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, '[redacted]')
2163
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted]')
2164
+ .replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g, '[redacted]')
2165
+ .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');
2166
+ }
2167
+ if (value === null || typeof value !== 'object') return value;
2168
+ if (Array.isArray(value)) return value.map((entry) => sanitizeLedgerValue(entry));
2169
+ const out = {};
2170
+ for (const [entryKey, entryValue] of Object.entries(value)) {
2171
+ if (entryValue !== undefined) out[entryKey] = sanitizeLedgerValue(entryValue, entryKey);
2172
+ }
2173
+ return out;
2174
+ }
2175
+
2176
+ function sanitizeLedgerEntry(entry) {
2177
+ return {
2178
+ key: entry.key,
2179
+ requestHash: entry.requestHash,
2180
+ at: entry.at,
2181
+ data: sanitizeLedgerValue(entry.data),
2182
+ warnings: sanitizeLedgerValue(entry.warnings ?? []),
2183
+ degraded: entry.degraded === true,
2184
+ };
2185
+ }
2186
+
2187
+ async function ledgerState() {
2188
+ if (ledger) return ledger;
2189
+ if (!ledgerFile) {
2190
+ ledger = new Map();
2191
+ return ledger;
2192
+ }
2193
+ if (!ledgerLoading) {
2194
+ ledgerLoading = (async () => {
2195
+ const state = new Map();
2196
+ try {
2197
+ const raw = JSON.parse(await readFile(ledgerFile, 'utf-8'));
2198
+ if (raw?.version === IDEMPOTENCY_LEDGER_VERSION && Array.isArray(raw.entries)) {
2199
+ ledgerLastPersisted = JSON.stringify({ version: raw.version, entries: raw.entries });
2200
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2201
+ for (const entry of raw.entries) {
2202
+ if (!isObject(entry) || typeof entry.key !== 'string' || !isObject(entry.data)) continue;
2203
+ if (typeof entry.at !== 'number' || entry.at <= cutoff) continue;
2204
+ state.set(entry.key, sanitizeLedgerEntry(entry));
2205
+ }
2206
+ }
2207
+ } catch {
2208
+ // 账本损坏/不存在:按空处理;clientItemId 与内容 hash 仍可防重。
2209
+ }
2210
+ ledger = state;
2211
+ return state;
2212
+ })().finally(() => {
2213
+ ledgerLoading = null;
2214
+ });
2215
+ }
2216
+ return ledgerLoading;
2217
+ }
2218
+
2219
+ async function saveLedgerUnlocked(state) {
2220
+ if (!ledgerFile || !ledgerDir) return 0;
2221
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2222
+ for (const [key, entry] of state) {
2223
+ if (typeof entry.at !== 'number' || entry.at <= cutoff) state.delete(key);
2224
+ }
2225
+ while (state.size > IDEMPOTENCY_MAX_ENTRIES) {
2226
+ const oldest = state.keys().next().value;
2227
+ if (oldest === undefined) break;
2228
+ state.delete(oldest);
2229
+ }
2230
+ const payload = {
2231
+ version: IDEMPOTENCY_LEDGER_VERSION,
2232
+ entries: [...state.values()].map(sanitizeLedgerEntry),
2233
+ };
2234
+ // 空账本且从未存在文件时不创建目录/文件(env-only token 与轻量启动保持零副作用)。
2235
+ if (state.size === 0 && ledgerLastPersisted === null) return 0;
2236
+ const serialized = JSON.stringify(payload);
2237
+ if (serialized === ledgerLastPersisted) return Buffer.byteLength(serialized, 'utf8');
2238
+ await mkdir(ledgerDir, { recursive: true, mode: 0o700 });
2239
+ await chmod(ledgerDir, 0o700);
2240
+ const tmp = `${ledgerFile}.tmp-${process.pid}-${randomUUID()}`;
2241
+ try {
2242
+ await writeFile(tmp, serialized, { encoding: 'utf-8', mode: 0o600 });
2243
+ await chmod(tmp, 0o600);
2244
+ await rename(tmp, ledgerFile);
2245
+ await chmod(ledgerFile, 0o600);
2246
+ ledgerLastPersisted = serialized;
2247
+ return Buffer.byteLength(serialized, 'utf8');
2248
+ } catch (error) {
2249
+ await rm(tmp, { force: true }).catch(() => undefined);
2250
+ throw error;
2251
+ }
2252
+ }
2253
+
2254
+ function saveLedger(state) {
2255
+ const run = ledgerWriteTail.then(
2256
+ () => saveLedgerUnlocked(state),
2257
+ () => saveLedgerUnlocked(state),
2258
+ );
2259
+ ledgerWriteTail = run.then(() => undefined, () => undefined);
2260
+ return run;
2261
+ }
2262
+
2263
+ function runIdempotencyMaintenance() {
2264
+ if (idempotencyMaintenanceRun) return idempotencyMaintenanceRun;
2265
+ const at = now();
2266
+ idempotencyMaintenanceStatus.lastAttemptAt = at;
2267
+ idempotencyMaintenanceRun = (async () => {
2268
+ try {
2269
+ const state = await ledgerState();
2270
+ const before = state.size;
2271
+ const bytes = await saveLedger(state);
2272
+ const oldestAt = state.size > 0 ? Math.min(...[...state.values()].map((entry) => entry.at)) : null;
2273
+ idempotencyMaintenanceStatus.lastSuccessAt = at;
2274
+ idempotencyMaintenanceStatus.lastError = null;
2275
+ idempotencyMaintenanceStatus.lastResult = {
2276
+ removed: Math.max(0, before - state.size),
2277
+ count: state.size,
2278
+ bytes,
2279
+ oldestAgeMs: oldestAt === null ? null : Math.max(0, at - oldestAt),
2280
+ at,
2281
+ };
2282
+ return idempotencyMaintenanceStatus.lastResult;
2283
+ } catch (error) {
2284
+ const code = typeof error?.code === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(error.code)
2285
+ ? error.code
2286
+ : 'idempotency_maintenance_failed';
2287
+ idempotencyMaintenanceStatus.lastError = { code, at };
2288
+ return idempotencyMaintenanceStatus.lastError;
2289
+ } finally {
2290
+ idempotencyMaintenanceRun = null;
2291
+ }
2292
+ })();
2293
+ return idempotencyMaintenanceRun;
2294
+ }
2295
+
2296
+ function startIdempotencyMaintenance() {
2297
+ if (idempotencyTimer || disposed) return;
2298
+ idempotencyTimer = setIntervalFn(() => {
2299
+ void runIdempotencyMaintenance();
2300
+ void runCheckpointMaintenance();
2301
+ }, idempotencyMaintenanceStatus.intervalMs);
2302
+ idempotencyTimer?.unref?.();
2303
+ idempotencyMaintenanceStatus.running = true;
2304
+ checkpointMaintenanceStatus.running = true;
2305
+ void runIdempotencyMaintenance();
2306
+ void runCheckpointMaintenance();
2307
+ }
2308
+
2309
+ function stopIdempotencyMaintenance() {
2310
+ if (idempotencyTimer) {
2311
+ clearIntervalFn(idempotencyTimer);
2312
+ idempotencyTimer = null;
2313
+ }
2314
+ idempotencyMaintenanceStatus.running = false;
2315
+ }
2316
+
2317
+
2318
+ // [internal-object-write] 内部对象允许直接 GraphStore 写入;普通 MemoryRecord 禁止。
2319
+ function runCheckpointMaintenance() {
2320
+ if (checkpointMaintenanceRun) return checkpointMaintenanceRun;
2321
+ const at = now();
2322
+ checkpointMaintenanceStatus.lastAttemptAt = at;
2323
+ checkpointMaintenanceRun = (async () => {
2324
+ try {
2325
+ const appValue = getApp?.() ?? null;
2326
+ if (!appValue) {
2327
+ const result = { removed: 0, scanned: 0, checkedAt: at, skipped: 'capability_unavailable' };
2328
+ checkpointMaintenanceStatus.lastResult = result;
2329
+ return result;
2330
+ }
2331
+ const nodes = await listNodesOfType(appValue, 'context_checkpoint');
2332
+ const expired = nodes
2333
+ .filter((node) => node && !node.deletedAt
2334
+ && isV2CheckpointNode(node)
2335
+ && internalObjectKind(node) === 'context_checkpoint'
2336
+ && checkpointExpired(node, at))
2337
+ .slice(0, checkpointMaintenanceStatus.batchSize);
2338
+ let removed = 0;
2339
+ for (const node of expired) {
2340
+ await appValue.graph.deleteNode(node.id);
2341
+ removed += 1;
2342
+ }
2343
+ const result = {
2344
+ removed,
2345
+ scanned: nodes.length,
2346
+ remainingExpired: Math.max(0, nodes.filter((node) => node && !node.deletedAt
2347
+ && isV2CheckpointNode(node)
2348
+ && internalObjectKind(node) === 'context_checkpoint'
2349
+ && checkpointExpired(node, at)).length - removed),
2350
+ checkedAt: at,
2351
+ };
2352
+ checkpointMaintenanceStatus.lastSuccessAt = at;
2353
+ checkpointMaintenanceStatus.lastError = null;
2354
+ checkpointMaintenanceStatus.lastResult = result;
2355
+ return result;
2356
+ } catch (error) {
2357
+ const code = typeof error?.code === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(error.code)
2358
+ ? error.code
2359
+ : 'checkpoint_maintenance_failed';
2360
+ checkpointMaintenanceStatus.lastError = { code, at };
2361
+ return checkpointMaintenanceStatus.lastError;
2362
+ } finally {
2363
+ checkpointMaintenanceRun = null;
2364
+ }
2365
+ })();
2366
+ return checkpointMaintenanceRun;
2367
+ }
2368
+
2369
+
1914
2370
  const handle = async function handleMemoryCapabilityRequest({ req, res, url, body }) {
1915
2371
  const path = url?.pathname ?? '';
1916
2372
  if (!isMemoryCapabilityPath(path)) return false;
@@ -2026,71 +2482,6 @@ export function createMemoryCapabilityHandler({
2026
2482
  return parsed;
2027
2483
  };
2028
2484
 
2029
- // ---------- 写路径:幂等账本(24h,本地过渡数据,不进入图/同步) ----------
2030
-
2031
- const ledgerDir = typeof home === 'string' && home.length > 0 ? join(home, 'memory-runtime') : null;
2032
- const ledgerFile = ledgerDir ? join(ledgerDir, IDEMPOTENCY_LEDGER_FILE) : null;
2033
- let ledger = null;
2034
- let ledgerLoading = null;
2035
-
2036
- async function ledgerState() {
2037
- if (ledger) return ledger;
2038
- if (!ledgerFile) {
2039
- ledger = new Map();
2040
- return ledger;
2041
- }
2042
- if (!ledgerLoading) {
2043
- ledgerLoading = (async () => {
2044
- const state = new Map();
2045
- try {
2046
- const raw = JSON.parse(await readFile(ledgerFile, 'utf-8'));
2047
- if (raw?.version === IDEMPOTENCY_LEDGER_VERSION && Array.isArray(raw.entries)) {
2048
- const cutoff = now() - IDEMPOTENCY_TTL_MS;
2049
- for (const entry of raw.entries) {
2050
- if (!isObject(entry) || typeof entry.key !== 'string' || !isObject(entry.data)) continue;
2051
- if (typeof entry.at !== 'number' || entry.at < cutoff) continue;
2052
- state.set(entry.key, entry);
2053
- }
2054
- }
2055
- } catch {
2056
- // 账本损坏/不存在:按空处理;clientItemId 与内容 hash 仍可防重。
2057
- }
2058
- ledger = state;
2059
- return state;
2060
- })().finally(() => {
2061
- ledgerLoading = null;
2062
- });
2063
- }
2064
- return ledgerLoading;
2065
- }
2066
-
2067
- async function saveLedger(state) {
2068
- if (!ledgerFile || !ledgerDir) return;
2069
- const cutoff = now() - IDEMPOTENCY_TTL_MS;
2070
- const entries = [...state.values()].filter((entry) => entry.at >= cutoff);
2071
- while (entries.length > IDEMPOTENCY_MAX_ENTRIES) {
2072
- const oldest = entries.shift();
2073
- if (oldest) state.delete(oldest.key);
2074
- }
2075
- // 重新过滤:淘汰后 entries 与 state 保持一致。
2076
- const payload = {
2077
- version: IDEMPOTENCY_LEDGER_VERSION,
2078
- entries: entries.filter((entry) => state.has(entry.key)),
2079
- };
2080
- await mkdir(ledgerDir, { recursive: true, mode: 0o700 });
2081
- await chmod(ledgerDir, 0o700);
2082
- const tmp = `${ledgerFile}.tmp-${process.pid}-${randomUUID()}`;
2083
- try {
2084
- await writeFile(tmp, JSON.stringify(payload), { encoding: 'utf-8', mode: 0o600 });
2085
- await chmod(tmp, 0o600);
2086
- await rename(tmp, ledgerFile);
2087
- await chmod(ledgerFile, 0o600);
2088
- } catch (error) {
2089
- await rm(tmp, { force: true }).catch(() => undefined);
2090
- throw error;
2091
- }
2092
- }
2093
-
2094
2485
  function idempotencyKeyOf(req, payload) {
2095
2486
  const header = req?.headers?.['idempotency-key'];
2096
2487
  if (hasValue(header) && header !== '') {
@@ -2111,58 +2502,116 @@ export function createMemoryCapabilityHandler({
2111
2502
  async function withIdempotency(route, payload, tokenId, execute) {
2112
2503
  const key = idempotencyKeyOf(req, payload);
2113
2504
  if (key === null) return execute();
2114
- const state = await ledgerState();
2115
2505
  const composite = `${tokenId ?? 'none'}\u0000${route}\u0000${key}`;
2116
2506
  const requestHash = sha256Hex(canonicalJson(payload));
2117
- const existing = state.get(composite);
2118
- if (existing) {
2119
- if (existing.requestHash !== requestHash) {
2507
+
2508
+ const joinFlight = (flight) => {
2509
+ if (flight.requestHash !== requestHash) {
2120
2510
  throw new CapabilityError(409, 'idempotency_conflict', '同一幂等键对应了不同请求体', {
2121
2511
  key,
2122
2512
  route,
2123
2513
  });
2124
2514
  }
2125
- return {
2126
- data: { ...jsonClone(existing.data), replayed: true },
2127
- warnings: jsonClone(existing.warnings ?? []),
2128
- degraded: existing.degraded === true,
2515
+ // 等待同一在途执行,返回等价的深拷贝,避免两个响应共享可变对象。
2516
+ return flight.promise.then((result) => jsonClone(result));
2517
+ };
2518
+
2519
+ const inFlight = idempotencyInFlight.get(composite);
2520
+ if (inFlight) return joinFlight(inFlight);
2521
+
2522
+ const flight = { requestHash, promise: null };
2523
+ flight.promise = (async () => {
2524
+ const state = await ledgerState();
2525
+ let existing = state.get(composite);
2526
+ if (existing && (typeof existing.at !== 'number' || existing.at <= now() - IDEMPOTENCY_TTL_MS)) {
2527
+ state.delete(composite);
2528
+ existing = null;
2529
+ }
2530
+ if (existing) {
2531
+ if (existing.requestHash !== requestHash) {
2532
+ throw new CapabilityError(409, 'idempotency_conflict', '同一幂等键对应了不同请求体', {
2533
+ key,
2534
+ route,
2535
+ });
2536
+ }
2537
+ return {
2538
+ data: { ...jsonClone(existing.data), replayed: true },
2539
+ warnings: jsonClone(existing.warnings ?? []),
2540
+ degraded: existing.degraded === true,
2541
+ };
2542
+ }
2543
+ const result = await execute();
2544
+ // 空/缺项/部分响应不进入幂等缓存:同一 outbox 键必须能重新执行未确认项。
2545
+ // 已成功项仍由 clientItemId/contentHash 去重,不会重复写。
2546
+ if ((route === 'write' || route === 'detail:write') && Array.isArray(payload.items)) {
2547
+ const results = result?.data?.results;
2548
+ const expectedIds = payload.items.map((item) => item?.clientItemId).filter((id) => typeof id === 'string');
2549
+ const actualIds = Array.isArray(results)
2550
+ ? results.map((entry) => entry?.clientItemId).filter((id) => typeof id === 'string')
2551
+ : [];
2552
+ const allHaveClientItemIds = expectedIds.length === payload.items.length;
2553
+ const hasUnexpected = allHaveClientItemIds && actualIds.some((id) => !expectedIds.includes(id));
2554
+ const hasMissing = allHaveClientItemIds && expectedIds.some((id) => !actualIds.includes(id));
2555
+ const hasFailedResult = Array.isArray(results) && results.some((entry) =>
2556
+ entry?.status !== 'created' && entry?.status !== 'duplicate');
2557
+ // 成功状态也必须带可重放的权威字段;malformed 成功响应不得进入永久账本。
2558
+ const hasMalformedSuccess = Array.isArray(results) && results.some((entry) => {
2559
+ if (!isObject(entry) || (entry.status !== 'created' && entry.status !== 'duplicate')) return false;
2560
+ if (typeof entry.id !== 'string' || entry.id.trim().length === 0) return true;
2561
+ if ((route === 'write' || route === 'detail:write')
2562
+ && (typeof entry.domain !== 'string' || entry.domain.trim().length === 0)) return true;
2563
+ if (route === 'detail:write'
2564
+ && (typeof entry.detailKind !== 'string' || entry.detailKind.trim().length === 0)) return true;
2565
+ return false;
2566
+ });
2567
+ if (result?.data?.partial === true
2568
+ || (typeof result?.data?.failed === 'number' && result.data.failed > 0)
2569
+ || !Array.isArray(results)
2570
+ || results.length !== payload.items.length
2571
+ || hasUnexpected
2572
+ || hasMissing
2573
+ || hasFailedResult
2574
+ || hasMalformedSuccess) {
2575
+ return result;
2576
+ }
2577
+ }
2578
+ const entry = {
2579
+ key: composite,
2580
+ requestHash,
2581
+ at: now(),
2582
+ data: jsonClone({ ...(result.data ?? {}), replayed: false }),
2583
+ warnings: jsonClone(result.warnings ?? []),
2584
+ degraded: result.degraded === true,
2129
2585
  };
2130
- }
2131
- const result = await execute();
2132
- // 详情批量部分失败不缓存:同一 outbox 键重放时应重新尝试失败项;
2133
- // 已成功项仍由 clientItemId/contentHash 去重,不会重复写。
2134
- if (route === 'detail:write' && result?.data?.partial === true) {
2586
+ // LRU:同键刷新到队尾。
2587
+ state.delete(composite);
2588
+ state.set(composite, sanitizeLedgerEntry(entry));
2589
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2590
+ for (const [entryKey, value] of state) {
2591
+ if (typeof value.at !== 'number' || value.at <= cutoff) state.delete(entryKey);
2592
+ }
2593
+ while (state.size > IDEMPOTENCY_MAX_ENTRIES) {
2594
+ const oldest = state.keys().next().value;
2595
+ if (oldest === undefined) break;
2596
+ state.delete(oldest);
2597
+ }
2598
+ try {
2599
+ await saveLedger(state);
2600
+ } catch {
2601
+ result.warnings = [
2602
+ ...(result.warnings ?? []),
2603
+ { code: 'idempotency_ledger_unavailable', message: '幂等账本写入失败;仍可依赖内容 hash 防重' },
2604
+ ];
2605
+ }
2135
2606
  return result;
2136
- }
2137
- const entry = {
2138
- key: composite,
2139
- requestHash,
2140
- at: now(),
2141
- data: jsonClone({ ...(result.data ?? {}), replayed: false }),
2142
- warnings: jsonClone(result.warnings ?? []),
2143
- degraded: result.degraded === true,
2144
- };
2145
- // LRU:同键刷新到队尾。
2146
- state.delete(composite);
2147
- state.set(composite, entry);
2148
- const cutoff = now() - IDEMPOTENCY_TTL_MS;
2149
- for (const [entryKey, value] of state) {
2150
- if (typeof value.at !== 'number' || value.at < cutoff) state.delete(entryKey);
2151
- }
2152
- while (state.size > IDEMPOTENCY_MAX_ENTRIES) {
2153
- const oldest = state.keys().next().value;
2154
- if (oldest === undefined) break;
2155
- state.delete(oldest);
2156
- }
2607
+ })();
2608
+ idempotencyInFlight.set(composite, flight);
2157
2609
  try {
2158
- await saveLedger(state);
2159
- } catch {
2160
- result.warnings = [
2161
- ...(result.warnings ?? []),
2162
- { code: 'idempotency_ledger_unavailable', message: '幂等账本写入失败;仍可依赖内容 hash 防重' },
2163
- ];
2610
+ return await flight.promise;
2611
+ } finally {
2612
+ // 只清理自己的条目;主请求失败时也要释放,后续同键请求可重试。
2613
+ if (idempotencyInFlight.get(composite) === flight) idempotencyInFlight.delete(composite);
2164
2614
  }
2165
- return result;
2166
2615
  }
2167
2616
 
2168
2617
  // ---------- /write ----------
@@ -2360,7 +2809,8 @@ export function createMemoryCapabilityHandler({
2360
2809
  };
2361
2810
  }
2362
2811
 
2363
- async function performWriteItem(appValue, item) {
2812
+ async function performWriteItem(appValue, item, generation) {
2813
+ assertRequestGeneration(generation, 'write');
2364
2814
  if (!appValue?.graph?.getNode) {
2365
2815
  throw new CapabilityError(503, 'capability_unavailable', '图存储不可用', undefined, true);
2366
2816
  }
@@ -2402,10 +2852,11 @@ export function createMemoryCapabilityHandler({
2402
2852
  return { node: stored.node, warnings };
2403
2853
  }
2404
2854
 
2405
- async function applyWriteSupersedes(item, newNode) {
2855
+ async function applyWriteSupersedes(item, newNode, generation) {
2406
2856
  if (!Array.isArray(item.supersedes) || item.supersedes.length === 0) {
2407
2857
  return { superseded: [], skipped: [] };
2408
2858
  }
2859
+ assertRequestGeneration(generation, 'write.supersede');
2409
2860
  const currentService = service();
2410
2861
  if (typeof currentService.supersedeRecords !== 'function') {
2411
2862
  throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持记录替代', undefined, true);
@@ -2417,7 +2868,7 @@ export function createMemoryCapabilityHandler({
2417
2868
  });
2418
2869
  }
2419
2870
 
2420
- async function handleWrite(payload, actor) {
2871
+ async function handleWrite(payload, actor, generation) {
2421
2872
  const items = payload.items;
2422
2873
  if (!Array.isArray(items) || items.length === 0) {
2423
2874
  throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
@@ -2452,7 +2903,7 @@ export function createMemoryCapabilityHandler({
2452
2903
  ?? dedupe.hash.get(dedupeKey('hash', item.domain, item.contentHash));
2453
2904
  if (existing) {
2454
2905
  try {
2455
- const replaced = await applyWriteSupersedes(item, existing);
2906
+ const replaced = await applyWriteSupersedes(item, existing, generation);
2456
2907
  duplicates += 1;
2457
2908
  results.push(recordWriteResult('duplicate', existing, item, item.owner, replaced.superseded));
2458
2909
  for (const id of replaced.skipped) {
@@ -2463,6 +2914,7 @@ export function createMemoryCapabilityHandler({
2463
2914
  });
2464
2915
  }
2465
2916
  } catch (error) {
2917
+ if (isLifecycleError(error)) throw error;
2466
2918
  failed += 1;
2467
2919
  results.push({
2468
2920
  ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
@@ -2477,10 +2929,10 @@ export function createMemoryCapabilityHandler({
2477
2929
  continue;
2478
2930
  }
2479
2931
  try {
2480
- const written = await performWriteItem(appValue, item);
2932
+ const written = await performWriteItem(appValue, item, generation);
2481
2933
  warnings.push(...written.warnings);
2482
2934
  const node = written.node;
2483
- const replaced = await applyWriteSupersedes(item, node);
2935
+ const replaced = await applyWriteSupersedes(item, node, generation);
2484
2936
  for (const id of replaced.skipped) {
2485
2937
  warnings.push({
2486
2938
  code: 'supersedes_skipped',
@@ -2495,6 +2947,7 @@ export function createMemoryCapabilityHandler({
2495
2947
  }
2496
2948
  dedupe.hash.set(dedupeKey('hash', item.domain, item.contentHash), node);
2497
2949
  } catch (error) {
2950
+ if (isLifecycleError(error)) throw error;
2498
2951
  failed += 1;
2499
2952
  results.push({
2500
2953
  ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
@@ -2536,7 +2989,7 @@ export function createMemoryCapabilityHandler({
2536
2989
  return raw;
2537
2990
  }
2538
2991
 
2539
- async function handleUpdate(payload, actor) {
2992
+ async function handleUpdate(payload, actor, generation) {
2540
2993
  const items = payload.items;
2541
2994
  if (!Array.isArray(items) || items.length === 0) {
2542
2995
  throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
@@ -2682,6 +3135,7 @@ export function createMemoryCapabilityHandler({
2682
3135
  let failed = 0;
2683
3136
  for (const plan of plans) {
2684
3137
  try {
3138
+ assertRequestGeneration(generation, 'update');
2685
3139
  const currentService = service();
2686
3140
  if (typeof currentService.updateRecord !== 'function') {
2687
3141
  throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持统一更新', undefined, true);
@@ -2718,6 +3172,7 @@ export function createMemoryCapabilityHandler({
2718
3172
  validTo: normalizeValidTo(node.validTo),
2719
3173
  });
2720
3174
  } catch (error) {
3175
+ if (isLifecycleError(error)) throw error;
2721
3176
  failed += 1;
2722
3177
  results.push({
2723
3178
  id: plan.id,
@@ -2782,12 +3237,14 @@ export function createMemoryCapabilityHandler({
2782
3237
  return { appValue, nodes, allowed, notFound, forbidden, internal };
2783
3238
  }
2784
3239
 
2785
- async function handleDelete(payload, actor) {
3240
+ async function handleDelete(payload, actor, generation) {
2786
3241
  if (payload.sync !== undefined) {
2787
3242
  throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync 字段');
2788
3243
  }
3244
+ assertRequestGeneration(generation, 'delete');
2789
3245
  const ids = parseIdList(payload);
2790
3246
  const classified = await classifyGovernanceTargets(ids, actor);
3247
+ assertRequestGeneration(generation, 'delete.commit');
2791
3248
  const deleted = [];
2792
3249
  let detailsDeleted = [];
2793
3250
  if (classified.allowed.length > 0) {
@@ -2814,16 +3271,18 @@ export function createMemoryCapabilityHandler({
2814
3271
  };
2815
3272
  }
2816
3273
 
2817
- async function handleArchive(payload, actor) {
3274
+ async function handleArchive(payload, actor, generation) {
2818
3275
  if (payload.sync !== undefined) {
2819
3276
  throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync 字段');
2820
3277
  }
3278
+ assertRequestGeneration(generation, 'archive');
2821
3279
  if (payload.archived !== undefined && typeof payload.archived !== 'boolean') {
2822
3280
  throw new CapabilityError(400, 'invalid_request', 'archived 必须是布尔值');
2823
3281
  }
2824
3282
  const archived = payload.archived !== false;
2825
3283
  const ids = parseIdList(payload);
2826
3284
  const classified = await classifyGovernanceTargets(ids, actor);
3285
+ assertRequestGeneration(generation, 'archive.commit');
2827
3286
  const skipped = [];
2828
3287
  const allowed = [];
2829
3288
  for (const id of classified.allowed) {
@@ -2889,7 +3348,6 @@ export function createMemoryCapabilityHandler({
2889
3348
  && internalObjectMetadata(node).identityKey === identityKey) ?? null;
2890
3349
  }
2891
3350
 
2892
- // [internal-object-write] 内部对象允许直接 GraphStore 写入;普通 MemoryRecord 禁止。
2893
3351
  async function handleCompactObject(payload, actor) { const op = payload.op;
2894
3352
  if (!['upsert', 'get', 'list', 'delete'].includes(op)) {
2895
3353
  throw new CapabilityError(400, 'internal_kind_invalid', 'compact op 必须是 upsert/get/list/delete');
@@ -2930,13 +3388,9 @@ export function createMemoryCapabilityHandler({
2930
3388
  }
2931
3389
  const provenanceInput = parseProvenanceInput(payload.provenance, 0);
2932
3390
  assertDomainWrite(actor, domain, provenanceInput, payload.threadId);
2933
- const summary = nonEmptyString(payload.summary, 'summary', 0);
2934
- if (Buffer.byteLength(summary, 'utf-8') > MAX_COMPACT_SUMMARY_BYTES) {
2935
- throw new CapabilityError(413, 'payload_too_large', 'summary 超过 64 KiB');
2936
- }
2937
- const tokenCount = optionalNumber(payload.tokenCount, 'tokenCount', 0);
2938
- if (tokenCount !== undefined && tokenCount < 0) {
2939
- throw validationError(0, 'tokenCount', 'tokenCount 不能为负数');
3391
+ const deferredSummary = payload.deferredSummary === true;
3392
+ if (!deferredSummary && payload.summary !== undefined && typeof payload.summary !== 'string') {
3393
+ throw validationError(0, 'summary', 'summary 必须是字符串');
2940
3394
  }
2941
3395
  const model = isObject(payload.model) ? jsonClone(payload.model) : undefined;
2942
3396
  if (model && byteSize(model) > MAX_JSON_FIELD_BYTES) {
@@ -2961,6 +3415,32 @@ export function createMemoryCapabilityHandler({
2961
3415
  }
2962
3416
  sourceNodes.push(source);
2963
3417
  }
3418
+ let summary;
3419
+ let tokenCount;
3420
+ if (deferredSummary) {
3421
+ const regenerated = buildCompactSummaryFromNodes(sourceNodes, strategy);
3422
+ if (!regenerated.summary.includes('\n')) {
3423
+ throw new CapabilityError(422, 'compact_summary_placeholder', 'compact 来源没有可摘要正文');
3424
+ }
3425
+ summary = regenerated.summary;
3426
+ if (Buffer.byteLength(summary, 'utf-8') > MAX_COMPACT_SUMMARY_BYTES) {
3427
+ throw new CapabilityError(413, 'payload_too_large', 'summary 超过 64 KiB');
3428
+ }
3429
+ tokenCount = regenerated.tokenCount;
3430
+ } else {
3431
+ summary = nonEmptyString(payload.summary, 'summary', 0);
3432
+ if (Buffer.byteLength(summary, 'utf-8') > MAX_COMPACT_SUMMARY_BYTES) {
3433
+ throw new CapabilityError(413, 'payload_too_large', 'summary 超过 64 KiB');
3434
+ }
3435
+ // 只有标题/计数的占位摘要不得落图;恢复路径应使用 deferredSummary。
3436
+ if (/^Compact · \d+ records(?: · [^\n]*)?$/.test(summary.trim())) {
3437
+ throw new CapabilityError(422, 'compact_summary_placeholder', 'compact 摘要不能是占位标题');
3438
+ }
3439
+ tokenCount = optionalNumber(payload.tokenCount, 'tokenCount', 0);
3440
+ if (tokenCount !== undefined && tokenCount < 0) {
3441
+ throw validationError(0, 'tokenCount', 'tokenCount 不能为负数');
3442
+ }
3443
+ }
2964
3444
  const effectiveSourceHashes = sourceHashes.length > 0
2965
3445
  ? [...sourceHashes]
2966
3446
  : sourceNodes.map((source) => `sha256:${sha256Hex(canonicalJson(source.content ?? null))}`);
@@ -3175,6 +3655,82 @@ export function createMemoryCapabilityHandler({
3175
3655
  };
3176
3656
  }
3177
3657
 
3658
+ function checkpointGraphReferences(state, payload) {
3659
+ const recordIds = [
3660
+ ...(Array.isArray(payload.recordIds) ? payload.recordIds : []),
3661
+ ...(Array.isArray(state?.references?.recordIds) ? state.references.recordIds : []),
3662
+ ...(Array.isArray(state?.decisions) ? state.decisions.flatMap((entry) => entry?.recordIds ?? []) : []),
3663
+ ...(isObject(state?.progress)
3664
+ ? ['done', 'doing', 'blocked'].flatMap((key) => (
3665
+ Array.isArray(state.progress[key]) ? state.progress[key].flatMap((entry) => entry?.recordIds ?? []) : []
3666
+ ))
3667
+ : []),
3668
+ ];
3669
+ const detailIds = [
3670
+ ...(Array.isArray(payload.detailIds) ? payload.detailIds : []),
3671
+ ...(Array.isArray(state?.references?.detailIds) ? state.references.detailIds : []),
3672
+ ];
3673
+ return {
3674
+ recordIds: [...new Set(recordIds.filter((id) => typeof id === 'string' && id.length > 0))],
3675
+ detailIds: [...new Set(detailIds.filter((id) => typeof id === 'string' && id.length > 0))],
3676
+ };
3677
+ }
3678
+
3679
+ async function validateCheckpointGraphReferences(appValue, checkpointDomain, { recordIds, detailIds }) {
3680
+ let referenceDomain = null;
3681
+ for (const id of recordIds) {
3682
+ const node = await appValue.graph.getNode(id);
3683
+ if (!node || node.deletedAt) {
3684
+ throw new CapabilityError(404, 'not_found', 'checkpoint 引用的 MemoryRecord 不存在或已删除', { id });
3685
+ }
3686
+ if (isInternalNode(node) || !RECORD_NODE_TYPES.has(node.type)) {
3687
+ throw new CapabilityError(400, 'invalid_reference_type', 'checkpoint recordIds 必须是 MemoryRecord', {
3688
+ id,
3689
+ type: node.type,
3690
+ });
3691
+ }
3692
+ const domain = domainOfNamespace(node.namespace);
3693
+ if (domain.startsWith('__')) {
3694
+ throw new CapabilityError(400, 'invalid_reference_type', 'checkpoint 不能引用内部域对象', { id, domain });
3695
+ }
3696
+ if (domain !== checkpointDomain) {
3697
+ throw new CapabilityError(400, 'domain_mismatch', 'checkpoint 引用必须与 checkpoint 同域', {
3698
+ domain: checkpointDomain,
3699
+ referenceDomain: domain,
3700
+ id,
3701
+ });
3702
+ }
3703
+ referenceDomain = domain;
3704
+ }
3705
+ for (const id of detailIds) {
3706
+ const node = await appValue.graph.getNode(id);
3707
+ if (!node || node.deletedAt) {
3708
+ throw new CapabilityError(404, 'not_found', 'checkpoint 引用的 DetailRecord 不存在或已删除', { id });
3709
+ }
3710
+ if (node.type !== 'detail_record') {
3711
+ throw new CapabilityError(400, 'invalid_reference_type', 'checkpoint detailIds 必须是 DetailRecord', {
3712
+ id,
3713
+ type: node.type,
3714
+ });
3715
+ }
3716
+ const content = isObject(node.content) ? node.content : {};
3717
+ const expiresAt = typeof content.expiresAt === 'number' ? content.expiresAt : 0;
3718
+ if (expiresAt > 0 && expiresAt < now()) {
3719
+ throw new CapabilityError(400, 'reference_expired', 'checkpoint 不能引用已过期 DetailRecord', { id });
3720
+ }
3721
+ const domain = domainOfNamespace(node.namespace);
3722
+ if (domain !== checkpointDomain) {
3723
+ throw new CapabilityError(400, 'domain_mismatch', 'checkpoint 引用必须与 checkpoint 同域', {
3724
+ domain: checkpointDomain,
3725
+ referenceDomain: domain,
3726
+ id,
3727
+ });
3728
+ }
3729
+ referenceDomain = domain;
3730
+ }
3731
+ return referenceDomain;
3732
+ }
3733
+
3178
3734
  async function handleCheckpointObject(payload, actor) {
3179
3735
  const op = payload.op;
3180
3736
  if (!['upsert', 'get', 'list', 'delete'].includes(op)) {
@@ -3239,15 +3795,25 @@ export function createMemoryCapabilityHandler({
3239
3795
  let visible = null;
3240
3796
  for (const domain of candidates) {
3241
3797
  const node = await currentCheckpoint(appValue, { agentId, threadId, domain });
3242
- if (!node || checkpointExpired(node, now())) continue;
3798
+ if (!node || node.deletedAt || checkpointExpired(node, now())) continue;
3243
3799
  visible = node;
3244
3800
  break;
3245
3801
  }
3246
3802
  const view = visible ? checkpointObjectView(visible, { userId: identity.userId }) : null;
3247
3803
  if (view) assertCheckpointRead(view.domain);
3804
+ let highWater = 0;
3805
+ for (const entry of candidates) {
3806
+ highWater = Math.max(highWater, await highestCheckpointRevision(appValue, {
3807
+ agentId,
3808
+ threadId,
3809
+ domain: entry,
3810
+ }));
3811
+ }
3248
3812
  return {
3249
3813
  data: {
3250
3814
  object: view,
3815
+ highWater,
3816
+ latestRevision: highWater,
3251
3817
  replayed: false,
3252
3818
  },
3253
3819
  warnings: checkpointWarnings(view),
@@ -3259,16 +3825,17 @@ export function createMemoryCapabilityHandler({
3259
3825
  const threadId = payload.threadId === undefined ? null : parseThreadId(payload.threadId);
3260
3826
  const limit = clampLimit(payload.limit, 20);
3261
3827
  if (!readDomain?.startsWith('task:')) assertInternalObjectActor(actor, agentId);
3262
- const nodes = (await allCheckpoints(appValue, agentId, threadId))
3828
+ const nodes = (await allCheckpoints(appValue, agentId, threadId, { includeDeleted: true }))
3263
3829
  .filter((node) => (readDomain ? domainOfNamespace(node.namespace) === readDomain : true))
3264
- .filter((node) => !checkpointExpired(node, now()))
3265
3830
  .sort(compareInternalObjectNodes);
3266
3831
  const latestByKey = new Map();
3267
3832
  for (const node of nodes) {
3268
3833
  const key = checkpointRevisionKey(node);
3269
3834
  if (!latestByKey.has(key)) latestByKey.set(key, node);
3270
3835
  }
3271
- const views = [...latestByKey.values()].map((node) => checkpointObjectView(node, { userId: identity.userId }));
3836
+ const views = [...latestByKey.values()]
3837
+ .filter((node) => !node.deletedAt && !checkpointExpired(node, now()))
3838
+ .map((node) => checkpointObjectView(node, { userId: identity.userId }));
3272
3839
  return {
3273
3840
  data: { objects: views.slice(0, limit), total: views.length, replayed: false },
3274
3841
  warnings: [...new Set(views.flatMap((view) => checkpointWarnings(view)))],
@@ -3378,12 +3945,19 @@ export function createMemoryCapabilityHandler({
3378
3945
  }
3379
3946
  }
3380
3947
  const current = await currentCheckpoint(appValue, { agentId, threadId, domain });
3381
- const currentRevision = current ? internalObjectRevision(current) : 0;
3948
+ const currentRevision = await highestCheckpointRevision(appValue, { agentId, threadId, domain });
3949
+ const liveCurrent = current && !current.deletedAt && !checkpointExpired(current, now())
3950
+ ? current
3951
+ : null;
3382
3952
  if (hasValue(payload.expectedRevision)) {
3383
3953
  if (typeof payload.expectedRevision !== 'number' || !Number.isInteger(payload.expectedRevision) || payload.expectedRevision < 0) {
3384
3954
  throw new CapabilityError(400, 'invalid_request', 'expectedRevision 必须是非负整数');
3385
3955
  }
3386
- if (payload.expectedRevision !== currentRevision) {
3956
+ // 兼容策略:没有 live checkpoint(显式删除或全部过期)时,宿主按
3957
+ // existing create convention 发送 expectedRevision=0 仍允许重建;
3958
+ // revision 仍从 high-water 前进,不复用旧 revision。
3959
+ const createAfterNoLive = payload.expectedRevision === 0 && liveCurrent === null;
3960
+ if (payload.expectedRevision !== currentRevision && !createAfterNoLive) {
3387
3961
  throw new CapabilityError(409, 'revision_mismatch', 'checkpoint revision 冲突', {
3388
3962
  agentId,
3389
3963
  threadId,
@@ -3393,7 +3967,7 @@ export function createMemoryCapabilityHandler({
3393
3967
  }, true);
3394
3968
  }
3395
3969
  }
3396
- const currentContent = isObject(current?.content) ? current.content : {};
3970
+ const currentContent = liveCurrent && isObject(liveCurrent.content) ? liveCurrent.content : {};
3397
3971
  const currentLease = isObject(currentContent.lease) ? currentContent.lease : null;
3398
3972
  if (currentLease && typeof currentLease.until === 'number' && currentLease.until > now()
3399
3973
  && currentLease.hostId !== hostId) {
@@ -3407,14 +3981,21 @@ export function createMemoryCapabilityHandler({
3407
3981
  throw new CapabilityError(403, 'forbidden_scope', '只有 user/system 可以抢占租约');
3408
3982
  }
3409
3983
  }
3410
- const recordIds = stringArray(payload.recordIds, 'recordIds', 0, {
3984
+ const payloadRecordIds = stringArray(payload.recordIds, 'recordIds', 0, {
3411
3985
  maxItems: MAX_COMPACT_SOURCES,
3412
3986
  maxChars: 128,
3413
3987
  }) ?? [];
3414
- const detailIds = stringArray(payload.detailIds, 'detailIds', 0, {
3988
+ const payloadDetailIds = stringArray(payload.detailIds, 'detailIds', 0, {
3415
3989
  maxItems: MAX_COMPACT_SOURCES,
3416
3990
  maxChars: 128,
3417
- }) ?? state.references.detailIds;
3991
+ }) ?? [];
3992
+ const graphReferences = checkpointGraphReferences(state, {
3993
+ recordIds: payloadRecordIds,
3994
+ detailIds: payloadDetailIds,
3995
+ });
3996
+ await validateCheckpointGraphReferences(appValue, domain, graphReferences);
3997
+ const recordIds = graphReferences.recordIds;
3998
+ const detailIds = graphReferences.detailIds;
3418
3999
  const expiresAt = payload.expiresAt === undefined || payload.expiresAt === null
3419
4000
  ? 0
3420
4001
  : optionalNumber(payload.expiresAt, 'expiresAt', 0);
@@ -3491,11 +4072,14 @@ export function createMemoryCapabilityHandler({
3491
4072
  };
3492
4073
  }
3493
4074
 
4075
+
4076
+
3494
4077
  // [/internal-object-write]
3495
- async function handleInternalObject(payload, actor) {
4078
+ async function handleInternalObject(payload, actor, generation) {
3496
4079
  if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
3497
4080
  throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
3498
4081
  }
4082
+ assertRequestGeneration(generation, 'internal-object');
3499
4083
  const kind = payload.kind;
3500
4084
  if (!INTERNAL_OBJECT_KINDS.includes(kind)) {
3501
4085
  throw new CapabilityError(400, 'internal_kind_invalid', 'kind 必须是 compact | self_record | context_checkpoint');
@@ -3621,6 +4205,12 @@ export function createMemoryCapabilityHandler({
3621
4205
  if (raw.detailKind === 'raw_chunk' && !hasValue(raw.role)) {
3622
4206
  throw validationError(index, 'role', 'raw_chunk 需要 role');
3623
4207
  }
4208
+ if (raw.role === 'tool' && raw.detailKind !== 'tool_output') {
4209
+ throw validationError(index, 'detailKind', 'tool role 必须使用 tool_output');
4210
+ }
4211
+ if (raw.detailKind === 'tool_output' && hasValue(raw.role) && raw.role !== 'tool') {
4212
+ throw validationError(index, 'role', 'tool_output 必须使用 tool role');
4213
+ }
3624
4214
  if (hasValue(raw.messageId)
3625
4215
  && (typeof raw.messageId !== 'string' || raw.messageId.length > 256)) {
3626
4216
  throw validationError(index, 'messageId', 'messageId 需为 1–256 字符');
@@ -3636,7 +4226,22 @@ export function createMemoryCapabilityHandler({
3636
4226
  if (hasValue(raw.retentionClass) && !isDetailRetentionClass(raw.retentionClass)) {
3637
4227
  throw validationError(index, 'retentionClass', 'retentionClass 非法');
3638
4228
  }
3639
- const retentionClass = hasValue(raw.retentionClass) ? raw.retentionClass : 'conversation';
4229
+ if (raw.role === 'tool' && raw.detailKind === 'document_slice') {
4230
+ throw validationError(index, 'detailKind', 'tool role 不能使用 document_slice');
4231
+ }
4232
+ const expectedRetentionClass = raw.role === 'tool' || raw.detailKind === 'tool_output'
4233
+ ? 'tool_output'
4234
+ : raw.detailKind === 'document_slice' ? 'document_slice' : 'conversation';
4235
+ if (raw.retentionClass === 'pinned' && actor.type !== 'user' && actor.type !== 'system') {
4236
+ throw validationError(index, 'retentionClass', 'pinned 仅允许 user/system 显式治理');
4237
+ }
4238
+ if (hasValue(raw.retentionClass) && raw.retentionClass !== 'pinned'
4239
+ && raw.retentionClass !== expectedRetentionClass) {
4240
+ throw validationError(index, 'retentionClass', 'retentionClass 与 role/detailKind 不一致', {
4241
+ expected: expectedRetentionClass,
4242
+ });
4243
+ }
4244
+ const retentionClass = hasValue(raw.retentionClass) ? raw.retentionClass : expectedRetentionClass;
3640
4245
  if (hasValue(raw.expiresAt)
3641
4246
  && (typeof raw.expiresAt !== 'number' || !Number.isFinite(raw.expiresAt) || raw.expiresAt < 0)) {
3642
4247
  throw validationError(index, 'expiresAt', 'expiresAt 必须是非负数字');
@@ -3768,7 +4373,8 @@ export function createMemoryCapabilityHandler({
3768
4373
  };
3769
4374
  }
3770
4375
 
3771
- async function handleDetailWrite(payload, actor) {
4376
+ async function handleDetailWrite(payload, actor, generation) {
4377
+ assertRequestGeneration(generation, 'detail.write');
3772
4378
  const items = payload.items;
3773
4379
  if (!Array.isArray(items) || items.length === 0) {
3774
4380
  throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
@@ -3785,6 +4391,7 @@ export function createMemoryCapabilityHandler({
3785
4391
  if (typeof currentService.writeDetails !== 'function') {
3786
4392
  throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持详情写入', undefined, true);
3787
4393
  }
4394
+ assertRequestGeneration(generation, 'detail.write.commit');
3788
4395
  let result;
3789
4396
  try {
3790
4397
  result = await currentService.writeDetails(validated, {
@@ -3816,6 +4423,7 @@ export function createMemoryCapabilityHandler({
3816
4423
  duplicates: result.duplicates,
3817
4424
  failed: result.failed,
3818
4425
  partial: result.partial,
4426
+ evicted: Array.isArray(result.evicted) ? [...result.evicted] : [],
3819
4427
  replayed: false,
3820
4428
  },
3821
4429
  warnings,
@@ -3942,7 +4550,8 @@ export function createMemoryCapabilityHandler({
3942
4550
  return { data: result, warnings: resolved.warnings, degraded: false };
3943
4551
  }
3944
4552
 
3945
- async function handleDetailDelete(payload, actor) {
4553
+ async function handleDetailDelete(payload, actor, generation) {
4554
+ assertRequestGeneration(generation, 'detail.delete');
3946
4555
  const ids = parseIdList(payload);
3947
4556
  const reason = payload.reason === undefined ? 'user_requested' : payload.reason;
3948
4557
  if (!isDetailDeleteReason(reason)) {
@@ -3995,7 +4604,7 @@ export function createMemoryCapabilityHandler({
3995
4604
  return defaults.includes(domain);
3996
4605
  }
3997
4606
 
3998
- async function handleDetail(payload, actor) {
4607
+ async function handleDetail(payload, actor, generation) {
3999
4608
  const op = payload.op;
4000
4609
  if (!['write', 'get', 'list', 'delete'].includes(op)) {
4001
4610
  throw new CapabilityError(400, 'invalid_request', 'detail op 必须是 write/get/list/delete');
@@ -4003,10 +4612,10 @@ export function createMemoryCapabilityHandler({
4003
4612
  if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
4004
4613
  throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
4005
4614
  }
4006
- if (op === 'write') return handleDetailWrite(payload, actor);
4615
+ if (op === 'write') return handleDetailWrite(payload, actor, generation);
4007
4616
  if (op === 'get') return handleDetailGet(payload, actor);
4008
4617
  if (op === 'list') return handleDetailList(payload, actor);
4009
- return handleDetailDelete(payload, actor);
4618
+ return handleDetailDelete(payload, actor, generation);
4010
4619
  }
4011
4620
 
4012
4621
  // ---------- /sync ----------
@@ -4089,8 +4698,13 @@ export function createMemoryCapabilityHandler({
4089
4698
  };
4090
4699
  }
4091
4700
 
4701
+ activeRequests += 1;
4092
4702
  try {
4093
4703
  if (disposed) throw new CapabilityError(503, 'capability_unavailable', '能力接口已关闭', undefined, true);
4704
+ if (draining && !revoked) {
4705
+ throw new CapabilityError(409, 'mode_mismatch', '能力接口正在关闭,拒绝新的请求', undefined, false);
4706
+ }
4707
+ const requestGeneration = tokenGeneration;
4094
4708
 
4095
4709
  // 1) 挂载开关:轻量模式不创建目录/token/进程,直接 404。
4096
4710
  if (!isMemoryRuntimeEnabled(getConfig())) {
@@ -4117,8 +4731,13 @@ export function createMemoryCapabilityHandler({
4117
4731
  }
4118
4732
 
4119
4733
  // 4) Bearer capability token。
4734
+ if (revoked) {
4735
+ res.setHeader('www-authenticate', 'Bearer');
4736
+ throw new CapabilityError(401, 'capability_token_invalid', 'capability token 已撤销');
4737
+ }
4120
4738
  if (tokenError) throw new CapabilityError(503, 'capability_unavailable', '能力令牌不可用', undefined, true);
4121
- const record = await ensureToken().catch(() => {
4739
+ const record = await ensureToken().catch((error) => {
4740
+ if (error instanceof CapabilityError) throw error;
4122
4741
  throw new CapabilityError(503, 'capability_unavailable', '能力令牌不可用', undefined, true);
4123
4742
  });
4124
4743
  const authorization = req?.headers?.authorization;
@@ -4148,6 +4767,7 @@ export function createMemoryCapabilityHandler({
4148
4767
  }
4149
4768
  if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'sync 仅接受 GET/POST');
4150
4769
  const payload = requireObjectBody();
4770
+ assertRequestGeneration(requestGeneration, 'sync');
4151
4771
  const result = await withIdempotency('sync', payload, record.tokenId, () => handleSyncPost(payload));
4152
4772
  return sendOk(result.data, result.warnings, 200, result.degraded);
4153
4773
  }
@@ -4157,7 +4777,8 @@ export function createMemoryCapabilityHandler({
4157
4777
  const payload = requireObjectBody();
4158
4778
  const actor = parseActor(payload.actor);
4159
4779
  const op = payload.op;
4160
- const execute = () => handleDetail(payload, actor);
4780
+ const execute = () => handleDetail(payload, actor, requestGeneration);
4781
+ if (op === 'write' || op === 'delete') assertRequestGeneration(requestGeneration, `detail.${String(op)}`);
4161
4782
  const result = (op === 'write' || op === 'delete')
4162
4783
  ? await withIdempotency(`detail:${op}`, payload, record.tokenId, execute)
4163
4784
  : await execute();
@@ -4169,12 +4790,13 @@ export function createMemoryCapabilityHandler({
4169
4790
  const payload = requireObjectBody();
4170
4791
  const actor = parseActor(payload.actor);
4171
4792
  let execute;
4172
- if (route === 'write') execute = () => handleWrite(payload, actor);
4173
- else if (route === 'update') execute = () => handleUpdate(payload, actor);
4174
- else if (route === 'delete') execute = () => handleDelete(payload, actor);
4175
- else if (route === 'archive') execute = () => handleArchive(payload, actor);
4176
- else if (route === 'internal-object') execute = () => handleInternalObject(payload, actor);
4793
+ if (route === 'write') execute = () => handleWrite(payload, actor, requestGeneration);
4794
+ else if (route === 'update') execute = () => handleUpdate(payload, actor, requestGeneration);
4795
+ else if (route === 'delete') execute = () => handleDelete(payload, actor, requestGeneration);
4796
+ else if (route === 'archive') execute = () => handleArchive(payload, actor, requestGeneration);
4797
+ else if (route === 'internal-object') execute = () => handleInternalObject(payload, actor, requestGeneration);
4177
4798
  else throw new CapabilityError(404, 'not_found', '未知能力端点', { path: relative });
4799
+ assertRequestGeneration(requestGeneration, route);
4178
4800
  const result = await withIdempotency(route, payload, record.tokenId, execute);
4179
4801
  return sendOk(result.data, result.warnings, 200, result.degraded);
4180
4802
  }
@@ -4203,6 +4825,14 @@ export function createMemoryCapabilityHandler({
4203
4825
  counts: includeCounts ? stats.counts : null,
4204
4826
  detailQuota: detailLimitsForConfig(),
4205
4827
  detailRetentionDays: { ...DETAIL_RETENTION_DAYS, pinned: 0 },
4828
+ idempotency: {
4829
+ running: idempotencyMaintenanceStatus.running,
4830
+ intervalMs: idempotencyMaintenanceStatus.intervalMs,
4831
+ lastAttemptAt: idempotencyMaintenanceStatus.lastAttemptAt,
4832
+ lastSuccessAt: idempotencyMaintenanceStatus.lastSuccessAt,
4833
+ lastError: idempotencyMaintenanceStatus.lastError,
4834
+ lastResult: idempotencyMaintenanceStatus.lastResult,
4835
+ },
4206
4836
  domains: includeCounts
4207
4837
  ? stats.domains.map((entry) => ({
4208
4838
  domain: entry.domain,
@@ -4721,6 +5351,8 @@ export function createMemoryCapabilityHandler({
4721
5351
  }
4722
5352
  // 不把内部错误细节(含路径/内容)回给调用方;不记录 token。
4723
5353
  return sendError(500, 'internal', '能力接口内部错误', undefined, true);
5354
+ } finally {
5355
+ finishActiveRequest();
4724
5356
  }
4725
5357
  };
4726
5358
 
@@ -4728,7 +5360,34 @@ export function createMemoryCapabilityHandler({
4728
5360
  prepare,
4729
5361
  revoke,
4730
5362
  dispose,
5363
+ close,
5364
+ abandon,
5365
+ beginDrain,
5366
+ drain,
5367
+ isDraining: () => draining,
4731
5368
  isEnabled: () => isMemoryRuntimeEnabled(getConfig()),
4732
5369
  tokenId: () => tokenRecord?.tokenId ?? null,
5370
+ runIdempotencyMaintenance,
5371
+ idempotencyIdle: () => idempotencyMaintenanceRun ?? Promise.resolve(null),
5372
+ runCheckpointMaintenance,
5373
+ checkpointMaintenanceIdle: () => checkpointMaintenanceRun ?? Promise.resolve(null),
5374
+ checkpointMaintenance: () => ({
5375
+ ...checkpointMaintenanceStatus,
5376
+ lastError: checkpointMaintenanceStatus.lastError
5377
+ ? { ...checkpointMaintenanceStatus.lastError }
5378
+ : null,
5379
+ lastResult: checkpointMaintenanceStatus.lastResult
5380
+ ? { ...checkpointMaintenanceStatus.lastResult }
5381
+ : null,
5382
+ }),
5383
+ idempotencyMaintenance: () => ({
5384
+ ...idempotencyMaintenanceStatus,
5385
+ lastError: idempotencyMaintenanceStatus.lastError
5386
+ ? { ...idempotencyMaintenanceStatus.lastError }
5387
+ : null,
5388
+ lastResult: idempotencyMaintenanceStatus.lastResult
5389
+ ? { ...idempotencyMaintenanceStatus.lastResult }
5390
+ : null,
5391
+ }),
4733
5392
  });
4734
5393
  }