From 717d68e142c8ea63a35a49c827b0039463d26cb3 Mon Sep 17 00:00:00 2001 From: Michel Lind Date: Tue, 3 Nov 2026 11:42:10 +0000 Subject: [PATCH] fix: follow symlinks in atomicWrite so linked state files stay linked Linking ~/.claude/plugins/codachi/memory.json into a synced folder, to carry pet progress between machines, stops working after the first write: the file becomes a plain local copy and the synced one stops updating, with nothing to say so. atomicWrite writes a temp file and renames it over the path, and a rename onto a symlink replaces the link itself. It now resolves the link first and writes the temp file next to its target, so the rename replaces the target and the link stays. A link whose target does not exist yet is followed too, rather than replaced. Plain files are written exactly as before. Assisted-by: Claude Code:claude-opus-5-5 --- CHANGELOG.md | 12 ++++++++ src/fs-utils.symlink.test.ts | 59 ++++++++++++++++++++++++++++++++++++ src/fs-utils.test.ts | 7 +++++ src/fs-utils.ts | 33 ++++++++++++++++++-- 4 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 src/fs-utils.symlink.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 62a0b0c..0639950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to codachi are documented here. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- **Symlinked state files stay linked** — every write is a temp file + renamed into place, and renaming onto a symlink replaces the link + itself. A `memory.json` linked into a synced folder (to carry pet + progress between machines) became a plain local file on the first + write and silently stopped syncing. Writes now follow the link and + replace the file it points to, including a link whose target does + not exist yet. + ## [0.3.0] — 2026-04-18 ### Added diff --git a/src/fs-utils.symlink.test.ts b/src/fs-utils.symlink.test.ts new file mode 100644 index 0000000..f312b6c --- /dev/null +++ b/src/fs-utils.symlink.test.ts @@ -0,0 +1,59 @@ +// Real-filesystem tests for atomicWrite and symlinks. fs-utils.test.ts mocks +// node:fs for the whole module, so link behaviour needs a file of its own. +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { atomicWrite } from './fs-utils.js'; + +let dir: string; + +beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codachi-fs-')); }); +afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +describe('atomicWrite with symlinks', () => { + it('keeps a symlinked file linked and updates its target', () => { + const target = path.join(dir, 'synced', 'memory.json'); + fs.mkdirSync(path.dirname(target)); + fs.writeFileSync(target, '{"totalSessions":1}'); + const link = path.join(dir, 'memory.json'); + fs.symlinkSync(target, link); + + expect(atomicWrite(link, '{"totalSessions":2}')).toBe(true); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(fs.readFileSync(target, 'utf8')).toBe('{"totalSessions":2}'); + }); + + it('follows a relative link', () => { + fs.mkdirSync(path.join(dir, 'synced')); + fs.writeFileSync(path.join(dir, 'synced', 'state.json'), '{}'); + const link = path.join(dir, 'state.json'); + fs.symlinkSync(path.join('synced', 'state.json'), link); + + expect(atomicWrite(link, '{"v":1}')).toBe(true); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(fs.readFileSync(path.join(dir, 'synced', 'state.json'), 'utf8')).toBe('{"v":1}'); + }); + + it('creates the target of a dangling link instead of replacing the link', () => { + fs.mkdirSync(path.join(dir, 'synced')); + const target = path.join(dir, 'synced', 'memory.json'); + const link = path.join(dir, 'memory.json'); + fs.symlinkSync(target, link); + + expect(atomicWrite(link, '{"new":true}')).toBe(true); + + expect(fs.lstatSync(link).isSymbolicLink()).toBe(true); + expect(fs.readFileSync(target, 'utf8')).toBe('{"new":true}'); + }); + + it('still writes plain files, and leaves no temp files behind', () => { + const file = path.join(dir, 'events.json'); + expect(atomicWrite(file, '{"events":[]}')).toBe(true); + expect(fs.lstatSync(file).isFile()).toBe(true); + expect(fs.readFileSync(file, 'utf8')).toBe('{"events":[]}'); + expect(fs.readdirSync(dir)).toEqual(['events.json']); + }); +}); diff --git a/src/fs-utils.test.ts b/src/fs-utils.test.ts index 16a1012..0559065 100644 --- a/src/fs-utils.test.ts +++ b/src/fs-utils.test.ts @@ -8,6 +8,9 @@ vi.mock('node:fs', () => ({ unlinkSync: vi.fn(), mkdirSync: vi.fn(), statSync: vi.fn(() => { throw new Error('ENOENT'); }), + realpathSync: vi.fn(() => { throw new Error('ENOENT'); }), + lstatSync: vi.fn(() => { throw new Error('ENOENT'); }), + readlinkSync: vi.fn(), appendFileSync: vi.fn(), }, })); @@ -17,6 +20,10 @@ let atomicWrite: typeof import('./fs-utils.js')['atomicWrite']; beforeEach(async () => { vi.resetAllMocks(); vi.resetModules(); + // resetAllMocks drops the factory implementations; nothing exists yet. + const enoent = () => { throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); }; + vi.mocked(fs.realpathSync).mockImplementation(enoent as unknown as typeof fs.realpathSync); + vi.mocked(fs.lstatSync).mockImplementation(enoent as unknown as typeof fs.lstatSync); const mod = await import('./fs-utils.js'); atomicWrite = mod.atomicWrite; }); diff --git a/src/fs-utils.ts b/src/fs-utils.ts index 6910c5c..57d3f8f 100644 --- a/src/fs-utils.ts +++ b/src/fs-utils.ts @@ -1,13 +1,40 @@ import fs from 'node:fs'; +import path from 'node:path'; import crypto from 'node:crypto'; import { logError } from './log.js'; -/** Atomic write: write to tmp file then rename. Prevents corruption on crash/concurrent access. */ +/** + * The file a write to `filePath` should replace. When `filePath` is a + * symlink (e.g. memory.json linked into a synced folder), the rename must + * land on the file it points to: renaming onto the link itself would + * replace the link with a regular file and silently stop the syncing. + */ +function writeTarget(filePath: string): string { + try { + return fs.realpathSync(filePath); + } catch { + // Missing file (the usual first-run case), or a link whose target does + // not exist yet: write where the link points rather than replacing it. + try { + if (fs.lstatSync(filePath).isSymbolicLink()) { + return path.resolve(path.dirname(filePath), fs.readlinkSync(filePath)); + } + } catch { /* not there at all */ } + return filePath; + } +} + +/** + * Atomic write: write to tmp file then rename. Prevents corruption on + * crash/concurrent access. Symlinks are followed, so a linked file stays + * linked. + */ export function atomicWrite(filePath: string, data: string): boolean { - const tmp = filePath + '.tmp.' + crypto.randomUUID(); + const target = writeTarget(filePath); + const tmp = target + '.tmp.' + crypto.randomUUID(); try { fs.writeFileSync(tmp, data); - fs.renameSync(tmp, filePath); + fs.renameSync(tmp, target); return true; } catch (err) { logError('fs.atomicWrite', err);