@mebular/mcp 0.3.5 → 0.3.7

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/src/clients.mjs CHANGED
@@ -1606,6 +1606,33 @@ async function attachSkills(result, id, options = {}) {
1606
1606
  return result;
1607
1607
  }
1608
1608
 
1609
+ /** 接入成功后顺带 ensure 该客户端的 Adapter;失败只记录,绝不阻断 MCP 接入。 */
1610
+ async function attachAdapter(result, id, options = {}) {
1611
+ if (!result?.ok || options.ensureAdapter === false) return result;
1612
+ try {
1613
+ const { ensureAdapter } = await import('./adapter-provision.mjs');
1614
+ result.adapter = await ensureAdapter(id, {
1615
+ ...(options.home ? { home: options.home } : {}),
1616
+ ...(options.userHome ? { userHome: options.userHome } : {}),
1617
+ ...(options.cwd ? { cwd: options.cwd } : {}),
1618
+ ...(options.env ? { env: options.env } : {}),
1619
+ ...(typeof options.adapterPackagePath === 'string' ? { adapterPackagePath: options.adapterPackagePath } : {}),
1620
+ ...(typeof options.packagePath === 'string' ? { packagePath: options.packagePath } : {}),
1621
+ ...(typeof options.resourcesPath === 'string' ? { resourcesPath: options.resourcesPath } : {}),
1622
+ ...(typeof options.expectedVersion === 'string' ? { expectedVersion: options.expectedVersion } : {}),
1623
+ ...(typeof options.run === 'function' ? { run: options.run } : {}),
1624
+ ...(typeof options.runAsync === 'function' ? { runAsync: options.runAsync } : {}),
1625
+ ...(options.canRestartHost !== undefined ? { canRestartHost: options.canRestartHost } : {}),
1626
+ ...(typeof options.reloadHost === 'function' ? { reloadHost: options.reloadHost } : {}),
1627
+ ...(typeof options.restartHost === 'function' ? { restartHost: options.restartHost } : {}),
1628
+ connected: true,
1629
+ });
1630
+ } catch {
1631
+ result.adapter = { ok: false, code: 'ADAPTER_FAILED' };
1632
+ }
1633
+ return result;
1634
+ }
1635
+
1609
1636
  /** 接入:merge-key(备份 → 原子写)/ cli-set(官方 CLI)/ manual(仅片段)。 */
1610
1637
  export async function connectClient(id, options = {}) {
1611
1638
  const assistant = descriptorFor(id, options);
@@ -1618,7 +1645,7 @@ export async function connectClient(id, options = {}) {
1618
1645
  if (isForbidden(assistant, primary)) {
1619
1646
  return { ok: false, reason: `禁写路径(landing.forbiddenPaths):${primary}` };
1620
1647
  }
1621
- if (strategy === 'cli-set') return attachSkills(await connectViaCli(assistant, options), id, options);
1648
+ if (strategy === 'cli-set') return attachAdapter(await attachSkills(await connectViaCli(assistant, options), id, options), id, options);
1622
1649
  const existing = safeReadText(primary);
1623
1650
  const merged = computeMerged(assistant, existing, options);
1624
1651
  if (merged.error) {
@@ -1626,7 +1653,7 @@ export async function connectClient(id, options = {}) {
1626
1653
  }
1627
1654
  const preview = lineDiff(existing ?? '', merged.text);
1628
1655
  if (!merged.changed) {
1629
- return attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options);
1656
+ return attachAdapter(await attachSkills({ ok: true, changed: false, configPath: primary, backupPath: null, preview, note: '已接入(幂等:无需改动)' }, id, options), id, options);
1630
1657
  }
1631
1658
  const backupPath = existing !== null ? `${primary}.bak-${tsStamp()}` : null;
1632
1659
  if (backupPath) await copyFile(primary, backupPath);
@@ -1637,7 +1664,7 @@ export async function connectClient(id, options = {}) {
1637
1664
  if (backupPath) await copyFile(backupPath, primary); // 失败回滚
1638
1665
  return { ok: false, changed: false, rolledBack: Boolean(backupPath), backupPath, reason: `写入失败已回滚:${redactSecrets(error?.message ?? error)}` };
1639
1666
  }
1640
- return attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options);
1667
+ return attachAdapter(await attachSkills({ ok: true, changed: true, configPath: primary, backupPath, preview }, id, options), id, options);
1641
1668
  }
1642
1669
 
1643
1670
  /**
@@ -1794,6 +1821,16 @@ export async function rollbackClient(id, options = {}) {
1794
1821
  // 验证闭环(A-9/A-10/A-11)
1795
1822
  // ---------------------------------------------------------------------------
1796
1823
 
1824
+ /** 该 plugin 条目是否属于 Mebular 自己的 adapter(读回比对时忽略它,保留用户插件)。 */
1825
+ function isMebularPluginEntry(entry) {
1826
+ const refs = typeof entry === 'string'
1827
+ ? [entry]
1828
+ : (entry !== null && typeof entry === 'object' && !Array.isArray(entry)
1829
+ ? ['package', 'path', 'module', 'plugin'].map((key) => entry[key]).filter((value) => typeof value === 'string')
1830
+ : []);
1831
+ return refs.some((ref) => ref === '@mebular/opencode-plugin' || /(^|[/\\])opencode-plugin([/\\]|$)/.test(ref));
1832
+ }
1833
+
1797
1834
  /** 回读校验:条目存在 ∧ 原配置其余键无损(有备份时逐键比对)。 */
1798
1835
  export function readbackCheck(assistant, options = {}) {
1799
1836
  const landing = landingState(assistant, options);
@@ -1830,6 +1867,13 @@ export function readbackCheck(assistant, options = {}) {
1830
1867
  let node = clone;
1831
1868
  for (const key of path.slice(0, -1)) { if (node?.[key] === undefined) return clone; node = node[key]; }
1832
1869
  if (node && typeof node === 'object') delete node[path[path.length - 1]];
1870
+ // Adapter provisioning may also add its own entry to `plugins`; ignore
1871
+ // only Mebular's entry so user plugins are still compared.
1872
+ if (Array.isArray(clone.plugins)) {
1873
+ const remaining = clone.plugins.filter((entry) => !isMebularPluginEntry(entry));
1874
+ if (remaining.length === 0) delete clone.plugins;
1875
+ else clone.plugins = remaining;
1876
+ }
1833
1877
  return pruneEmpty(clone);
1834
1878
  };
1835
1879
  intact = JSON.stringify(strip(before)) === JSON.stringify(strip(after));
@@ -2285,7 +2329,13 @@ export async function repairClients(options = {}) {
2285
2329
  continue;
2286
2330
  }
2287
2331
  try {
2288
- base.connect = await connectClient(assistant.id, { ...options, skipSkills: true });
2332
+ base.connect = await connectClient(assistant.id, {
2333
+ ...options,
2334
+ skipSkills: true,
2335
+ // Repair fans out to detected hosts; adapter provisioning is only
2336
+ // allowed for hosts that were already connected before this repair.
2337
+ ensureAdapter: assistant.connected === true,
2338
+ });
2289
2339
  } catch (error) {
2290
2340
  base.connect = { ok: false, reason: `接入失败:${redactSecrets(error?.message ?? error)}` };
2291
2341
  }
@@ -0,0 +1,343 @@
1
+ // 0.4.0 W1b:全新空 home 的一次性首启初始化(唯一允许的“新安装默认 immersive”路径)。
2
+ //
3
+ // 契约(docs/design/0.4.0-w0-contract.md §2.4):
4
+ // - 只在真正空 home / 首次安装时命中;已有 home 永不写 marker / 不补字段;
5
+ // - marker `<home>/first-run.json`(0600,原子写)只表达披露生命周期,不是第二个 mode;
6
+ // - 披露在现有首启页展示;ack 只由 Console 显式回传 `firstRunDisclosure` + 版本触发;
7
+ // - ack 后初始化(幂等):sidecar seed `{"schema":1,"model":{"source":"auto"}}`(仅当 sidecar
8
+ // config 不存在)+ 合并 `<home>/config.json` `memoryRuntime.enabled=true`(保留其他字段);
9
+ // - 不写 `intervention.mode`,不重写已有 `model.source`,不迁移、不删除任何旧字段;
10
+ // - 任一步失败 → 不写(或只保留未启用的部分)并保持 off;调用方只记录 `first_run_init_failed`,
11
+ // 不阻塞 serve,不回退到 heuristic。
12
+ //
13
+ // 本模块不 import 图谱/事件/sync,也不读写宿主私有存储。
14
+
15
+ import { existsSync } from 'node:fs';
16
+ import { chmod, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises';
17
+ import { randomBytes } from 'node:crypto';
18
+ import { dirname, join, resolve } from 'node:path';
19
+ import { acquireConfigFileLock } from './config-lock.mjs';
20
+ import { resolveMemoryRuntimePaths } from './memory-runtime-supervisor.mjs';
21
+
22
+ export const FIRST_RUN_FILE = 'first-run.json';
23
+ export const FIRST_RUN_SCHEMA = 1;
24
+ export const FIRST_RUN_DISCLOSURE_VERSION = 1;
25
+ /** 失败时的稳定 warning code;不含路径/配置正文。 */
26
+ export const FIRST_RUN_INIT_FAILED = 'first_run_init_failed';
27
+
28
+ const ALLOWED_EMPTY_ENTRIES = new Set(['.DS_Store', 'Thumbs.db', FIRST_RUN_FILE]);
29
+ const BLOCKING_ENTRIES = [
30
+ 'config.json',
31
+ 'user-master-key.json',
32
+ 'store.jsonl',
33
+ 'store.jsonl.identity.json',
34
+ 'runtime.json',
35
+ 'memory-runtime',
36
+ 'net',
37
+ ];
38
+ const VALID_STATES = new Set(['pending', 'acked', 'done']);
39
+
40
+ function isObject(value) {
41
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
42
+ }
43
+
44
+ function stringOrNull(value) {
45
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
46
+ }
47
+
48
+ function isoTimestamp(now) {
49
+ const value = typeof now === 'function' ? now() : now;
50
+ const date = value instanceof Date ? value : new Date(value ?? Date.now());
51
+ return date.toISOString();
52
+ }
53
+
54
+ function mcpConfigPath(home, env) {
55
+ return env?.MEBULAR_CONFIG ?? join(home, 'config.json');
56
+ }
57
+
58
+ function firstRunPath(home) {
59
+ return join(home, FIRST_RUN_FILE);
60
+ }
61
+
62
+ /** marker 文件存在且形状合法才返回;损坏/未知 state 视为不存在,避免把坏文件当 ack。 */
63
+ export async function readFirstRunMarker({ home } = {}) {
64
+ if (typeof home !== 'string' || home.length === 0) return null;
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(await readFile(firstRunPath(home), 'utf-8'));
68
+ } catch {
69
+ return null;
70
+ }
71
+ if (!isObject(parsed) || parsed.schema !== FIRST_RUN_SCHEMA) return null;
72
+ if (typeof parsed.state !== 'string' || !VALID_STATES.has(parsed.state)) return null;
73
+ if (!Number.isInteger(parsed.disclosureVersion) || parsed.disclosureVersion < 1) return null;
74
+ return {
75
+ schema: parsed.schema,
76
+ disclosureVersion: parsed.disclosureVersion,
77
+ state: parsed.state,
78
+ createdAt: stringOrNull(parsed.createdAt),
79
+ ...(stringOrNull(parsed.ackedAt) ? { ackedAt: stringOrNull(parsed.ackedAt) } : {}),
80
+ ...(stringOrNull(parsed.initializedAt) ? { initializedAt: stringOrNull(parsed.initializedAt) } : {}),
81
+ };
82
+ }
83
+
84
+ /** 给 Console/provision status 的最小只读视图;不含路径/用户数据。 */
85
+ export function firstRunPublicView(marker) {
86
+ if (!marker) return null;
87
+ return {
88
+ pending: marker.state === 'pending',
89
+ disclosureVersion: marker.disclosureVersion,
90
+ state: marker.state,
91
+ };
92
+ }
93
+
94
+ async function writeJsonAtomic(path, value) {
95
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
96
+ const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`;
97
+ try {
98
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
99
+ await chmod(tmp, 0o600).catch(() => undefined);
100
+ await rename(tmp, path);
101
+ await chmod(path, 0o600).catch(() => undefined);
102
+ } catch (error) {
103
+ await unlink(tmp).catch(() => undefined);
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 极窄空 home 判定(契约 §2.4):
110
+ * - 无 config / 主密钥 / store / identity / runtime.json / memory-runtime/ / net/;
111
+ * - 目录为空,或只含 `.DS_Store` / `Thumbs.db` / `first-run.json`;
112
+ * - 设置了 `MEBULAR_CONFIG` / `MEBULAR_MEMORY_RUNTIME_HOME` / `MEBULAR_STORAGE_PATH` 时
113
+ * 一律不命中(外部存储可能在 home 之外已有 store,不能证明“首次安装”)。
114
+ *
115
+ * 非 ENOENT 的 readdir 错误不当作空 home(失败闭合)。
116
+ */
117
+ export async function detectFreshHome({ home, env = process.env } = {}) {
118
+ if (typeof home !== 'string' || home.length === 0) return false;
119
+ if (stringOrNull(env?.MEBULAR_CONFIG)
120
+ || stringOrNull(env?.MEBULAR_MEMORY_RUNTIME_HOME)
121
+ || stringOrNull(env?.MEBULAR_STORAGE_PATH)) {
122
+ return false;
123
+ }
124
+ const root = resolve(home);
125
+ for (const name of BLOCKING_ENTRIES) {
126
+ if (existsSync(join(root, name))) return false;
127
+ }
128
+ let entries;
129
+ try {
130
+ entries = await readdir(root);
131
+ } catch (error) {
132
+ // 空 home 可能尚未创建目录;只有 ENOENT 视为空。
133
+ return error?.code === 'ENOENT';
134
+ }
135
+ return entries.every((entry) => ALLOWED_EMPTY_ENTRIES.has(entry));
136
+ }
137
+
138
+ /**
139
+ * 首启检测:只有真正空 home 才写 `pending` marker。
140
+ * 已有 home、非空目录、显式 env 覆盖一律 no-op(返回 null,不创建文件)。
141
+ */
142
+ export async function markFirstRunPending({ home, env = process.env, now = Date.now } = {}) {
143
+ if (!(await detectFreshHome({ home, env }))) return null;
144
+ const existing = await readFirstRunMarker({ home });
145
+ if (existing) return existing;
146
+ const marker = {
147
+ schema: FIRST_RUN_SCHEMA,
148
+ disclosureVersion: FIRST_RUN_DISCLOSURE_VERSION,
149
+ state: 'pending',
150
+ createdAt: isoTimestamp(now),
151
+ };
152
+ try {
153
+ await writeJsonAtomic(firstRunPath(home), marker);
154
+ } catch {
155
+ // 写 marker 失败 = 无法证明披露已发生:不落盘、不启用;调用方保持 off。
156
+ return null;
157
+ }
158
+ return readFirstRunMarker({ home });
159
+ }
160
+
161
+ /**
162
+ * 披露成功的显式 ack。只有 pending marker + 匹配的 disclosureVersion 才接受;
163
+ * 其他情况(已有用户 / 无 marker / 版本不符)返回 null,绝不凭空创建 marker。
164
+ */
165
+ export async function markFirstRunAcked({
166
+ home,
167
+ disclosureVersion = FIRST_RUN_DISCLOSURE_VERSION,
168
+ now = Date.now,
169
+ } = {}) {
170
+ const marker = await readFirstRunMarker({ home });
171
+ if (!marker || marker.state !== 'pending') return null;
172
+ if (!Number.isInteger(disclosureVersion) || disclosureVersion !== marker.disclosureVersion) return null;
173
+ const next = {
174
+ ...marker,
175
+ state: 'acked',
176
+ ackedAt: isoTimestamp(now),
177
+ };
178
+ try {
179
+ await writeJsonAtomic(firstRunPath(home), next);
180
+ } catch {
181
+ return null;
182
+ }
183
+ return readFirstRunMarker({ home });
184
+ }
185
+
186
+ async function markFirstRunDone({ home, marker, now = Date.now } = {}) {
187
+ if (!marker) return null;
188
+ const next = {
189
+ ...marker,
190
+ state: 'done',
191
+ initializedAt: marker.initializedAt ?? isoTimestamp(now),
192
+ };
193
+ try {
194
+ await writeJsonAtomic(firstRunPath(home), next);
195
+ } catch {
196
+ return null;
197
+ }
198
+ return readFirstRunMarker({ home });
199
+ }
200
+
201
+ async function readConfigObject(path) {
202
+ let text;
203
+ try {
204
+ text = await readFile(path, 'utf-8');
205
+ } catch (error) {
206
+ if (error?.code === 'ENOENT') return { exists: false, config: {} };
207
+ throw error;
208
+ }
209
+ let parsed;
210
+ try {
211
+ parsed = JSON.parse(text);
212
+ } catch {
213
+ const error = new Error('config_invalid');
214
+ error.code = 'config_invalid';
215
+ throw error;
216
+ }
217
+ if (!isObject(parsed)) {
218
+ const error = new Error('config_invalid');
219
+ error.code = 'config_invalid';
220
+ throw error;
221
+ }
222
+ return { exists: true, config: parsed };
223
+ }
224
+
225
+ function withMemoryRuntimeEnabled(config) {
226
+ const next = { ...config };
227
+ const memoryRuntime = isObject(next.memoryRuntime) ? { ...next.memoryRuntime } : {};
228
+ memoryRuntime.enabled = true;
229
+ next.memoryRuntime = memoryRuntime;
230
+ return next;
231
+ }
232
+
233
+ /**
234
+ * 把 acked marker 落成真正的 immersive 初始化。幂等、原子、失败闭合:
235
+ * - 无 marker / 非 acked → `{ ok:false, reason:'no_marker'|'not_acked' }`,不写任何配置;
236
+ * - 已 enabled → 只把 marker 收敛为 done;
237
+ * - sidecar config 不存在才写 seed(source=auto,sourcePresent 自然为 true);
238
+ * - MCP config 只合并 `memoryRuntime.enabled=true`,其他键逐字保留;
239
+ * - 任一步失败 → 返回 `{ ok:false, reason }`(调用方记录 warning),不抛异常、不阻塞启动。
240
+ */
241
+ export async function initializeFirstRunHome({ home, env = process.env, now = Date.now } = {}) {
242
+ if (typeof home !== 'string' || home.length === 0) {
243
+ return { ok: false, reason: 'home_required' };
244
+ }
245
+ const root = resolve(home);
246
+ let marker = await readFirstRunMarker({ home: root });
247
+ if (!marker) return { ok: false, reason: 'no_marker' };
248
+ if (marker.state === 'done') {
249
+ return { ok: true, skipped: 'done', initialized: false, enabled: false };
250
+ }
251
+ if (marker.state !== 'acked') return { ok: false, reason: 'not_acked' };
252
+
253
+ const configFile = mcpConfigPath(root, env);
254
+ const release = await acquireConfigFileLock(configFile, { timeoutMs: 2000 });
255
+ if (!release) return { ok: false, reason: 'config_locked' };
256
+ try {
257
+ // 锁内重查 marker + enabled:并发初始化/用户手动开启时只允许一个写者。
258
+ marker = await readFirstRunMarker({ home: root });
259
+ if (!marker || marker.state === 'done') {
260
+ return marker?.state === 'done'
261
+ ? { ok: true, skipped: 'done', initialized: false, enabled: false }
262
+ : { ok: false, reason: 'no_marker' };
263
+ }
264
+ if (marker.state !== 'acked') return { ok: false, reason: 'not_acked' };
265
+
266
+ const { config } = await readConfigObject(configFile);
267
+ // memoryRuntime 不是对象 = 用户配置损坏/未知形态:fail closed,绝不覆盖成 {enabled:true}。
268
+ if (config.memoryRuntime !== undefined && !isObject(config.memoryRuntime)) {
269
+ return { ok: false, reason: 'config_invalid', enabled: false };
270
+ }
271
+ const explicitEnabled = isObject(config.memoryRuntime)
272
+ && typeof config.memoryRuntime.enabled === 'boolean';
273
+ if (explicitEnabled) {
274
+ // 显式 enabled 已存在(用户/模板写过)→ 绝不覆盖;false 也视为用户选择,停止重试。
275
+ await markFirstRunDone({ home: root, marker, now });
276
+ const enabled = config.memoryRuntime.enabled === true;
277
+ return {
278
+ ok: true,
279
+ skipped: enabled ? 'already_enabled' : 'explicit_disabled',
280
+ initialized: false,
281
+ enabled,
282
+ };
283
+ }
284
+
285
+ // 先写 sidecar seed:失败则 MCP 仍保持 disabled(off),不会出现“enabled 但没有 source”。
286
+ const sidecarConfigPath = join(resolveMemoryRuntimePaths({ home: root, env }).dataDir, 'config.json');
287
+ let sidecarSeed = 'existing';
288
+ if (!existsSync(sidecarConfigPath)) {
289
+ try {
290
+ await mkdir(dirname(sidecarConfigPath), { recursive: true, mode: 0o700 });
291
+ await writeJsonAtomic(sidecarConfigPath, { schema: 1, model: { source: 'auto' } });
292
+ sidecarSeed = 'created';
293
+ } catch (error) {
294
+ return {
295
+ ok: false,
296
+ reason: 'sidecar_seed_failed',
297
+ error: String(error?.code ?? error?.message ?? error),
298
+ };
299
+ }
300
+ }
301
+
302
+ const next = withMemoryRuntimeEnabled(config);
303
+ try {
304
+ await writeJsonAtomic(configFile, next);
305
+ } catch (error) {
306
+ return {
307
+ ok: false,
308
+ reason: 'config_write_failed',
309
+ error: String(error?.code ?? error?.message ?? error),
310
+ sidecarSeed,
311
+ };
312
+ }
313
+
314
+ const done = await markFirstRunDone({ home: root, marker, now });
315
+ return {
316
+ ok: true,
317
+ initialized: true,
318
+ enabled: true,
319
+ source: sidecarSeed === 'created' ? 'auto' : 'existing',
320
+ sidecarSeed,
321
+ markerState: done?.state ?? marker.state,
322
+ };
323
+ } catch (error) {
324
+ return {
325
+ ok: false,
326
+ reason: error?.code === 'config_invalid' ? 'config_invalid' : 'first_run_init_failed',
327
+ error: String(error?.code ?? error?.message ?? error),
328
+ };
329
+ } finally {
330
+ await release().catch(() => undefined);
331
+ }
332
+ }
333
+
334
+ /** `first-run.json` 是否存在(诊断用;不创建目录)。 */
335
+ export async function firstRunMarkerExists({ home } = {}) {
336
+ if (typeof home !== 'string' || home.length === 0) return false;
337
+ try {
338
+ const info = await stat(firstRunPath(home));
339
+ return info.isFile();
340
+ } catch {
341
+ return false;
342
+ }
343
+ }
@@ -78,6 +78,8 @@ export async function readMemoryRuntimeModelSource({ home, env = process.env } =
78
78
  const normalized = normalizeMemoryRuntimeModelSource(model.source);
79
79
  return {
80
80
  source: normalized ?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
81
+ /** 缺失 ≠ 显式 heuristic;effective mode 依赖这个标志。 */
82
+ sourcePresent: model.source !== undefined && model.source !== null,
81
83
  defaultSource: DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
82
84
  values: [...MEMORY_RUNTIME_MODEL_SOURCES],
83
85
  exists,
@@ -0,0 +1,91 @@
1
+ // 0.4.0 Memory Runtime effective mode(MCP 轻量视图)。
2
+ //
3
+ // 与 sidecar `src/sidecar/effective.ts` 同一张推导表:
4
+ // - `memoryRuntime.enabled` 是 immersive 的唯一真值;
5
+ // - enabled=false / 缺少字段 → lightweight / off,不启动 sidecar;
6
+ // - enabled=true 但 `model.source` 缺失 → off(保持 0.3 baseline,不能静默 heuristic);
7
+ // - enabled=true + 显式 heuristic → heuristic;
8
+ // - enabled=true + local/host/api/auto → model(0.4.0 local 仅 assisted/shadow);
9
+ // - 旧 intervention.mode 不参与 production,只产生稳定 warning(显式 off 也不例外);
10
+ // - shadow 只能由内部 diagnostic 打开。
11
+ //
12
+ // 本模块只做纯计算,不读文件/环境;不返回 token、keyRef 或配置正文。
13
+
14
+ import {
15
+ DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE,
16
+ normalizeMemoryRuntimeModelSource,
17
+ } from './memory-runtime-config.mjs';
18
+
19
+ export const MEMORY_RUNTIME_MODES = Object.freeze(['lightweight', 'immersive']);
20
+ export const LEGACY_INTERVENTION_MODE_IGNORED = 'legacy_intervention_mode_ignored';
21
+ export const MODEL_SOURCE_MISSING = 'model_source_missing';
22
+
23
+ function isObject(value) {
24
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
25
+ }
26
+
27
+ /**
28
+ * 由 MCP 配置 + sidecar model.source 推导 effective mode。
29
+ *
30
+ * 输入 `config` 是 MCP `<home>/config.json` 的(结构化)视图;`modelSource`/`sourcePresent`
31
+ * 由调用方从 sidecar 只读视图传入。`legacyMode`/`legacyModePresent` 只在状态诊断时需要。
32
+ */
33
+ export function resolveMemoryRuntimeEffectiveMode({
34
+ config,
35
+ modelSource,
36
+ sourcePresent,
37
+ legacyMode = null,
38
+ legacyModePresent,
39
+ diagnosticShadow = false,
40
+ } = {}) {
41
+ const root = isObject(config) ? config : {};
42
+ const memoryRuntime = isObject(root.memoryRuntime) ? root.memoryRuntime : {};
43
+ const enabled = memoryRuntime.enabled === true;
44
+ const configuredSource = modelSource
45
+ ?? root.modelSource
46
+ ?? (isObject(root.model) ? root.model.source : undefined);
47
+ const source = normalizeMemoryRuntimeModelSource(configuredSource)
48
+ ?? DEFAULT_MEMORY_RUNTIME_MODEL_SOURCE;
49
+ // 未显式传入 presence 时,按“是否提供了 source”推断;空配置视为缺失。
50
+ const present = sourcePresent
51
+ ?? (configuredSource !== undefined && configuredSource !== null);
52
+
53
+ // enabled=false 时没有 sidecar,也不进入介入;但诊断仍按 source 推导。
54
+ const production = !present ? 'off' : source === 'heuristic' ? 'heuristic' : 'model';
55
+ const effectivePlanner = enabled ? production : 'off';
56
+ const effective = !enabled ? 'off' : (diagnosticShadow && present ? 'shadow' : production);
57
+
58
+ const legacyModeValue = legacyMode ?? null;
59
+ const legacyModeIsPresent = legacyModePresent
60
+ ?? (legacyModeValue !== null);
61
+ let legacyModeIgnored = false;
62
+ let legacyModeConflict = false;
63
+ const warnings = [];
64
+
65
+ // 只有 immersive 的缺失 source 才值得告警;lightweight 不启动介入。
66
+ if (enabled && !present) warnings.push(MODEL_SOURCE_MISSING);
67
+
68
+ if (legacyModeIsPresent && legacyModeValue !== null) {
69
+ // 显式旧值一律不参与 production;显式 off 也不例外(W1a review B2)。
70
+ legacyModeIgnored = legacyModeValue !== production;
71
+ legacyModeConflict = (legacyModeValue === 'off' && production === 'model')
72
+ || (legacyModeValue === 'heuristic' && production === 'model')
73
+ || (legacyModeValue === 'model' && production === 'heuristic');
74
+ if (legacyModeIgnored) warnings.push(LEGACY_INTERVENTION_MODE_IGNORED);
75
+ }
76
+
77
+ return {
78
+ mode: enabled ? 'immersive' : 'lightweight',
79
+ enabled,
80
+ effective,
81
+ planner: effectivePlanner,
82
+ source,
83
+ sourcePresent: present,
84
+ derivedMode: production,
85
+ legacyModePresent: legacyModeIsPresent && legacyModeValue !== null,
86
+ legacyModeIgnored,
87
+ legacyModeConflict,
88
+ diagnosticShadow: enabled && present && diagnosticShadow === true,
89
+ warnings,
90
+ };
91
+ }