Skip to content

fix(mcp): hold Muse Code's .settings.json.lock across settings writes - #4026

Open
superbiche wants to merge 1 commit into
dyoshikawa:mainfrom
superbiche:fix/musecode-settings-advisory-lock
Open

superbiche wants to merge 1 commit into
dyoshikawa:mainfrom
superbiche:fix/musecode-settings-advisory-lock

Conversation

@superbiche

Copy link
Copy Markdown

Summary

Coordinates global musecode MCP writes to ~/.config/muse/settings.json with Muse Code's sibling advisory lock ~/.config/muse/.settings.json.lock, without adding any native dependency (keeping Bun-compiled release binaries unaffected).

Closes #3498.

What changed

  • Zero-dependency POSIX flock(2) helper (src/utils/advisory-lock.ts):
    • Linux / other POSIX: spawns flock -x -- <lockfile> cat (compatible with both util-linux and BusyBox flock), falling back on ENOENT to perl (Fcntl::flock) and isolated python3 -I -S (fcntl.flock). Fails closed with AdvisoryLockUnavailableError if none of the helpers exist on PATH, or AdvisoryLockTimeoutError if the lock stays held past the 10 s timeout.
    • macOS (darwin): uses perl (/usr/bin/perl fallback) via core Fcntl::flock, which ships with macOS, calls flock(2) directly, and avoids Homebrew flock flag incompatibilities or /usr/bin/python3 Xcode CLT prompts.
    • Windows (win32): flock(2) does not exist on Windows and Muse Code's Windows settings lock protocol is unverified; logs a one-time warning and continues unlocked so Windows users and the windows-x64 E2E matrix keep working (happy to switch Windows to fail-closed if you prefer).
    • Uses an explicit "locked\n" stdout handshake so the critical section never starts while the helper is still blocked waiting for the lock, closes stdin unconditionally on release (preventing orphaned cat grandchildren), and never unlinks the lock file.
  • Lock-scoped read → patch → atomic write transaction (src/types/ai-file.ts, src/types/feature-processor.ts, src/features/mcp/musecode-mcp.ts, src/utils/file.ts):
    • MusecodeMcp declares getAdvisoryLockPath() (sibling .settings.json.lock in global mode) and overrides composeWrittenContent() to re-parse and re-apply the MCP patch onto the fresh settings.json read inside the lock.
    • FeatureProcessor.writeAiFiles verifies symlink containment (refusesAnyWriteOutsideRoot) for both filePath and advisoryLockPath, holds the lock across read/compose/compare/commit on real writes (skipping lock acquisition in --dry-run / --check), and commits locked files via writeFileContentAtomic (sibling O_CREAT | O_EXCL temp file + FileHandle.chmod mode preservation + rename, atomically replacing resolved targets of existing symlinks).
  • Docs (docs/reference/file-formats.md, src/generated/docs-content.ts): updated the Meta Muse Code MCP note to document the advisory lock behavior and Windows caveat.
  • Tests (src/utils/advisory-lock.test.ts, src/utils/file.test.ts, src/features/mcp/musecode-mcp.test.ts, src/e2e/e2e-mcp.spec.ts): covers exclusive locking, wait-on-contention, timeout without writing, release on error, darwin perl & isolated python3 -I -S (with decoy fcntl.py), missing/failing helpers, win32 warning path, both concurrent interleavings, dry-run non-locking, lock-symlink escape refusal, atomic replace permission/symlink/cleanup behavior, and E2E subprocess lock coordination.

Test plan

  • pnpm cicheck (format, oxlint, tsgo, all 666 unit test suites, docs sync, gitignore, supported-tools tables, cspell, secretlint)
  • pnpm build
  • pnpm test:e2e for src/e2e/e2e-mcp.spec.ts (both via tsx and against a locally compiled Bun standalone binary)
  • Verified 3-way .settings.json.lock serialization on Linux against real Muse Code 1.4.24-R9131.1 (muse skills disable --scope user --json) + Rulesync dist/cli/index.js + cooperating Python fcntl.flock writer in a disposable home

@superbiche · user · drafted with Gemini 4 Neon.

@dyoshikawa dyoshikawa left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up, and for keeping it free of native dependencies. That was the main thing #3498 was waiting on, and spawning flock/perl/python3 with a -I -S Python and a 3-arg Perl open looks careful. The re-read and re-patch inside the lock is the right shape too.

A few things need to change before this can merge. First, the branch now conflicts with main: docs/reference/file-formats.md, src/generated/docs-content.ts, src/e2e/e2e-mcp.spec.ts and the MCP processor (preserveUnownedMcpServers landed in #4028). Merging main and running pnpm run generate:docs-content should clear most of it. Second, three behaviour points, inline below. The biggest one is Windows: #3498 asked for a clear failure over an unlocked write, and Muse Code does ship Windows fixes, so a warning followed by an unlocked write brings back the original bug there.

On the protocol itself, the only evidence that Muse takes flock on .settings.json.lock is your /proc/locks check on Linux. Muse's docs and changelog don't mention it, and macOS is still unverified. If you can confirm the macOS side (for example with lsof, or by showing that a running Muse blocks on the lock this PR takes), please add it to the PR description.

Smaller things, none of them blocking: the new atomic write never fsyncs the temp file before rename, and on win32 it switches to rename even though no lock is held there (antivirus handles can cause EPERM/EBUSY). The e2e lock test holds the lock for a fixed 1.5 s, so it can pass without the child ever waiting on it. The python3 and darwin-perl unit tests need skipIf guards for machines without those tools. composeWrittenContent only re-applies pendingMcpServers, which is worth a comment in case musecode ever honours preserveUnownedMcpServers.

const { lockPath, action, timeoutMs = DEFAULT_TIMEOUT_MS, logger, helpers } = params;
const platform = params.platform ?? process.platform;
if (platform === "win32" && helpers === undefined) {
warnOnceWithFallback(

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On Windows this logs a warning and writes without the lock, which is the race #3498 is about. That issue preferred failing clearly over writing unlocked, and Muse Code does run on Windows (its changelog has Windows-only fixes from 1.4.15 to 1.4.25). Could this fail closed on win32 with a clear error and an explicit opt-out? If Muse uses LockFileEx on the same file on Windows, a helper that takes that lock would be even better, once that's verified.

let stdout = "";
let stderr = "";
const isClosed = () => closed;
const settle = (): boolean => {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the helper reports "locked", settle() removes the close/error listeners, so nothing notices if the helper exits while rulesync is still writing. The helper runs in rulesync's own process group, so Ctrl+C in generate --watch sends SIGINT to it as well. The lock is dropped, while the shutdown lets the in-flight read, patch and rename finish. An OOM kill does the same. Spawning with detached: true keeps it out of the terminal's signals (stdin EOF still ends it if rulesync dies). Tracking an unexpected exit after "locked" and throwing before the rename would close the rest.

if (!this.global) {
return undefined;
}
return join(dirname(this.getFilePath()), MUSECODE_SETTINGS_LOCK_FILE_NAME);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock goes next to getFilePath(), but writeFileContentAtomic resolves a symlinked settings.json and renames into the target's directory. Muse 1.4.24 moved its auth/trust locks "beside the resolved write destination". If settings works the same way, a stow/chezmoi user with a symlinked settings.json gets two different lock files and no mutual exclusion. Could you check where Muse locks in that case? Then either lock beside the resolved path, or refuse to write through a symlink, with a test either way.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

musecode MCP writes settings.json without taking Muse’s .settings.json.lock

2 participants