Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

10.7 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import {
  chmodSync,
  lstatSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  readdirSync,
  readlinkSync,
  realpathSync,
  rmSync,
  statSync,
  symlinkSync,
  writeFileSync,
} from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { IS_WINDOWS, writeJsonFileAtomic } from '../src/npx-cli/utils/paths.js';
import { renameWithWindowsRetry } from '../src/shared/atomic-json.js';

/**
 * Tests for writeJsonFileAtomic's crash-safe semantics.
 *
 * Per CodeRabbit on PR #2281: the prior implementation was a single
 * writeFileSync call that could leave a truncated/corrupt file on a mid-write
 * crash — relevant because callers include disableClaudeAutoMemory's write to
 * ~/.claude/settings.json (a user-owned global config).
 *
 * The new implementation uses temp file + fsync + rename. These tests verify
 * that contract.
 */

describe('writeJsonFileAtomic', () => {
  let tempDir: string;

  beforeEach(() => {
    tempDir = mkdtempSync(join(tmpdir(), 'claude-mem-atomic-'));
  });

  afterEach(() => {
    rmSync(tempDir, { recursive: true, force: true });
  });

  it('writes JSON to the destination path with a trailing newline', () => {
    const target = join(tempDir, 'config.json');
    writeJsonFileAtomic(target, { foo: 'bar', n: 1 });
    const raw = readFileSync(target, 'utf-8');
    expect(raw).toBe('{\n  "foo": "bar",\n  "n": 1\n}\n');
  });

  it('replaces existing content without leaving a temp file behind', () => {
    const target = join(tempDir, 'config.json');
    writeJsonFileAtomic(target, { v: 1 });
    writeJsonFileAtomic(target, { v: 2 });
    expect(JSON.parse(readFileSync(target, 'utf-8'))).toEqual({ v: 2 });

    // No leftover .tmp files should remain in the directory.
    const leftovers = readdirSync(tempDir).filter(name => name.endsWith('.tmp'));
    expect(leftovers).toEqual([]);
  });

  it('creates parent directories when they do not exist', () => {
    const target = join(tempDir, 'nested', 'deeper', 'config.json');
    writeJsonFileAtomic(target, { ok: true });
    expect(JSON.parse(readFileSync(target, 'utf-8'))).toEqual({ ok: true });
  });

  it('keeps an existing group-writable mode exactly, whatever the umask', () => {
    if (IS_WINDOWS) return;
    const target = join(tempDir, 'shared-config.json');
    writeFileSync(target, '{}');
    chmodSync(target, 0o660);

    // open(2) masks the mode it is given with the umask; 022 would turn 0660 into 0640.
    const previousUmask = process.umask(0o022);
    try {
      writeJsonFileAtomic(target, { shared: true });
    } finally {
      process.umask(previousUmask);
    }

    expect(statSync(target).mode & 0o777).toBe(0o660);
  });

  it('can tighten an existing destination mode before writing secrets', () => {
    if (IS_WINDOWS) return;
    const target = join(tempDir, 'previously-public.json');
    writeFileSync(target, '{}', { mode: 0o644 });
    chmodSync(target, 0o644);

    writeJsonFileAtomic(target, { secret: true }, { mode: 0o600 });

    expect(statSync(target).mode & 0o777).toBe(0o600);
    expect(JSON.parse(readFileSync(target, 'utf-8'))).toEqual({ secret: true });
  });

  it('throws on serialization failure without creating a temp file', () => {
    // A circular structure makes JSON.stringify throw before openSync runs,
    // so no temp file should ever appear in the destination directory.
    const target = join(tempDir, 'config.json');
    const circular: any = { a: 1 };
    circular.self = circular;

    expect(() => writeJsonFileAtomic(target, circular)).toThrow();

    const leftovers = readdirSync(tempDir).filter(name => name.endsWith('.tmp'));
    expect(leftovers).toEqual([]);
  });

  it('writes through a symlinked destination instead of replacing the link', () => {
    if (IS_WINDOWS) {
      // Symlink creation requires elevated privileges on Windows; skip there.
      return;
    }
    // Users who keep ~/.claude/settings.json under a dotfiles repo often
    // symlink it. POSIX rename(2) replaces the symlink with the temp file,
    // which would silently break the link — verify we resolve it instead.
    const realDir = mkdtempSync(join(tmpdir(), 'claude-mem-real-'));
    try {
      const realTarget = join(realDir, 'real-config.json');
      writeFileSync(realTarget, '{"v":0}');
      const linkPath = join(tempDir, 'config.json');
      symlinkSync(realTarget, linkPath);

      writeJsonFileAtomic(linkPath, { v: 42 });

      // Underlying file is updated.
      expect(JSON.parse(readFileSync(realTarget, 'utf-8'))).toEqual({ v: 42 });
      // Symlink is preserved (not clobbered into a regular file).
      expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
      // And it still resolves to the same realpath.
      expect(realpathSync(linkPath)).toBe(realpathSync(realTarget));
      // Temp file landed next to the real target, not at the symlink site.
      const realDirLeftovers = readdirSync(realDir).filter(name => name.endsWith('.tmp'));
      expect(realDirLeftovers).toEqual([]);
      const tempDirLeftovers = readdirSync(tempDir).filter(name => name.endsWith('.tmp'));
      expect(tempDirLeftovers).toEqual([]);
    } finally {
      rmSync(realDir, { recursive: true, force: true });
    }
  });

  it('writes through a dangling symlink destination instead of replacing the link', () => {
    if (IS_WINDOWS) {
      // Symlink creation requires elevated privileges on Windows; skip there.
      return;
    }

    const linkTarget = join('dotfiles', 'settings.json');
    const realTarget = join(tempDir, linkTarget);
    const linkPath = join(tempDir, 'settings.json');
    symlinkSync(linkTarget, linkPath);

    writeJsonFileAtomic(linkPath, { env: { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } });

    expect(JSON.parse(readFileSync(realTarget, 'utf-8'))).toEqual({
      env: { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' },
    });
    expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
    expect(realpathSync(linkPath)).toBe(realpathSync(realTarget));
    const tempDirLeftovers = readdirSync(tempDir).filter(name => name.endsWith('.tmp'));
    expect(tempDirLeftovers).toEqual([]);
    const realDirLeftovers = readdirSync(join(tempDir, 'dotfiles')).filter(name => name.endsWith('.tmp'));
    expect(realDirLeftovers).toEqual([]);
  });

  it('cleans up the temp file when the rename step fails', () => {
    // Force the catch-block cleanup path: pre-create a directory at the
    // destination so renameSync(tmpPath, filepath) fails (EISDIR/ENOTDIR).
    // By that point the temp file has already been opened, written, fsync'd,
    // and closed — so the catch must unlinkSync the leftover .tmp file.
    const target = join(tempDir, 'config.json');
    mkdirSync(target);

    expect(() => writeJsonFileAtomic(target, { v: 1 })).toThrow();

    const leftovers = readdirSync(tempDir).filter(name => name.endsWith('.tmp'));
    expect(leftovers).toEqual([]);
    // The pre-existing directory should still be there — we didn't clobber it.
    expect(statSync(target).isDirectory()).toBe(true);
  });

  it('preserves every link in a dangling symlink chain', () => {
    if (IS_WINDOWS) return;
    const first = join(tempDir, 'settings.json');
    const second = join(tempDir, 'alias.json');
    const target = join(tempDir, 'dotfiles', 'settings.json');
    symlinkSync('alias.json', first);
    symlinkSync('dotfiles/settings.json', second);

    writeJsonFileAtomic(first, { owned: true });

    expect(lstatSync(first).isSymbolicLink()).toBe(true);
    expect(lstatSync(second).isSymbolicLink()).toBe(true);
    expect(readlinkSync(first)).toBe('alias.json');
    expect(readlinkSync(second)).toBe('dotfiles/settings.json');
    expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ owned: true });
    expect(realpathSync(first)).toBe(realpathSync(target));
    expect(readdirSync(join(tempDir, 'dotfiles'))).toEqual(['settings.json']);
  });

  it('resolves a dangling relative link against the physical parent of a symlinked directory', () => {
    if (IS_WINDOWS) return;
    // project/config -> dotfiles/config, and dotfiles/config/settings.json -> ../shared.json
    // (dangling). The link lives in dotfiles/config, so ../shared.json means
    // dotfiles/shared.json, never project/shared.json.
    mkdirSync(join(tempDir, 'dotfiles', 'config'), { recursive: true });
    mkdirSync(join(tempDir, 'project'), { recursive: true });
    symlinkSync(join(tempDir, 'dotfiles', 'config'), join(tempDir, 'project', 'config'));
    symlinkSync('../shared.json', join(tempDir, 'dotfiles', 'config', 'settings.json'));

    writeJsonFileAtomic(join(tempDir, 'project', 'config', 'settings.json'), { owned: true });

    expect(JSON.parse(readFileSync(join(tempDir, 'dotfiles', 'shared.json'), 'utf8'))).toEqual({ owned: true });
    expect(readdirSync(join(tempDir, 'project'))).toEqual(['config']);
    expect(lstatSync(join(tempDir, 'dotfiles', 'config', 'settings.json')).isSymbolicLink()).toBe(true);
  });

  it('rejects a symlink loop without replacing either link', () => {
    if (IS_WINDOWS) return;
    const first = join(tempDir, 'first');
    const second = join(tempDir, 'second');
    symlinkSync('second', first);
    symlinkSync('first', second);

    expect(() => writeJsonFileAtomic(first, { owned: true })).toThrow();

    expect(lstatSync(first).isSymbolicLink()).toBe(true);
    expect(lstatSync(second).isSymbolicLink()).toBe(true);
    expect(readlinkSync(first)).toBe('second');
    expect(readlinkSync(second)).toBe('first');
    expect(readdirSync(tempDir).sort()).toEqual(['first', 'second']);
  });
});

describe('renameWithWindowsRetry', () => {
  function lockError(code: string): NodeJS.ErrnoException {
    return Object.assign(new Error(`${code}: operation not permitted, rename`), { code });
  }

  it('retries a transient Windows lock until the rename succeeds', () => {
    for (const code of ['EPERM', 'EBUSY', 'EACCES']) {
      let calls = 0;
      renameWithWindowsRetry('a.tmp', 'a.json', () => {
        calls++;
        if (calls < 3) throw lockError(code);
      }, true);
      expect(calls).toBe(3);
    }
  });

  it('throws the lock error when it outlasts the retry budget', () => {
    let calls = 0;
    expect(() => renameWithWindowsRetry('a.tmp', 'a.json', () => {
      calls++;
      throw lockError('EPERM');
    }, true)).toThrow('EPERM');
    expect(calls).toBe(7);
  });

  it('does not retry other errors or other platforms', () => {
    let calls = 0;
    expect(() => renameWithWindowsRetry('a.tmp', 'a.json', () => {
      calls++;
      throw lockError('ENOENT');
    }, true)).toThrow('ENOENT');
    expect(calls).toBe(1);

    calls = 0;
    expect(() => renameWithWindowsRetry('a.tmp', 'a.json', () => {
      calls++;
      throw lockError('EPERM');
    }, false)).toThrow('EPERM');
    expect(calls).toBe(1);
  });
});