Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

6.3 KB
Raw Blame
/**
 * Album file-backend store — CRUD + LWW merge outcomes.
 *
 * Covers the CRUD round-trip the normal (non-DB) suite exercises plus the
 * `mergeAlbumsFromSync` LWW outcomes plus the sync side effects that make
 * federation safe: base-hash seeding and conflict journaling before overwrite.
 * Runs against a tmpdir so it never touches real `data/`.
 */

import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';

const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'albums-file-test-'));
const writeCounter = vi.hoisted(() => ({ baseHash: 0 }));

vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
  const actual = await importOriginal();
  return {
    ...actual,
    PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
    atomicWrite: async (path, data) => {
      if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
      return actual.atomicWrite(path, data);
    },
  };
});

const file = await import('./file.js');
const cj = await import('../../lib/conflictJournal.js');

function reset() {
  rmSync(join(TEST_DATA_ROOT, 'albums.json'), { force: true });
  rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });
  rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });
  cj.__resetBaseHashCacheForTests();
  writeCounter.baseHash = 0;
}

const journalEntries = () => cj.conflictJournalStore().loadAll();

const album = (id, extra = {}) => ({
  id, title: id, artistId: '', artist: '', description: '', genre: '',
  releaseYear: null, coverImageUrl: '', trackIds: [],
  createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',
  deleted: false, deletedAt: null, ...extra,
});

beforeEach(reset);
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));

describe('albums file backend — CRUD', () => {
  it('creates, reads, updates and soft-deletes an album', async () => {
    const created = await file.createAlbum({ title: 'Debut', genre: 'folk', trackIds: ['track-1'] });
    expect(created.id).toMatch(/^album-/);
    expect((await file.getAlbum(created.id)).trackIds).toEqual(['track-1']);

    const updated = await file.updateAlbum(created.id, { trackIds: ['track-2', 'track-1'] });
    expect(updated.trackIds).toEqual(['track-2', 'track-1']);

    await file.deleteAlbum(created.id);
    expect(await file.getAlbum(created.id)).toBeNull();
    expect(await file.listAlbums()).toHaveLength(0);
  });

  it('lists live albums sorted by title', async () => {
    await file.createAlbum({ title: 'Zenith' });
    await file.createAlbum({ title: 'Aurora' });
    expect((await file.listAlbums()).map((a) => a.title)).toEqual(['Aurora', 'Zenith']);
  });
});

describe('albums file backend — mergeAlbumsFromSync (LWW outcomes)', () => {
  it('inserts, then newer wins / older no-ops', async () => {
    expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'v1', updatedAt: '2026-02-01T00:00:00.000Z' })]))
      .toEqual({ applied: true, count: 1 });
    expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'v2', updatedAt: '2026-03-01T00:00:00.000Z' })]))
      .toEqual({ applied: true, count: 1 });
    expect((await file.getAlbum('album-1')).genre).toBe('v2');
    expect(await file.mergeAlbumsFromSync([album('album-1', { genre: 'stale', updatedAt: '2020-01-01T00:00:00.000Z' })]))
      .toEqual({ applied: false, count: 0 });
  });

  it('pruneTombstonedAlbums hard-removes an old tombstone', async () => {
    await file.mergeAlbumsFromSync([album('album-dead', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' })]);
    expect(await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'))).toEqual({ pruned: 1 });
    expect(await file.getAlbum('album-dead', { includeDeleted: true })).toBeNull();
  });

  it('seeds the base hash on first insert of a remote album', async () => {
    const remote = album('album-2', { description: 'inserted' });
    expect(await cj.getSyncBaseHash('album', 'album-2')).toBeNull();
    await file.mergeAlbumsFromSync([remote]);
    expect(await cj.getSyncBaseHash('album', 'album-2'))
      .toBe(cj.contentHashForRecord('album', remote));
  });

  it('journals the losing local album on true 3-way divergence', async () => {
    const local = album('album-3', { genre: 'local jazz', updatedAt: '2026-02-01T00:00:00.000Z' });
    await file.mergeAlbumsFromSync([local]);
    const base = album('album-3', { genre: 'common folk', updatedAt: '2026-01-01T00:00:00.000Z' });
    await cj.setSyncBaseHash('album', 'album-3', cj.contentHashForRecord('album', base));

    const remoteWinner = album('album-3', { genre: 'remote pop', updatedAt: '2026-03-01T00:00:00.000Z' });
    await file.mergeAlbumsFromSync([remoteWinner], { source: { via: 'peer-push', peerId: 'peer-A' } });

    const entry = (await journalEntries()).find((e) => e.recordKind === 'album' && e.recordId === 'album-3');
    expect(entry).toBeTruthy();
    expect(entry.source.peerId).toBe('peer-A');
    expect(entry.localSnapshot.genre).toBe('local jazz');
    expect(entry.remoteSnapshot.genre).toBe('remote pop');
    expect((await file.getAlbum('album-3')).genre).toBe('remote pop');
    expect(await cj.getSyncBaseHash('album', 'album-3'))
      .toBe(cj.contentHashForRecord('album', remoteWinner));
  });

  it('pruneTombstonedAlbums batches base-hash eviction for multiple tombstones', async () => {
    await file.mergeAlbumsFromSync([
      album('album-dead-base-1', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),
      album('album-dead-base-2', { deleted: true, deletedAt: '2020-01-02T00:00:00.000Z', updatedAt: '2020-01-02T00:00:00.000Z' }),
    ]);
    expect(await cj.getSyncBaseHash('album', 'album-dead-base-1')).not.toBeNull();
    expect(await cj.getSyncBaseHash('album', 'album-dead-base-2')).not.toBeNull();

    writeCounter.baseHash = 0;
    expect(await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z')))
      .toEqual({ pruned: 2 });
    expect(writeCounter.baseHash).toBe(1);
    expect(await cj.getSyncBaseHash('album', 'album-dead-base-1')).toBeNull();
    expect(await cj.getSyncBaseHash('album', 'album-dead-base-2')).toBeNull();
  });
});