Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
59 changes: 59 additions & 0 deletions src/fs-utils.symlink.test.ts
Original file line number Diff line number Diff line change
@@ -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']);
});
});
7 changes: 7 additions & 0 deletions src/fs-utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
},
}));
Expand All @@ -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;
});
Expand Down
33 changes: 30 additions & 3 deletions src/fs-utils.ts
Original file line number Diff line number Diff line change
@@ -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);
Expand Down