Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): SSH remote 会话支持 Maker Memory (#989)

yan6df2b3b2d6b4
diff --git a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
index fe4b6ed785..6bb69fa28e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/cc-remote-mcp.test.ts
@@ -352,4 +352,76 @@ describe('buildCcRemoteHttpMcpServers', () => {
expect(servers).toEqual({});
expect(ensureForward).not.toHaveBeenCalled();
});
+
+ it('injects cindy_memory alongside collab servers when the session Maker Memory flag is on, with remoteHostId in ctx', async () => {
+ const { bridge, registered } = fakeBridge();
+ const { servers } = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo', makerMemoryEnabled: true },
+ {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'orca_worker_bridge', 'cindy_memory', 'cindy_ssh'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ synthesizeVendorOptions: async () => ({}),
+ },
+ );
+ expect(Object.keys(servers).sort()).toEqual(['cindy_memory', 'cindy_orca', 'orca_worker_bridge']);
+ expect(servers.cindy_memory).toEqual({
+ type: 'http',
+ url: 'http://127.0.0.1:47921/mcp/cindy_memory?session=s1',
+ headers: { Authorization: 'Bearer persistent-test-token' },
+ });
+ // ctx 必须带 remoteHostId — cindy_memory 据此把远端路径隔离到
+ // ssh:<hostId>:<path> 的独立 store。
+ expect(registered.get('s1')).toMatchObject({ remoteHostId: 'host-1', workingDir: '/remote/repo' });
+ });
+
+ it('injects only cindy_memory when collab is disabled but the session Maker Memory flag is on', async () => {
+ const { bridge } = fakeBridge();
+ const { servers } = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo', makerMemoryEnabled: true },
+ {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'orca_worker_bridge', 'cindy_memory'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ isCollabEnabled: () => false,
+ synthesizeVendorOptions: async () => ({}),
+ },
+ );
+ expect(Object.keys(servers)).toEqual(['cindy_memory']);
+ });
+
+ it('memory flag flips change the generation fingerprint (server set is part of the generation)', async () => {
+ const { bridge } = fakeBridge();
+ const deps = {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'orca_worker_bridge', 'cindy_memory'],
+ bridge,
+ }),
+ ensureForward: vi.fn(async () => 47921),
+ getBridgeToken: async () => 'persistent-test-token',
+ synthesizeVendorOptions: async () => ({}),
+ };
+ const withMemory = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo', makerMemoryEnabled: true },
+ deps,
+ );
+ const withoutMemory = await buildCcRemoteHttpMcpServers(
+ { host: HOST, sessionId: 's1', workingDir: '/remote/repo' },
+ deps,
+ );
+ expect(withMemory.fingerprint).toBeDefined();
+ expect(withoutMemory.fingerprint).toBeDefined();
+ // 开关翻转 = 注入集合变化 = 新代际, attach 回旧集合的 alive query 必须
+ // 被判 drift 重建。
+ expect(withMemory.fingerprint).not.toBe(withoutMemory.fingerprint);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts
index ecb73d88ae..7919306ae0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/remote-codex-mcp-recovery.test.ts
@@ -32,6 +32,7 @@ function makeDeps(overrides?: Partial<Parameters<typeof refreshRemoteCodexMcpAft
ensureBridgeStarted: async () => ({ port: 38080, serverNames: ['cindy_orca'], bridgeInstanceId: 'bridge-2' }),
getLiveTurnChecker: () => checker,
isCollabEnabled: () => true,
+ isMakerMemoryEnabled: () => false,
detachRemoteCodexSessionsOnHost: vi.fn(),
log: { warn },
...overrides,
@@ -55,6 +56,8 @@ describe('refreshRemoteCodexMcpAfterBridgeRecreate', () => {
expect(callDeps.hasLiveTurnOnHost).toBe(checker);
// R21 P1: 恢复路径必须透传 Collab 闸门 — 禁用时 ensure 走清理而非重注入。
expect(callDeps.isCollabEnabled).toBe(deps.isCollabEnabled);
+ // Maker Memory 同源闸门:缺省 false 会让补刀把已注入的 cindy_memory 剥掉。
+ expect(callDeps.isMakerMemoryEnabled).toBe(deps.isMakerMemoryEnabled);
}
});
diff --git a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
index eabe499456..f2b3f4c2fe 100644
--- a/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
+++ b/apps/desktop/src/main/maker-host/cc-remote-mcp.ts
@@ -13,7 +13,6 @@
* 端口, 与 codex daemon 共用同一条) 与 codex 路径完全一致。
*/
-import { createHash } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
@@ -21,19 +20,13 @@ import { app } from 'electron';
import type { RemoteHost } from '@cindy/maker-remote-ssh';
import type { CodexHttpBridge } from '../mcp-integrations/codexHttpBridge.js';
-import { REMOTE_COLLAB_SERVER_NAMES } from '../mcp-integrations/codexHttpBridge.js';
+import {
+ computeRemoteMcpFingerprint,
+ selectRemoteInjectableServerNames,
+} from '../mcp-integrations/codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';
import { getSessionOrcaRole, getWorkerLink } from '../localDb/orcaTeamStore.js';
-/**
- * cc 远端允许经 remote-forward 暴露的 server 白名单 — 唯一真源在
- * codexHttpBridge.ts (REMOTE_COLLAB_SERVER_NAMES, bridge 鉴权层对
- * persistent token 也按它 scope):只放协同必需的 cindy_orca /
- * orca_worker_bridge;其余 in-process server (cindy_memory 远端本就显式
- * 禁用、cindy_ssh 的 exec 从本机发起等) 维持"远端不可用"现状,收窄影响面。
- */
-const CC_REMOTE_HTTP_MCP_SERVER_NAMES = REMOTE_COLLAB_SERVER_NAMES;
-
/**
* cc remote 的 MCP session ctx 合成:与 synthesizeOrcaVendorOptionsFromDb
* (maker-ipc/orcaSessionStartOptions.ts) 同一语义,但这里不能反向依赖
@@ -112,6 +105,13 @@ export async function buildCcRemoteHttpMcpServers(
workingDir: string;
/** session 自己的 vendorOptions (maker-core startSession 透传); 优先于 DB 合成。 */
vendorOptions?: Record<string, unknown>;
+ /**
+ * per-session Maker Memory 开关 (maker-core startSession 归一后透传)。
+ * true 时把 cindy_memory 一并注入 — 必须与 maker-core 的 prompt 注入
+ * (rules + MEMORY.md index) 同源同值, 否则模型被 rules 引导去调不存在
+ * 的工具。缺省 false。
+ */
+ makerMemoryEnabled?: boolean;
},
deps: CcRemoteHttpMcpDeps,
): Promise<{
@@ -140,11 +140,13 @@ export async function buildCcRemoteHttpMcpServers(
const started = await deps.ensureBridgeStarted();
if (!started) return empty;
// collab 全局禁用时 bridge 名单不反映开关 (keepOrcaProviderStable) —
- // 远端注入以同一闸门为准, 整个不注入 (codex-connector R20 P2)。
- const collabEnabled = deps.isCollabEnabled?.() ?? true;
- const names = collabEnabled
- ? started.serverNames.filter((n) => CC_REMOTE_HTTP_MCP_SERVER_NAMES.has(n))
- : [];
+ // 远端注入以同一闸门为准, 协同段整个不注入 (codex-connector R20 P2)。
+ // cindy_memory 独立走 per-session Maker Memory 开关, 与 collab 互不牵连。
+ // 合成规则唯一真源在 selectRemoteInjectableServerNames (codexHttpBridge.ts)。
+ const names = selectRemoteInjectableServerNames(started.serverNames, {
+ collabEnabled: deps.isCollabEnabled?.() ?? true,
+ memoryEnabled: args.makerMemoryEnabled === true,
+ });
if (names.length === 0) {
// 无注入也是一代 (collab 禁用 / 白名单空):指纹常量 'disabled',
// 开→关的重启后 drift 判定成立 (R23 P2);不含 instanceId, 一直禁用
@@ -171,6 +173,8 @@ export async function buildCcRemoteHttpMcpServers(
agentKind: 'claude-code' as const,
sessionId: args.sessionId,
workingDir: args.workingDir,
+ // remote ctx: scope key 语义见 maker-core buildMemoryScopeKey。
+ remoteHostId: args.host.id,
vendorOptions: args.vendorOptions ?? (await synthesize(args.sessionId)),
};
// 同 session 重建 (resume/rebuild/reattach) 直接覆盖注册,注册表以 sessionId
@@ -190,10 +194,11 @@ export async function buildCcRemoteHttpMcpServers(
return {
servers,
cleanup: () => started.bridge.unregisterSessionCtx(args.sessionId, ctx),
- fingerprint: computeCcRemoteMcpFingerprint({
+ fingerprint: computeRemoteMcpFingerprint({
token: bridgeToken,
bridgeInstanceId: started.bridge.instanceId,
remotePort,
+ serverNames: names,
}),
};
} catch (err) {
@@ -213,26 +218,18 @@ export async function buildCcRemoteHttpMcpServers(
* stale 集合清空, 没有它 factory 会 attach 回带旧 collab URL 的 query
* (codex-connector R23 P2)。
*
- * 成分:token|bridgeInstanceId|remotePort (注入代际);无注入代际用常量
- * 'disabled' (collab 禁用 / 白名单为空) — 不含 instanceId, 避免「collab
- * 一直禁用」的健康 query 在每次 bridge 重建后被误判 drift 白杀。
- * bridge 不在 (shutdown) 时不产指纹 — 判定方跳过 (forceFresh 也无 bridge
- * 可用, 恢复由 lazy 重建路径负责)。
+ * 成分:token|bridgeInstanceId|remotePort|serverNames (注入代际; server 名单
+ * 进指纹 — cc 的注入集合随 per-session Maker Memory 开关变化, 开关翻转后
+ * attach 回旧集合的 alive query 必须判为 drift 重建), 公式唯一真源在
+ * computeRemoteMcpFingerprint (codexHttpBridge.ts, 与 codex 侧共用);无注入
+ * 代际用常量 'disabled' (collab 与 memory 都关 / 白名单为空) — 不含
+ * instanceId, 避免「一直禁用」的健康 query 在每次 bridge 重建后被误判
+ * drift 白杀。bridge 不在 (shutdown) 时不产指纹 — 判定方跳过 (forceFresh
+ * 也无 bridge 可用, 恢复由 lazy 重建路径负责)。
*/
const CC_DISABLED_GENERATION = 'disabled';
-export function computeCcRemoteMcpFingerprint(opts: {
- token: string;
- bridgeInstanceId: string;
- remotePort: number;
-}): string {
- return createHash('sha256')
- .update(`${opts.token}|${opts.bridgeInstanceId}|${opts.remotePort}`, 'utf8')
- .digest('hex')
- .slice(0, 12);
-}
-
export const CC_MCP_DISABLED_FINGERPRINT = CC_DISABLED_GENERATION;
type CcFreshPrefs = Record<string, string>;
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 388acdcc19..26a406914b 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -428,6 +428,8 @@ export async function ensureCodexMcpBridgeStartedForRemote(): Promise<{
// 恢复路径同闸门 (codex-connector R21 P1):collab 全局禁用时
// ensure 走清理而非重注入。
isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
+ // Maker Memory 同源闸门:开着时补刀不得把 cindy_memory 剥掉。
+ isMakerMemoryEnabled: () => _maker?.makerMemory?.isEnabled() ?? false,
detachRemoteCodexSessionsOnHost: (hostId) =>
detachActiveRemoteCodexSessions(hostId, 'bridge-recreate-rebootstrap'),
log: desktopMakerLogger,
@@ -604,13 +606,16 @@ export function getMaker(): Maker {
// MCP 注入) — 与 IPC create/send 路径同一 preflight。holder 在 IPC
// 注册时填入 (晚于本 deps 构造, 早于任何 bridge 回调)。
ensureRemoteSessionStart: async (params) => {
- await getRemoteSessionStartEnsure()?.({
- createOpts: {
- id: params.sessionId,
- agentKind: params.agentKind,
- remoteHostId: params.remoteHostId,
- },
- });
+ // ensure 会在 createOpts 上就地归一化 makerMemoryEnabled (全局设置
+ // backfill + stale-bridge 钳制) — 这里是临时对象, 必须把结果读回
+ // 交给 bridge 的真实 createSession (review R6 P2)。
+ const createOpts: { id: string; agentKind: typeof params.agentKind; remoteHostId: string; makerMemoryEnabled?: boolean } = {
+ id: params.sessionId,
+ agentKind: params.agentKind,
+ remoteHostId: params.remoteHostId,
+ };
+ await getRemoteSessionStartEnsure()?.({ createOpts });
+ return { makerMemoryEnabled: createOpts.makerMemoryEnabled === true };
},
orcaTeamStore: orcaTeamStoreAdapter,
dispatchInterAgentMessage,
@@ -691,7 +696,7 @@ export function getMaker(): Maker {
// RemoteQuery 实现 SDK Query interface 的子集 (ClaudeCodeAgent 实际只调
// for-await / interrupt / setModel / setPermissionMode / applyFlagSettings),
// factory 返回时直接 `as unknown as Query` cast 即可。
- remoteCcQueryFactory: async ({ remoteHostId, sessionId, startParams, vendorOptions, onApprovalRequest }) => {
+ remoteCcQueryFactory: async ({ remoteHostId, sessionId, startParams, vendorOptions, onApprovalRequest, makerMemoryEnabled }) => {
const host = getRemoteSshPool().get(remoteHostId);
if (host?.getStatus() !== 'ready') {
throw new Error(`remote ssh host not ready: ${remoteHostId}`);
@@ -722,6 +727,8 @@ export function getMaker(): Maker {
sessionId,
workingDir: typeof startParams.cwd === 'string' ? startParams.cwd : '',
vendorOptions,
+ // per-session Maker Memory 开关 (maker-core 归一后透传)。
+ makerMemoryEnabled,
},
{
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
@@ -974,7 +981,7 @@ export function getMaker(): Maker {
: {}),
};
},
- registerCodexMcpThreadContext: ({ threadId, sessionId, workingDir, vendorOptions }) => {
+ registerCodexMcpThreadContext: ({ threadId, sessionId, workingDir, remoteHostId, vendorOptions }) => {
// Codex shares one app-server across sessions. Freeze the effective
// ordinary-tool policy at thread creation so later Settings changes do
// not mutate a runtime that is already running.
@@ -983,6 +990,8 @@ export function getMaker(): Maker {
agentKind: 'codex',
sessionId,
workingDir,
+ // remote thread ctx: scope key 语义见 buildMemoryScopeKey。
+ ...(remoteHostId ? { remoteHostId } : {}),
vendorOptions: {
...vendorOptions,
[CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY]: disabledPluginIds,
diff --git a/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts b/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts
index 2bfcc28cd5..5c13e16888 100644
--- a/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts
+++ b/apps/desktop/src/main/maker-host/remote-codex-mcp-recovery.ts
@@ -35,6 +35,11 @@ export interface RemoteCodexMcpRecoveryDeps {
* 重新注入回去 (codex-connector R21 P1)。
*/
isCollabEnabled: () => boolean;
+ /**
+ * Maker Memory 全局开关。恢复路径的 ensure 同样必须透传 — 缺省 false 会
+ * 让 bridge 重建后的补刀把已注入的 cindy_memory 从远端 config 剥掉。
+ */
+ isMakerMemoryEnabled: () => boolean;
/**
* detach 该 host 上活跃的远端 codex session (跳过 turn 中的)。ensure
* 成功 (且非 live-turn defer) ⇒ daemon 已 rebootstrap ⇒ 旧 transport
@@ -56,6 +61,7 @@ export function refreshRemoteCodexMcpAfterBridgeRecreate(deps: RemoteCodexMcpRec
ensureBridgeStarted: deps.ensureBridgeStarted,
hasLiveTurnOnHost: liveTurnChecker,
isCollabEnabled: deps.isCollabEnabled,
+ isMakerMemoryEnabled: deps.isMakerMemoryEnabled,
}).then((result) => {
if (!result.ok) {
deps.log.warn('remote MCP recovery after bridge recreate failed', {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts
new file mode 100644
index 0000000000..e7cd59c919
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteSessionMakerMemory.test.ts
@@ -0,0 +1,99 @@
+/**
+ * SSH remote 会话的 Maker Memory 开关链路 (review R1 P1/P2) 的结构性回归断言。
+ *
+ * register.ts 是巨型组装函数, 闭包逻辑难以直接单测; 与
+ * remoteCcQueryFactory.test.ts 同一模式用源码结构守住两条回归:
+ *
+ * 1. R1 P1: ensureRemoteReadyForSessionStart 曾对所有远端 createOpts 强制
+ * `makerMemoryEnabled = false`, 把 renderer/DB-hydrate 侧已放开的开关又
+ * 盖回去 — 远端会话永远拿不到记忆注入。现在必须保留调用方值, 缺失时按
+ * 全局开关补齐。
+ * 2. R1 P2: cindy_memory provider 的 isEnabled 在 codex HTTP bridge 启动时
+ * 冻结。Maker Memory 开关翻转必须重建 bridge (shutdownCodexEnvironment,
+ * 与 contacts / 全局插件开关同机制), 否则旧 bridge 缺/多 cindy_memory:
+ * 远端 CC prompt 与工具面失配, codex 远端漂移判定永不收敛。
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const source = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8').replace(/\r\n?/g, '\n');
+
+describe('ensureRemoteReadyForSessionStart Maker Memory flag (R1 P1)', () => {
+ it('no longer hard-forces makerMemoryEnabled=false on remote createOpts', () => {
+ // 旧回归形态:remoteHostId 赋值后紧跟无条件覆盖 false。R2 的 stale-bridge
+ // 钳制分支里也有受守卫的 `= false` 赋值, 所以只锁「无条件」形态。
+ expect(source).not.toMatch(
+ /remoteHostId = remoteHostIdToEnsure;\s*\n\s*mutableCreateOpts\.makerMemoryEnabled = false;/,
+ );
+ });
+
+ it('preserves the caller flag and only backfills from the global manager state', () => {
+ const fnStart = source.indexOf('async function ensureRemoteReadyForSessionStart');
+ expect(fnStart).toBeGreaterThan(-1);
+ const backfill = source.indexOf(
+ 'mutableCreateOpts.makerMemoryEnabled ??= maker.makerMemory?.isEnabled() ?? false;',
+ fnStart,
+ );
+ expect(backfill).toBeGreaterThan(fnStart);
+ });
+
+ it('clamps the session flag when the active (stale) bridge lacks cindy_memory (R2 P2)', () => {
+ // busy 延迟窗口:manager 已翻转、bridge 重建被推迟。flag 保持 true 会让
+ // prompt 注入 memory rules 而工具面没有 server — 必须按活跃 bridge 的
+ // server 快照 (activeBridgeMissingMemory 谓词, 与 drift 判定共用) 钳制
+ // 到关闭, 保持 prompt / 工具面同源。
+ expect(source).toContain('function activeBridgeMissingMemory()');
+ const fnStart = source.indexOf('async function ensureRemoteReadyForSessionStart');
+ const backfill = source.indexOf('mutableCreateOpts.makerMemoryEnabled ??=', fnStart);
+ const clamp = source.indexOf(
+ 'if (mutableCreateOpts.makerMemoryEnabled && activeBridgeMissingMemory()) {',
+ backfill,
+ );
+ const clampAssign = source.indexOf('mutableCreateOpts.makerMemoryEnabled = false;', clamp);
+ expect(backfill).toBeGreaterThan(fnStart);
+ expect(clamp).toBeGreaterThan(backfill);
+ expect(clampAssign).toBeGreaterThan(clamp);
+ });
+});
+
+describe('codex remote drift uses the bridge-clamped memory flag (R2 P2)', () => {
+ it('routes both hasPendingRemoteMcpDrift call sites through the shared bridge-clamped opts', () => {
+ // desired 集合必须与 ensure 实际能注入的集合同源:旧 bridge 缺
+ // cindy_memory 时不能只看 manager 现值, 否则 drift 永不收敛, 每次
+ // live send 白跑一次完整 remote ensure。opts 单点构造在
+ // codexRemoteDriftOpts (内部走 remoteMakerMemoryEnabledForBridge)。
+ expect(source).toContain('function remoteMakerMemoryEnabledForBridge()');
+ expect(source).toContain('makerMemoryEnabled: remoteMakerMemoryEnabledForBridge()');
+ const driftCalls = source.match(/hasPendingRemoteMcpDrift\(live\.remoteHostId, codexRemoteDriftOpts\(\)\)/g) ?? [];
+ expect(driftCalls.length).toBe(2);
+ // drift 调用点不得残留裸 manager 现值。
+ expect(source).not.toContain('makerMemoryEnabled: maker.makerMemory?.isEnabled() ?? false');
+ });
+});
+
+describe('maker-memory toggle rebuilds the codex MCP bridge (R1 P2)', () => {
+ it('MAKER_MEMORY_SET_ENABLED applyRuntime shuts down the codex environment when the flag flips', () => {
+ const handler = source.indexOf('MAKER_INVOKE.MAKER_MEMORY_SET_ENABLED');
+ expect(handler).toBeGreaterThan(-1);
+ const guard = source.indexOf('if (wasEnabled !== enabled) {', handler);
+ expect(guard).toBeGreaterThan(handler);
+ const shutdown = source.indexOf('await shutdownCodexEnvironmentBestEffort(', guard);
+ expect(shutdown).toBeGreaterThan(guard);
+ // 同值调用 (无翻转) 不得白杀 bridge — shutdown 必须在翻转守卫之内。
+ const wasEnabledSnapshot = source.indexOf('const wasEnabled = makerMemory.isEnabled();', handler);
+ expect(wasEnabledSnapshot).toBeGreaterThan(handler);
+ expect(wasEnabledSnapshot).toBeLessThan(guard);
+ });
+
+ it('MEMORY_RESET_SETTINGS applyRuntime shuts down the codex environment when the maker flag flips', () => {
+ const handler = source.indexOf('MAKER_INVOKE.MEMORY_RESET_SETTINGS');
+ expect(handler).toBeGreaterThan(-1);
+ const guard = source.indexOf('if (wasMakerEnabled !== resetSettings_.maker) {', handler);
+ expect(guard).toBeGreaterThan(handler);
+ const shutdown = source.indexOf('await shutdownCodexEnvironmentBestEffort(', guard);
+ expect(shutdown).toBeGreaterThan(guard);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b9a6b6f3d0..2688605cde 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -81,7 +81,8 @@ import {
getBrowserAvailability,
openBrowserForLogin,
} from '../mcp-integrations/browser.js';
-import { getActiveCodexBridgeInstanceId, shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.js';
+import { getActiveCodexBridgeInstanceId, getActiveCodexBridgeServerNames, shutdownCodexEnvironment } from '../mcp-integrations/codexEnvironment.js';
+import { REMOTE_MEMORY_SERVER_NAME } from '../mcp-integrations/codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';
import {
checkComputerDriverUpdate,
@@ -695,6 +696,28 @@ function memorySettingsWire() {
* 文本裸曝给 renderer(review P1 2026-07-23)。执行体见
* runMemoryChangeWithCodexRestart。
*/
+/**
+ * Maker Memory 开关翻转后的 codex bridge 失效 (review R1 P2)。cindy_memory
+ * provider 的 isEnabled 在 bridge 启动时冻结 (codexEnvironment doStart 快照
+ * provider 集合), 不重建的话老 bridge 缺/多 cindy_memory server — 远端 CC
+ * 会出现 prompt 注入了 memory rules 但工具面没有 server 的失配, codex 远端
+ * 漂移判定永不收敛。与 contacts / 全局插件开关同机制:best-effort shutdown,
+ * 下一次使用 lazy 重建出与新开关一致的 bridge;远端失效与重注入由
+ * shutdownCodexEnvironment 的既有 hook 链自愈。调用方须放在 applyRuntime
+ * (prepare 已停 app-server / 延迟路径全员空闲) 满足「先停 app-server 再关
+ * bridge」的顺序约束, 并用翻转守卫包住 (同值调用不白杀 bridge)。失败只记
+ * warn — 设置已落盘, 旧 bridge 的失配窗口由下一次 bridge 重建收敛。
+ */
+async function shutdownCodexEnvironmentBestEffort(reason: string): Promise<void> {
+ try {
+ await shutdownCodexEnvironment();
+ } catch (err) {
+ log.warn(`shutdownCodexEnvironment on ${reason} failed — cached bridge still stale`, {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+}
+
async function applyMemoryChangeWithCodexRestart<T extends object>(
parts: MemoryChangeParts<T>,
): Promise<T & { codexRestartDeferred: boolean }> {
@@ -4321,6 +4344,41 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// DB 异常不缓存 null)。
const readSessionRemoteHostIdCached = createSessionRemoteHostIdReader();
+ /**
+ * stale-bridge 谓词 (review R2 P2):bridge 的 provider 集合在启动时冻结;
+ * Maker Memory 开关翻转而 codex busy 时, bridge 重建被
+ * DeferredCodexRestartService 推迟, 窗口内活跃 bridge 缺 cindy_memory。
+ * 远端链路 (per-session flag 钳制 / drift 判定) 必须以它为准 — 否则
+ * prompt 注入与工具面失配、drift 追一个注不进去的 server 永不收敛。
+ * 无活跃 bridge 时返回 false (接下来的 lazy 重建会产出与 manager 现值
+ * 一致的新 bridge, 不构成缺失)。
+ */
+ function activeBridgeMissingMemory(): boolean {
+ const bridgeServers = getActiveCodexBridgeServerNames();
+ return bridgeServers !== null && !bridgeServers.includes(REMOTE_MEMORY_SERVER_NAME);
+ }
+
+ /** 远端会话视角的 Maker Memory 有效开关 = manager 现值 + stale-bridge 钳制。 */
+ function remoteMakerMemoryEnabledForBridge(): boolean {
+ return (maker.makerMemory?.isEnabled() ?? false) && !activeBridgeMissingMemory();
+ }
+
+ /**
+ * live-send 轻量漂移判定 (hasPendingRemoteMcpDrift) 的 opts。函数而非常量:
+ * 第二次判定发生在 ensure 之后, bridge 可能已 lazy 重建, 四个成分都要现读。
+ */
+ function codexRemoteDriftOpts() {
+ return {
+ collabEnabled: getPluginRegistry().isEnabled('collab'),
+ // desired 集合要跟 ensure 实际能注入的集合同源 (stale-bridge 钳制),
+ // 不能只看 manager 现值 — 否则旧 bridge 缺 cindy_memory 时 drift 永不
+ // 收敛, 每次 live send 白跑完整 ensure。
+ makerMemoryEnabled: remoteMakerMemoryEnabledForBridge(),
+ token: getRemoteMcpBridgeToken(),
+ bridgeInstanceId: getActiveCodexBridgeInstanceId(),
+ };
+ }
+
async function ensureRemoteReadyForSessionStart(params: {
session?: { agentKind: AgentKind; remoteHostId: string | null } | null;
createOpts?: unknown;
@@ -4354,7 +4412,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (createOpts && typeof createOpts === 'object') {
const mutableCreateOpts = createOpts as { remoteHostId?: string; makerMemoryEnabled?: boolean };
mutableCreateOpts.remoteHostId = remoteHostIdToEnsure;
- mutableCreateOpts.makerMemoryEnabled = false;
+ // SSH remote 与本地同语义:Maker Memory 跟随控制端设置 (scope 由
+ // maker-core 按 remoteHostId+workingDir 隔离)。调用方显式给的值优先
+ // (renderer 已按全局设置填);main 侧发起、快照缺该字段的路径 (Orca
+ // worker 派活 / scheduler / lazy-resume 等) 按全局开关补齐 — 这里
+ // 不得再强制 false (review R1 P1:此前的强制覆盖让远端会话永远
+ // 拿不到记忆注入)。
+ mutableCreateOpts.makerMemoryEnabled ??= maker.makerMemory?.isEnabled() ?? false;
+ // stale-bridge 钳制 (见 activeBridgeMissingMemory):窗口内本会话统一
+ // 按关闭注入 (prompt 与工具面同源), bridge 重建后新会话自然恢复。
+ if (mutableCreateOpts.makerMemoryEnabled && activeBridgeMissingMemory()) {
+ mutableCreateOpts.makerMemoryEnabled = false;
+ }
}
await ensureRemoteHostReady(remoteHostIdToEnsure);
@@ -4406,6 +4475,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// collab 全局禁用 (Tier 4) 时按清理路径剥远端受管段 — bridge
// 名单不反映开关 (codex-connector R20 P2)。
isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
+ // Maker Memory 全局开着时把 cindy_memory 一并注入远端 daemon config。
+ isMakerMemoryEnabled: () => maker.makerMemory?.isEnabled() ?? false,
});
if (result.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostIdToEnsure)) {
await detachIdleRemoteCodexSessionsOnHost(remoteHostIdToEnsure, 'codex-mcp-daemon-rebootstrap');
@@ -4472,6 +4543,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ensureBridgeStarted: ensureCodexMcpBridgeStartedForRemote,
hasLiveTurnOnHost: codexRemoteHasLiveTurn,
isCollabEnabled: () => getPluginRegistry().isEnabled('collab'),
+ isMakerMemoryEnabled: () => maker.makerMemory?.isEnabled() ?? false,
}).then(async (result) => {
if (result.ok && result.daemonRebootstrapped && !codexRemoteHasLiveTurn(remoteHostId)) {
await detachIdleRemoteCodexSessionsOnHost(remoteHostId, 'codex-mcp-turn-settled-rebootstrap');
@@ -5229,11 +5301,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (
live.remoteHostId &&
live.agentKind === 'codex' &&
- hasPendingRemoteMcpDrift(live.remoteHostId, {
- collabEnabled: getPluginRegistry().isEnabled('collab'),
- token: getRemoteMcpBridgeToken(),
- bridgeInstanceId: getActiveCodexBridgeInstanceId(),
- })
+ hasPendingRemoteMcpDrift(live.remoteHostId, codexRemoteDriftOpts())
) {
const ensureResult = await ensureRemoteReadyForSessionStart({ session: live });
// ensure 完整生效 ⇒ daemon 已 (重) bootstrap ⇒ 长命 transport
@@ -5245,11 +5313,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (ensureResult?.remoteCodexDaemonRebootstrapped) {
live = undefined;
} else {
- const driftCleared = !hasPendingRemoteMcpDrift(live.remoteHostId, {
- collabEnabled: getPluginRegistry().isEnabled('collab'),
- token: getRemoteMcpBridgeToken(),
- bridgeInstanceId: getActiveCodexBridgeInstanceId(),
- });
+ const driftCleared = !hasPendingRemoteMcpDrift(live.remoteHostId, codexRemoteDriftOpts());
if (driftCleared) {
try {
await live.detach();
@@ -7892,6 +7956,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 立刻按新值注入);native setMemory 的 live-host RPC 热推放 applyRuntime ——
// Codex busy 的延迟路径把它挪到所有会话空闲后执行,不 mid-turn 热更正在跑的
// 任务(review P1 2026-07-23)。
+ const wasEnabled = makerMemory.isEnabled();
let persistedSettings: MemorySettings | null = null;
return applyMemoryChangeWithCodexRestart({
persist: async () => {
@@ -7922,6 +7987,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} else if (persistedSettings && !persistedSettings.maker) {
await maker.setAgentMemory('codex', persistedSettings.codex);
}
+ // 开关翻转 ⇒ 重建 codex bridge, 理由与约束见
+ // shutdownCodexEnvironmentBestEffort 文档 (review R1 P2)。
+ if (wasEnabled !== enabled) {
+ await shutdownCodexEnvironmentBestEffort('maker-memory toggle');
+ }
},
});
});
@@ -7931,6 +8001,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// registerIpcHandlers() 里, 见那里的注释。
ipcMain.handle(MAKER_INVOKE.MEMORY_RESET_SETTINGS, async () => {
// 同 MAKER_MEMORY_SET_ENABLED 的 persist / applyRuntime 拆分。
+ const wasMakerEnabled = maker.makerMemory?.isEnabled() ?? false;
let resetSettings_: MemorySettings | null = null;
return applyMemoryChangeWithCodexRestart({
persist: async () => {
@@ -7958,6 +8029,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
} else {
await maker.setAgentMemory('codex', resetSettings_.codex);
}
+ // maker 开关随 reset 翻转时同样要重建 codex bridge — 见
+ // shutdownCodexEnvironmentBestEffort 文档 (review R1 P2)。
+ if (wasMakerEnabled !== resetSettings_.maker) {
+ await shutdownCodexEnvironmentBestEffort('memory settings reset');
+ }
},
});
});
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
index c68c7a5fe4..c343078cfe 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts
@@ -3,6 +3,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { Logger, McpProvider } from '@cindy/maker-core';
import {
+ getActiveCodexBridgeServerNames,
getCodexExtraSpawnConfig,
registerCodexMcpThreadContext,
setCodexEnvironmentShutdownHook,
@@ -190,6 +191,19 @@ describe('codexEnvironment', () => {
expect(Object.getPrototypeOf({} as Record<string, unknown>)).toBe(Object.prototype);
});
+ it('exposes the active bridge server-name snapshot and clears it on shutdown (R2 P2)', async () => {
+ // stale-bridge 钳制的数据源:活跃 bridge 的 server 集合 (启动时冻结),
+ // 远端 flag 钳制 / drift 判定用它区分「bridge 缺 cindy_memory 的窗口」
+ // 与「无 bridge (lazy 重建在即)」。
+ expect(getActiveCodexBridgeServerNames()).toBeNull(); // 未启动
+
+ await getCodexExtraSpawnConfig({ mcpProviders: [testProvider()], logger: noopLogger() });
+ expect(getActiveCodexBridgeServerNames()).toEqual(['cindy_test']);
+
+ await shutdownCodexEnvironment();
+ expect(getActiveCodexBridgeServerNames()).toBeNull(); // shutdown 后清空
+ });
+
it('invokes the shutdown hook after the bridge stops, on every shutdown path (R22 P1)', async () => {
// 远端失效钩子折进 shutdownCodexEnvironment 内部:任何调用点 (插件开关 /
// custom MCP CRUD / contacts / 账号切换) 都自动覆盖, 不靠逐点挂接。
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
index 023cd5ee02..b6c35623a8 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
@@ -4,6 +4,8 @@ import { getLiziMcpSessionContext } from '@cindy/mcps';
import type { Logger } from '@cindy/maker-core';
import {
+ computeRemoteMcpFingerprint,
+ selectRemoteInjectableServerNames,
startCodexHttpBridge,
type CodexHttpBridge,
} from '../codexHttpBridge.js';
@@ -67,6 +69,51 @@ async function readAllRpcResponses(resp: Response): Promise<unknown[]> {
return Array.isArray(parsed) ? parsed : [parsed];
}
+describe('remote injection shared pure functions (R4 P3)', () => {
+ // 这两个函数是 CC 注入 / Codex ensure / Codex drift 三条路径的唯一真源,
+ // 间接测试出错时定位困难 — 这里直接锁 gate 组合与指纹敏感性。
+ const AVAILABLE = ['cindy_orca', 'orca_worker_bridge', 'cindy_memory', 'cindy_ssh'];
+
+ it('selectRemoteInjectableServerNames: gate 组合与白名单过滤', () => {
+ expect(selectRemoteInjectableServerNames(AVAILABLE, { collabEnabled: true, memoryEnabled: true }))
+ .toEqual(['cindy_orca', 'orca_worker_bridge', 'cindy_memory']);
+ expect(selectRemoteInjectableServerNames(AVAILABLE, { collabEnabled: true, memoryEnabled: false }))
+ .toEqual(['cindy_orca', 'orca_worker_bridge']);
+ // collab 关 + memory 开 → 只出 cindy_memory。
+ expect(selectRemoteInjectableServerNames(AVAILABLE, { collabEnabled: false, memoryEnabled: true }))
+ .toEqual(['cindy_memory']);
+ expect(selectRemoteInjectableServerNames(AVAILABLE, { collabEnabled: false, memoryEnabled: false }))
+ .toEqual([]);
+ // cindy_ssh 等非白名单 server 任何 gate 组合下都不可选(上面四例已隐含,
+ // 这里显式断言防未来放宽)。
+ for (const collabEnabled of [true, false]) {
+ for (const memoryEnabled of [true, false]) {
+ expect(
+ selectRemoteInjectableServerNames(AVAILABLE, { collabEnabled, memoryEnabled }),
+ ).not.toContain('cindy_ssh');
+ }
+ }
+ // memory 开但 bridge 没挂 cindy_memory → 不凭空注入。
+ expect(
+ selectRemoteInjectableServerNames(['cindy_orca'], { collabEnabled: true, memoryEnabled: true }),
+ ).toEqual(['cindy_orca']);
+ });
+
+ it('computeRemoteMcpFingerprint: 对 serverNames 顺序不敏感, 对集合/成分敏感', () => {
+ const base = { token: 'tok', bridgeInstanceId: 'b1', remotePort: 47921 };
+ const fp = computeRemoteMcpFingerprint({ ...base, serverNames: ['cindy_orca', 'cindy_memory'] });
+ expect(fp).toMatch(/^[0-9a-f]{12}$/);
+ // 顺序不敏感 — 调用方无需预排序。
+ expect(computeRemoteMcpFingerprint({ ...base, serverNames: ['cindy_memory', 'cindy_orca'] })).toBe(fp);
+ // 集合敏感 — memory 开关翻转必须构成新代际。
+ expect(computeRemoteMcpFingerprint({ ...base, serverNames: ['cindy_orca'] })).not.toBe(fp);
+ // 其余成分敏感 — token 轮换 / bridge 换代 / 端口重绑都构成新代际。
+ expect(computeRemoteMcpFingerprint({ ...base, token: 'tok2', serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
+ expect(computeRemoteMcpFingerprint({ ...base, bridgeInstanceId: 'b2', serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
+ expect(computeRemoteMcpFingerprint({ ...base, remotePort: 47922, serverNames: ['cindy_orca', 'cindy_memory'] })).not.toBe(fp);
+ });
+});
+
describe('codexHttpBridge', () => {
let bridge: CodexHttpBridge | null = null;
@@ -77,7 +124,11 @@ describe('codexHttpBridge', () => {
it('accepts an additional bearer token (remote daemon) and rejects unknown tokens', async () => {
bridge = await startCodexHttpBridge({
- serverFactories: { cindy_orca: createTestServer, cindy_test: createTestServer },
+ serverFactories: {
+ cindy_orca: createTestServer,
+ cindy_test: createTestServer,
+ cindy_memory: createTestServer,
+ },
additionalBearerTokens: () => ['remote-persistent-token'],
logger: noopLogger(),
});
@@ -117,6 +168,11 @@ describe('codexHttpBridge', () => {
const remoteResp = await postInit('cindy_orca', 'remote-persistent-token');
expect(remoteResp.status).toBe(200);
await remoteResp.text();
+ // cindy_memory 属远端白名单 (Maker Memory 经 bridge 回本机 store) — scoped
+ // token 放行;其余 in-process server (cindy_test 代表) 仍 403。
+ const remoteMemory = await postInit('cindy_memory', 'remote-persistent-token');
+ expect(remoteMemory.status).toBe(200);
+ await remoteMemory.text();
const remoteNonCollab = await postInit('cindy_test', 'remote-persistent-token');
expect(remoteNonCollab.status).toBe(403);
await remoteNonCollab.text();
diff --git a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
index 958005f765..7ee00b1f1f 100644
--- a/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexEnvironment.ts
@@ -51,6 +51,7 @@ export interface GetCodexExtraSpawnConfigOptions {
let cached: Promise<CodexExtraSpawnConfig> | null = null;
let activeBridge: CodexHttpBridge | null = null;
+let activeBridgeServerNames: string[] | null = null;
const disabledPluginIdsByThread = new Map<string, unknown>();
/**
@@ -96,6 +97,20 @@ export function getActiveCodexBridgeInstanceId(): string | null {
return activeBridge?.instanceId ?? null;
}
+/**
+ * 当前活跃 bridge 上实际挂出的 server 名 (不触发 lazy 启动;未启动 / 已
+ * shutdown 时 null)。provider 集合在 bridge 启动时冻结 (isEnabled 快照) —
+ * Maker Memory 等开关翻转后、bridge 重建前的窗口里, 远端注入 / 漂移判定 /
+ * per-session flag 钳制必须以本快照为准, 不能只看 manager 现值, 否则
+ * prompt 注入与工具面失配、drift 永不收敛 (review R2 P2)。
+ */
+export function getActiveCodexBridgeServerNames(): string[] | null {
+ // 与 activeBridge 同生共死 (doStart 同步赋值 / shutdown finally 同步清空)。
+ // 返回防御性拷贝: 内部数组同时是 drift 判定 / stale-bridge 钳制的数据源,
+ // 调用方误改不得污染快照。
+ return activeBridgeServerNames ? [...activeBridgeServerNames] : null;
+}
+
export async function shutdownCodexEnvironment(): Promise<void> {
const cur = cached;
if (!cur) return;
@@ -108,7 +123,10 @@ export async function shutdownCodexEnvironment(): Promise<void> {
} catch {
/* 启动本身失败的 cached promise — shutdown 无 op */
} finally {
- if (!bridge || activeBridge === bridge) activeBridge = null;
+ if (!bridge || activeBridge === bridge) {
+ activeBridge = null;
+ activeBridgeServerNames = null;
+ }
}
// bridge 实际 shutdown 后失效远端 (URL/session id 必然指向已停实例)。
// cached 为空 (从未启动) 时 early return 不调 — 彼时本就不存在指向
@@ -166,6 +184,10 @@ async function doStart(
return {
agentKind: active.agentKind,
workingDir: active.workingDir,
+ // SSH remote 会话的 ctx 字段必须透传 — cindy_memory 用它算 scope key
+ // (buildMemoryScopeKey);丢掉的话远端工具会落到本地路径 key 的 store,
+ // 与 agent prompt 注入读的 ssh:<hostId>:<path> store 分家 (review R4 P1)。
+ ...(active.remoteHostId ? { remoteHostId: active.remoteHostId } : {}),
vendorOptions: active.vendorOptions,
sessionId: active.sessionId,
getSessionContext: ctx.getSessionContext,
@@ -267,7 +289,9 @@ async function doStart(
logger: opts.logger,
})
: null;
+ const bridgeServerNames = Object.keys(serverFactories);
activeBridge = bridge;
+ activeBridgeServerNames = bridge ? bridgeServerNames : null;
const extraArgs: string[] = [];
// 远程 MCP server:直接把 codex 指向远端 URL,token 走 env (bearer_token_env_var)。
@@ -287,7 +311,7 @@ async function doStart(
extraArgs.push('-c', `mcp_servers.${name}.startup_timeout_sec=${MCP_TIMEOUT_SEC}`);
extraArgs.push('-c', `mcp_servers.${name}.tool_timeout_sec=${MCP_TIMEOUT_SEC}`);
}
- for (const name of Object.keys(serverFactories)) {
+ for (const name of bridgeServerNames) {
const url = bridge!.url(name);
// TOML 字符串值必须带双引号 (codex `-c` 解析时按 TOML literal);
// bearer_token_env_var 让 codex 从 env 读 token,不暴露在 process args。
@@ -299,7 +323,7 @@ async function doStart(
log.info('codex MCP bridge wired', {
port: bridge?.port ?? null,
- servers: [...Object.keys(serverFactories), ...Object.keys(remoteHttpServers)],
+ servers: [...bridgeServerNames, ...Object.keys(remoteHttpServers)],
remoteHttpServers: Object.keys(remoteHttpServers),
extraArgsCount: extraArgs.length,
});
@@ -311,6 +335,6 @@ async function doStart(
...(bridge ? { [TOKEN_ENV]: bridge.token } : {}),
},
bridge,
- bridgeServerNames: Object.keys(serverFactories),
+ bridgeServerNames,
};
}
diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
index 3ebb554bc4..24696506f9 100644
--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
@@ -16,7 +16,7 @@
import http from 'node:http';
import type { AddressInfo } from 'node:net';
-import { randomBytes, randomUUID } from 'node:crypto';
+import { createHash, randomBytes, randomUUID } from 'node:crypto';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
@@ -31,17 +31,72 @@ const SERVER_HEADER = 'Lizi_MCPS/1.0';
const MCP_PATH_PREFIX = '/mcp/';
const SHUTDOWN_TIMEOUT_MS = 5_000;
/**
- * 远端 (SSH remote-forward) 允许暴露的 server 白名单 — additionalBearerTokens
- * (persistent token) 认证的请求只能访问这些 server。这是 codex/cc 两条远端
- * 注入路径共享的唯一真源 (remote-ssh/codex-remote-mcp.ts 与
- * maker-host/cc-remote-mcp.ts 都引用它, 不要各自另立常量):只放协同必需的
- * cindy_orca / orca_worker_bridge;拿到 persistent token 的远端进程不得经
- * bridge 初始化 cindy_ssh / cindy_memory 等本机 server。
+ * 协同 MCP 的远端 server 名单 — codex/cc 两条远端注入路径共享的唯一真源
+ * (remote-ssh/codex-remote-mcp.ts 与 maker-host/cc-remote-mcp.ts 都引用它,
+ * 不要各自另立常量)。协同注入随 collab 全局开关走, 与 Maker Memory 的
+ * cindy_memory 注入 (随 Maker Memory 开关走) 互相独立。
*/
export const REMOTE_COLLAB_SERVER_NAMES: ReadonlySet<string> = new Set([
'cindy_orca',
'orca_worker_bridge',
]);
+/**
+ * Maker Memory 的远端 server 名。SSH remote 会话的记忆读写经 bridge 回到
+ * 本机 store (per hostId+远端路径 分区, 见 maker-core buildMemoryScopeKey)。
+ */
+export const REMOTE_MEMORY_SERVER_NAME = 'cindy_memory';
+/**
+ * 远端 (SSH remote-forward) 允许暴露的 server 全集 — additionalBearerTokens
+ * (persistent token) 认证的请求只能访问这些 server, 鉴权层按它 scope。
+ * 只放协同 (cindy_orca / orca_worker_bridge) 与 Maker Memory (cindy_memory,
+ * 2026-07 放行: 工具面固定、只触达本机 maker-memory 目录, 与协同同威胁模型);
+ * 拿到 persistent token 的远端进程仍不得经 bridge 初始化 cindy_ssh 等其余
+ * 本机 server。
+ */
+export const REMOTE_ALLOWED_SERVER_NAMES: ReadonlySet<string> = new Set([
+ ...REMOTE_COLLAB_SERVER_NAMES,
+ REMOTE_MEMORY_SERVER_NAME,
+]);
+
+/**
+ * 「gate 集合 → 远端注入名单」的唯一合成规则:协同段 = available ∩ 协同白名单
+ * (collab 开时);memory 段 = cindy_memory (memory 开且 available 含它时)。
+ * cc 注入 (cc-remote-mcp) / codex ensure (codex-remote-mcp) / codex drift 的
+ * desired 集合 (available 传白名单全集, 保留「provider 恒注册」假设) 三处
+ * 必须同走本函数 — drift 与 ensure 的集合靠构造同源, 不靠注释人肉维持
+ * (simplify R4)。新增远端 server 时:加常量 + 在这里加一个 gate 分支。
+ */
+export function selectRemoteInjectableServerNames(
+ available: readonly string[],
+ gates: { collabEnabled: boolean; memoryEnabled: boolean },
+): string[] {
+ return [
+ ...(gates.collabEnabled ? available.filter((n) => REMOTE_COLLAB_SERVER_NAMES.has(n)) : []),
+ ...(gates.memoryEnabled && available.includes(REMOTE_MEMORY_SERVER_NAME)
+ ? [REMOTE_MEMORY_SERVER_NAME]
+ : []),
+ ];
+}
+
+/**
+ * 远端 MCP 注入代际指纹的唯一公式 (sha256 前 12 hex)。cc 的 per-session
+ * applied 指纹与 codex 的 desired/applied 指纹共用 — 成分或格式要变只改
+ * 这里, drift 判定与 ensure 落盘天然同构 (simplify R4)。
+ */
+export function computeRemoteMcpFingerprint(opts: {
+ token: string;
+ bridgeInstanceId: string;
+ remotePort: number;
+ serverNames: readonly string[];
+}): string {
+ return createHash('sha256')
+ .update(
+ `${opts.token}|${opts.bridgeInstanceId}|${opts.remotePort}|${[...opts.serverNames].sort().join(',')}`,
+ 'utf8',
+ )
+ .digest('hex')
+ .slice(0, 12);
+}
/**
* init request body 上限 (1MB)。codex MCP init payload 实际 < 1KB,
* 1MB 给极端情况留余量。超限直接 413 拒绝 — 防巨大 body 在 JSON.parse
@@ -141,8 +196,8 @@ export async function startCodexHttpBridge(
// bearer token 鉴权:主 token (per-run, 本地 codex 子进程) / 额外 token
// (persistent, 远端常驻 codex daemon 与远端 cc 共用)。两类 token 权限
- // 不同:主 token 全通;额外 token 只允许访问 REMOTE_COLLAB_SERVER_NAMES
- // 白名单 (远端进程拿到 token 也不得初始化本机非协同 server)。
+ // 不同:主 token 全通;额外 token 只允许访问 REMOTE_ALLOWED_SERVER_NAMES
+ // 白名单 (协同 + cindy_memory; 远端进程拿到 token 也不得初始化其余本机 server)。
const auth = req.headers['authorization'];
const presented =
typeof auth === 'string' && auth.startsWith('Bearer ') ? auth.slice(7) : null;
@@ -192,10 +247,10 @@ export async function startCodexHttpBridge(
res.end();
return;
}
- // scoped (persistent) token 仅限协同白名单 server:同一 remote-forward
- // 能摸到完整 /mcp/<name> 路由, 不得经它初始化本机非协同 server
- // (cindy_ssh / cindy_memory 等) — codex-connector P1。
- if (isScopedRemoteToken && !REMOTE_COLLAB_SERVER_NAMES.has(serverName)) {
+ // scoped (persistent) token 仅限远端白名单 server (协同 + cindy_memory):
+ // 同一 remote-forward 能摸到完整 /mcp/<name> 路由, 不得经它初始化
+ // cindy_ssh 等其余本机 server — codex-connector P1。
+ if (isScopedRemoteToken && !REMOTE_ALLOWED_SERVER_NAMES.has(serverName)) {
res.statusCode = 403;
res.end();
log.warn('rejected scoped remote token for non-collab server', { serverName });
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
index a7374f37dd..5b9c6517b0 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/codex-remote-mcp.test.ts
@@ -545,6 +545,47 @@ describe('ensureRemoteCodexMcpBridge server whitelist', () => {
expect(written).not.toContain('cindy_ssh');
});
+ it('adds cindy_memory to the managed block when Maker Memory is globally enabled', async () => {
+ // Maker Memory 开启时远端 daemon config 一并注入 cindy_memory (记忆读写
+ // 经 bridge 回本机 store);cindy_ssh 等其余 in-process server 仍不放行。
+ const { host, inputs } = fakeHost('host-memory-on', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'cindy_memory', 'orca_worker_bridge', 'cindy_ssh'],
+ bridgeInstanceId: 'bridge-1',
+ }),
+ hasLiveTurnOnHost: () => false,
+ isMakerMemoryEnabled: () => true,
+ });
+ expect(result.ok).toBe(true);
+ const written = decodeWrittenConfig(inputs);
+ expect(written).not.toBeNull();
+ expect(written).toContain('[mcp_servers.cindy_orca]');
+ expect(written).toContain('[mcp_servers.cindy_memory]');
+ expect(written).not.toContain('cindy_ssh');
+ });
+
+ it('keeps cindy_memory injected when collab is disabled but Maker Memory stays on', async () => {
+ const { host, inputs } = fakeHost('host-memory-only', '');
+ const result = await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({
+ port: 38080,
+ serverNames: ['cindy_orca', 'cindy_memory', 'orca_worker_bridge'],
+ bridgeInstanceId: 'bridge-1',
+ }),
+ hasLiveTurnOnHost: () => false,
+ isCollabEnabled: () => false,
+ isMakerMemoryEnabled: () => true,
+ });
+ expect(result.ok).toBe(true);
+ const written = decodeWrittenConfig(inputs);
+ expect(written).not.toBeNull();
+ expect(written).toContain('[mcp_servers.cindy_memory]');
+ expect(written).not.toContain('[mcp_servers.cindy_orca]');
+ expect(written).not.toContain('[mcp_servers.orca_worker_bridge]');
+ });
+
it('is a no-op success when the bridge exposes no whitelist server and nothing was ever injected', async () => {
// collab plugin 禁用 → bridge 上没有 cindy_orca;远端 config 本来就没
// 注入过 → merge('') 无漂移:不写 config, 不重启 daemon。
@@ -1129,7 +1170,7 @@ describe('codex-connector R21 regressions', () => {
});
describe('hasPendingRemoteMcpDrift (R23 P1 lightweight live-send gate)', () => {
- const base = { collabEnabled: true, token: 'tok', bridgeInstanceId: 'bridge-1' };
+ const base = { collabEnabled: true, makerMemoryEnabled: false, token: 'tok', bridgeInstanceId: 'bridge-1' };
it('is true when the host was never injected (no applied fingerprint)', () => {
expect(hasPendingRemoteMcpDrift('host-drift-new', base)).toBe(true);
@@ -1143,11 +1184,13 @@ describe('hasPendingRemoteMcpDrift (R23 P1 lightweight live-send gate)', () => {
});
expect(hasPendingRemoteMcpDrift('host-drift-match', {
collabEnabled: true,
+ makerMemoryEnabled: false,
token: 'test-persistent-token',
bridgeInstanceId: 'bridge-1',
})).toBe(false);
expect(hasPendingRemoteMcpDrift('host-drift-match', {
collabEnabled: true,
+ makerMemoryEnabled: false,
token: 'test-persistent-token',
bridgeInstanceId: 'bridge-2',
})).toBe(true);
@@ -1162,12 +1205,13 @@ describe('hasPendingRemoteMcpDrift (R23 P1 lightweight live-send gate)', () => {
await stripRemoteCodexMcpConfig(host, { hasLiveTurnOnHost: () => false });
expect(hasPendingRemoteMcpDrift('host-drift-strip', {
collabEnabled: true,
+ makerMemoryEnabled: false,
token: 'test-persistent-token',
bridgeInstanceId: null,
})).toBe(true);
});
- it('follows cleanup semantics when collab is disabled or token is missing', async () => {
+ it('follows cleanup semantics when both gates are off or token is missing', async () => {
const { host } = fakeHost('host-drift-collab-off', '');
await ensureRemoteCodexMcpBridge(host, {
ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
@@ -1178,6 +1222,23 @@ describe('hasPendingRemoteMcpDrift (R23 P1 lightweight live-send gate)', () => {
await stripRemoteCodexMcpConfig(host, { hasLiveTurnOnHost: () => false });
expect(hasPendingRemoteMcpDrift('host-drift-collab-off', { ...base, collabEnabled: false })).toBe(false);
});
+
+ it('treats a Maker Memory toggle as drift (server set is part of the desired state)', async () => {
+ const { host } = fakeHost('host-drift-memory', '');
+ // 注入时 memory 关 → applied 只含协同集合。
+ await ensureRemoteCodexMcpBridge(host, {
+ ensureBridgeStarted: async () => ({ port: 38080, serverNames: SERVERS, bridgeInstanceId: 'bridge-1' }),
+ hasLiveTurnOnHost: () => false,
+ });
+ const opts = {
+ collabEnabled: true,
+ token: 'test-persistent-token',
+ bridgeInstanceId: 'bridge-1',
+ };
+ expect(hasPendingRemoteMcpDrift('host-drift-memory', { ...opts, makerMemoryEnabled: false })).toBe(false);
+ // 用户打开 Maker Memory → desired 集合多出 cindy_memory → 判 drift。
+ expect(hasPendingRemoteMcpDrift('host-drift-memory', { ...opts, makerMemoryEnabled: true })).toBe(true);
+ });
});
describe('codex-connector R24 regressions', () => {
diff --git a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
index f1347631a9..4c0807a9b1 100644
--- a/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
+++ b/apps/desktop/src/main/remote-ssh/codex-remote-mcp.ts
@@ -33,14 +33,21 @@ import path from 'node:path';
import type { RemoteHost } from '@cindy/maker-remote-ssh';
import { createLogger } from '../logger.js';
-import { REMOTE_COLLAB_SERVER_NAMES } from '../mcp-integrations/codexHttpBridge.js';
+import {
+ REMOTE_ALLOWED_SERVER_NAMES,
+ REMOTE_COLLAB_SERVER_NAMES,
+ computeRemoteMcpFingerprint,
+ selectRemoteInjectableServerNames,
+} from '../mcp-integrations/codexHttpBridge.js';
import { getRemoteMcpBridgeToken } from '../mcp-integrations/remoteMcpBridgeToken.js';
const log = createLogger('codex-remote-mcp');
const TOKEN_ENV = 'LIZI_MCP_TOKEN';
-// 远端注入白名单的唯一真源在 codexHttpBridge.ts (bridge 鉴权层也用它
-// scope persistent token) — 这里取别名保持本文件既有引用点不变。
+// 远端注入白名单的唯一真源在 codexHttpBridge.ts (bridge 鉴权层按
+// REMOTE_ALLOWED_SERVER_NAMES = 协同 + cindy_memory scope persistent token)。
+// 这里取协同别名保持本文件既有引用点不变;cindy_memory 独立走 Maker Memory
+// 全局开关 (daemon config 是 per-host 共享的, 没有 per-session 粒度)。
const CODEX_REMOTE_MCP_SERVER_NAMES = REMOTE_COLLAB_SERVER_NAMES;
const MANAGED_BEGIN = '# >>> cindy-remote-mcp (managed, do not edit) >>>';
const MANAGED_END = '# <<< cindy-remote-mcp <<<';
@@ -645,12 +652,17 @@ export function hasPendingRemoteMcpDrift(
hostId: string,
opts: {
collabEnabled: boolean;
+ /**
+ * Maker Memory 全局开关 (manager.isEnabled)。开着时 desired server 列表
+ * 含 cindy_memory — 与 ensure 内的注入集合同源, 开关翻转构成漂移。
+ */
+ makerMemoryEnabled: boolean;
token: string | null;
bridgeInstanceId: string | null;
},
): boolean {
const applied = readPortPrefs()[hostId]?.appliedFingerprint ?? null;
- if (!opts.collabEnabled || !opts.token) {
+ if ((!opts.collabEnabled && !opts.makerMemoryEnabled) || !opts.token) {
// 清理语义:applied 存在 = 待清理 (strip / 清理路径未跑过)。
return applied !== null;
}
@@ -658,13 +670,18 @@ export function hasPendingRemoteMcpDrift(
return true;
}
const remotePort = readPortPrefs()[hostId]?.remotePort ?? DEFAULT_REMOTE_PORT_START;
- const desired = createHash('sha256')
- .update(
- `${opts.token}|${opts.bridgeInstanceId}|${remotePort}|${[...CODEX_REMOTE_MCP_SERVER_NAMES].sort().join(',')}`,
- 'utf8',
- )
- .digest('hex')
- .slice(0, 12);
+ // desired 集合与 ensure 的注入集合靠 selectRemoteInjectableServerNames 构造
+ // 同源;available 传白名单全集 = 「provider 恒注册」假设 (keepOrcaProviderStable,
+ // memory 侧由调用方按活跃 bridge 快照预钳制)。
+ const desired = computeRemoteMcpFingerprint({
+ token: opts.token,
+ bridgeInstanceId: opts.bridgeInstanceId,
+ remotePort,
+ serverNames: selectRemoteInjectableServerNames([...REMOTE_ALLOWED_SERVER_NAMES], {
+ collabEnabled: opts.collabEnabled,
+ memoryEnabled: opts.makerMemoryEnabled,
+ }),
+ });
return desired !== applied;
}
@@ -695,6 +712,14 @@ export function ensureRemoteCodexMcpBridge(
* 闸门为准: 禁用时按清理路径剥受管段 (codex-connector R20 P2)。
*/
isCollabEnabled?: () => boolean;
+ /**
+ * Maker Memory 全局开关 (manager.isEnabled)。开着时把 cindy_memory 一并
+ * 写进远端 daemon config (daemon 是 per-host 共享的, 无 per-session
+ * 粒度; per-session prompt 注入仍由 maker-core 按 session flag 决定,
+ * withStore 在 manager 禁用时返回 MAKER_MEMORY_NOT_READY 兜底)。缺省
+ * 视为关闭 — 未接线的调用方不改变既有行为。
+ */
+ isMakerMemoryEnabled?: () => boolean;
},
): Promise<EnsureRemoteCodexMcpResult> {
return withHostSerial(host.id, () => doEnsureRemoteCodexMcpBridge(host, deps));
@@ -712,6 +737,8 @@ async function doEnsureRemoteCodexMcpBridge(
* 闸门为准: 禁用时按清理路径剥受管段 (codex-connector R20 P2)。
*/
isCollabEnabled?: () => boolean;
+ /** 见 ensureRemoteCodexMcpBridge.deps.isMakerMemoryEnabled。 */
+ isMakerMemoryEnabled?: () => boolean;
},
): Promise<EnsureRemoteCodexMcpResult> {
try {
@@ -725,12 +752,14 @@ async function doEnsureRemoteCodexMcpBridge(
// 对象的维持 bridge-unavailable 早退。
const applied = readPortPrefs()[host.id]?.appliedFingerprint;
const collabEnabled = deps.isCollabEnabled?.() ?? true;
+ const memoryEnabled = deps.isMakerMemoryEnabled?.() ?? false;
const token = getRemoteMcpBridgeToken();
- if (applied || !collabEnabled || !token) {
+ if (applied || (!collabEnabled && !memoryEnabled) || !token) {
log.warn('bridge unavailable — running cleanup-only strip on remote host', {
host: host.id,
hadAppliedFingerprint: Boolean(applied),
collabEnabled,
+ memoryEnabled,
hasToken: Boolean(token),
});
// 已在 per-host 串行锁内 (ensure 持锁), 直调无锁核心 (R27 P2 自死锁修正)。
@@ -740,17 +769,25 @@ async function doEnsureRemoteCodexMcpBridge(
log.warn('remote MCP injection skipped: http bridge unavailable', { host: host.id });
return { ok: false, reason: 'bridge-unavailable' };
}
- // 只注入协同白名单 server:bridge 上还挂着其他 in-process provider
- // (cindy_memory / cindy_ssh 等), 全量写进远端 daemon config 会让远端
- // session 获得本机 MCP 能力, 越出协同边界 (与 cc 侧白名单同语义)。
- const filteredNames = bridge.serverNames.filter((n) => CODEX_REMOTE_MCP_SERVER_NAMES.has(n));
+ // 只注入白名单 server (协同 + 开着 Maker Memory 时的 cindy_memory):
+ // bridge 上还挂着其他 in-process provider (cindy_ssh 等), 全量写进远端
+ // daemon config 会让远端 session 获得本机 MCP 能力, 越出边界。合成规则
+ // 唯一真源在 selectRemoteInjectableServerNames (codexHttpBridge.ts, 与
+ // cc 侧 / drift 判定共用)。
const token = getRemoteMcpBridgeToken();
const collabEnabled = deps.isCollabEnabled?.() ?? true;
- let serverNames = collabEnabled ? filteredNames : [];
- if (!collabEnabled && filteredNames.length > 0) {
- // collab 全局禁用:bridge 名单不反映开关 (keepOrcaProviderStable) —
- // 按清理路径剥受管段, 远端从「工具可见但调用必败」降级为不暴露
- // (codex-connector R20 P2)。
+ let serverNames = selectRemoteInjectableServerNames(bridge.serverNames, {
+ collabEnabled,
+ memoryEnabled: deps.isMakerMemoryEnabled?.() ?? false,
+ });
+ if (
+ !collabEnabled &&
+ serverNames.length === 0 &&
+ bridge.serverNames.some((n) => CODEX_REMOTE_MCP_SERVER_NAMES.has(n))
+ ) {
+ // collab 全局禁用 (且 memory 也没开):bridge 名单不反映开关
+ // (keepOrcaProviderStable) — 按清理路径剥受管段, 远端从「工具可见但
+ // 调用必败」降级为不暴露 (codex-connector R20 P2)。
log.info('collab globally disabled — cleaning remote managed block', { host: host.id });
}
if (serverNames.length > 0 && !token) {
@@ -829,13 +866,12 @@ async function doEnsureRemoteCodexMcpBridge(
// 失败时缺了它们 driftUnapplied 会漏判, daemon 永远拿着旧 URL /
// server 列表 (codex-connector R19 P1)。changed 仍是并列独立触发。
const desiredFingerprint = serverNames.length > 0
- ? createHash('sha256')
- .update(
- `${effectiveToken}|${bridge.bridgeInstanceId}|${remotePort}|${[...serverNames].sort().join(',')}`,
- 'utf8',
- )
- .digest('hex')
- .slice(0, 12)
+ ? computeRemoteMcpFingerprint({
+ token: effectiveToken,
+ bridgeInstanceId: bridge.bridgeInstanceId,
+ remotePort,
+ serverNames,
+ })
: null;
const appliedFingerprint = readPortPrefs()[host.id]?.appliedFingerprint ?? null;
const driftUnapplied = desiredFingerprint !== appliedFingerprint;
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index c70c14463a..4811f98320 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -728,22 +728,24 @@ describe('远程交互接线不变式', () => {
expect(src).not.toContain('electronAPI.maker.resolveInteraction');
});
- it('makerChatStore 不向 device-link 远程 session 透传本地 Maker Memory 开关', () => {
+ it('makerChatStore 不向 device-link 远程 session 透传本地 Maker Memory 开关;SSH 跟随全局设置', () => {
const src = read('lib/makerChatStore.ts');
expect(src).toContain('const deviceLinkRemote = isRemoteSession(sessionId);');
- expect(src).toContain('const sshRemote = Boolean(current.remoteHostId);');
- // 该三元可能被 prettier 折成多行:先把空白折叠成单空格,只锁 token 序列。
+ // 该表达式可能被 prettier 折成多行:先把空白折叠成单空格,只锁 token 序列。
+ // SSH remote 与本地同语义 (memory 按 hostId+远端路径 scope 存本机),
+ // 不再出现 ssh 强制 false 的三元;device-link 仍整体省略该字段。
expect(src.replace(/\s+/g, ' ')).toContain(
- '...(deviceLinkRemote ? {} : { makerMemoryEnabled: sshRemote ? false : getMakerMemoryEnabled() })',
+ '...(deviceLinkRemote ? {} : { makerMemoryEnabled: getMakerMemoryEnabled() })',
);
+ expect(src).not.toContain('sshRemote ? false');
});
- it('context usage 对 SSH 显式关闭本地 Maker Memory,对 device-link 仍省略', () => {
+ it('context usage 对 SSH 跟随全局 Maker Memory 设置,对 device-link 仍省略', () => {
const src = read('features/cc-agent/CCAgentSessionView.tsx');
- expect(src).toContain('...(remoteDeviceId');
- expect(src).toContain('makerMemoryEnabled: session.remoteHostId');
- expect(src).toContain('? false');
- expect(src).toContain(': getMakerMemoryEnabled()');
+ expect(src.replace(/\s+/g, ' ')).toContain(
+ '...(remoteDeviceId ? {} : { makerMemoryEnabled: getMakerMemoryEnabled() })',
+ );
+ expect(src).not.toContain('makerMemoryEnabled: session.remoteHostId ? false');
});
it('ChatInput 的 setPermissionMode 远程经隧道(makerApiFor),本机才走本机 IPC', () => {
diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
index 67191fb0f8..53f12a63ca 100644
--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts
@@ -2640,7 +2640,7 @@ describe('makerChatStore text delta batching', () => {
expect(makerChatStore.getSnapshot(SESSION_ID).messages.at(-1)?.errorDismissed).not.toBe(true);
});
- it('forces DB-hydrated SSH UI triggers off controller-local Maker Memory', async () => {
+ it('keeps DB-hydrated SSH UI triggers on the controller-global Maker Memory setting', async () => {
vi.mocked(sessionService.get).mockResolvedValueOnce({
agentKind: 'codex',
remoteHostId: 'remote-host',
@@ -2663,7 +2663,10 @@ describe('makerChatStore text delta batching', () => {
expect.objectContaining({
createOpts: expect.objectContaining({
remoteHostId: 'remote-host',
- makerMemoryEnabled: false,
+ // SSH remote 与本地同语义:跟随控制端全局 Maker Memory 设置
+ // (默认开启), 不再被强制 false;scope 隔离由 maker-core 按
+ // remoteHostId+workingDir 处理。
+ makerMemoryEnabled: true,
}),
}),
expect.any(Object),
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 86dd8d0fc9..a45ffd69b7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -2224,13 +2224,10 @@ export function CCAgentSessionView({
permissionMode: session.permissionMode,
userPrompt: getUserPrompt(),
// device-link executes on the target desktop, so let that runtime
- // own the setting. SSH still lazy-starts through this process and
- // must explicitly disable controller-local Cindy Memory.
- ...(remoteDeviceId
- ? {}
- : {
- makerMemoryEnabled: session.remoteHostId ? false : getMakerMemoryEnabled(),
- }),
+ // own the setting. SSH remote follows the controller's global
+ // setting like local sessions (memory scoped per hostId+remote
+ // path on this machine, see maker-core buildMemoryScopeKey).
+ ...(remoteDeviceId ? {} : { makerMemoryEnabled: getMakerMemoryEnabled() }),
extraDirs: session.extraDirs ?? [],
displayReasoning: 'summarized' as const,
...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 2a6b58e90b..0b7c999512 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -6570,7 +6570,6 @@ function buildCreateOptsForCurrentSession(
): AgentInputCreateOpts {
const current = getOrCreateState(sessionId);
const deviceLinkRemote = isRemoteSession(sessionId);
- const sshRemote = Boolean(current.remoteHostId);
return {
agentKind: current.agentKind,
workingDir,
@@ -6581,12 +6580,12 @@ function buildCreateOptsForCurrentSession(
planMode: current.planModeEnabled,
displayReasoning: 'summarized',
userPrompt: getUserPrompt(),
- // device-link routes to the target desktop, so omit the controller setting;
- // SSH still starts the agent through this process and must not inherit the
- // controller's default-enabled Maker Memory for a remote working directory.
- ...(deviceLinkRemote
- ? {}
- : { makerMemoryEnabled: sshRemote ? false : getMakerMemoryEnabled() }),
+ // device-link routes to the target desktop, so omit the controller setting.
+ // SSH remote follows the controller's global setting like local sessions:
+ // memory lives on this machine, scoped per hostId+remote path
+ // (maker-core buildMemoryScopeKey), and reaches the remote agent via the
+ // host HTTP MCP bridge.
+ ...(deviceLinkRemote ? {} : { makerMemoryEnabled: getMakerMemoryEnabled() }),
...(current.remoteHostId ? { remoteHostId: current.remoteHostId } : {}),
...(opts?.vendorOptions ? { vendorOptions: opts.vendorOptions } : {}),
...(current.sdkSessionId ? { resumeSessionId: current.sdkSessionId } : {}),
@@ -8542,10 +8541,9 @@ function sendUiTrigger(sessionId: string, prompt: string): Promise<void> {
...((session.sdkSessionId ?? state.sdkSessionId)
? { resumeSessionId: (session.sdkSessionId ?? state.sdkSessionId) as string }
: {}),
- // buildQueuedMessage may have used a pre-hydration store snapshot.
- // The DB row is authoritative here: SSH lazy-create must not inherit
- // controller-local Cindy Memory. Device-link keeps target ownership.
- ...(session.remoteHostId && !deviceLinkRemote ? { makerMemoryEnabled: false } : {}),
+ // SSH remote 与本地同语义: Maker Memory 跟随控制端全局开关 (scope 由
+ // maker-core 按 remoteHostId+workingDir 隔离), 这里不再强制关闭;
+ // device-link 仍由目标端自己的设置决定 (buildQueuedMessage 已省略)。
// 远端 SSH 会话:重启后 lazy-create 缺它会把远端 workingDir 当本地路径。
...(session.remoteHostId ? { remoteHostId: session.remoteHostId } : {}),
};
diff --git a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts b/packages/lizi-mcps/src/__tests__/sessionContext.test.ts
index 1667b90fe1..39a07290df 100644
--- a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts
+++ b/packages/lizi-mcps/src/__tests__/sessionContext.test.ts
@@ -224,6 +224,55 @@ describe('dynamic lizi MCP session context', () => {
expect(getStore).toHaveBeenLastCalledWith('/repo');
});
+ it('scopes cindy_memory stores by remoteHostId for SSH remote session contexts', async () => {
+ // SSH remote ctx 带 remoteHostId:workingDir 是远端机器上的路径, 直接当
+ // store key 会与本地同名路径互串 — withStore 必须经 buildMemoryScopeKey
+ // 定位到 ssh:<hostId>:<path> 的独立 store。
+ const getStore = vi.fn(async (_workdir: string) => ({
+ list: vi.fn(async () => []),
+ }));
+ const getManager = () => ({
+ isEnabled: () => true,
+ getStore,
+ }) as never;
+ const provider = createLiziMcpProviders({ memory: { getManager } })
+ .find((p) => p.name === 'cindy_memory');
+ if (!provider) throw new Error('cindy_memory provider missing');
+
+ const cfg = provider.toClaudeSdkConfig({
+ agentKind: 'codex',
+ workingDir: '',
+ vendorOptions: {},
+ }) as { type: 'sdk'; instance: unknown };
+ const server = cfg.instance;
+
+ const remote = await runWithLiziMcpSessionContext(
+ {
+ agentKind: 'claude-code',
+ workingDir: '/home/me/proj',
+ remoteHostId: 'my-ssh-host',
+ sessionId: 'remote-session',
+ vendorOptions: {},
+ },
+ () => tools(server).call_tool.handler({ name: 'memory_list', args: {} }),
+ );
+ expect(parse(remote as never)).toMatchObject({ ok: true, data: [] });
+ expect(getStore).toHaveBeenLastCalledWith('ssh:my-ssh-host:/home/me/proj');
+
+ // 本地 ctx (无 remoteHostId) 保持原样键 — 既有存储目录不迁移。
+ const local = await runWithLiziMcpSessionContext(
+ {
+ agentKind: 'claude-code',
+ workingDir: '/home/me/proj',
+ sessionId: 'local-session',
+ vendorOptions: {},
+ },
+ () => tools(server).call_tool.handler({ name: 'memory_list', args: {} }),
+ );
+ expect(parse(local as never)).toMatchObject({ ok: true, data: [] });
+ expect(getStore).toHaveBeenLastCalledWith('/home/me/proj');
+ });
+
it('advertises Cindy as the helper self-inspection category', async () => {
const server = createXdtHelperMcpServer(
{},
diff --git a/packages/lizi-mcps/src/memory/_shared.ts b/packages/lizi-mcps/src/memory/_shared.ts
index 0aecbbed6a..cf66af4ea3 100644
--- a/packages/lizi-mcps/src/memory/_shared.ts
+++ b/packages/lizi-mcps/src/memory/_shared.ts
@@ -13,7 +13,7 @@
* thread 的真实 workingDir。
*/
-import type { MakerMemoryStore } from '@cindy/maker-core';
+import { buildMemoryScopeKey, type MakerMemoryStore } from '@cindy/maker-core';
import type { MemoryToolResult } from '../cindy_memoryToolRegistry.js';
import type { MemoryMcpDeps } from '../types.js';
@@ -43,8 +43,11 @@ export async function withStore(
true,
);
}
- const workdir = deps.getSessionContext?.().workingDir ?? deps.workdir;
- store = await manager.getStore(workdir);
+ const ctx = deps.getSessionContext?.();
+ const workdir = ctx?.workingDir ?? deps.workdir;
+ // SSH remote 会话 (ctx 带 remoteHostId) 的 workdir 是远端路径 — 经 scope
+ // key 定位, 与 agent 启动注入 (claude-code/codex index.ts) 同一键规则。
+ store = await manager.getStore(buildMemoryScopeKey(workdir, ctx?.remoteHostId));
} catch (err) {
const { code, message } = classifyMemoryError(err);
return buildJsonResult({ ok: false, code, message }, true);
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index c62179c3ea..e241d89478 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -726,6 +726,13 @@ export interface AndroidMcpDeps {
export interface LiziMcpSessionContext {
agentKind: string;
workingDir: string;
+ /**
+ * SSH remote 会话的 host id (本地会话缺省)。workingDir 此时是远端机器上的
+ * 路径字符串 — cindy_memory 等按 workdir 分区的工具必须用
+ * buildMemoryScopeKey(workingDir, remoteHostId) 定位 store, 不得把远端路径
+ * 直接当本地键 (会与本地同名路径互串)。
+ */
+ remoteHostId?: string;
vendorOptions?: Record<string, unknown>;
/**
* Business 层 session id (host 在 createSession 时通过 opts.id 注入, maker-core
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index f18af54056..ce45e5a5de 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -72,6 +72,11 @@ export interface CodexMcpThreadContextArgs {
threadId: string;
sessionId: string;
workingDir: string;
+ /**
+ * SSH remote 会话的 host id。cindy_memory 的 store 定位键要靠它区分
+ * 「远端路径」与「本地同名路径」(buildMemoryScopeKey), 缺省 = 本地会话。
+ */
+ remoteHostId?: string;
vendorOptions: Record<string, unknown>;
}
@@ -418,6 +423,14 @@ export interface AgentDeps {
* but typed as unknown here to avoid cross-package dependency.
*/
onApprovalRequest?: (params: unknown) => Promise<unknown>;
+ /**
+ * 本 session 的 Maker Memory 注入开关 (startSession 时已按 per-session flag
+ * + manager 就绪归一)。host 据此决定是否把 cindy_memory 以 http 形态经
+ * bridge 注进远端 startParams.mcpServers — prompt 段 (rules + MEMORY.md
+ * index) 由 maker-core 自己拼, 两侧必须同源同值, 否则模型被 rules 引导去
+ * 调不存在的工具。缺省视为 false。
+ */
+ makerMemoryEnabled?: boolean;
}) => Promise<Query>;
}
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index f55c3cf69f..88f4a746c6 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -54,6 +54,7 @@ import {
import { SYSTEM_PROMPT_APPEND as MAKER_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';
import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';
import { MemoryFlushController } from '../../memory/flush-controller.js';
+import { buildMemoryScopeKey } from '../../memory/storage.js';
import type {
Capabilities,
EffortDescriptor,
@@ -923,15 +924,18 @@ export class ClaudeCodeAgent extends BaseAgent {
opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false;
const makerMemory = this.deps.makerMemory;
const makerMemoryEnabled = makerMemoryFlag === true && !!makerMemory;
+ // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key,
+ // 键规则与理由见 buildMemoryScopeKey (memory/storage.ts)。
+ const memoryScopeKey = buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);
// This per-session injection flag must not mutate the shared manager.
if (makerMemoryEnabled && makerMemory) {
try {
- const store = await makerMemory.getStore(opts.workingDir);
+ const store = await makerMemory.getStore(memoryScopeKey);
makerMemoryRules = MAKER_MEMORY_RULES;
makerMemoryIndex = await store.getIndex();
memoryFlushController = new MemoryFlushController({
logger: log.child('memory-flush'),
- workdir: opts.workingDir,
+ workdir: memoryScopeKey,
agentKind: 'claude-code',
});
log.debug('maker memory loaded for session', {
@@ -979,6 +983,9 @@ export class ClaudeCodeAgent extends BaseAgent {
// 普通字符串键。
const out: Record<string, McpServerConfig> = Object.create(null);
for (const provider of providers) {
+ // cindy_memory: per-session flag 关 → 不注册; remote → in-process sdk 实例
+ // 不可序列化, 这里跳过, 由 host 的 remoteCcQueryFactory 按同一 flag 以
+ // http 形态经 bridge 注入 (见 cc-remote-mcp.ts)。
if (provider.name === 'cindy_memory' && (!makerMemoryEnabled || opts.remoteHostId)) continue;
if (provider.isEnabled && !provider.isEnabled(context)) continue;
// 同名 provider 先注册者胜 —— host 把用户自定义 MCP **追加**在内置之后, 后写
@@ -1384,9 +1391,11 @@ export class ClaudeCodeAgent extends BaseAgent {
const buildSettings = (): Settings =>
buildClaudeFlagSettings({
showThinkingSummaries,
- // Maker Memory is not available on SSH targets. Do not carry the local
- // manager's native-memory suppression across that boundary: the remote
- // host must retain its own Claude memory configuration.
+ // Do not carry the local manager's native-memory suppression across the
+ // SSH boundary: the remote host retains its own Claude memory
+ // configuration. Maker Memory on remote sessions is injected via the
+ // host bridge (prompt + http MCP), which coexists with — but does not
+ // rewrite — the remote machine's native memory settings.
memoryOverride: opts.remoteHostId ? undefined : this.memoryOverride,
// Fast 模式:进 flag settings 层(= --settings),解锁 cc 二进制在 Agent SDK 通道下的
// fast(否则二进制按 "Agent SDK 不可用" 拒绝)。是否 Opus/官方/firstParty 由二进制把关,
@@ -1915,6 +1924,9 @@ export class ClaudeCodeAgent extends BaseAgent {
// DB 标记尚未写入, host 现场查库会拿到空角色)。见 base-agent.ts
// remoteCcQueryFactory 的 vendorOptions 注释。
vendorOptions: vo,
+ // per-session Maker Memory 开关 — host 据此决定是否把 cindy_memory
+ // 以 http 形态注进远端 startParams.mcpServers (cc-remote-mcp.ts)。
+ makerMemoryEnabled,
onApprovalRequest: async (rawParams: unknown) => {
// 110s timeout — must respond before daemon's 120s server-request timeout.
// On timeout, dismiss the pending interaction (clears UI) and reject to
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index a833281e40..de704caae7 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -4240,6 +4240,9 @@ describe('CodexAgent MCP thread context hooks', () => {
threadId: 'start-thread-id',
sessionId: 'session-remote-codex-mcp-context',
workingDir: '/repo',
+ // remote thread 的 ctx 带 hostId — cindy_memory 据此把远端路径隔离到
+ // ssh:<hostId>:<path> 的独立 store。
+ remoteHostId: 'remote-host-1',
vendorOptions: {},
});
await handle.close();
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d597d7b484..7d47e911f9 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -104,6 +104,7 @@ import { CodexInteractionBroker } from './interaction-broker.js';
import { SYSTEM_PROMPT_APPEND as MAKER_CODEX_SYSTEM_PROMPT_APPEND } from './system-prompt-append.js';
import { MAKER_MEMORY_RULES } from '../../memory/system-prompt.js';
import { MemoryFlushController } from '../../memory/flush-controller.js';
+import { buildMemoryScopeKey } from '../../memory/storage.js';
import { CODEX_AGENT_COMMANDS } from './commands.js';
import {
canReuseCodexHostForCredentialMode,
@@ -2074,15 +2075,18 @@ export class CodexAgent extends BaseAgent {
opts.makerMemoryEnabled ?? this.deps.runtimeConfig.makerMemoryEnabled ?? false;
const makerMemory = this.deps.makerMemory;
const makerMemoryEnabled = makerMemoryFlag === true && !!makerMemory;
+ // SSH remote 的 workingDir 是远端路径 — store 定位统一经 scope key,
+ // 键规则与理由见 buildMemoryScopeKey (memory/storage.ts)。
+ const memoryScopeKey = buildMemoryScopeKey(opts.workingDir, opts.remoteHostId);
// This per-session injection flag must not mutate the shared manager.
if (makerMemoryEnabled && makerMemory) {
try {
- const store = await makerMemory.getStore(opts.workingDir);
+ const store = await makerMemory.getStore(memoryScopeKey);
makerMemoryRules = MAKER_MEMORY_RULES;
makerMemoryIndex = await store.getIndex();
memoryFlushController = new MemoryFlushController({
logger: log.child('memory-flush'),
- workdir: opts.workingDir,
+ workdir: memoryScopeKey,
agentKind: 'codex',
});
log.debug('maker memory loaded for session', {
@@ -2388,6 +2392,8 @@ export class CodexAgent extends BaseAgent {
threadId,
sessionId: sid,
workingDir: opts.workingDir,
+ // remote thread ctx: scope key 语义见 buildMemoryScopeKey。
+ ...(opts.remoteHostId ? { remoteHostId: opts.remoteHostId } : {}),
vendorOptions: vo,
});
log.debug('codex MCP thread context registered', {
diff --git a/packages/maker-core/src/index.ts b/packages/maker-core/src/index.ts
index 2efea2aeab..2d45d6d037 100644
--- a/packages/maker-core/src/index.ts
+++ b/packages/maker-core/src/index.ts
@@ -38,6 +38,8 @@ export * from './memory/types.js';
export {
MemoryStorage,
sanitizeWorkdir,
+ buildMemoryScopeKey,
+ memoryScopeDirName,
buildFilename,
parseFilename,
validateSlug,
diff --git a/packages/maker-core/src/memory/manager.ts b/packages/maker-core/src/memory/manager.ts
index 80b4888951..54f01cd880 100644
--- a/packages/maker-core/src/memory/manager.ts
+++ b/packages/maker-core/src/memory/manager.ts
@@ -25,7 +25,7 @@
import * as path from 'node:path';
import type Database from 'better-sqlite3';
-import { MakerMemoryStore, sanitizeWorkdir } from './store.js';
+import { MakerMemoryStore, memoryScopeDirName } from './store.js';
import {
type MemoryConfig,
type WriteOptions,
@@ -198,6 +198,10 @@ export class MakerMemoryManager {
* - 调 store.init() (创建 FTS 表 + sanity check)
*
* 同 workdir 复用同一 store + db 实例。失败 (db open 失败 / mkdir 失败) 抛错。
+ *
+ * key 语义: 本地会话传 workdir 绝对路径; SSH remote 会话传
+ * buildMemoryScopeKey 产出的 `ssh:<hostId>:<path>` 复合键 (调用方负责,
+ * manager 不自己判远端) — 见 storage.ts buildMemoryScopeKey。
*/
async getStore(absWorkdir: string): Promise<MakerMemoryStore> {
if (!absWorkdir || absWorkdir.length === 0) {
@@ -206,7 +210,9 @@ export class MakerMemoryManager {
const cached = this.stores.get(absWorkdir);
if (cached) return cached.store;
- const sanitized = sanitizeWorkdir(absWorkdir);
+ // 目录名派生见 memoryScopeDirName:本地键 = sanitizeWorkdir 原规则 (不迁移),
+ // 远端 ssh: 键 = 碰撞安全的 hash 形态 (review R4 P2)。
+ const sanitized = memoryScopeDirName(absWorkdir);
const storageDir = path.join(this.deps.basePath, MEMORY_SUBDIR, sanitized);
const dbPath = path.join(storageDir, FTS_DB_FILENAME);
diff --git a/packages/maker-core/src/memory/scope-key.test.ts b/packages/maker-core/src/memory/scope-key.test.ts
new file mode 100644
index 0000000000..af0e8192ec
--- /dev/null
+++ b/packages/maker-core/src/memory/scope-key.test.ts
@@ -0,0 +1,71 @@
+/**
+ * buildMemoryScopeKey / memoryScopeDirName — Maker Memory 的 store 定位键与
+ * 落盘目录名规则:
+ * - 本地会话原样用 workdir(既有存储目录不迁移,目录名走 sanitizeWorkdir);
+ * - SSH remote 会话用 `ssh:<hostId>:<workdir>` 复合键,目录名走碰撞安全的
+ * hash 形态 — 有损的 sanitizeWorkdir 会让 `ssh:prod:/repo` 与本地路径
+ * `/ssh/prod:/repo` 撞成同一目录 (review R4 P2)。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { buildMemoryScopeKey, memoryScopeDirName, sanitizeWorkdir } from './storage.js';
+
+describe('buildMemoryScopeKey', () => {
+ it('本地会话 (无 remoteHostId) 原样返回 workdir — 既有 store 目录不迁移', () => {
+ expect(buildMemoryScopeKey('/Users/sam/proj')).toBe('/Users/sam/proj');
+ expect(buildMemoryScopeKey('E:\\AIWork\\xdt-maker', null)).toBe('E:\\AIWork\\xdt-maker');
+ expect(buildMemoryScopeKey('/Users/sam/proj', undefined)).toBe('/Users/sam/proj');
+ });
+
+ it('SSH remote 会话产出 ssh:<host 段>:<workdir> 复合键 (常规 alias 编码前后相同)', () => {
+ expect(buildMemoryScopeKey('/home/me/proj', 'my-host')).toBe('ssh:my-host:/home/me/proj');
+ });
+
+ it('key 对 (hostId, workdir) 是单射 — 分隔符拼接歧义回归 (review R5 P2)', () => {
+ // 裸拼接时这两组会撞成同一个 `ssh:prod:/x:/repo`。
+ const a = buildMemoryScopeKey('/x:/repo', 'prod');
+ const b = buildMemoryScopeKey('/repo', 'prod:/x');
+ expect(a).not.toBe(b);
+ expect(memoryScopeDirName(a)).not.toBe(memoryScopeDirName(b));
+ });
+
+ it('远端路径与本地同名路径隔离;不同 host 上的同名路径互相隔离', () => {
+ const local = buildMemoryScopeKey('/home/me/proj');
+ const hostA = buildMemoryScopeKey('/home/me/proj', 'host-a');
+ const hostB = buildMemoryScopeKey('/home/me/proj', 'host-b');
+ expect(new Set([local, hostA, hostB]).size).toBe(3);
+ expect(
+ new Set([memoryScopeDirName(local), memoryScopeDirName(hostA), memoryScopeDirName(hostB)]).size,
+ ).toBe(3);
+ });
+});
+
+describe('memoryScopeDirName', () => {
+ it('本地键沿用 sanitizeWorkdir — 既有目录不迁移', () => {
+ for (const dir of ['/Users/sam/proj', 'E:\\AIWork\\xdt-maker']) {
+ expect(memoryScopeDirName(buildMemoryScopeKey(dir))).toBe(sanitizeWorkdir(dir));
+ }
+ });
+
+ it('远端键的目录名对 sanitize 撞车免疫 (review R4 P2 回归)', () => {
+ // sanitizeWorkdir 有损:这两个 key 的 sanitize 结果相同, 目录名必须不同。
+ const remote = buildMemoryScopeKey('/repo', 'prod'); // ssh:prod:/repo
+ const localTrap = buildMemoryScopeKey('/ssh/prod:/repo'); // 本地路径
+ expect(sanitizeWorkdir(remote)).toBe(sanitizeWorkdir(localTrap)); // 前提成立
+ expect(memoryScopeDirName(remote)).not.toBe(memoryScopeDirName(localTrap));
+ // hostId 含冒号 (SSH alias 未限制冒号) 也互不相撞。
+ const tricky = buildMemoryScopeKey('/repo', 'prod:/x');
+ expect(memoryScopeDirName(tricky)).not.toBe(memoryScopeDirName(remote));
+ });
+
+ it('远端目录名定长有界且只含文件名安全字符 (非 ASCII / 超长路径免疫)', () => {
+ const long = buildMemoryScopeKey(`/远端/项目/${'x'.repeat(500)}`, '跳板机-α');
+ const dir = memoryScopeDirName(long);
+ expect(dir.length).toBeLessThanOrEqual(64);
+ expect(dir).toMatch(/^ssh-.*-[0-9a-f]{16}$/);
+ expect(dir).not.toMatch(/[\\/:]/);
+ // 同 key 稳定 (目录名是持久事实, 不能随进程变)。
+ expect(memoryScopeDirName(long)).toBe(dir);
+ });
+});
diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.ts
index 0ead78ccaa..ba4d54c31b 100644
--- a/packages/maker-core/src/memory/storage.ts
+++ b/packages/maker-core/src/memory/storage.ts
@@ -19,6 +19,7 @@
* 最坏情况 MEMORY.md 短暂不一致, rebuildIndex 幂等可恢复。要 ACID 加 SQLite 太重。
*/
+import { createHash } from 'node:crypto';
import { promises as fs } from 'node:fs';
import * as path from 'node:path';
import matter from 'gray-matter';
@@ -58,6 +59,40 @@ export function sanitizeWorkdir(absPath: string): string {
.replace(/^-+/, ''); // 去除最前面的 leading '-' (Unix 路径 / 开头转完是 '-Users-...')
}
+/**
+ * Maker Memory 的 store 定位键(scope key)。本地会话直接用 workdir 绝对路径
+ * (保持既有存储目录不迁移);SSH remote 会话用 `ssh:<host 段>:<workdir>` 复合键 —
+ * 远端路径是远端机器上的字符串,直接当 key 会跟本地同名路径共用一个 store
+ * (两台机器各有 /home/me/proj 时记忆互串)。host 段经 encodeURIComponent 编码:
+ * 编码后不含 `:`,前缀后的首个 `:` 即边界,(hostId, workdir) → key 是单射 —
+ * 裸拼接时 ('/x:/repo','prod') 与 ('/repo','prod:/x') 会撞成同一个 key
+ * (review R5 P2);常规 alias 编码前后相同,键仍可读。数据仍存控制端本机,
+ * 目录名经 memoryScopeDirName 派生。所有 getStore 调用方 (agent 启动注入 /
+ * MCP withStore) 必须统一经本函数取键,不得各自拼接。
+ */
+export function buildMemoryScopeKey(workingDir: string, remoteHostId?: string | null): string {
+ return remoteHostId ? `ssh:${encodeURIComponent(remoteHostId)}:${workingDir}` : workingDir;
+}
+
+/** buildMemoryScopeKey 的远端键前缀。本地键恒为绝对路径, 不会以它开头。 */
+const SSH_SCOPE_KEY_PREFIX = 'ssh:';
+
+/**
+ * scope key → 落盘目录名。本地键沿用 sanitizeWorkdir(既有目录不迁移);远端
+ * 键不能走有损的 sanitizeWorkdir — `ssh:prod:/repo` 与本地路径 `/ssh/prod:/repo`
+ * 会 sanitize 成同一个目录名, 隔离承诺被撞破 (review R4 P2)。远端目录名 =
+ * `ssh-<host 可读片段>-<sha256(完整 key) 前 16 hex>`:key 是 (hostId, 路径)
+ * 对的单射 (见 buildMemoryScopeKey), hash 因此保证目录唯一性, 且对特殊字符/
+ * 超长路径免疫 (定长, Windows MAX_PATH 安全);host 片段 (编码形态, 不含 `:`)
+ * 只为肉眼可辨识。
+ */
+export function memoryScopeDirName(scopeKey: string): string {
+ if (!scopeKey.startsWith(SSH_SCOPE_KEY_PREFIX)) return sanitizeWorkdir(scopeKey);
+ const hostSegment = scopeKey.slice(SSH_SCOPE_KEY_PREFIX.length).split(':', 1)[0] ?? '';
+ const digest = createHash('sha256').update(scopeKey, 'utf8').digest('hex').slice(0, 16);
+ return `ssh-${sanitizeWorkdir(hostSegment).slice(0, 24)}-${digest}`;
+}
+
/** filename = `<type>_<slug>.md` */
export function buildFilename(type: MemoryType, slug: string): string {
return `${type}_${slug}${SHARD_EXT}`;
diff --git a/packages/maker-core/src/memory/store.ts b/packages/maker-core/src/memory/store.ts
index 3b80a2d8f4..408aa66efb 100644
--- a/packages/maker-core/src/memory/store.ts
+++ b/packages/maker-core/src/memory/store.ts
@@ -248,3 +248,4 @@ export class MakerMemoryStore {
// 跟 storage helper 同步导出, 让 manager 不用各处 import
export { sanitizeWorkdir, buildFilename, parseFilename };
+export { memoryScopeDirName } from './storage.js';
diff --git a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
index 04e4a0fc67..201f4184dd 100644
--- a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
+++ b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
@@ -485,8 +485,8 @@ describe('orca_worker_bridge MCP helpers', () => {
expect(parseToolJson(result)).toMatchObject({ ok: true, lead_session_id: 'lead-1' });
expect(createSessionCalls).toHaveLength(1);
expect(createSessionCalls[0]).toMatchObject({ id: 'lead-1', remoteHostId: 'host-remote-1' });
- // R22 P2:远端 rehydrate 必须带 makerMemoryEnabled=false (与 IPC create/send
- // 的 remote ensure 归一化对齐), 不注入本地 Maker Memory 上下文。
+ // R6 P2:未注入 ensureRemoteSessionStart (老宿主 / no-op) 时按 false 保守
+ // 处理 — 记忆开关必须经宿主 preflight 归一化后才允许开。
expect(createSessionCalls[0]).toMatchObject({ makerMemoryEnabled: false });
});
@@ -557,6 +557,63 @@ describe('orca_worker_bridge MCP helpers', () => {
workingDir: '/remote/repo',
});
expect(order).toEqual(['ensure', 'create']);
+ // preflight 返回 void (老宿主形态) → 记忆保守关闭。
+ expect(base.createSessionCalls[0]).toMatchObject({ makerMemoryEnabled: false });
+ });
+
+ it('applies the preflight-normalized Maker Memory flag to remote rehydration (R6 P2)', async () => {
+ // SSH remote 与 IPC create/send 同语义:全局开着时远端 rehydrate 不再
+ // 硬编码 false;开关值 = 宿主 preflight 归一化 (backfill + stale-bridge
+ // 钳制) 后回传的结果。
+ const workerLink: OrcaWorkerLink = {
+ workerId: 'worker-1',
+ workflowId: 'workflow-1',
+ workerSessionId: 'worker-session-1',
+ leadSessionId: 'lead-1',
+ leadSession: {
+ sessionId: 'lead-1',
+ agentKind: 'claude-code',
+ workingDir: '/remote/repo',
+ model: 'claude-opus-4-7',
+ providerId: 'anthropic',
+ remoteHostId: 'host-remote-1',
+ },
+ };
+ const { createSessionCalls, maker } = makeProvider({ workerLink });
+ const provider = createOrcaWorkerBridgeMcpProvider({
+ getMaker: () => maker as unknown as Maker,
+ logger: makeLogger() as never,
+ persistUserMessage: async () => {},
+ wireSession: () => {},
+ ensureRemoteSessionStart: async () => ({ makerMemoryEnabled: true }),
+ orcaTeamStore: {
+ async getWorkerLink() {
+ return workerLink;
+ },
+ async updateWorkerStatus() {},
+ },
+ });
+ const server = getServer(provider, {
+ agentKind: 'claude-code',
+ workingDir: '/remote/repo',
+ vendorOptions: {
+ orcaRole: 'worker',
+ orcaWorkerId: 'worker-1',
+ orcaWorkerSessionId: 'worker-session-1',
+ },
+ });
+
+ const result = await server._registeredTools.send_to_lead.handler({
+ worker_id: 'worker-1',
+ message: 'hello remote lead',
+ });
+
+ expect(parseToolJson(result)).toMatchObject({ ok: true });
+ expect(createSessionCalls[0]).toMatchObject({
+ id: 'lead-1',
+ remoteHostId: 'host-remote-1',
+ makerMemoryEnabled: true,
+ });
});
it('does not run the remote preflight when rehydrating a local lead', async () => {
diff --git a/packages/orca-workflow/src/orca-bridge-mcp.ts b/packages/orca-workflow/src/orca-bridge-mcp.ts
index f77940d2f2..3d622d5373 100644
--- a/packages/orca-workflow/src/orca-bridge-mcp.ts
+++ b/packages/orca-workflow/src/orca-bridge-mcp.ts
@@ -103,7 +103,15 @@ export interface OrcaBridgeMcpDeps {
agentKind: AgentKind;
remoteHostId: string;
workingDir: string;
- }) => Promise<void>;
+ }) => Promise<void | {
+ /**
+ * 宿主 preflight 归一化后的 per-session Maker Memory 开关 (全局设置
+ * backfill + stale-bridge 钳制, 与 IPC create/send 路径同一套 mutate)。
+ * rehydrate 的 createSession 必须用它 — 缺省 (老宿主 / no-op) 按 false
+ * 保守处理, 不得在未归一化的情况下注入记忆 (review R6 P2)。
+ */
+ makerMemoryEnabled?: boolean;
+ }>;
orcaTeamStore?: OrcaTeamStore;
dispatchInterAgentMessage?: (params: {
targetSessionId: string;
@@ -431,13 +439,20 @@ async function ensureSessionFromMeta(
// 远端 lead 重建前必须跑宿主 remote preflight (SSH 重连 / agent install /
// 远端 MCP 注入):bridge 直调 core createSession 不经 maker-ipc, 跳过这步
// 会让 app 重启后的首次 worker 回报 host-not-ready 或远端无协同 MCP。
+ let remoteMakerMemoryEnabled = false;
if (meta.remoteHostId) {
- await deps.ensureRemoteSessionStart?.({
+ const preflight = await deps.ensureRemoteSessionStart?.({
sessionId: meta.sessionId,
agentKind: meta.agentKind,
remoteHostId: meta.remoteHostId,
workingDir: meta.workingDir,
});
+ // SSH remote 的 Maker Memory 与 IPC create/send 路径同语义:开关由
+ // preflight 归一化 (全局设置 backfill + stale-bridge 钳制) 后回传;
+ // 老宿主 / 未注入 preflight 时保守按 false — 不得在未归一化的情况下
+ // 注入 (review R6 P2:此前这里硬编码 false, 把远端 rehydrate 会话的
+ // 记忆永久关死, 与已放开的其余路径分叉)。
+ remoteMakerMemoryEnabled = preflight?.makerMemoryEnabled === true;
}
const session = await maker.createSession({
id: meta.sessionId,
@@ -451,14 +466,10 @@ async function ensureSessionFromMeta(
title: meta.title,
...(vendorOptions ? { vendorOptions } : {}),
...(meta.sdkSessionId ? { resumeSessionId: meta.sdkSessionId } : {}),
- // 远端 lead 在同一台 SSH 主机上重建 (host 侧 createSession 会先做
- // remote ensure); 本地 lead 无此字段。
- // 远端 lead 在同一台 SSH 主机上重建 (host 侧 createSession 会先做
- // remote ensure); 本地 lead 无此字段。makerMemoryEnabled=false 与 IPC
- // create/send 路径的 remote ensure 归一化对齐 (ensure 里对 createOpts
- // 的同款 mutate) — 远端 workdir 不得注入本地 Cindy Memory 上下文
- // (codex-connector R22 P2;preflight 用临时 opts, mutation 到不了这里)。
- ...(meta.remoteHostId ? { remoteHostId: meta.remoteHostId, makerMemoryEnabled: false } : {}),
+ // 远端 lead 在同一台 SSH 主机上重建; 本地 lead 无这两个字段。
+ ...(meta.remoteHostId
+ ? { remoteHostId: meta.remoteHostId, makerMemoryEnabled: remoteMakerMemoryEnabled }
+ : {}),
});
deps.wireSession(session);
return session;