fix(cloud): per-computer MCP sync ledger and Codex block, so two computers on one shared sandbox keep each other's servers (first computer adopts the shared ledger once)

This commit is contained in:
Neil
2026-11-09 15:20:58 -08:00
parent fe0aa07c0a
commit 9634bb7049
5 changed files with 141 additions and 16 deletions
@@ -1,3 +1,4 @@
import { randomBytes } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
@@ -145,15 +146,41 @@ export function createCloudMcpSync(deps: CloudMcpSyncDeps): CloudMcpSync {
}
}
let syncer: string | null = null
/** This computer's stable sync identity (random, not a device fingerprint). */
function syncerId(): string {
if (syncer) {
return syncer
}
const path = join(deps.userDataPath, 'mcp-sync-syncer-id')
try {
const stored = readFileSync(path, 'utf8').trim()
if (/^[a-f0-9]{16}$/.test(stored)) {
syncer = stored
return stored
}
} catch {
// First sync from this computer.
}
syncer = randomBytes(8).toString('hex')
try {
writeFileAtomically(path, `${syncer}\n`)
} catch {
// Unwritable profile: this run still syncs as itself; the next launch gets a new id.
}
return syncer
}
async function plan(environmentId: string) {
const runtime = cloudRuntime(environmentId)
const local = await readLocal(runtime?.repoPath ?? null)
return planMcpSync({
const planned = planMcpSync({
servers: local.servers,
excluded: new Set(getPreferences().excluded),
repoServerNames: local.repoServerNames,
homeDir: homedir()
})
return { ...planned, params: { ...planned.params, syncer: syncerId() } }
}
function publish(status: McpSyncStatus): McpSyncStatus {
@@ -17,13 +17,22 @@ export type CodexMcpMergeResult = {
type Block = { before: string; body: string; after: string }
function findBlock(text: string): Block | null {
export type CodexMcpBlockMarkers = { start: string; end: string }
/** One marked block per syncing computer, so two computers syncing one host never rewrite each other's. */
export function codexMcpBlockMarkers(syncer: string | undefined): CodexMcpBlockMarkers {
return syncer
? { start: `${CODEX_MCP_BLOCK_START} [${syncer}]`, end: `${CODEX_MCP_BLOCK_END} [${syncer}]` }
: { start: CODEX_MCP_BLOCK_START, end: CODEX_MCP_BLOCK_END }
}
function findBlock(text: string, markers: CodexMcpBlockMarkers): Block | null {
const lines = text.split('\n')
const start = lines.indexOf(CODEX_MCP_BLOCK_START)
const start = lines.indexOf(markers.start)
if (start === -1) {
return null
}
const end = lines.indexOf(CODEX_MCP_BLOCK_END, start + 1)
const end = lines.indexOf(markers.end, start + 1)
if (end === -1) {
throw new Error('codex_config_block_unterminated')
}
@@ -54,12 +63,15 @@ function joinParts(parts: string[]): string {
export function mergeCodexMcpServers(
text: string | null,
desired: Readonly<Record<string, Record<string, unknown>>>,
lastBlockPrint: string | null
lastBlockPrint: string | null,
markers: CodexMcpBlockMarkers = codexMcpBlockMarkers(undefined),
/** Markers of a block this computer is taking over (the pre-per-computer block it wrote). */
adopt?: CodexMcpBlockMarkers
): CodexMcpMergeResult {
const source = text ?? ''
// Refuse to edit a file Codex itself could not load.
parseToml(source)
const block = findBlock(source)
const block = findBlock(source, markers) ?? (adopt ? findBlock(source, adopt) : null)
const handEdited = block !== null && fingerprintMcpValue(block.body) !== lastBlockPrint
const outside = block
? handEdited
@@ -89,7 +101,7 @@ export function mergeCodexMcpServers(
if (!block && !body) {
return { text: null, blockPrint: null, outcomes }
}
const blockText = body ? `${CODEX_MCP_BLOCK_START}\n${body}\n${CODEX_MCP_BLOCK_END}` : ''
const blockText = body ? `${markers.start}\n${body}\n${markers.end}` : ''
const next =
block && !handEdited
? joinParts([block.before, blockText, block.after])
@@ -70,4 +70,53 @@ describe('syncHostMcpServers', () => {
mine: { command: 'host-only' }
})
})
it('two computers syncing one shared sandbox keep each other’s servers (no flapping)', async () => {
const a = {
claude: { fromA: { command: 'npx' } },
codex: { fromA: { command: 'npx' } },
syncer: 'aaaa'
}
const b = {
claude: { fromB: { command: 'npx' } },
codex: { fromB: { command: 'npx' } },
syncer: 'bbbb'
}
await syncHostMcpServers(a, deps())
await syncHostMcpServers(b, deps())
const again = await syncHostMcpServers(a, deps())
expect(again.claude).toEqual({ fromA: 'unchanged' })
expect(again.codex).toEqual({ fromA: 'unchanged' })
expect(
Object.keys(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers).sort()
).toEqual(['fromA', 'fromB'])
const toml = readFileSync(paths.codexConfig, 'utf8')
expect(toml).toContain('[aaaa]')
expect(toml).toContain('[bbbb]')
// A stops syncing fromA: only A's entry goes.
await syncHostMcpServers({ claude: {}, codex: {}, syncer: 'aaaa' }, deps())
expect(Object.keys(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers)).toEqual([
'fromB'
])
expect(readFileSync(paths.codexConfig, 'utf8')).not.toContain('fromA')
})
it('the first computer with an id takes over what the shared ledger wrote, once', async () => {
await syncHostMcpServers(
{ claude: { old: { command: 'npx' } }, codex: { old: { command: 'npx' } } },
deps()
)
const adopted = await syncHostMcpServers(
{ claude: { old: { command: 'npx' } }, codex: { old: { command: 'npx' } }, syncer: 'cccc' },
deps()
)
expect(adopted.claude).toEqual({ old: 'unchanged' })
expect(adopted.codex).toEqual({ old: 'unchanged' })
const toml = readFileSync(paths.codexConfig, 'utf8')
expect(toml.match(/mcp_servers\.old/g)).toHaveLength(1)
expect(toml).toContain('[cccc]')
// Removing works through the adopted ledger.
await syncHostMcpServers({ claude: {}, codex: {}, syncer: 'cccc' }, deps())
expect(JSON.parse(readFileSync(paths.claudeConfig, 'utf8')).mcpServers ?? {}).toEqual({})
})
})
+40 -8
View File
@@ -12,8 +12,8 @@ import { writeFileAtomicallyIfUnchanged } from '../../filesystem/atomic-file-pub
import { isCommandOnLocalPath } from '../../ipc/command-path/command-path-resolver'
import { hostShellEnvironment } from '../../runtime/agent-session/environment/structured-agent-shell-environment'
import { mergeClaudeMcpServers } from './claude-json-mcp-merge'
import { mergeCodexMcpServers } from './codex-toml-mcp-merge'
import { parseMcpSyncLedger, type McpSyncLedger } from './mcp-sync-ledger'
import { codexMcpBlockMarkers, mergeCodexMcpServers } from './codex-toml-mcp-merge'
import { EMPTY_MCP_SYNC_LEDGER, parseMcpSyncLedger, type McpSyncLedger } from './mcp-sync-ledger'
// Agent configs carry MCP env tokens and headers; keep them owner-only.
const PRIVATE_FILE = { mode: 0o600 } as const
@@ -33,6 +33,10 @@ export type HostMcpSyncDeps = {
resolves?: (hostname: string) => Promise<boolean>
}
export function syncerLedgerPath(sharedLedger: string, syncer: string): string {
return sharedLedger.replace(/\.json$/, `-${syncer}.json`)
}
export function defaultHostMcpSyncPaths(userDataPath: string): HostMcpSyncPaths {
const claudeDir = process.env.CLAUDE_CONFIG_DIR?.trim()
return {
@@ -150,13 +154,21 @@ async function syncClaude(
async function syncCodex(
paths: HostMcpSyncPaths,
desired: Record<string, Record<string, unknown>>,
ledger: McpSyncLedger
ledger: McpSyncLedger,
syncer: string | undefined,
adoptLegacy: boolean
): Promise<Record<string, McpSyncHostOutcome>> {
for (let attempt = 0; attempt < WRITE_ATTEMPTS; attempt += 1) {
const text = await readText(paths.codexConfig)
let merged: ReturnType<typeof mergeCodexMcpServers>
try {
merged = mergeCodexMcpServers(text, desired, ledger.codexBlock)
merged = mergeCodexMcpServers(
text,
desired,
ledger.codexBlock,
codexMcpBlockMarkers(syncer),
adoptLegacy ? codexMcpBlockMarkers(undefined) : undefined
)
} catch {
return unreadable(desired)
}
@@ -175,8 +187,17 @@ export async function syncHostMcpServers(
): Promise<AgentMcpSyncResult> {
const commandExists = deps.commandExists ?? defaultCommandExists
const resolves = deps.resolves ?? defaultResolves
const ledgerText = await readText(deps.paths.ledger)
const ledger = parseMcpSyncLedger(ledgerText)
// Each syncing computer has its own ledger: entries another computer wrote are not this one's to
// remove (they read as the host's own), so two computers on one shared sandbox never flap.
const ledgerPath = params.syncer
? syncerLedgerPath(deps.paths.ledger, params.syncer)
: deps.paths.ledger
const ownText = await readText(ledgerPath)
// The first computer to sync after per-computer ledgers takes over what the shared ledger recorded.
const legacyText = params.syncer && ownText === null ? await readText(deps.paths.ledger) : null
const adoptLegacy = legacyText !== null
const ledgerText = ownText
const ledger = parseMcpSyncLedger(ownText ?? legacyText)
const result: AgentMcpSyncResult = {}
if (params.claude) {
const outcomes: Record<string, McpSyncHostOutcome> = {}
@@ -186,11 +207,22 @@ export async function syncHostMcpServers(
if (params.codex) {
const outcomes: Record<string, McpSyncHostOutcome> = {}
const desired = await runnable(params.codex, commandExists, outcomes)
result.codex = { ...outcomes, ...(await syncCodex(deps.paths, desired, ledger)) }
result.codex = {
...outcomes,
...(await syncCodex(deps.paths, desired, ledger, params.syncer, adoptLegacy))
}
}
const nextLedger = `${JSON.stringify(ledger, null, 2)}\n`
if (nextLedger !== ledgerText) {
await writePrivate(deps.paths.ledger, ledgerText, nextLedger)
await writePrivate(ledgerPath, ledgerText, nextLedger)
}
if (adoptLegacy) {
// Claimed: a second computer must not adopt the same entries.
await writePrivate(
deps.paths.ledger,
legacyText,
`${JSON.stringify(EMPTY_MCP_SYNC_LEDGER, null, 2)}\n`
)
}
const hostnames = remoteHostnames(params)
const reachable = await Promise.all(hostnames.map(resolves))
@@ -47,7 +47,12 @@ const ServerSet = z
export const AgentMcpSyncParams = z
.object({
claude: ServerSet.optional(),
codex: ServerSet.optional()
codex: ServerSet.optional(),
/** Stable id of the syncing computer: each one owns (and only removes) its own entries. */
syncer: z
.string()
.regex(/^[A-Za-z0-9_-]{1,64}$/)
.optional()
})
.strict()
export type AgentMcpSyncParams = z.infer<typeof AgentMcpSyncParams>