Repository navigation
fix(mcp): hold Muse Code's .settings.json.lock across settings writes - #4026
superbiche wants to merge 1 commit into
Conversation
dyoshikawa
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 => { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
Summary
Coordinates global
musecodeMCP writes to~/.config/muse/settings.jsonwith 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
flock(2)helper (src/utils/advisory-lock.ts):flock -x -- <lockfile> cat(compatible with both util-linux and BusyBoxflock), falling back onENOENTtoperl(Fcntl::flock) and isolatedpython3 -I -S(fcntl.flock). Fails closed withAdvisoryLockUnavailableErrorif none of the helpers exist onPATH, orAdvisoryLockTimeoutErrorif the lock stays held past the 10 s timeout.darwin): usesperl(/usr/bin/perlfallback) via coreFcntl::flock, which ships with macOS, callsflock(2)directly, and avoids Homebrewflockflag incompatibilities or/usr/bin/python3Xcode CLT prompts.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 thewindows-x64E2E matrix keep working (happy to switch Windows to fail-closed if you prefer)."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 orphanedcatgrandchildren), and never unlinks the lock file.src/types/ai-file.ts,src/types/feature-processor.ts,src/features/mcp/musecode-mcp.ts,src/utils/file.ts):MusecodeMcpdeclaresgetAdvisoryLockPath()(sibling.settings.json.lockin global mode) and overridescomposeWrittenContent()to re-parse and re-apply the MCP patch onto the freshsettings.jsonread inside the lock.FeatureProcessor.writeAiFilesverifies symlink containment (refusesAnyWriteOutsideRoot) for bothfilePathandadvisoryLockPath, holds the lock across read/compose/compare/commit on real writes (skipping lock acquisition in--dry-run/--check), and commits locked files viawriteFileContentAtomic(siblingO_CREAT | O_EXCLtemp file +FileHandle.chmodmode preservation +rename, atomically replacing resolved targets of existing symlinks).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.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,darwinperl& isolatedpython3 -I -S(with decoyfcntl.py), missing/failing helpers,win32warning 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 buildpnpm test:e2eforsrc/e2e/e2e-mcp.spec.ts(both viatsxand against a locally compiled Bun standalone binary).settings.json.lockserialization on Linux against real Muse Code1.4.24-R9131.1(muse skills disable --scope user --json) + Rulesyncdist/cli/index.js+ cooperating Pythonfcntl.flockwriter in a disposable home@superbiche · user · drafted with Gemini 4 Neon.