You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by as...@apache.org on 2026/09/09 09:36:42 UTC
(maka) branch main updated: fix(storage): unify atomic writes for JSON config stores (#4505)
This is an automated email from the ASF dual-hosted git repository.
Astro-Han pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/main by this push:
new fcff80f589 fix(storage): unify atomic writes for JSON config stores (#4505)
fcff80f589 is described below
commit fcff80f58910f4de118fd7edbf7f02068239c50a
Author: Dante.Cloud <ch...@163.com>
AuthorDate: Wed Sep 9 17:36:37 2026 +0800
fix(storage): unify atomic writes for JSON config stores (#4505)
Consolidate settings, MCP configuration and credential JSON publication on the shared atomic writer while preserving each store's permission policy and platform-specific synchronization guarantees.
Distinguish post-rename durability uncertainty from pre-publication failure. Reconcile MCP runtime and visible state from the authoritative published configuration without replaying mutations or credential retirement, and expose actionable localized errors.
The JSON format is unchanged. Synchronization guarantees remain conditional on the filesystem, hardware and operating system APIs.
Refs #4285
Generated-by: OpenAI Codex
---
.github/workflows/windows-recovery.yml | 2 +-
.../main/__tests__/mcp-ipc-commit-unknown.test.ts | 274 +++++++++++++++++++++
.../src/main/__tests__/mcp-page-model.test.ts | 22 ++
apps/desktop/src/main/mcp-ipc-main.ts | 82 ++++--
apps/desktop/src/renderer/locales/mcp-copy.ts | 7 +
apps/desktop/src/renderer/mcp-page-model.ts | 13 +
apps/desktop/src/renderer/mcp-page.tsx | 22 +-
docs/windows-test-inventory.md | 16 +-
.../cli/src/__tests__/pi-tui-mcp-status.test.ts | 9 +
packages/cli/src/__tests__/tui-mcp-control.test.ts | 258 ++++++++++++++++++-
packages/cli/src/tui-copy-catalog.ts | 12 +-
packages/cli/src/tui-mcp-control.ts | 57 ++++-
.../src/__tests__/atomic-file-write.test.ts | 249 +++++++++++++++++++
.../storage/src/__tests__/credential-store.test.ts | 6 +-
.../storage/src/__tests__/mcp-config-store.test.ts | 11 +-
.../__tests__/settings-store-onboarding.test.ts | 24 +-
.../storage/src/__tests__/stable-storage.test.ts | 37 ++-
packages/storage/src/atomic-file-write.ts | 122 +++++++++
packages/storage/src/credential-store.ts | 74 +-----
packages/storage/src/mcp-config-store.ts | 37 ++-
packages/storage/src/settings-store.ts | 12 +-
packages/storage/src/stable-storage.ts | 16 +-
22 files changed, 1221 insertions(+), 141 deletions(-)
diff --git a/.github/workflows/windows-recovery.yml b/.github/workflows/windows-recovery.yml
index aa7598430b..886404f416 100644
--- a/.github/workflows/windows-recovery.yml
+++ b/.github/workflows/windows-recovery.yml
@@ -116,7 +116,7 @@ on:
- 'packages/storage/src/artifact-store.ts'
- 'packages/storage/src/artifact-writer-bootstrap-lock.ts'
- 'packages/storage/src/artifact-writer-lock.ts'
- - 'packages/storage/src/credential-store.ts'
+ - 'packages/storage/src/atomic-file-write.ts'
- 'packages/storage/src/file-lifetime-owner.ts'
- 'packages/storage/src/managed-dependency-environment.ts'
- 'packages/storage/src/marker-file.ts'
diff --git a/apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts b/apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts
new file mode 100644
index 0000000000..c9f12ae74c
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts
@@ -0,0 +1,274 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import fs, { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { syncBuiltinESMExports } from 'node:module';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { test, type TestContext } from 'node:test';
+import { fileURLToPath } from 'node:url';
+import { MCP_CONFIG_VERSION, type McpConfigFile, type McpServerStatus } from '@maka/core/mcp';
+import { McpClientManager } from '@maka/mcp';
+import {
+ AtomicFileWriteCommitUnknownError,
+ createMcpConfigStore,
+ type McpConfigStore,
+} from '@maka/storage/mcp-config-store';
+import { registerMcpIpcMain, type McpIpcMainDeps } from '../mcp-ipc-main.js';
+import { getMcpCopy } from '../../renderer/locales/mcp-copy.js';
+import { mcpWriteFailureMessage } from '../../renderer/mcp-page-model.js';
+
+test('MCP remove reconciles a live manager after the real store publishes then fails directory sync', {
+ skip: process.platform === 'win32',
+}, async (t) => {
+ const { root, store } = await fixtureStore(t);
+ const fixturePath = fileURLToPath(new URL(
+ '../../../../../packages/mcp/dist/__fixtures__/stdio-server.js', import.meta.url,
+ ));
+ const config = await store.upsert('fixture', {
+ command: process.execPath,
+ args: [fixturePath],
+ });
+ const manager = new McpClientManager({
+ timeouts: { stdioConnectMs: 5_000, listToolsMs: 5_000 },
+ });
+ t.after(() => manager.close());
+ await manager.sync(config);
+ assert.equal(manager.status('fixture')?.state, 'connected');
+ assert.ok(manager.toolSnapshot().tools.length > 0);
+
+ const fault = failDirectorySync(t, root);
+ const tracked = trackTransform(t, store);
+ const publicationError = new Error('capability publication unavailable');
+ const ipc = mutationHarness(store, {
+ manager,
+ publishCapabilities: async () => { throw publicationError; },
+ });
+ await assert.rejects(ipc.invoke('mcp:remove', 'fixture'), (error) => {
+ assert.equal(error, tracked.error());
+ assert.ok(error instanceof AtomicFileWriteCommitUnknownError);
+ assert.equal(error.published, true);
+ assert.equal(error.cause, fault.error);
+ assert.equal(mcpWriteFailureMessage(error, getMcpCopy('en')), getMcpCopy('en').errors.writeDurabilityUnknown);
+ return true;
+ });
+ assert.deepEqual(await diskConfig(root), { version: MCP_CONFIG_VERSION, mcpServers: {} });
+ assert.deepEqual(manager.statuses(), []);
+ assert.deepEqual(manager.toolSnapshot().tools, []);
+ assert.deepEqual(ipc.emitted, [[]]);
+ assert.equal(tracked.calls(), 1);
+ assert.equal(tracked.applied(), 1);
+ assert.equal(fault.calls(), 1);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(ipc.publicationErrors, [publicationError]);
+});
+
+test('MCP upsert reconciles the reread authority including an intervening writer without replaying its mutation', {
+ skip: process.platform === 'win32',
+}, async (t) => {
+ const { root, store } = await fixtureStore(t);
+ await store.upsert('remote', { url: 'https://old.example.com/mcp', enabled: false });
+ failDirectorySync(t, root);
+ const otherStore = createMcpConfigStore(root);
+ const tracked = trackTransform(t, store, async () => {
+ await otherStore.upsert('remote', { url: 'https://latest.example.com/mcp', enabled: false });
+ });
+ const ipc = mutationHarness(store);
+ await assert.rejects(
+ ipc.invoke('mcp:upsert', 'remote', { url: 'https://proposed.example.com/mcp', enabled: false }),
+ (error) => error === tracked.error(),
+ );
+ const authoritative = await diskConfig(root);
+ assert.equal((authoritative.mcpServers.remote as { url: string }).url, 'https://latest.example.com/mcp');
+ assert.deepEqual(ipc.synced, [authoritative]);
+ assert.equal(ipc.emitted.length, 1);
+ assert.deepEqual(ipc.retired, ['remote']);
+ assert.equal(tracked.calls(), 1);
+ assert.equal(tracked.applied(), 1);
+});
+
+for (const phase of ['read', 'sync', 'emit'] as const) {
+ test(`MCP published write explicitly reports out-of-sync when reconciliation ${phase} fails`, {
+ skip: process.platform === 'win32',
+ }, async (t) => {
+ const { root, store } = await fixtureStore(t);
+ failDirectorySync(t, root);
+ const tracked = trackTransform(t, store);
+ const reconciliationError = new Error(`injected ${phase} failure`);
+ const ipc = mutationHarness(store);
+ if (phase === 'read') {
+ t.mock.method(store, 'get', async () => { throw reconciliationError; });
+ } else if (phase === 'sync') {
+ t.mock.method(ipc.deps.manager, 'sync', async () => { throw reconciliationError; });
+ } else {
+ t.mock.method(ipc.deps, 'emitChanged', () => { throw reconciliationError; });
+ }
+ await assert.rejects(ipc.invoke('mcp:upsert', 'fixture', { command: 'node', enabled: false }), (error) => {
+ assert.ok(error instanceof AggregateError);
+ assert.match(error.message, /out of sync/u);
+ assert.equal(error.cause, tracked.error());
+ assert.deepEqual(error.errors, [tracked.error(), reconciliationError]);
+ assert.equal(mcpWriteFailureMessage(error, getMcpCopy('en')), getMcpCopy('en').errors.writeOutOfSync);
+ return true;
+ });
+ assert.ok((await diskConfig(root)).mcpServers.fixture);
+ assert.equal(tracked.calls(), 1);
+ assert.equal(tracked.applied(), 1);
+ });
+}
+
+test('MCP pre-publication failure does not reconcile or retry the failed mutation', async (t) => {
+ const { root, store } = await fixtureStore(t);
+ const error = new Error('injected transform failure');
+ const transform = t.mock.method(store, 'transform', async () => { throw error; });
+ const get = t.mock.method(store, 'get');
+ const ipc = mutationHarness(store);
+ await assert.rejects(ipc.invoke('mcp:upsert', 'fixture', { command: 'node' }), (caught) => caught === error);
+ assert.equal(transform.mock.callCount(), 1);
+ assert.equal(get.mock.callCount(), 0);
+ assert.deepEqual(await diskConfig(root), { version: MCP_CONFIG_VERSION, mcpServers: {} });
+ assert.deepEqual(ipc.synced, []);
+ assert.deepEqual(ipc.emitted, []);
+});
+
+test('MCP cancelled install does not start a new connection during post-rename reconciliation', {
+ skip: process.platform === 'win32',
+ timeout: 5_000,
+}, async (t) => {
+ const { root, store } = await fixtureStore(t);
+ let published!: () => void;
+ const publication = new Promise<void>((resolve) => { published = resolve; });
+ let finishSync!: () => void;
+ const syncGate = new Promise<void>((resolve) => { finishSync = resolve; });
+ const fault = failDirectorySync(t, root, async () => {
+ published();
+ await syncGate;
+ });
+ const ipc = mutationHarness(store);
+ const installing = ipc.invoke('mcp:install', 'fixture', { command: 'node' }).catch((error) => error);
+ await publication;
+ const cancelling = ipc.invoke('mcp:cancelInstall', 'fixture');
+ finishSync();
+ const installationError = await installing;
+ const cancelled = await cancelling;
+ assert.ok(installationError instanceof AggregateError);
+ assert.ok(installationError.cause instanceof AtomicFileWriteCommitUnknownError);
+ assert.equal(installationError.cause.cause, fault.error);
+ assert.match(installationError.message, /out of sync/u);
+ assert.match(installationError.errors[1].message, /cancelled/u);
+ const empty = { version: MCP_CONFIG_VERSION, mcpServers: {} };
+ assert.deepEqual(cancelled, empty);
+ assert.deepEqual(await diskConfig(root), empty);
+ assert.deepEqual(ipc.synced, [empty], 'only the cancellation rollback may sync the manager');
+});
+
+async function fixtureStore(t: TestContext): Promise<{ root: string; store: McpConfigStore }> {
+ const root = await mkdtemp(join(tmpdir(), 'mcp-ipc-commit-unknown-'));
+ t.after(async () => {
+ t.mock.restoreAll();
+ syncBuiltinESMExports();
+ await rm(root, { recursive: true, force: true });
+ });
+ const store = createMcpConfigStore(root);
+ await store.get();
+ return { root, store };
+}
+
+function failDirectorySync(t: TestContext, root: string, beforeFailure?: () => Promise<void>) {
+ const error = Object.assign(new Error('injected post-rename directory sync failure'), { code: 'EIO' });
+ const open = fs.open;
+ let calls = 0;
+ t.mock.method(fs, 'open', async (...args: Parameters<typeof open>) => {
+ const handle = await open(...args);
+ if (args[0] === root && args[1] === 'r' && calls === 0) {
+ t.mock.method(handle, 'sync', async () => {
+ calls += 1;
+ await beforeFailure?.();
+ throw error;
+ }, { times: 1 });
+ }
+ return handle;
+ });
+ syncBuiltinESMExports();
+ return { error, calls: () => calls };
+}
+
+function trackTransform(t: TestContext, store: McpConfigStore, afterFailure?: () => Promise<void>) {
+ const transform = store.transform.bind(store);
+ let error: unknown;
+ let applied = 0;
+ const tracked = t.mock.method(store, 'transform', async (apply: Parameters<McpConfigStore['transform']>[0]) => {
+ try {
+ return await transform((current) => {
+ applied += 1;
+ return apply(current);
+ });
+ } catch (caught) {
+ error = caught;
+ await afterFailure?.();
+ throw caught;
+ }
+ });
+ return { error: () => error, calls: () => tracked.mock.callCount(), applied: () => applied };
+}
+
+async function diskConfig(root: string): Promise<McpConfigFile> {
+ return JSON.parse(await readFile(join(root, 'mcp.json'), 'utf8'));
+}
+
+function mutationHarness(store: McpConfigStore, overrides: Partial<McpIpcMainDeps> = {}) {
+ const handlers = new Map<string, (...args: any[]) => Promise<any>>();
+ const synced: McpConfigFile[] = [];
+ const emitted: McpServerStatus[][] = [];
+ const retired: string[] = [];
+ const publicationErrors: unknown[] = [];
+ const deps: McpIpcMainDeps = {
+ ipcMain: { handle(channel, handler) { handlers.set(channel, handler as (...args: any[]) => Promise<any>); } },
+ store,
+ manager: {
+ cancelConnect: () => false,
+ forgetServerCredentials: async (serverId) => { retired.push(serverId); },
+ sync: async (next) => { synced.push(structuredClone(next)); },
+ statuses: () => [],
+ test: async () => { throw new Error('not used'); },
+ },
+ oauth: {
+ isActive: () => false,
+ cancelLogin: () => false,
+ login: async () => { throw new Error('not used'); },
+ logout: async () => { throw new Error('not used'); },
+ resumeLogin: async () => undefined,
+ },
+ ensureReady: async () => {},
+ publishCapabilities: async () => {},
+ onPublicationError: (error) => { publicationErrors.push(error); },
+ emitChanged: (statuses) => { emitted.push(statuses); },
+ ...overrides,
+ };
+ registerMcpIpcMain(deps);
+ return {
+ deps, synced, emitted, retired, publicationErrors,
+ invoke(channel: string, ...args: unknown[]) {
+ const handler = handlers.get(channel);
+ assert.ok(handler);
+ return handler({}, ...args);
+ },
+ };
+}
diff --git a/apps/desktop/src/main/__tests__/mcp-page-model.test.ts b/apps/desktop/src/main/__tests__/mcp-page-model.test.ts
index 30afdc6d7b..1da68a9ef8 100644
--- a/apps/desktop/src/main/__tests__/mcp-page-model.test.ts
+++ b/apps/desktop/src/main/__tests__/mcp-page-model.test.ts
@@ -21,6 +21,7 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { isMcpStdioConfig, type McpServerStatus } from '@maka/core/mcp';
import { MCP_CATALOG } from '../../renderer/mcp-catalog.js';
+import { AtomicFileWriteCommitUnknownError } from '@maka/storage/mcp-config-store';
import { getMcpCopy } from '../../renderer/locales/mcp-copy.js';
import {
createEmptyMcpDraft,
@@ -28,10 +29,31 @@ import {
mcpDraftProtocolPreference,
mcpDraftFromConfig,
presentMcpNegotiatedProtocol,
+ mcpWriteFailureMessage,
} from '../../renderer/mcp-page-model.js';
const copy = getMcpCopy('en');
+test('MCP write errors retain actionable localized meaning across Electron serialization', () => {
+ const durabilityError = new AtomicFileWriteCommitUnknownError({ cause: new Error('EIO') });
+ const outOfSync = 'MCP write durability is uncertain and runtime state is out of sync; reload before retrying';
+ for (const locale of ['en', 'zh-CN', 'zh-TW'] as const) {
+ const localized = getMcpCopy(locale);
+ for (const [message, expected] of [
+ [durabilityError.message, localized.errors.writeDurabilityUnknown],
+ [outOfSync, localized.errors.writeOutOfSync],
+ ]) {
+ assert.equal(mcpWriteFailureMessage(message, localized), expected);
+ assert.equal(
+ mcpWriteFailureMessage(new Error(`Error invoking remote method 'mcp:remove': Error: ${message}`), localized),
+ expected,
+ );
+ }
+ assert.equal(mcpWriteFailureMessage(new Error('unrelated private details'), localized), undefined);
+ assert.equal(mcpWriteFailureMessage(undefined, localized), undefined);
+ }
+});
+
test('a newly-authored remote MCP persists an explicit auto preference', () => {
const config = mcpConfigFromDraft(
{
diff --git a/apps/desktop/src/main/mcp-ipc-main.ts b/apps/desktop/src/main/mcp-ipc-main.ts
index 0cb59d44fe..368155cfb1 100644
--- a/apps/desktop/src/main/mcp-ipc-main.ts
+++ b/apps/desktop/src/main/mcp-ipc-main.ts
@@ -29,6 +29,7 @@ import {
} from '@maka/core/mcp';
import type { McpClientManager } from '@maka/mcp';
import {
+ AtomicFileWriteCommitUnknownError,
assertMcpEndpointPolicyOnChanges,
McpServerExistsError,
McpConfigSourceError,
@@ -107,32 +108,56 @@ export function registerMcpIpcMain(deps: McpIpcMainDeps): void {
const inMutationLane = deps.exclusiveLane ?? createMcpExclusiveLane();
const commitConfig = async (
mutate: (current: McpConfigFile) => McpConfigFile,
- ): Promise<McpConfigFile> =>
- deps.store.transform(async (current) => {
- const next = mutate(current);
- assertMcpEndpointPolicyOnChanges(current, next);
- // The authoritative gate: every server this commit semantically touches
- // is re-checked INSIDE the lane. The handler-entry checks are advisory
- // fast-fails; this one cannot race a login claim, because claims travel
- // the same lane.
- for (const serverId of new Set([
- ...Object.keys(current.mcpServers),
- ...Object.keys(next.mcpServers),
- ])) {
- const before = current.mcpServers[serverId];
- const after = next.mcpServers[serverId];
- if (JSON.stringify(before) !== JSON.stringify(after)) assertNoActiveLogin(serverId);
- }
- // Erases are per-server and not transactional as a set: if one fails
- // partway, the commit aborts with the EARLIER servers already logged
- // out. That partial effect is deliberately in the fail-closed direction
- // — a re-login is recoverable, a credential outliving its removed or
- // repointed config is not.
- for (const serverId of credentialRetirements(current, next)) {
- await deps.manager.forgetServerCredentials(serverId);
+ assertReconciliationAllowed?: () => void,
+ ): Promise<McpConfigFile> => {
+ try {
+ return await deps.store.transform(async (current) => {
+ const next = mutate(current);
+ assertMcpEndpointPolicyOnChanges(current, next);
+ // The authoritative gate: every server this commit semantically touches
+ // is re-checked INSIDE the lane. The handler-entry checks are advisory
+ // fast-fails; this one cannot race a login claim, because claims travel
+ // the same lane.
+ for (const serverId of new Set([
+ ...Object.keys(current.mcpServers),
+ ...Object.keys(next.mcpServers),
+ ])) {
+ const before = current.mcpServers[serverId];
+ const after = next.mcpServers[serverId];
+ if (JSON.stringify(before) !== JSON.stringify(after)) assertNoActiveLogin(serverId);
+ }
+ // Erases are per-server and not transactional as a set: if one fails
+ // partway, the commit aborts with the EARLIER servers already logged
+ // out. That partial effect is deliberately in the fail-closed direction
+ // — a re-login is recoverable, a credential outliving its removed or
+ // repointed config is not.
+ for (const serverId of credentialRetirements(current, next)) {
+ await deps.manager.forgetServerCredentials(serverId);
+ }
+ return next;
+ });
+ } catch (error) {
+ if (!(error instanceof AtomicFileWriteCommitUnknownError)) throw error;
+ // Rename has already published a file even though its durability fence
+ // failed. Read the authority again rather than replaying the mutation
+ // or assuming our proposed snapshot is still current. Keep this in the
+ // mutation lane so another local mutation or OAuth claim cannot pass
+ // the reconciliation, and retain the original durability failure.
+ try {
+ const authoritative = await deps.store.get();
+ assertReconciliationAllowed?.();
+ await deps.manager.sync(authoritative);
+ changed(deps);
+ } catch (reconciliationError) {
+ throw new AggregateError(
+ [error, reconciliationError],
+ 'MCP write durability is uncertain and runtime state is out of sync; reload before retrying',
+ { cause: error },
+ );
}
- return next;
- });
+ throw error;
+ }
+ };
// The renderer is semi-trusted (SECURITY.md §3): every config that crosses
// toward it leaves with clientSecret replaced by the sentinel, and every
// config it sends back has sentinels restored from disk before the store
@@ -255,6 +280,13 @@ export function registerMcpIpcMain(deps: McpIpcMainDeps): void {
...current,
mcpServers: { ...current.mcpServers, [serverId]: installed },
};
+ }, () => {
+ // Cancellation may have called cancelConnect while the write was
+ // pending. Do not start a new connection after that cancellation;
+ // the existing settled/rollback path will reconcile the removal.
+ if (operation.cancelled) {
+ throw new Error('MCP installation cancelled; awaiting configuration rollback');
+ }
}),
);
if (operation.cancelled) return redactMcpConfigSecrets(next);
diff --git a/apps/desktop/src/renderer/locales/mcp-copy.ts b/apps/desktop/src/renderer/locales/mcp-copy.ts
index 8eb2ad8aaf..12f67ae260 100644
--- a/apps/desktop/src/renderer/locales/mcp-copy.ts
+++ b/apps/desktop/src/renderer/locales/mcp-copy.ts
@@ -24,6 +24,7 @@ export type McpCopy = {
load: string; install(name: string): string; cancelInstall(name: string): string; save: string; import: string;
update: string; test: string; remove: string; unavailableStatus: string; mapLine(line: number): string;
importJson: string; importObject: string; importVersion(version: string): string; importServersObject: string; importProtocolVersion: string;
+ writeDurabilityUnknown: string; writeOutOfSync: string;
};
toast: {
templateInstalled(name: string): string; templateInstalledDetail: string; installed(name: string): string;
@@ -74,6 +75,8 @@ const MCP_COPY = {
'zh-CN': {
errors: {
load: '载入 MCP 失败', install: (name) => `安装 ${name} 失败`, cancelInstall: (name) => `取消安装 ${name} 失败`, save: '保存 MCP 失败',
+ writeDurabilityUnknown: '写入已发布,但无法确认断电后是否保留。请检查刷新后的配置再决定是否重试。',
+ writeOutOfSync: '写入的持久性尚未确认,MCP 运行状态也未能与配置同步。请检查配置并重新同步后再重试。',
import: '导入 MCP 失败', update: '更新 MCP 失败', test: 'MCP 测试失败', remove: '删除 MCP 失败', unavailableStatus: 'Server 没有返回可用状态。',
mapLine: (line) => `第 ${line} 行应为 KEY=value`, importJson: 'MCP 配置必须是有效的 JSON', importObject: 'MCP JSON 必须是 object',
importVersion: (version) => `不支持 MCP 配置版本 ${version},当前支持 version 1、2 和 3`, importServersObject: 'mcpServers 必须是 object',
@@ -133,6 +136,8 @@ const MCP_COPY = {
'zh-TW': {
errors: {
load: '載入 MCP 失敗', install: (name) => `安裝 ${name} 失敗`, cancelInstall: (name) => `取消安裝 ${name} 失敗`, save: '儲存 MCP 失敗',
+ writeDurabilityUnknown: '寫入已發布,但無法確認斷電後是否保留。請檢查重新整理後的設定再決定是否重試。',
+ writeOutOfSync: '寫入的持久性尚未確認,MCP 執行狀態也未能與設定同步。請檢查設定並重新同步後再重試。',
import: '匯入 MCP 失敗', update: '更新 MCP 失敗', test: 'MCP 測試失敗', remove: '刪除 MCP 失敗', unavailableStatus: 'Server 沒有返回可用狀態。',
mapLine: (line) => `第 ${line} 行應為 KEY=value`, importJson: 'MCP 設定必須是有效的 JSON', importObject: 'MCP JSON 必須是 object',
importVersion: (version) => `不支援 MCP 設定版本 ${version},目前支援 version 1、2 和 3`, importServersObject: 'mcpServers 必須是 object',
@@ -192,6 +197,8 @@ const MCP_COPY = {
en: {
errors: {
load: 'Failed to load MCP', install: (name) => `Failed to install ${name}`, cancelInstall: (name) => `Failed to cancel installation of ${name}`, save: 'Failed to save MCP',
+ writeDurabilityUnknown: 'The write was published, but survival after power loss could not be confirmed. Check the refreshed configuration before retrying.',
+ writeOutOfSync: 'Write durability could not be confirmed, and MCP runtime state is out of sync with the configuration. Check the configuration and resynchronize before retrying.',
import: 'Failed to import MCP', update: 'Failed to update MCP', test: 'MCP test failed', remove: 'Failed to delete MCP', unavailableStatus: 'The server did not return an available status.',
mapLine: (line) => `Line ${line} must use KEY=value`, importJson: 'MCP configuration must be valid JSON', importObject: 'MCP JSON must be an object',
importVersion: (version) => `Unsupported MCP config version ${version}; versions 1, 2, and 3 are supported`, importServersObject: 'mcpServers must be an object',
diff --git a/apps/desktop/src/renderer/mcp-page-model.ts b/apps/desktop/src/renderer/mcp-page-model.ts
index e4520cea06..5ac7688628 100644
--- a/apps/desktop/src/renderer/mcp-page-model.ts
+++ b/apps/desktop/src/renderer/mcp-page-model.ts
@@ -27,6 +27,19 @@ import { isMcpStdioConfig, resolveMcpProtocolPreference } from '@maka/core/mcp';
import type { McpCopy } from './locales/mcp-copy.js';
import { formatCommandLine, parseCommandLine } from './mcp-command-line.js';
+/** Electron preserves error messages, but not custom error fields. Map only
+ * the fixed publication-error messages to safe, localized presentation. */
+export function mcpWriteFailureMessage(error: unknown, copy: McpCopy): string | undefined {
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
+ if (message.includes('MCP write durability is uncertain and runtime state is out of sync')) {
+ return copy.errors.writeOutOfSync;
+ }
+ if (message.includes('Atomic file commit outcome is unknown; reload before retrying')) {
+ return copy.errors.writeDurabilityUnknown;
+ }
+ return undefined;
+}
+
export type McpEditorDraft = {
id: string;
kind: 'stdio' | 'remote';
diff --git a/apps/desktop/src/renderer/mcp-page.tsx b/apps/desktop/src/renderer/mcp-page.tsx
index 2e540d4c0a..96aac359a2 100644
--- a/apps/desktop/src/renderer/mcp-page.tsx
+++ b/apps/desktop/src/renderer/mcp-page.tsx
@@ -107,6 +107,7 @@ import {
mcpDraftProtocolPreference,
mcpDraftFromConfig,
presentMcpNegotiatedProtocol,
+ mcpWriteFailureMessage,
type McpEditorDraft,
} from './mcp-page-model';
import { settingsActionErrorMessage } from './settings/settings-error-copy';
@@ -296,9 +297,10 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current && !cancelledInstalls.current.has(entry.id)) {
reportRuntimeHostError(
copy.errors.install(entry.name),
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
+ await reload();
}
} finally {
const wasCancelled = cancelledInstalls.current.delete(entry.id);
@@ -325,10 +327,10 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current) {
reportRuntimeHostError(
copy.errors.cancelInstall(entry.name),
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
- void reload();
+ await reload();
}
} finally {
if (mounted.current) setInstallPhases((current) => omitKey(current, entry.id));
@@ -362,9 +364,12 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current) {
reportRuntimeHostError(
copy.errors.save,
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
+ // A rejected mutation may already have replaced mcp.json. Refresh
+ // both the configured rows and statuses before another user action.
+ await reload();
}
} finally {
if (mounted.current) setBusy(null);
@@ -392,9 +397,10 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current) {
reportRuntimeHostError(
copy.errors.import,
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
+ await reload();
}
} finally {
if (mounted.current) setBusy(null);
@@ -412,9 +418,10 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current) {
reportRuntimeHostError(
copy.errors.update,
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
+ await reload();
}
} finally {
if (mounted.current) setBusy(null);
@@ -477,9 +484,10 @@ export function McpPage(props: { hubHeader?: ModuleHubHeader }) {
if (mounted.current) {
reportRuntimeHostError(
copy.errors.remove,
- settingsActionErrorMessage(error, locale),
+ mcpWriteFailureMessage(error, copy) ?? settingsActionErrorMessage(error, locale),
defaultRuntimeHostDiagnosticTarget(error),
);
+ await reload();
}
} finally {
if (mounted.current) setBusy(null);
diff --git a/docs/windows-test-inventory.md b/docs/windows-test-inventory.md
index 50f0f66928..79974a1a54 100644
--- a/docs/windows-test-inventory.md
+++ b/docs/windows-test-inventory.md
@@ -16,15 +16,19 @@ Locations intentionally omit line numbers so unrelated edits do not invalidate t
| Classification | Count |
|---|---:|
| windows-backend-gap | 27 |
-| portable-candidate | 19 |
+| portable-candidate | 31 |
| platform-contract | 31 |
-Total Windows-excluded declarations: **77**
+Total Windows-excluded declarations: **89**
## Inventory
| Classification | Test | Skip expression |
|---|---|---|
+| portable-candidate | `apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts` MCP remove reconciles a live manager after the real store publishes then fails directory sync | `process.platform === 'win32'` |
+| portable-candidate | `apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts` MCP upsert reconciles the reread authority including an intervening writer without replaying its mutation | `process.platform === 'win32'` |
+| portable-candidate | `apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts` MCP published write explicitly reports out-of-sync when reconciliation ${phase} fails | `process.platform === 'win32'` |
+| portable-candidate | `apps/desktop/src/main/__tests__/mcp-ipc-commit-unknown.test.ts` MCP cancelled install does not start a new connection during post-rename reconciliation | `process.platform === 'win32'` |
| platform-contract | `apps/desktop/src/main/__tests__/project-context-root.test.ts` rejects a session cwd without read and traversal access | `process.platform === 'win32' ? 'POSIX permissions are required to make the session cwd inaccessible' : process.getuid?.() === 0` |
| platform-contract | `apps/desktop/src/main/__tests__/shell-env.test.ts` imports the login PATH without importing application control variables | `process.platform === 'win32'` |
| platform-contract | `apps/desktop/src/main/__tests__/shell-env.test.ts` keeps the inherited PATH and does not log shell stderr when capture fails | `process.platform === 'win32'` |
@@ -34,6 +38,7 @@ Total Windows-excluded declarations: **77**
| portable-candidate | `packages/cli/src/__tests__/pi-transcript.test.ts` keeps POSIX paths outside the home directory absolute | `process.platform === 'win32'` |
| portable-candidate | `packages/cli/src/__tests__/runtime-host-local-managed-activation.test.ts` local CLI cold-starts through the installed ${legacy ? 'legacy' : 'Node'} operator | `process.platform === 'win32'` |
| portable-candidate | `packages/cli/src/__tests__/runtime-host-setup.test.ts` managed operator binds its Client Data Root and routes deployment cleanup | `process.platform === 'win32'` |
+| portable-candidate | `packages/cli/src/__tests__/tui-mcp-control.test.ts` TUI MCP reconciles an already-published write through execute: ${scenario} | `process.platform === 'win32'` |
| portable-candidate | `packages/eval/src/__tests__/install-preflight.test.ts` rejects an unusable trials root before invoking external prerequisites | `process.platform === 'win32' \|\| process.geteuid?.() === 0` |
| windows-backend-gap | `packages/runtime-host/src/__tests__/connection-effect-coordinator.test.ts` leaves canonical onboarding state unchanged when the durable intent cannot be published | `process.platform === 'win32'` |
| windows-backend-gap | `packages/runtime-host/src/__tests__/connection-effect-coordinator.test.ts` recovers a durable onboarding intent instead of rolling back a partial publication | `process.platform === 'win32'` |
@@ -77,6 +82,10 @@ Total Windows-excluded declarations: **77**
| platform-contract | `packages/runtime/src/__tests__/shell-run-manager.test.ts` settles after root exit when a detached descendant retains inherited stdout | `process.platform === 'win32' ? 'POSIX detached process-group semantics required' : false` |
| platform-contract | `packages/runtime/src/__tests__/shell-run-manager.test.ts` keeps the first committed lifecycle cause across Stop and timeout races | `process.platform === 'win32' ? 'Windows tree termination has no graceful SIGTERM phase' : false` |
| platform-contract | `packages/runtime/src/__tests__/shell-run-manager.test.ts` keeps SIGTERM final output and escalates an ignored SIGTERM without leaking slots | `process.platform === 'win32' ? 'Windows tree termination has no graceful SIGTERM phase' : false` |
+| portable-candidate | `packages/storage/src/__tests__/atomic-file-write.test.ts` removes its temp file and rethrows after a chmod failure | `process.platform === 'win32'` |
+| portable-candidate | `packages/storage/src/__tests__/atomic-file-write.test.ts` creates the target 0600 on POSIX | `process.platform === 'win32'` |
+| portable-candidate | `packages/storage/src/__tests__/atomic-file-write.test.ts` re-chmods a pre-existing world-readable target to 0600 on the next write | `process.platform === 'win32'` |
+| portable-candidate | `packages/storage/src/__tests__/atomic-file-write.test.ts` refuses to write through a pre-planted symlink at the temp path | `process.platform === 'win32'` |
| portable-candidate | `packages/storage/src/__tests__/managed-dependency-environment.test.ts` accepts a POSIX package bin symlink whose target remains inside the dependency root | `process.platform === 'win32'` |
| portable-candidate | `packages/storage/src/__tests__/managed-dependency-environment.test.ts` isolates published POSIX content from a producer-retained writable handle | `process.platform === 'win32'` |
| platform-contract | `packages/storage/src/__tests__/operational-state-store.test.ts` does not classify a SQLite write failure as a migration blocker | `process.platform === 'win32' ? 'POSIX permissions are required to make the SQLite database read-only' : false` |
@@ -98,7 +107,10 @@ Total Windows-excluded declarations: **77**
| portable-candidate | `packages/storage/src/__tests__/runtime-policy-stores.test.ts` disabling proxy authentication commits policy before deleting its credential | `process.platform === 'win32' ? 'POSIX file handles are required to inject persistence failures' : false` |
| platform-contract | `packages/storage/src/__tests__/runtime-policy-stores.test.ts` successor recovery removes credentials orphaned by an interrupted connection removal | `process.platform === 'win32' ? 'POSIX permissions are required to inject a persistence failure' : false` |
| platform-contract | `packages/storage/src/__tests__/runtime-policy-stores.test.ts` fails closed on final symlinks, FIFOs, and oversized documents without changing bytes | `process.platform === 'win32'` |
+| portable-candidate | `packages/storage/src/__tests__/settings-store-onboarding.test.ts` preserves a restrictive umask-derived settings.json mode and leaves no temp file behind | `process.platform === 'win32'` |
| portable-candidate | `packages/storage/src/__tests__/stable-storage.test.ts` rejects a symlink instead of following it | `process.platform === 'win32' ? 'POSIX no-follow semantics are required' : false` |
+| portable-candidate | `packages/storage/src/__tests__/stable-storage.test.ts` hardenDirectory creates a 0700 directory chain | `process.platform === 'win32'` |
+| portable-candidate | `packages/storage/src/__tests__/stable-storage.test.ts` hardenDirectory re-chmods a pre-existing world-accessible directory to 0700 | `process.platform === 'win32'` |
| platform-contract | `packages/storage/src/__tests__/usage-stores.test.ts` classifies a renamed or replaced live root as a draining persistence failure | `process.platform === 'win32' ? 'Windows does not permit renaming a directory with an open SQLite database' : false` |
| platform-contract | `packages/storage/src/__tests__/workspace-identity.test.ts` an unmarked read-only workspace fails without leaving marker state | `process.platform === 'win32' ? 'POSIX permissions are required to create a read-only workspace fixture' : false` |
| portable-candidate | `scripts/release-cli-eval-support.test.mjs` preserves the primary process failure when diagnostics cannot be read | `process.platform === 'win32'` |
diff --git a/packages/cli/src/__tests__/pi-tui-mcp-status.test.ts b/packages/cli/src/__tests__/pi-tui-mcp-status.test.ts
index 5744e490f0..73b8936200 100644
--- a/packages/cli/src/__tests__/pi-tui-mcp-status.test.ts
+++ b/packages/cli/src/__tests__/pi-tui-mcp-status.test.ts
@@ -21,6 +21,7 @@ import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import type { TUI } from '@earendil-works/pi-tui';
import type { McpTestResult } from '@maka/core/mcp';
+import { AtomicFileWriteCommitUnknownError } from '@maka/storage/mcp-config-store';
import { McpManagementOverlay } from '../pi-tui-mcp-status.js';
import type {
TuiMcpAction,
@@ -436,6 +437,14 @@ describe('MCP management overlay', () => {
[{ status: 'failed', reason: 'invalid-config' }, 'invalid-config'],
[{ status: 'failed', reason: 'credential-cleanup-failed' }, 'credential-cleanup-failed'],
[{ status: 'failed', reason: 'persist-failed' }, 'persist-failed'],
+ [
+ {
+ status: 'failed',
+ reason: 'commit-unknown',
+ cause: new AtomicFileWriteCommitUnknownError({ cause: new Error('directory sync failed') }),
+ },
+ 'commit-unknown',
+ ],
[{ status: 'failed', reason: 'manager-failed' }, 'manager-failed'],
[{ status: 'applied', effect: 'published' }, 'published'],
[{ status: 'applied', effect: 'pending_host' }, 'pending_host'],
diff --git a/packages/cli/src/__tests__/tui-mcp-control.test.ts b/packages/cli/src/__tests__/tui-mcp-control.test.ts
index 32d893e483..2c6977babf 100644
--- a/packages/cli/src/__tests__/tui-mcp-control.test.ts
+++ b/packages/cli/src/__tests__/tui-mcp-control.test.ts
@@ -19,7 +19,8 @@
import { deferred } from '@maka/core/test-only/async-primitives';
import assert from 'node:assert/strict';
-import { mkdtemp, rm } from 'node:fs/promises';
+import fs, { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { syncBuiltinESMExports } from 'node:module';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
@@ -29,7 +30,10 @@ import type {
ClientCapabilityProvider,
RuntimeHostConnectionAvailability,
} from '@maka/runtime-host/client';
-import { createMcpConfigStore } from '@maka/storage/mcp-config-store';
+import {
+ AtomicFileWriteCommitUnknownError,
+ createMcpConfigStore,
+} from '@maka/storage/mcp-config-store';
import { createTuiMcpController, type TuiMcpPublicationAvailability } from '../tui-mcp-control.js';
import { waitFor } from './tui-terminal-mock.js';
@@ -524,6 +528,256 @@ test('TUI MCP keeps a durable mutation visible when manager synchronization fail
await controller.close();
});
+for (const scenario of [
+ 'remove',
+ 'edit',
+ 'newer-config',
+ 'read-failure',
+ 'sync-failure',
+ 'publication-failure',
+] as const) {
+ test(`TUI MCP reconciles an already-published write through execute: ${scenario}`, {
+ skip: process.platform === 'win32',
+ }, async (t) => {
+ const root = await mkdtemp(join(tmpdir(), 'maka-tui-mcp-commit-unknown-'));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const store = createMcpConfigStore(root);
+ await store.upsert('docs', { url: 'https://old.example/mcp' });
+ const previous = await store.get();
+ let activeConfig = structuredClone(previous);
+ const statuses = [connectedStatus('docs', 1)];
+ const manager = managerHarness(1, statuses);
+ const connection = connectionHarness();
+ const fenceError = new Error('injected post-rename directory sync failure');
+ const reconciliationError = new Error('injected reconciliation failure');
+ let failing = false;
+ let transforms = 0;
+ let reloads = 0;
+ let synchronizations = 0;
+ let retirements = 0;
+ let revision = 1;
+ let writeError: unknown;
+ manager.manager.sync = async (config) => {
+ synchronizations += 1;
+ if (failing && scenario === 'sync-failure') throw reconciliationError;
+ activeConfig = structuredClone(config);
+ statuses.splice(
+ 0,
+ statuses.length,
+ ...Object.keys(config.mcpServers).map((id) => connectedStatus(id, 1)),
+ );
+ manager.changeRevision(++revision, statuses.length);
+ };
+ manager.manager.forgetServerCredentials = async () => {
+ retirements += 1;
+ };
+ const controller = createTuiMcpController(
+ { workspaceRoot: root, connection: connection.connection },
+ {
+ configStore: {
+ get: async () => {
+ reloads += 1;
+ if (failing && scenario === 'read-failure') throw reconciliationError;
+ return store.get();
+ },
+ transform: async (apply) => {
+ transforms += 1;
+ try {
+ return await store.transform(apply);
+ } catch (error) {
+ writeError = error;
+ if (scenario === 'newer-config') {
+ // Another writer commits after the failed transform releases
+ // its lock, before this caller reloads the authority.
+ await store.upsert('external', { command: 'concurrent-server' });
+ }
+ throw error;
+ }
+ },
+ },
+ manager: manager.manager,
+ createProvider: (current) =>
+ current.toolSnapshot().tools.length === 0 ? undefined : provider('docs'),
+ },
+ );
+ t.after(() => controller.close());
+ await waitFor(
+ () => controller.snapshot().publication === 'published',
+ 'initial MCP publication before injected directory sync failure',
+ );
+ synchronizations = 0;
+ reloads = 0;
+ const originalOpen = fs.open;
+ let failedFences = 0;
+ t.mock.method(fs, 'open', async (...args: Parameters<typeof fs.open>) => {
+ const handle = await originalOpen(...args);
+ if (args[0] === root && args[1] === 'r' && failedFences === 0) {
+ t.mock.method(handle, 'sync', async () => {
+ failedFences += 1;
+ throw fenceError;
+ });
+ }
+ return handle;
+ });
+ syncBuiltinESMExports();
+ t.after(() => {
+ t.mock.restoreAll();
+ syncBuiltinESMExports();
+ });
+ failing = true;
+ if (scenario === 'publication-failure') {
+ connection.replace = async () => {
+ throw reconciliationError;
+ };
+ }
+ const edit = controller.configForEdit('docs');
+ assert.ok(edit);
+ const result = await controller.execute(
+ scenario === 'edit' || scenario === 'publication-failure'
+ ? {
+ kind: 'edit',
+ serverId: 'docs',
+ expectedRevision: edit.revision,
+ config: { url: 'https://new.example/mcp' },
+ }
+ : { kind: 'remove', serverId: 'docs' },
+ );
+
+ assert.equal(result.status, 'failed');
+ if (result.status !== 'failed' || result.reason !== 'commit-unknown') {
+ assert.fail('published write must retain its uncertain durability result');
+ }
+ assert.equal(result.cause, writeError);
+ assert.ok(result.cause instanceof AtomicFileWriteCommitUnknownError);
+ assert.equal(result.cause.published, true);
+ assert.equal(result.cause.cause, fenceError);
+ assert.equal(failedFences, 1);
+ assert.equal(transforms, 1);
+ assert.equal(retirements, 1);
+ assert.equal(reloads, 1);
+ const published = JSON.parse(await readFile(join(root, 'mcp.json'), 'utf8')) as McpConfigFile;
+ if (scenario === 'edit' || scenario === 'publication-failure') {
+ assert.equal((published.mcpServers.docs as { url: string }).url, 'https://new.example/mcp');
+ } else if (scenario === 'newer-config') {
+ assert.deepEqual(Object.keys(published.mcpServers), ['external']);
+ assert.equal(
+ (published.mcpServers.external as { command: string }).command,
+ 'concurrent-server',
+ );
+ } else {
+ assert.deepEqual(published.mcpServers, {});
+ }
+ if (scenario === 'read-failure' || scenario === 'sync-failure') {
+ assert.equal(result.reconciliationError, reconciliationError);
+ assert.equal(controller.snapshot().configuration, 'out_of_sync');
+ assert.ok(controller.snapshot().servers.every((server) => !server.synchronized));
+ assert.deepEqual(activeConfig, previous);
+ assert.equal(synchronizations, scenario === 'read-failure' ? 0 : 1);
+ } else {
+ assert.deepEqual(activeConfig, published);
+ assert.equal(synchronizations, 1);
+ assert.equal(controller.snapshot().configuration, 'ready');
+ if (scenario === 'remove') {
+ assert.equal(controller.configForEdit('docs'), undefined);
+ assert.deepEqual(controller.snapshot().servers, []);
+ assert.equal(controller.snapshot().publication, 'not_published');
+ assert.equal(connection.unregisters, 1);
+ } else if (scenario === 'newer-config') {
+ assert.equal(controller.configForEdit('docs'), undefined);
+ assert.deepEqual(
+ controller.configForEdit('external')?.config,
+ published.mcpServers.external,
+ );
+ assert.deepEqual(
+ controller.snapshot().servers.map((server) => server.serverId),
+ ['external'],
+ );
+ assert.equal(controller.snapshot().servers[0]?.synchronized, true);
+ assert.equal(controller.snapshot().publication, 'published');
+ assert.equal(connection.replacements.length, 2);
+ } else {
+ assert.deepEqual(controller.configForEdit('docs')?.config, published.mcpServers.docs);
+ assert.equal(controller.snapshot().servers[0]?.synchronized, true);
+ assert.equal(
+ controller.snapshot().publication,
+ scenario === 'publication-failure' ? 'error' : 'published',
+ );
+ if (scenario === 'edit') assert.equal(connection.replacements.length, 2);
+ }
+ }
+ });
+}
+
+test('TUI MCP does not reconcile or replay a write that fails before publication', async (t) => {
+ const initial: McpConfigFile = { version: 3, mcpServers: { docs: { command: 'server' } } };
+ let reads = 0;
+ let transforms = 0;
+ const manager = managementManager([]);
+ const controller = createTuiMcpController(
+ { workspaceRoot: '/unused', connection: connectionHarness().connection },
+ {
+ configStore: {
+ get: async () => {
+ reads += 1;
+ return initial;
+ },
+ transform: async () => {
+ transforms += 1;
+ throw new Error('temporary file write failed');
+ },
+ },
+ manager: manager.manager,
+ createProvider: () => undefined,
+ },
+ );
+ t.after(() => controller.close());
+ await waitFor(() => controller.snapshot().initialization === 'ready', 'MCP initialization');
+ assert.deepEqual(await controller.execute({ kind: 'remove', serverId: 'docs' }), {
+ status: 'failed',
+ reason: 'persist-failed',
+ });
+ assert.equal(reads, 1);
+ assert.equal(transforms, 1);
+ assert.deepEqual(controller.configForEdit('docs')?.config, initial.mcpServers.docs);
+ assert.equal(controller.snapshot().configuration, 'ready');
+});
+
+test('TUI MCP close fences reconciliation while retaining the published write error', async () => {
+ const initial: McpConfigFile = { version: 3, mcpServers: { docs: { command: 'server' } } };
+ const reload = deferredValue<McpConfigFile>();
+ const writeError = new AtomicFileWriteCommitUnknownError({ cause: new Error('directory sync') });
+ let reads = 0;
+ const order: string[] = [];
+ const manager = managementManager(order);
+ const controller = createTuiMcpController(
+ { workspaceRoot: '/unused', connection: connectionHarness().connection },
+ {
+ configStore: {
+ get: async () => (++reads === 1 ? initial : reload.promise),
+ transform: async () => {
+ throw writeError;
+ },
+ },
+ manager: manager.manager,
+ createProvider: () => undefined,
+ },
+ );
+ await waitFor(() => controller.snapshot().initialization === 'ready', 'MCP initialization');
+ order.length = 0;
+ const executing = controller.execute({ kind: 'remove', serverId: 'docs' });
+ await waitFor(() => reads === 2, 'authoritative reload before closing');
+ const closing = controller.close();
+ reload.resolve(emptyConfig());
+ assert.deepEqual(await executing, {
+ status: 'failed',
+ reason: 'commit-unknown',
+ cause: writeError,
+ });
+ await closing;
+ assert.deepEqual(order, []);
+ assert.equal(controller.configForEdit('docs'), undefined);
+});
+
test('TUI MCP reports a committed action as pending while the Host is unavailable', async () => {
const order: string[] = [];
const store = mutableConfigStore(emptyConfig(), order);
diff --git a/packages/cli/src/tui-copy-catalog.ts b/packages/cli/src/tui-copy-catalog.ts
index 2a47b36284..9272b0b0c1 100644
--- a/packages/cli/src/tui-copy-catalog.ts
+++ b/packages/cli/src/tui-copy-catalog.ts
@@ -355,6 +355,8 @@ export const TUI_COPY_RESOURCES = {
'publication-credential-failed':
'The provider credential could not be stored or applied.',
'persist-failed': 'The configuration could not be saved.',
+ 'commit-unknown':
+ 'Configuration published; crash durability is uncertain. Check synchronization before retrying.',
'manager-failed': 'The MCP connection action failed.',
turn_active: 'MCP cannot be changed while a turn or another control action is running.',
invalid: 'Check the value and try again.',
@@ -454,6 +456,7 @@ export const TUI_COPY_RESOURCES = {
'credential-cleanup-failed': '无法删除旧凭据,配置未修改。',
'publication-credential-failed': '无法保存或应用 Provider 凭据。',
'persist-failed': '无法保存配置。',
+ 'commit-unknown': '配置已发布,但无法确认崩溃后的持久性。请先检查同步状态再重试。',
'manager-failed': 'MCP 连接操作失败。',
turn_active: 'Turn 或其他控制操作运行期间不能修改 MCP。',
invalid: '请检查输入后重试。',
@@ -554,6 +557,7 @@ export const TUI_COPY_RESOURCES = {
'credential-cleanup-failed': '無法移除已儲存的認證資料;設定未變更。',
'publication-credential-failed': '無法儲存或套用 Provider 認證資料。',
'persist-failed': '無法儲存設定。',
+ 'commit-unknown': '設定已發布,但無法確認當機後的持久性。請先檢查同步狀態再重試。',
'manager-failed': 'MCP 連線操作失敗。',
turn_active: 'Turn 或其他控制操作執行期間無法修改 MCP。',
invalid: '請檢查輸入後重試。',
@@ -653,7 +657,7 @@ export const TUI_COPY_RESOURCES = {
en: {
modelPickerTitle: 'Select Model',
modelSwitchCacheWarning:
- '⚠ Switching models may rebuild the prompt cache; the next request may be slower or cost more.',
+ '\u26a0 Switching models may rebuild the prompt cache; the next request may be slower or cost more.',
modelSearchHint:
'Search models / providers / connections · ↑↓ select · Enter confirm · Esc cancel',
searchLabel: 'Search',
@@ -759,7 +763,8 @@ export const TUI_COPY_RESOURCES = {
},
'zh-CN': {
modelPickerTitle: '选择模型',
- modelSwitchCacheWarning: '⚠ 切换模型可能需要重建提示缓存;下一次请求可能更慢或成本更高。',
+ modelSwitchCacheWarning:
+ '\u26a0 切换模型可能需要重建提示缓存;下一次请求可能更慢或成本更高。',
modelSearchHint: '搜索模型 / 服务商 / 连接 · ↑↓ 选择 · Enter 确认 · Esc 取消',
searchLabel: '搜索',
noMatchingModels: '没有匹配的模型',
@@ -854,7 +859,8 @@ export const TUI_COPY_RESOURCES = {
},
'zh-TW': {
modelPickerTitle: '選擇模型',
- modelSwitchCacheWarning: '⚠ 切換模型可能需要重建提示快取;下一次請求可能較慢或成本較高。',
+ modelSwitchCacheWarning:
+ '\u26a0 切換模型可能需要重建提示快取;下一次請求可能較慢或成本較高。',
modelSearchHint: '搜尋模型 / 服務商 / 連線 · ↑↓ 選擇 · Enter 確認 · Esc 取消',
searchLabel: '搜尋',
noMatchingModels: '沒有符合的模型',
diff --git a/packages/cli/src/tui-mcp-control.ts b/packages/cli/src/tui-mcp-control.ts
index e0df998355..31dac5580f 100644
--- a/packages/cli/src/tui-mcp-control.ts
+++ b/packages/cli/src/tui-mcp-control.ts
@@ -32,6 +32,7 @@ import {
import { createCredentialMcpOAuthStorage, McpClientManager } from '@maka/mcp';
import { createFileCredentialStore } from '@maka/storage/credential-store';
import {
+ AtomicFileWriteCommitUnknownError,
createMcpConfigStore,
assertMcpEndpointPolicyOnChanges,
McpConfigSourceError,
@@ -137,6 +138,12 @@ export type TuiMcpActionEffect =
export type TuiMcpActionResult =
| { readonly status: 'applied'; readonly effect: TuiMcpActionEffect }
| { readonly status: 'tested'; readonly test: McpTestResult; readonly effect: TuiMcpActionEffect }
+ | {
+ readonly status: 'failed';
+ readonly reason: 'commit-unknown';
+ readonly cause: AtomicFileWriteCommitUnknownError;
+ readonly reconciliationError?: unknown;
+ }
| {
readonly status: 'conflict';
readonly reason: 'exists' | 'stale_config' | 'stale_edit' | 'stale_import' | 'missing';
@@ -495,9 +502,49 @@ class TuiMcpControllerImpl implements TuiMcpController {
});
} catch (error) {
if (error instanceof TuiMcpMutationError) return error.result;
+ if (error instanceof AtomicFileWriteCommitUnknownError) {
+ // The transform has already published, including any credential
+ // retirement. Reload its authority; never replay those effects.
+ this.#preparedImport = undefined;
+ let reconciliationError: unknown;
+ if (!this.#closed) {
+ try {
+ ({ reconciliationError } = await this.#synchronizeCommittedConfig(
+ await this.#deps.configStore.get(),
+ ));
+ } catch (failure) {
+ reconciliationError = failure;
+ this.#publicationSuppressed = false;
+ this.#snapshot = freezeSnapshot({
+ ...this.#snapshot,
+ configuration: 'out_of_sync',
+ servers: this.#snapshot.servers.map((server) => ({
+ ...server,
+ synchronized: false,
+ })),
+ });
+ this.#notify();
+ }
+ }
+ // Reconciliation does not establish the missing durability fence,
+ // and its own failure must not replace the original write error.
+ return {
+ status: 'failed',
+ reason: 'commit-unknown',
+ cause: error,
+ ...(reconciliationError === undefined ? {} : { reconciliationError }),
+ };
+ }
return { status: 'failed', reason: 'persist-failed' };
}
- if (this.#closed) return { status: 'failed', reason: 'closed' };
+ return (await this.#synchronizeCommittedConfig(committed)).result;
+ }
+
+ async #synchronizeCommittedConfig(committed: McpConfigFile): Promise<{
+ readonly result: TuiMcpActionResult;
+ readonly reconciliationError?: unknown;
+ }> {
+ if (this.#closed) return { result: { status: 'failed', reason: 'closed' } };
this.#preparedImport = undefined;
this.#config = cloneConfig(committed);
this.#updateSnapshot({ configuration: 'synchronizing' });
@@ -505,18 +552,18 @@ class TuiMcpControllerImpl implements TuiMcpController {
this.#publicationSuppressed = true;
try {
await this.#deps.manager.sync(committed);
- } catch {
+ } catch (error) {
this.#publicationSuppressed = false;
this.#updateSnapshot({ configuration: 'out_of_sync' });
this.#refreshManagerSnapshot();
await this.#settlePublication();
- return { status: 'applied', effect: 'sync_failed' };
+ return { result: { status: 'applied', effect: 'sync_failed' }, reconciliationError: error };
}
this.#publicationSuppressed = false;
- if (this.#closed) return { status: 'failed', reason: 'closed' };
+ if (this.#closed) return { result: { status: 'failed', reason: 'closed' } };
this.#updateSnapshot({ configuration: 'ready' });
this.#refreshManagerSnapshot();
- return { status: 'applied', effect: await this.#settlePublication() };
+ return { result: { status: 'applied', effect: await this.#settlePublication() } };
}
#prepareMutation(
diff --git a/packages/storage/src/__tests__/atomic-file-write.test.ts b/packages/storage/src/__tests__/atomic-file-write.test.ts
new file mode 100644
index 0000000000..9427351753
--- /dev/null
+++ b/packages/storage/src/__tests__/atomic-file-write.test.ts
@@ -0,0 +1,249 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import assert from 'node:assert/strict';
+import {
+ lstat,
+ mkdtemp,
+ open,
+ readdir,
+ readFile,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, test } from 'node:test';
+import {
+ AtomicFileWriteCommitUnknownError,
+ writeAtomicFile,
+ type AtomicFileWriteDependencies,
+ type AtomicFileWriteHandle,
+} from '../atomic-file-write.js';
+
+const isPosix = process.platform !== 'win32';
+const ownerOnlyFile = { fileMode: 0o600 } as const;
+
+async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
+ const dir = await mkdtemp(join(tmpdir(), 'maka-atomic-write-'));
+ try {
+ return await fn(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+describe('writeAtomicFile', () => {
+ test('writes the exact bytes and leaves no temp file behind', async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ await writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile);
+ assert.equal(await readFile(path, 'utf8'), '{"a":1}\n');
+ assert.deepEqual(await readdir(dir), ['settings.json']);
+ });
+ });
+
+ for (const failurePhase of ['write', 'sync', 'close'] as const) {
+ test(`removes its temp file and rethrows after a ${failurePhase} failure`, async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ const temporaryPath = join(dir, '.settings.json.fault.tmp');
+ const fault = new Error(`${failurePhase} failed`);
+ await assert.rejects(
+ () =>
+ writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile, {
+ randomUUID: () => 'fault',
+ open: faultingOpen(temporaryPath, failurePhase, fault),
+ }),
+ fault,
+ );
+ assert.deepEqual(await readdir(dir), []);
+ });
+ });
+ }
+
+ test('removes its temp file and rethrows after a chmod failure', {
+ skip: process.platform === 'win32',
+ }, async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ const temporaryPath = join(dir, '.settings.json.fault.tmp');
+ const fault = new Error('chmod failed');
+ await assert.rejects(
+ () =>
+ writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile, {
+ randomUUID: () => 'fault',
+ open: faultingOpen(temporaryPath, 'chmod', fault),
+ }),
+ fault,
+ );
+ assert.deepEqual(await readdir(dir), []);
+ });
+ });
+
+ test('sets the final mode before synchronizing the temp file', async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ const phases: string[] = [];
+ await writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile, {
+ open: async (temporaryPath, flags, mode) => {
+ const handle = await open(temporaryPath, flags, mode);
+ return {
+ writeFile: async (data, encoding) => {
+ phases.push('write');
+ await handle.writeFile(data, encoding);
+ },
+ chmod: async (nextMode) => {
+ phases.push('chmod');
+ await handle.chmod(nextMode);
+ },
+ sync: async () => {
+ phases.push('sync');
+ await handle.sync();
+ },
+ close: async () => {
+ phases.push('close');
+ await handle.close();
+ },
+ };
+ },
+ syncDirectory: async () => {
+ phases.push('sync-directory');
+ },
+ });
+ assert.deepEqual(
+ phases,
+ isPosix
+ ? ['write', 'chmod', 'sync', 'close', 'sync-directory']
+ : ['write', 'sync', 'close', 'sync-directory'],
+ );
+ });
+ });
+
+ test('reports an unknown commit outcome when directory fsync fails after publication', async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ const fault = new Error('dirsync failed');
+ await assert.rejects(
+ () =>
+ writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile, {
+ syncDirectory: async () => {
+ throw fault;
+ },
+ }),
+ (error: unknown) => {
+ assert.ok(error instanceof AtomicFileWriteCommitUnknownError);
+ assert.equal(error.published, true);
+ assert.equal(error.cause, fault);
+ assert.match(error.message, /reload before retrying/);
+ return true;
+ },
+ );
+ // rename is the commit point: the replacement is live (readers get the
+ // new bytes) even though its durability is not known to the caller.
+ assert.equal(await readFile(path, 'utf8'), '{"a":1}\n');
+ assert.deepEqual(await readdir(dir), ['settings.json']);
+ });
+ });
+
+ test('creates the target 0600 on POSIX', { skip: process.platform === 'win32' }, async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ await writeAtomicFile(path, '{}\n', ownerOnlyFile);
+ assert.equal((await stat(path)).mode & 0o777, 0o600);
+ });
+ });
+
+ test('re-chmods a pre-existing world-readable target to 0600 on the next write', {
+ skip: process.platform === 'win32',
+ }, async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'settings.json');
+ // A file created with a loose mode by an older writer.
+ await writeFile(path, '{}\n', { encoding: 'utf8', mode: 0o644 });
+ await writeAtomicFile(path, '{"a":1}\n', ownerOnlyFile);
+ assert.equal((await stat(path)).mode & 0o777, 0o600);
+ assert.equal(await readFile(path, 'utf8'), '{"a":1}\n');
+ });
+ });
+
+ test('refuses to write through a pre-planted symlink at the temp path', {
+ skip: process.platform === 'win32',
+ }, async () => {
+ await withTempDir(async (dir) => {
+ const path = join(dir, 'credentials.json');
+ const plantedTarget = join(dir, 'planted-target.json');
+ await writeFile(plantedTarget, 'do not touch\n', 'utf8');
+ // The injected randomUUID makes the unpredictable temp path knowable,
+ // which is exactly the attacker model 'wx'/O_EXCL answers.
+ const plantedTemp = join(dir, '.credentials.json.planted.tmp');
+ await symlink(plantedTarget, plantedTemp);
+ await assert.rejects(
+ () => writeAtomicFile(path, '{}\n', ownerOnlyFile, { randomUUID: () => 'planted' }),
+ { code: 'EEXIST' },
+ );
+ assert.equal(await readFile(plantedTarget, 'utf8'), 'do not touch\n');
+ assert.equal(await stat(path).catch(() => null), null);
+ // Cleanup removes only what the writer created: the planted entry is
+ // still a symlink, exactly where it was.
+ assert.equal((await lstat(plantedTemp)).isSymbolicLink(), true);
+ });
+ });
+});
+
+function faultingOpen(
+ temporaryPath: string,
+ failurePhase: 'write' | 'chmod' | 'sync' | 'close',
+ fault: Error,
+): AtomicFileWriteDependencies['open'] {
+ return async (path, flags, mode) => {
+ const handle = await open(path, flags, mode);
+ if (path !== temporaryPath) return handle;
+
+ let closeFailed = false;
+ const wrapped: AtomicFileWriteHandle = {
+ writeFile: async (data, encoding) => {
+ if (failurePhase === 'write') {
+ await handle.writeFile(data.slice(0, 1), encoding);
+ throw fault;
+ }
+ await handle.writeFile(data, encoding);
+ },
+ chmod: async (mode) => {
+ if (failurePhase === 'chmod') throw fault;
+ await handle.chmod(mode);
+ },
+ sync: async () => {
+ if (failurePhase === 'sync') throw fault;
+ await handle.sync();
+ },
+ close: async () => {
+ if (failurePhase === 'close' && !closeFailed) {
+ closeFailed = true;
+ await handle.close();
+ throw fault;
+ }
+ await handle.close();
+ },
+ };
+ return wrapped;
+ };
+}
diff --git a/packages/storage/src/__tests__/credential-store.test.ts b/packages/storage/src/__tests__/credential-store.test.ts
index 9f6e195a3b..4f577f8b98 100644
--- a/packages/storage/src/__tests__/credential-store.test.ts
+++ b/packages/storage/src/__tests__/credential-store.test.ts
@@ -144,9 +144,9 @@ describe('FileCredentialStore', () => {
await chmod(dir, 0o777); // a loose dir that predates the hardening
const store = createFileCredentialStore(dir);
await store.setSecret('a', 'api_key', 'k');
- // ensureSecretDir re-chmods an existing dir (mkdir's mode only applies on
- // creation); the writer and the lock share it, so the lock can't leave
- // the dir loose either.
+ // hardenDirectory re-chmods an existing dir (mkdir's mode only applies
+ // on creation); the writer and the lock share it, so the lock can't
+ // leave the dir loose either.
assert.equal((await stat(dir)).mode & 0o777, 0o700);
});
});
diff --git a/packages/storage/src/__tests__/mcp-config-store.test.ts b/packages/storage/src/__tests__/mcp-config-store.test.ts
index faff8d4dab..cf9fa323a1 100644
--- a/packages/storage/src/__tests__/mcp-config-store.test.ts
+++ b/packages/storage/src/__tests__/mcp-config-store.test.ts
@@ -19,7 +19,7 @@
import assert from 'node:assert/strict';
import { fork } from 'node:child_process';
-import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
+import { mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, test } from 'node:test';
@@ -58,6 +58,15 @@ test('creates and atomically updates a Claude-compatible mcp.json', async () =>
assert.deepEqual((await store.get()).mcpServers, {});
});
+test('leaves no temp file behind after writes', async () => {
+ const root = await tempRoot();
+ const store = createMcpConfigStore(root);
+ await store.upsert('filesystem', { command: 'npx', args: ['-y', 'server'] });
+ await store.remove('filesystem');
+ const strays = (await readdir(root)).filter((entry) => entry.endsWith('.tmp'));
+ assert.deepEqual(strays, []);
+});
+
test('reads version 1 without rewriting and persists version 3 on the next mutation', async () => {
const root = await tempRoot();
const path = join(root, 'mcp.json');
diff --git a/packages/storage/src/__tests__/settings-store-onboarding.test.ts b/packages/storage/src/__tests__/settings-store-onboarding.test.ts
index 525b41af13..7a99587d7e 100644
--- a/packages/storage/src/__tests__/settings-store-onboarding.test.ts
+++ b/packages/storage/src/__tests__/settings-store-onboarding.test.ts
@@ -30,7 +30,7 @@
import { strict as assert } from 'node:assert';
import { describe, it } from 'node:test';
-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createSettingsStore } from '../settings-store.js';
@@ -359,4 +359,26 @@ describe('SettingsStore.get file recovery', () => {
await rm(workspaceRoot, { recursive: true, force: true });
}
});
+
+ it('preserves a restrictive umask-derived settings.json mode and leaves no temp file behind', {
+ skip: process.platform === 'win32',
+ }, async () => {
+ const workspaceRoot = await mkdtemp(join(tmpdir(), 'maka-settings-mode-'));
+ const previousUmask = process.umask(0o027);
+ try {
+ const store = createSettingsStore(workspaceRoot);
+
+ await store.get(); // first run writes the defaults
+
+ assert.deepEqual(await readdir(workspaceRoot), ['settings.json']);
+ assert.equal(
+ (await stat(join(workspaceRoot, 'settings.json'))).mode & 0o777,
+ 0o640,
+ 'settings.json retains the mode produced by the legacy default and current umask',
+ );
+ } finally {
+ process.umask(previousUmask);
+ await rm(workspaceRoot, { recursive: true, force: true });
+ }
+ });
});
diff --git a/packages/storage/src/__tests__/stable-storage.test.ts b/packages/storage/src/__tests__/stable-storage.test.ts
index 8f4f715242..9d91e3bd3c 100644
--- a/packages/storage/src/__tests__/stable-storage.test.ts
+++ b/packages/storage/src/__tests__/stable-storage.test.ts
@@ -18,11 +18,23 @@
*/
import assert from 'node:assert/strict';
-import { appendFile, lstat, mkdtemp, open, rename, rm, symlink, writeFile } from 'node:fs/promises';
+import {
+ appendFile,
+ chmod,
+ lstat,
+ mkdir,
+ mkdtemp,
+ open,
+ rename,
+ rm,
+ stat,
+ symlink,
+ writeFile,
+} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
-import { readStableBoundedFile } from '../stable-storage.js';
+import { hardenDirectory, readStableBoundedFile } from '../stable-storage.js';
async function fixture(t: test.TestContext) {
const directory = await mkdtemp(join(tmpdir(), 'maka-stable-file-'));
@@ -99,3 +111,24 @@ test('rejects a pathname replaced after opening the file', async (t) => {
/invalid stable file/u,
);
});
+
+test('hardenDirectory creates a 0700 directory chain', {
+ skip: process.platform === 'win32',
+}, async (t) => {
+ const { directory } = await fixture(t);
+ const targetDir = join(directory, 'secrets', 'sub');
+ await hardenDirectory(targetDir);
+ assert.equal((await stat(join(directory, 'secrets'))).mode & 0o777, 0o700);
+ assert.equal((await stat(targetDir)).mode & 0o777, 0o700);
+});
+
+test('hardenDirectory re-chmods a pre-existing world-accessible directory to 0700', {
+ skip: process.platform === 'win32',
+}, async (t) => {
+ const { directory } = await fixture(t);
+ const loose = join(directory, 'loose');
+ await mkdir(loose, { recursive: true, mode: 0o777 });
+ await chmod(loose, 0o777); // mkdir's mode only applies on creation
+ await hardenDirectory(loose);
+ assert.equal((await stat(loose)).mode & 0o777, 0o700);
+});
diff --git a/packages/storage/src/atomic-file-write.ts b/packages/storage/src/atomic-file-write.ts
new file mode 100644
index 0000000000..f6a6320fb8
--- /dev/null
+++ b/packages/storage/src/atomic-file-write.ts
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { randomUUID } from 'node:crypto';
+import { open, rename, rm } from 'node:fs/promises';
+import { basename, dirname, join } from 'node:path';
+import { syncDirectory } from './stable-storage.js';
+
+/**
+ * Atomic writer shared by the legacy settings, MCP, and credentials JSON
+ * stores. It publishes an exclusive hidden temp file with rename and removes
+ * that temp on failures before publication.
+ *
+ * Durability support depends on the platform and storage stack:
+ * - Linux and POSIX systems other than macOS: sync the temp file before
+ * rename and fsync the parent directory afterwards. Persistence still
+ * depends on the filesystem, mount, device, and hardware honoring them.
+ * - macOS: use Node's ordinary fsync operations; Node does not expose
+ * F_FULLFSYNC here, so this is not a uniform sudden-power-loss guarantee.
+ * - Windows: sync the temp file before rename, but parent-directory sync is a
+ * no-op because Node does not provide an equivalent directory fence.
+ *
+ * The caller owns the final file-mode policy. The writer applies that mode
+ * through the open handle before synchronization, fail-loud on POSIX and
+ * skipped on Windows (no POSIX mode). Callers may supply an exact private mode
+ * or one already derived from the process umask.
+ * Directory creation and permission policy belong to each caller.
+ */
+
+export interface AtomicFileWriteOptions {
+ /** Effective mode to apply to the temporary file before it is synchronized
+ * and published. */
+ fileMode: number;
+}
+
+/** The fs surface `writeAtomicFile` needs; injectable for fault-injection
+ * tests (same pattern as marker-file.ts). */
+export interface AtomicFileWriteHandle {
+ writeFile(data: string, encoding: 'utf8'): Promise<void>;
+ chmod(mode: number): Promise<void>;
+ sync(): Promise<void>;
+ close(): Promise<void>;
+}
+
+export interface AtomicFileWriteDependencies {
+ open(path: string, flags: string, mode?: number): Promise<AtomicFileWriteHandle>;
+ randomUUID(): string;
+ syncDirectory(path: string): Promise<void>;
+}
+
+const defaultDependencies: AtomicFileWriteDependencies = {
+ open,
+ randomUUID,
+ syncDirectory,
+};
+
+export class AtomicFileWriteCommitUnknownError extends Error {
+ readonly published = true;
+
+ constructor(options: { cause: unknown }) {
+ super('Atomic file commit outcome is unknown; reload before retrying', options);
+ this.name = 'AtomicFileWriteCommitUnknownError';
+ }
+}
+
+export async function writeAtomicFile(
+ path: string,
+ contents: string,
+ options: AtomicFileWriteOptions,
+ dependencies: Partial<AtomicFileWriteDependencies> = {},
+): Promise<void> {
+ const deps = { ...defaultDependencies, ...dependencies };
+ const { fileMode } = options;
+ const tempPath = join(dirname(path), `.${basename(path)}.${deps.randomUUID()}.tmp`);
+ // Only the entry this call created — and hasn't renamed away — may be
+ // cleaned up. A pre-existing file or planted symlink the 'wx' open refused
+ // must not be deleted as "our" temp.
+ let tempCreated = false;
+ let published = false;
+ try {
+ const handle = await deps.open(tempPath, 'wx', fileMode);
+ tempCreated = true;
+ try {
+ await handle.writeFile(contents, 'utf8');
+ if (process.platform !== 'win32') await handle.chmod(fileMode);
+ await handle.sync();
+ await handle.close();
+ } catch (error) {
+ // Release the descriptor best-effort; never let a close failure mask
+ // the error that actually aborted the write.
+ await handle.close().catch(() => {});
+ throw error;
+ }
+ await rename(tempPath, path);
+ published = true;
+ tempCreated = false;
+ await deps.syncDirectory(dirname(path));
+ } catch (error) {
+ if (tempCreated) {
+ // Cleanup must never mask the original failure.
+ await rm(tempPath, { force: true }).catch(() => {});
+ }
+ if (published) throw new AtomicFileWriteCommitUnknownError({ cause: error });
+ throw error;
+ }
+}
diff --git a/packages/storage/src/credential-store.ts b/packages/storage/src/credential-store.ts
index 325227e8d5..1998bba41c 100644
--- a/packages/storage/src/credential-store.ts
+++ b/packages/storage/src/credential-store.ts
@@ -17,10 +17,11 @@
* under the License.
*/
-import { randomUUID } from 'node:crypto';
-import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
+import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
+import { writeAtomicFile } from './atomic-file-write.js';
import { withFileUpdateLock } from './file-update-lock.js';
+import { hardenDirectory } from './stable-storage.js';
/**
* Pure-Node credential store. Shared by the desktop app and any
@@ -242,67 +243,14 @@ class FileCredentialStore implements CredentialStore {
}
/**
- * Create (or harden) the directory that holds a secret file: 0700, and
- * re-chmod a pre-existing looser dir so neither the secret nor the lock can sit
- * world-readable. mkdir's mode only applies on creation, so the chmod is what
- * fixes an existing dir. On POSIX a chmod failure fails closed (we must not
- * write plaintext credentials into a dir we couldn't lock down); no-op on
- * Windows. Shared by the writer and the lock so their dir hardening can't drift.
- */
-async function ensureSecretDir(dir: string): Promise<void> {
- await mkdir(dir, { recursive: true, mode: 0o700 });
- await chmodStrict(dir, 0o700);
-}
-
-/**
- * Owner-only atomic write for a credentials file: a 0700 dir, an exclusive
- * 0600 temp ('wx'/O_EXCL so we never follow a pre-planted symlink at a
- * predictable path), a durability fence before and after the atomic rename,
- * and temp cleanup on failure.
+ * Owner-only atomic write for a credentials file. Directory hardening is an
+ * explicit credential-store policy; file publication uses the shared legacy
+ * JSON writer so its mode, synchronization, and cleanup behavior remains
+ * aligned with settings and MCP config.
*/
async function writeSecretFileAtomic(path: string, contents: string): Promise<void> {
- await ensureSecretDir(dirname(path));
- const tempPath = `${path}.${randomUUID()}.tmp`;
- try {
- const handle = await open(tempPath, 'wx', 0o600);
- try {
- await handle.writeFile(contents, 'utf8');
- await handle.sync();
- } finally {
- await handle.close();
- }
- await chmodStrict(tempPath, 0o600);
- await rename(tempPath, path);
- await syncDirectory(dirname(path));
- } catch (error) {
- await rm(tempPath, { force: true });
- throw error;
- }
-}
-
-async function syncDirectory(path: string): Promise<void> {
- if (process.platform === 'win32') return;
- const handle = await open(path, 'r');
- try {
- await handle.sync();
- } finally {
- await handle.close();
- }
-}
-
-/**
- * chmod that fails loud on POSIX and is best-effort on Windows. A secret file
- * or its directory left looser than intended breaks the 0600/0700 boundary, so
- * on POSIX we surface the failure rather than write plaintext into it; Windows
- * has no POSIX mode, so a failure there is a no-op. One policy for both the
- * secret file (0600) and its directory (0700) so they can't drift apart.
- */
-async function chmodStrict(path: string, mode: number): Promise<void> {
- if (process.platform === 'win32') {
- await chmod(path, mode).catch(() => {});
- return;
- }
- await chmod(path, mode);
+ await hardenDirectory(dirname(path));
+ await writeAtomicFile(path, contents, { fileMode: 0o600 });
}
const LOCK_TIMEOUT_MS = 10_000;
@@ -338,7 +286,9 @@ export async function withCredentialFileLock<T>(
fn: () => Promise<T>,
timeoutMs: number = LOCK_TIMEOUT_MS,
): Promise<T> {
- await ensureSecretDir(dirname(targetPath));
+ // Same owner-only hardening the writer applies, so the lock directory can
+ // never sit looser than the secret it guards.
+ await hardenDirectory(dirname(targetPath));
return withFileUpdateLock(targetPath, fn, timeoutMs);
}
diff --git a/packages/storage/src/mcp-config-store.ts b/packages/storage/src/mcp-config-store.ts
index c362d86eda..afadeb316c 100644
--- a/packages/storage/src/mcp-config-store.ts
+++ b/packages/storage/src/mcp-config-store.ts
@@ -17,8 +17,7 @@
* under the License.
*/
-import { randomUUID } from 'node:crypto';
-import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
+import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import {
MCP_CONFIG_VERSION,
@@ -32,7 +31,13 @@ import {
type McpServerConfig,
type McpStdioServerConfig,
} from '@maka/core/mcp';
+import { writeAtomicFile } from './atomic-file-write.js';
import { withProcessLifetimeFileUpdateLock } from './process-lifetime-file-update-lock.js';
+import { hardenDirectory } from './stable-storage.js';
+
+// Consumers reconcile an already-published write through this store's public
+// boundary; the shared atomic writer itself remains internal to storage.
+export { AtomicFileWriteCommitUnknownError } from './atomic-file-write.js';
const MAX_SERVERS = 100;
const MAX_ID_LENGTH = 128;
@@ -45,7 +50,10 @@ export interface McpConfigStore {
/** One cross-process read-transform-write transaction. `apply` sees the
* current on-disk config and may finish asynchronous effects that must
* precede the commit, such as retiring credentials. The shared file lock
- * remains held until the replacement document is durable. */
+ * remains held until the write settles. A write can fail after publication
+ * with AtomicFileWriteCommitUnknownError when durability is unconfirmed:
+ * reload with get() and reconcile consumers before considering a retry.
+ * Never blindly replay apply, whose effects may already have happened. */
transform(
apply: (current: McpConfigFile) => McpConfigFile | Promise<McpConfigFile>,
): Promise<McpConfigFile>;
@@ -195,30 +203,15 @@ class FileMcpConfigStore implements McpConfigStore {
}
private async write(config: McpConfigFile): Promise<void> {
- const dir = dirname(this.path);
await this.ensureDirectory();
- const tempPath = join(dir, `.mcp-${randomUUID()}.tmp`);
- try {
- await writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, {
- encoding: 'utf8',
- mode: 0o600,
- flag: 'wx',
- });
- if (process.platform !== 'win32') await chmod(tempPath, 0o600);
- await rename(tempPath, this.path);
- if (process.platform !== 'win32') await chmod(this.path, 0o600);
- } finally {
- await rm(tempPath, { force: true }).catch(() => {});
- }
+ await writeAtomicFile(this.path, `${JSON.stringify(config, null, 2)}\n`, {
+ fileMode: 0o600,
+ });
}
private ensureDirectory(): Promise<void> {
if (this.directoryReady) return this.directoryReady;
- const dir = dirname(this.path);
- const ready = (async () => {
- await mkdir(dir, { recursive: true, mode: 0o700 });
- if (process.platform !== 'win32') await chmod(dir, 0o700);
- })();
+ const ready = hardenDirectory(dirname(this.path), 0o700);
this.directoryReady = ready;
void ready.catch(() => {
if (this.directoryReady === ready) this.directoryReady = undefined;
diff --git a/packages/storage/src/settings-store.ts b/packages/storage/src/settings-store.ts
index 8b892e30df..94f549e310 100644
--- a/packages/storage/src/settings-store.ts
+++ b/packages/storage/src/settings-store.ts
@@ -17,12 +17,13 @@
* under the License.
*/
-import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
+import { mkdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import type { AppSettings, UpdateAppSettingsInput } from '@maka/core/settings';
import type { OnboardingMilestone, OnboardingMilestoneId } from '@maka/core/onboarding';
import { createDefaultSettings, mergeSettings, normalizeSettings } from '@maka/core/settings';
import { sanitizeOnboardingMilestones } from '@maka/core/onboarding';
+import { writeAtomicFile } from './atomic-file-write.js';
/**
* A conditional write's patch, either fixed or derived from the state the
@@ -189,10 +190,13 @@ class FileSettingsStore implements SettingsStore {
}
private async write(settings: AppSettings): Promise<void> {
+ // SettingsStore does not own the workspace directory's permission policy:
+ // sibling stores such as MCP config may independently harden the same root.
+ // Keep both directory creation and the historical umask-derived file mode.
await mkdir(dirname(this.settingsPath), { recursive: true });
- const tempPath = `${this.settingsPath}.${process.pid}.${Date.now()}.tmp`;
- await writeFile(tempPath, JSON.stringify(settings, null, 2) + '\n', 'utf8');
- await rename(tempPath, this.settingsPath);
+ await writeAtomicFile(this.settingsPath, JSON.stringify(settings, null, 2) + '\n', {
+ fileMode: 0o666 & ~process.umask(),
+ });
}
private withQueue(operation: () => Promise<void>): Promise<void> {
diff --git a/packages/storage/src/stable-storage.ts b/packages/storage/src/stable-storage.ts
index 45081ca9b1..50d515bf83 100644
--- a/packages/storage/src/stable-storage.ts
+++ b/packages/storage/src/stable-storage.ts
@@ -18,7 +18,7 @@
*/
import { constants, type BigIntStats } from 'node:fs';
-import { lstat, open } from 'node:fs/promises';
+import { chmod, lstat, mkdir, open } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
export interface ReadStableBoundedFileInput {
@@ -99,6 +99,20 @@ export async function syncFile(path: string): Promise<void> {
}
}
+/**
+ * Create (or harden) an owner-only directory: recursive mkdir plus a
+ * fail-closed chmod, since mkdir's mode only applies on creation. Callers that
+ * store secrets use this before creating their file or update lock.
+ */
+export async function hardenDirectory(dir: string, mode: number = 0o700): Promise<void> {
+ await mkdir(dir, { recursive: true, mode });
+ if (process.platform === 'win32') {
+ await chmod(dir, mode).catch(() => {});
+ return;
+ }
+ await chmod(dir, mode);
+}
+
export async function syncDirectoryChain(
path: string,
root: string,
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org