@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.
package/bin/mebular.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { existsSync } from 'node:fs';
8
8
  import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
9
+ import { acquireConfigFileLock } from '../src/config-lock.mjs';
9
10
  import { dirname, join, resolve } from 'node:path';
10
11
  import { fileURLToPath } from 'node:url';
11
12
  import { homeDir } from '../src/home.mjs';
@@ -211,6 +212,9 @@ async function runInit(flags) {
211
212
  const keyFile = join(home, 'user-master-key.json');
212
213
  await mkdir(home, { recursive: true });
213
214
 
215
+ const releaseConfigLock = await acquireConfigFileLock(configFile);
216
+ if (!releaseConfigLock) throw initError('配置文件正在被其他进程写入,请稍后重试', 'CONFIG_BUSY');
217
+ try {
214
218
  const config = existsSync(configFile)
215
219
  ? await readInitJson(configFile, { label: 'config.json', code: 'CONFIG_INVALID' })
216
220
  : null;
@@ -288,7 +292,7 @@ async function runInit(flags) {
288
292
  }
289
293
 
290
294
  if (config !== null) {
291
- const migrated = await cleanLegacyConfig({ configPath: configFile, identity });
295
+ const migrated = await cleanLegacyConfig({ configPath: configFile, identity, lock: false });
292
296
  console.log(`配置已存在,未覆盖:${configFile}`);
293
297
  if (migrated.migrated) {
294
298
  console.log(`已备份旧 config 身份字段:${migrated.backupPath},并以身份 ${identity.deviceId} 为准`);
@@ -308,6 +312,9 @@ async function runInit(flags) {
308
312
  await writeFile(configFile, JSON.stringify(nextConfig, null, 2), 'utf-8');
309
313
  console.log(`已写入配置:${configFile}(deviceId=${identity.deviceId},由身份文件提供)`);
310
314
  }
315
+ } finally {
316
+ await releaseConfigLock();
317
+ }
311
318
  // Skill 是部署产物:初始化成功后对已检测到的助手自动 ensure;失败只告警,不阻断 init。
312
319
  try {
313
320
  const { autoEnsureSkills, assistantUserHome } = await import('../src/clients.mjs');
@@ -1824,10 +1831,11 @@ function printMemoryRuntime(value, exitCode = 0) {
1824
1831
  process.exit(exitCode);
1825
1832
  }
1826
1833
 
1827
- async function runMemoryRuntime(action, flags) {
1828
- const usage = '用法:mebular memory-runtime <status|start|stop|restart> [--json] [--home DIR] [--timeout MS]';
1834
+ async function runMemoryRuntime(action, args, flags) {
1835
+ const usage = '用法:mebular memory-runtime <status|start|stop|restart|logs|doctor|outbox> [--json] [--home DIR] [--timeout MS] [logs --limit N|--tail N]';
1829
1836
  try {
1830
- if (!['status', 'start', 'stop', 'restart'].includes(action)) {
1837
+ const actions = ['status', 'start', 'stop', 'restart', 'logs', 'doctor', 'outbox'];
1838
+ if (!actions.includes(action)) {
1831
1839
  const error = new Error(usage);
1832
1840
  error.code = 'USAGE';
1833
1841
  throw error;
@@ -1839,7 +1847,199 @@ async function runMemoryRuntime(action, flags) {
1839
1847
  MemoryRuntimeSupervisor,
1840
1848
  inspectMemoryRuntimeStatus,
1841
1849
  memoryRuntimeStatusExitCode,
1850
+ resolveMemoryRuntimePaths,
1842
1851
  } = await import('../src/memory-runtime-supervisor.mjs');
1852
+ const {
1853
+ assertSafeMemoryRuntimeDataDir,
1854
+ inspectMemoryRuntimeOutbox,
1855
+ inspectMemoryRuntimeLocalCounts,
1856
+ memoryRuntimeDiskUsage,
1857
+ memoryRuntimeLogStatus,
1858
+ readMemoryRuntimeLogs,
1859
+ rebuildMemoryRuntimeOutboxItem,
1860
+ purgeMemoryRuntimeOutboxItem,
1861
+ sanitizeMemoryRuntimeEvent,
1862
+ } = await import('../src/memory-runtime-diagnostics.mjs');
1863
+ const dataDir = assertSafeMemoryRuntimeDataDir(
1864
+ resolveMemoryRuntimePaths({ home, env: process.env }).dataDir,
1865
+ home,
1866
+ );
1867
+
1868
+ if (action === 'logs') {
1869
+ const limitFlag = flags.limit === undefined ? flags.tail : flags.limit;
1870
+ const limitRaw = limitFlag === undefined ? 50 : Number(limitFlag);
1871
+ const limit = Number.isInteger(limitRaw) && limitRaw > 0 && limitRaw <= 500 ? limitRaw : 50;
1872
+ const [parsedEntries, status] = await Promise.all([
1873
+ readMemoryRuntimeLogs(dataDir, { limit }),
1874
+ memoryRuntimeLogStatus(dataDir),
1875
+ ]);
1876
+ const entries = parsedEntries.map((entry) => sanitizeMemoryRuntimeEvent(entry));
1877
+ printMemoryRuntime({
1878
+ ok: true,
1879
+ kind: 'memory-runtime',
1880
+ action,
1881
+ count: entries.length,
1882
+ truncated: entries.length >= limit,
1883
+ log: status,
1884
+ entries,
1885
+ }, 0);
1886
+ return;
1887
+ }
1888
+
1889
+ if (action === 'doctor') {
1890
+ const supervisor = new MemoryRuntimeSupervisor({ home, config, env: process.env });
1891
+ const [status, runtime, outbox, localCounts, disk, logStatus, logs] = await Promise.all([
1892
+ inspectMemoryRuntimeStatus({ home, config, env: process.env }),
1893
+ supervisor.readStatus().catch(() => null),
1894
+ inspectMemoryRuntimeOutbox(dataDir, { now: Date.now() }),
1895
+ inspectMemoryRuntimeLocalCounts(dataDir),
1896
+ memoryRuntimeDiskUsage(dataDir),
1897
+ memoryRuntimeLogStatus(dataDir),
1898
+ readMemoryRuntimeLogs(dataDir, { limit: 100 }),
1899
+ ]);
1900
+ const recentErrors = logs
1901
+ .filter((entry) => entry.level === 'error' || entry.level === 'warn')
1902
+ .map((entry) => ({
1903
+ ts: entry.ts,
1904
+ level: entry.level,
1905
+ event: entry.event,
1906
+ ...(typeof entry.code === 'string' ? { code: entry.code } : {}),
1907
+ ...(typeof entry.reason === 'string' ? { reason: entry.reason } : {}),
1908
+ ...(typeof entry.stage === 'string' ? { stage: entry.stage } : {}),
1909
+ ...(entry.possibleCommit === true ? { possibleCommit: true } : {}),
1910
+ }));
1911
+ for (const [source, error] of [['sidecar', status.error], ['runtime', runtime?.error]]) {
1912
+ if (!error?.code) continue;
1913
+ recentErrors.push({
1914
+ ts: Date.now(),
1915
+ level: 'error',
1916
+ event: `${source}_status`,
1917
+ code: error.code,
1918
+ });
1919
+ }
1920
+ recentErrors.splice(0, Math.max(0, recentErrors.length - 10));
1921
+ const restartEvents = logs.filter((entry) => entry.event === 'supervisor_restart');
1922
+ const lastRestart = restartEvents[restartEvents.length - 1]
1923
+ ?? [...logs].reverse().find((entry) => entry.event === 'runtime_start' || entry.event === 'runtime_resume');
1924
+ const restartReason = typeof lastRestart?.reason === 'string'
1925
+ ? lastRestart.reason
1926
+ : (status.reason ?? null);
1927
+ const next = [];
1928
+ if (status.error?.code) next.push(`sidecar 错误:${status.error.code}`);
1929
+ if (outbox.dead > 0) next.push(`${outbox.dead} 个 dead 操作:先看 deadReasons/lastConflict,再显式 outbox rebuild/purge`);
1930
+ if (outbox.lastConflict) next.push(`最近冲突 ${outbox.lastConflict.code}(requestId=${outbox.lastConflict.requestId})`);
1931
+ if (outbox.ambiguous.length > 0) next.push('存在超时/部分写入:结果未知,需按 committedObjects 做权威回读对账,不能当作已提交');
1932
+ if (runtime?.degraded) next.push(`运行时降级:${runtime.error?.code ?? 'degraded'}`);
1933
+ if (recentErrors.length === 0) next.push('最近没有日志错误');
1934
+ printMemoryRuntime({
1935
+ ok: true,
1936
+ kind: 'memory-runtime',
1937
+ action,
1938
+ enabled: status.enabled,
1939
+ available: status.available,
1940
+ state: status.state,
1941
+ degraded: status.degraded === true || outbox.dead > 0 || outbox.ambiguous.length > 0 || runtime?.degraded === true,
1942
+ installed: status.installed,
1943
+ restartReason,
1944
+ capability: runtime?.capability ?? null,
1945
+ model: runtime?.model ?? null,
1946
+ counts: {
1947
+ staging: localCounts.stagingChunks,
1948
+ traces: localCounts.traces,
1949
+ cache: localCounts.cacheEntries,
1950
+ detailCache: localCounts.detailCacheEntries,
1951
+ outbox: outbox.active,
1952
+ dead: outbox.dead,
1953
+ },
1954
+ outbox: {
1955
+ active: outbox.active,
1956
+ dead: outbox.dead,
1957
+ oldestAgeMs: outbox.oldestAgeMs,
1958
+ deadOldestAgeMs: outbox.deadOldestAgeMs,
1959
+ byOperation: outbox.byOperation,
1960
+ byEndpoint: outbox.byEndpoint,
1961
+ deadReasons: outbox.deadReasons,
1962
+ lastConflict: outbox.lastConflict,
1963
+ ambiguous: outbox.ambiguous,
1964
+ },
1965
+ logs: logStatus,
1966
+ disk,
1967
+ recentErrors,
1968
+ next,
1969
+ }, 0);
1970
+ return;
1971
+ }
1972
+
1973
+ if (action === 'outbox') {
1974
+ const sub = args[0] ?? 'list';
1975
+ if (sub === 'list') {
1976
+ const summary = await inspectMemoryRuntimeOutbox(dataDir, { now: Date.now(), includeItems: true });
1977
+ printMemoryRuntime({ ok: true, kind: 'memory-runtime', action, sub, ...summary }, 0);
1978
+ return;
1979
+ }
1980
+ const id = args[1];
1981
+ if (typeof id !== 'string' || id.length === 0) {
1982
+ const error = new Error('outbox 命令需要 id:list|show|rebuild|purge');
1983
+ error.code = 'USAGE';
1984
+ throw error;
1985
+ }
1986
+ if (sub === 'show') {
1987
+ const summary = await inspectMemoryRuntimeOutbox(dataDir, { now: Date.now(), includeItems: true });
1988
+ const item = summary.items.find((entry) => entry.id === id || entry.requestId === id);
1989
+ if (!item) {
1990
+ printMemoryRuntime({
1991
+ ok: false,
1992
+ kind: 'memory-runtime',
1993
+ action,
1994
+ sub,
1995
+ error: { code: 'outbox_not_found', message: 'outbox 项不存在' },
1996
+ }, 1);
1997
+ return;
1998
+ }
1999
+ printMemoryRuntime({ ok: true, kind: 'memory-runtime', action, sub, item }, 0);
2000
+ return;
2001
+ }
2002
+ if (sub === 'rebuild') {
2003
+ let expectedRevision;
2004
+ const revisionFlag = flags['expected-revision'];
2005
+ if (revisionFlag !== undefined) {
2006
+ if (typeof revisionFlag !== 'string' || !/^(?:0|[1-9]\d*)$/.test(revisionFlag)) {
2007
+ const error = new Error('--expected-revision 必须显式提供非负整数');
2008
+ error.code = 'usage';
2009
+ throw error;
2010
+ }
2011
+ expectedRevision = Number(revisionFlag);
2012
+ if (!Number.isSafeInteger(expectedRevision)) {
2013
+ const error = new Error('--expected-revision 超出安全整数范围');
2014
+ error.code = 'usage';
2015
+ throw error;
2016
+ }
2017
+ }
2018
+ const item = await rebuildMemoryRuntimeOutboxItem(dataDir, id, {
2019
+ ...(expectedRevision !== undefined ? { expectedRevision } : {}),
2020
+ now: Date.now(),
2021
+ });
2022
+ printMemoryRuntime({
2023
+ ok: true,
2024
+ kind: 'memory-runtime',
2025
+ action,
2026
+ sub,
2027
+ item,
2028
+ note: expectedRevision === undefined
2029
+ ? '已按原 revision 重建;不会自动 rebase 到新 revision'
2030
+ : '已按显式 --expected-revision 重建(人工覆盖,非自动)',
2031
+ }, 0);
2032
+ return;
2033
+ }
2034
+ if (sub === 'purge') {
2035
+ const result = await purgeMemoryRuntimeOutboxItem(dataDir, id);
2036
+ printMemoryRuntime({ ok: true, kind: 'memory-runtime', action, sub, ...result }, 0);
2037
+ return;
2038
+ }
2039
+ const error = new Error('outbox 子命令:list|show|rebuild|purge');
2040
+ error.code = 'USAGE';
2041
+ throw error;
2042
+ }
1843
2043
 
1844
2044
  if (action === 'status') {
1845
2045
  const status = await inspectMemoryRuntimeStatus({ home, config, env: process.env });
@@ -1880,7 +2080,7 @@ async function runMemoryRuntime(action, flags) {
1880
2080
  ...status,
1881
2081
  }, ok ? 0 : memoryRuntimeStatusExitCode(status));
1882
2082
  } catch (error) {
1883
- const code = error?.code === 'USAGE' ? 'usage' : (error?.code ?? 'error');
2083
+ const code = error?.code === 'USAGE' || error?.code === 'usage' ? 'usage' : (error?.code ?? 'error');
1884
2084
  printMemoryRuntime({
1885
2085
  ok: false,
1886
2086
  kind: 'memory-runtime',
@@ -2061,7 +2261,7 @@ async function main() {
2061
2261
  return;
2062
2262
  }
2063
2263
  case 'memory-runtime': {
2064
- await runMemoryRuntime(argv[1], flags);
2264
+ await runMemoryRuntime(argv[1], argv.slice(2), flags);
2065
2265
  return;
2066
2266
  }
2067
2267
  case 'models': {
@@ -2096,7 +2296,7 @@ async function main() {
2096
2296
  ' runtime current show|set|clear [--version V --runtime-path P --cli C --provider shared --owner O --installed-at ISO] current 指针(非敏感)',
2097
2297
  ' runtime service install|uninstall|restart|status [--json] 共享 mebular-serve 所有权/生命周期',
2098
2298
  ' runtime provider list|add|remove [--kind app|cli|shared --path P --version V --capabilities a,b --id ID] runtime provider 注册表',
2099
- ' memory-runtime status|start|stop|restart [--json] [--home DIR] 记忆运行时 sidecar(独立于 MCP daemon runtime)',
2299
+ ' memory-runtime status|start|stop|restart|logs|doctor|outbox [--json] [--home DIR] [logs --limit|--tail N] 记忆运行时 sidecar(独立于 MCP daemon runtime)',
2100
2300
  ' models list|status|install|download|select|remove|start|stop [--json] [--pack P] [--force] sidecar 模型(需 serve;不同步)',
2101
2301
  ' token grant|list|revoke [--scope a,b] [--id x] [--tokens-file p] bearer 令牌管理',
2102
2302
  ' token client add|list|remove [--redirect uri] [--scope a,b] [--id x] OAuth 客户端预注册',
@@ -2138,6 +2338,10 @@ async function main() {
2138
2338
  }
2139
2339
  return;
2140
2340
  case 'doctor':
2341
+ if (argv[1] === 'memory-runtime' || flags['memory-runtime'] === true || flags['memory-runtime'] === 'true') {
2342
+ await runMemoryRuntime('doctor', argv.slice(2), flags);
2343
+ return;
2344
+ }
2141
2345
  if (flags.net === true || flags.net === 'true') {
2142
2346
  await runNetDoctor();
2143
2347
  return;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mebular/mcp",
3
- "version": "0.3.0",
4
- "description": "Mebular MCP server(stdio + Streamable HTTP):把 Mebular 记忆能力暴露给任意 MCP client",
3
+ "version": "0.3.4",
4
+ "description": "Mebular MCP server (stdio + Streamable HTTP): exposes Mebular memory and task capabilities to any MCP client. | Mebular MCP server(stdio + Streamable HTTP):把 Mebular 的记忆与任务能力暴露给任意 MCP client。",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "Sobert Li (Windsander)",
@@ -29,10 +29,10 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@mebular/core": "^0.3.0",
33
- "@mebular/memory-runtime": "^0.3.0",
32
+ "@mebular/core": "^0.3.4",
33
+ "@mebular/memory-runtime": "^0.3.4",
34
34
  "@modelcontextprotocol/server": "^2.3.1",
35
35
  "zod": "^4.6.7",
36
- "@mebular/fleet": "^0.3.0"
36
+ "@mebular/fleet": "^0.3.4"
37
37
  }
38
38
  }
package/src/admin.mjs CHANGED
@@ -1007,9 +1007,15 @@ export async function buildSettings({ app, service, config, runtime, home }) {
1007
1007
  // A/D:三元组 + 暴露面(单一真源驱动;GUI 编辑器改由 configSchema 渲染)
1008
1008
  effective: effectiveRows,
1009
1009
  // G:应用结果(green=已生效 / red=未按预期生效或已回滚 / in-progress=重启中)
1010
- lastApply: applyPending
1011
- ? { status: 'in-progress', at: applyPending.at ?? null, fields: applyPending.fields ?? [], attempt: applyPending.attempt ?? null }
1012
- : (applyResult ?? null),
1010
+ // rollingBack 的 pending 只有在恢复失败时才会留下结果;此时必须优先展示 rollback-failed,
1011
+ // 不能被 pending 误报成 in-progress。
1012
+ lastApply: applyPending?.rollingBack === true
1013
+ ? (applyResult?.status === 'rollback-failed'
1014
+ ? applyResult
1015
+ : { status: 'in-progress', at: applyPending.at ?? null, fields: applyPending.fields ?? [], attempt: applyPending.attempt ?? null })
1016
+ : (applyPending
1017
+ ? { status: 'in-progress', at: applyPending.at ?? null, fields: applyPending.fields ?? [], attempt: applyPending.attempt ?? null }
1018
+ : (applyResult ?? null)),
1013
1019
  configSchema: consoleSchema(),
1014
1020
  statusSchema: consoleStatusSchema(),
1015
1021
  restart: {
@@ -12,10 +12,12 @@
12
12
  // 全部外部交互(健康探针 / 重启通道 / 时钟)可注入,便于 hermetic 测试;零 core 依赖。
13
13
 
14
14
  import { spawn } from 'node:child_process';
15
+ import { createHash } from 'node:crypto';
15
16
  import { existsSync } from 'node:fs';
16
17
  import { copyFile, readFile, rename, rm, writeFile } from 'node:fs/promises';
17
18
  import { join } from 'node:path';
18
19
  import { CONFIG_SCHEMA_BY_PATH } from './config-schema.mjs';
20
+ import { acquireConfigFileLock } from './config-lock.mjs';
19
21
 
20
22
  export const APPLY_RESULT_FILE = 'config-apply.result.json';
21
23
  export const APPLY_PENDING_FILE = 'config-apply.pending.json';
@@ -161,10 +163,197 @@ export function spawnSupervisor({ supervisorPath, args, env = process.env, spawn
161
163
  export const readJoinError = (home) => readJson(joinErrorPath(home));
162
164
 
163
165
  /** 还原备份(config.json ← config.json.bak)。返回是否真的还原了。 */
164
- export async function restoreBackup({ configFile, backupFile = `${configFile}.bak`, copyFileImpl = copyFile }) {
165
- if (!existsSync(backupFile)) return false;
166
- await copyFileImpl(backupFile, configFile);
167
- return true;
166
+ export async function restoreBackup({
167
+ configFile,
168
+ backupFile = `${configFile}.bak`,
169
+ copyFileImpl = copyFile,
170
+ expectedConfigHash = null,
171
+ }) {
172
+ const releaseConfigLock = await acquireConfigFileLock(configFile);
173
+ if (!releaseConfigLock) {
174
+ const error = new Error(`配置文件正在被其他进程写入:${configFile}`);
175
+ error.code = 'CONFIG_BUSY';
176
+ throw error;
177
+ }
178
+ try {
179
+ if (expectedConfigHash) {
180
+ const actual = await configFileHash(configFile);
181
+ if (actual !== expectedConfigHash) {
182
+ const error = new Error('当前配置文件已变化:拒绝恢复备份');
183
+ error.code = 'CONFIG_CHANGED';
184
+ throw error;
185
+ }
186
+ }
187
+ if (!existsSync(backupFile)) return false;
188
+ await copyFileImpl(backupFile, configFile);
189
+ return true;
190
+ } finally {
191
+ await releaseConfigLock();
192
+ }
193
+ }
194
+
195
+ /** pending 的完整身份:attempt/applyId/at/fields 任一变化都视为另一条 apply。 */
196
+ function pendingIdentity(pending) {
197
+ const record = pending && typeof pending === 'object' ? pending : {};
198
+ return {
199
+ attempt: record.attempt ?? null,
200
+ applyId: typeof record.applyId === 'string' ? record.applyId : null,
201
+ at: typeof record.at === 'string' ? record.at : null,
202
+ fields: Array.isArray(record.fields) ? record.fields.map(String) : [],
203
+ };
204
+ }
205
+
206
+ function samePendingIdentity(left, right) {
207
+ return left.attempt === right.attempt
208
+ && left.applyId === right.applyId
209
+ && left.at === right.at
210
+ && left.fields.length === right.fields.length
211
+ && left.fields.every((value, index) => value === right.fields[index]);
212
+ }
213
+
214
+ async function configFileHash(configFile) {
215
+ try {
216
+ return createHash('sha256').update(await readFile(configFile)).digest('hex');
217
+ } catch {
218
+ return null;
219
+ }
220
+ }
221
+
222
+ function rollbackSkippedRecord({
223
+ pending,
224
+ backupFile,
225
+ reason,
226
+ skipReason,
227
+ expectedConfigHash = null,
228
+ actualConfigHash = null,
229
+ configChanged = false,
230
+ }) {
231
+ return {
232
+ status: 'rollback-skipped',
233
+ attempt: pending.attempt ?? null,
234
+ applyId: pending.applyId ?? null,
235
+ at: new Date().toISOString(),
236
+ fields: Array.isArray(pending.fields) ? pending.fields : [],
237
+ reason,
238
+ skipReason,
239
+ ...(configChanged ? { configChanged: true } : {}),
240
+ restored: false,
241
+ backup: backupFile,
242
+ expectedConfigHash,
243
+ actualConfigHash,
244
+ recovered: false,
245
+ retries: Number(pending.attempts ?? 1),
246
+ };
247
+ }
248
+
249
+ async function recordAndClearMatchingPending({ home, pending, record }) {
250
+ await writeApplyResult(home, record);
251
+ // 恢复期间可能已有新的 apply 写入 pending:只有同一完整身份才允许清理。
252
+ const current = await readApplyPending(home);
253
+ if (current
254
+ && current.rollingBack === true
255
+ && samePendingIdentity(pendingIdentity(current), pendingIdentity(pending))) {
256
+ await clearApplyPending(home);
257
+ }
258
+ return record;
259
+ }
260
+
261
+ /** 生产启动/下次 apply:有界重试 rollingBack 的 restore;成功清理 pending,失败保留可重试状态。 */
262
+ export async function recoverPendingRollback({
263
+ home,
264
+ configFile = join(home, 'config.json'),
265
+ backupFile = `${configFile}.bak`,
266
+ log = () => {},
267
+ restoreImpl = restoreBackup,
268
+ } = {}) {
269
+ const pending = await readApplyPending(home);
270
+ if (!pending || pending.rollingBack !== true) return { status: 'not_pending' };
271
+ const fields = Array.isArray(pending.fields) ? pending.fields : [];
272
+ const expectedConfigHash = typeof pending.failedConfigHash === 'string' ? pending.failedConfigHash : null;
273
+ const actualConfigHash = await configFileHash(configFile);
274
+ if (!expectedConfigHash) {
275
+ const record = rollbackSkippedRecord({
276
+ pending,
277
+ backupFile,
278
+ reason: '缺少失败配置指纹:无法证明当前配置仍是失败 apply 的产物,拒绝覆盖',
279
+ skipReason: 'missing_config_hash',
280
+ actualConfigHash,
281
+ });
282
+ log('apply: rollingBack pending 缺少配置指纹,跳过自动恢复');
283
+ return recordAndClearMatchingPending({ home, pending, record });
284
+ }
285
+ if (actualConfigHash !== expectedConfigHash) {
286
+ const record = rollbackSkippedRecord({
287
+ pending,
288
+ backupFile,
289
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
290
+ skipReason: 'config_changed',
291
+ expectedConfigHash,
292
+ actualConfigHash,
293
+ configChanged: true,
294
+ });
295
+ log('apply: 当前配置已变化,跳过 rollingBack pending');
296
+ return recordAndClearMatchingPending({ home, pending, record });
297
+ }
298
+ try {
299
+ const restored = await restoreImpl({ configFile, backupFile, expectedConfigHash });
300
+ if (!restored) {
301
+ const error = new Error('回滚备份不存在');
302
+ error.code = 'BACKUP_MISSING';
303
+ throw error;
304
+ }
305
+ const record = {
306
+ status: 'rolled-back',
307
+ attempt: pending.attempt ?? null,
308
+ applyId: pending.applyId ?? null,
309
+ at: new Date().toISOString(),
310
+ fields,
311
+ reason: pending.reason ?? null,
312
+ restored: true,
313
+ backup: backupFile,
314
+ expectedConfigHash,
315
+ actualConfigHash,
316
+ recovered: true,
317
+ retries: Number(pending.attempts ?? 1),
318
+ };
319
+ log('apply: rollingBack pending 已自动恢复');
320
+ return recordAndClearMatchingPending({ home, pending, record });
321
+ } catch (error) {
322
+ if (error?.code === 'CONFIG_CHANGED') {
323
+ const record = rollbackSkippedRecord({
324
+ pending,
325
+ backupFile,
326
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
327
+ skipReason: 'config_changed',
328
+ expectedConfigHash,
329
+ actualConfigHash: await configFileHash(configFile),
330
+ configChanged: true,
331
+ });
332
+ log('apply: 恢复前配置已变化,跳过 rollingBack pending');
333
+ return recordAndClearMatchingPending({ home, pending, record });
334
+ }
335
+ const record = {
336
+ status: 'rollback-failed',
337
+ attempt: pending.attempt ?? null,
338
+ applyId: pending.applyId ?? null,
339
+ at: new Date().toISOString(),
340
+ fields,
341
+ reason: pending.reason ?? null,
342
+ restored: false,
343
+ backup: backupFile,
344
+ expectedConfigHash,
345
+ actualConfigHash,
346
+ restoreError: {
347
+ code: error?.code ?? 'RESTORE_FAILED',
348
+ message: String(error?.message ?? error),
349
+ },
350
+ recovered: false,
351
+ retries: Number(pending.attempts ?? 1),
352
+ };
353
+ await writeApplyResult(home, record);
354
+ // 保留 pending,允许下一次启动/apply 或人工重试。
355
+ return record;
356
+ }
168
357
  }
169
358
 
170
359
  /**
@@ -188,6 +377,9 @@ export async function runApplySupervisor({
188
377
  } = {}) {
189
378
  const now = () => Date.now();
190
379
  const pending = (await readApplyPending(home)) ?? { fields, at: new Date(since).toISOString(), attempts: 1 };
380
+ if (pending.rollingBack === true && configFile) {
381
+ return recoverPendingRollback({ home, configFile, backupFile, log });
382
+ }
191
383
  const attempts = Number(pending.attempts ?? 1);
192
384
  log(`apply: 等待新实例健康(fields=${fields.join(',')} timeout=${timeoutMs}ms)`);
193
385
  const outcome = await health({ home, port, oldPid, since, timeoutMs, now });
@@ -217,8 +409,64 @@ export async function runApplySupervisor({
217
409
  : `新实例在 ${timeoutMs}ms 内未健康(心跳/端口无响应)`;
218
410
  log(`apply: 新实例未健康(${reason})→ 回滚`);
219
411
  // 打标记:回滚实例启动时不得写 applied(否则会短暂谎报「已生效」)
220
- await writeApplyPending(home, { ...pending, rollingBack: true, reason }).catch(() => undefined);
221
- const restored = backupFile ? await restoreBackup({ configFile, backupFile }) : false;
412
+ const failedConfigHash = configFile ? await configFileHash(configFile) : null;
413
+ await writeApplyPending(home, {
414
+ ...pending,
415
+ rollingBack: true,
416
+ reason,
417
+ ...(failedConfigHash ? { failedConfigHash } : {}),
418
+ }).catch(() => undefined);
419
+ let restored = false;
420
+ let restoreError = null;
421
+ try {
422
+ restored = backupFile
423
+ ? await restoreBackup({
424
+ configFile,
425
+ backupFile,
426
+ ...(failedConfigHash ? { expectedConfigHash: failedConfigHash } : {}),
427
+ })
428
+ : false;
429
+ } catch (error) {
430
+ restoreError = error;
431
+ }
432
+ if (restoreError?.code === 'CONFIG_CHANGED') {
433
+ const record = {
434
+ status: 'rollback-skipped',
435
+ attempt: pending.attempt ?? null,
436
+ applyId: pending.applyId ?? null,
437
+ at: new Date(now()).toISOString(),
438
+ fields,
439
+ reason: '当前配置文件已变化:跳过旧 apply 的自动回滚,保留新配置',
440
+ skipReason: 'config_changed',
441
+ configChanged: true,
442
+ restored: false,
443
+ backup: backupFile,
444
+ expectedConfigHash: failedConfigHash,
445
+ actualConfigHash: await configFileHash(configFile),
446
+ retries: attempts,
447
+ };
448
+ await recordAndClearMatchingPending({ home, pending, record });
449
+ return record;
450
+ }
451
+ if (restoreError) {
452
+ const record = {
453
+ status: 'rollback-failed',
454
+ attempt: pending.attempt ?? null,
455
+ at: new Date(now()).toISOString(),
456
+ fields,
457
+ reason,
458
+ restored: false,
459
+ backup: backupFile,
460
+ restoreError: {
461
+ code: restoreError?.code ?? 'RESTORE_FAILED',
462
+ message: String(restoreError?.message ?? restoreError),
463
+ },
464
+ retries: attempts,
465
+ };
466
+ await writeApplyResult(home, record);
467
+ // 保留 pending(rollingBack=true):锁释放/人工处理后仍可恢复,不假装回滚完成。
468
+ return record;
469
+ }
222
470
  if (restored) {
223
471
  await restart({ home, kind, env: process.env });
224
472
  const after = await health({ home, port, oldPid, since: now(), timeoutMs, now });