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

13.7 KB
Raw Blame
import { describe, it, expect } from 'vitest';
import { IMAGE_GEN_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import {
  PORTOS_SCHEMA_VERSIONS,
  RECORD_KIND_SCHEMA_CATEGORIES,
  compareSchemaVersions,
  scopeVersionDiff,
  formatVersionGap,
  buildPortosMeta,
} from './schemaVersions.js';

describe('PORTOS_SCHEMA_VERSIONS', () => {
  it('is a frozen object', () => {
    expect(Object.isFrozen(PORTOS_SCHEMA_VERSIONS)).toBe(true);
    expect(() => { PORTOS_SCHEMA_VERSIONS.universes = 999; }).toThrow();
  });

  it('declares universes at the post-split layout version', () => {
    // If this changes, the corresponding migration in scripts/migrations/
    // must ship alongside it. The test exists to make a layout bump a
    // deliberate two-file edit.
    // v6 = canon characters gained relationshipLinks[] (#1287); v7 = canon
    // objects gained attachments[] (#1288); v8 adds styleReferences[]; v9 adds
    // moodBoardId (#4188); v10 adds character production packages (#5378);
    // v11 adds the optional character psychology profile (#6414);
    // v12 adds the universe factual flag (#7616).
    // These are additive + version-gated so an older peer
    // cannot strip-then-LWW them.
    expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(14);
  });

  it('declares pipeline collection layout versions', () => {
    // pipelineIssues v4 preserves text-stage generation ownership.
    expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(4);
    // pipelineSeries bumped to 14 for authored arc.seriesDesign; v13 added characterArcs[].evolution
    // (#6440) (v2 = readerMap, v3 = tickingClock, v4 = styleGuide,
    // v5 = coverImage, v6 = characterArcs, v7 = factCritical + factReference,
    // v8 = editorialCheckConfig, v9 = severityWeights + blockingSeverities,
    // v10 = arc.foreshadowing, v11 = styleGuide.voiceExemplars +
    // voiceAntiExemplars, v12 = exportSettings).
    expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(14);
  });

  it('gates mediaCollections at v2 so a v1 peer refuses collections carrying removal records (#12433)', () => {
    expect(PORTOS_SCHEMA_VERSIONS.mediaCollections).toBe(2);
    // A v1 receiver would strip `removedItems` and union the removed item back.
    const v1Receiver = { ...PORTOS_SCHEMA_VERSIONS, mediaCollections: 1 };
    const diff = scopeVersionDiff(
      compareSchemaVersions(PORTOS_SCHEMA_VERSIONS, v1Receiver),
      RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection,
    );
    expect(diff.ahead).toEqual([{ category: 'mediaCollections', senderV: 2, receiverV: 1 }]);
  });

  it('version-gates catalog object attachments and media generation provenance', () => {
    // v11 adds the ref/relation/media tombstone-revival guard (#8347).
    expect(PORTOS_SCHEMA_VERSIONS.catalog).toBe(13);
  });

  it('version-gates the persisted FableLoom shot and reference shape', () => {
    // v7 adds timed shots and draft character image anchors; v8 adds the
    // optional per-character five-stage evolution lens on the series plan; v9
    // adds the shared finite/renewable series-design brief.
    // Older peers stay behind the full render contract until they advertise
    // support for the additive fields.
    expect(PORTOS_SCHEMA_VERSIONS.fableLoom).toBe(11);
  });

  it('version-gates the additive Creative Commission taste brief shape', () => {
    expect(PORTOS_SCHEMA_VERSIONS.creativeCommissions).toBe(6);
  });

  it('moves the render-backend alphabets and their sync versions together', () => {
    // Older receivers coerce an unknown imageMode/videoMode to auto/null, then
    // LWW the lost pin back. Adding a backend means: update this snapshot AND
    // bump creativeCommissions + fableLoom (and their pins above).
    expect({
      image: [...IMAGE_GEN_MODES],
      video: [...VIDEO_GEN_MODES],
      creativeCommissions: PORTOS_SCHEMA_VERSIONS.creativeCommissions,
      fableLoom: PORTOS_SCHEMA_VERSIONS.fableLoom,
    }).toEqual({
      image: ['external', 'local', 'codex', 'grok', 'agy', 'fal', 'runway'],
      video: ['local', 'grok', 'fal', 'reactor', 'runway'],
      creativeCommissions: 6,
      fableLoom: 11,
    });
  });
});

describe('buildPortosMeta', () => {
  it('rejects repair, timing, narrative event, lyric warning, title/ending/subject/tool metadata and panel links on older music-video peers', async () => {
    const meta = await buildPortosMeta();
    expect(meta.schemaVersions.musicVideoProjects).toBe(24);
    // Older builds re-normalize the newer fields away; the gate must stop that peer receiving them.
    for (const receiverV of [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) {
      expect(compareSchemaVersions(meta.schemaVersions, { ...meta.schemaVersions, musicVideoProjects: receiverV }).ahead)
        .toContainEqual({ category: 'musicVideoProjects', senderV: 24, receiverV });
    }
    const olderPeer = { ...meta.schemaVersions, musicVideoProjects: 23 };
    expect(scopeVersionDiff(compareSchemaVersions(meta.schemaVersions, olderPeer), RECORD_KIND_SCHEMA_CATEGORIES.musicVideoProject))
      .toMatchObject({ compatible: false, ahead: [{ category: 'musicVideoProjects', senderV: 24, receiverV: 23 }] });
  });

  it('advertises lyric provenance to pause track transfers to caption-only peers', async () => {
    const meta = await buildPortosMeta();
    expect(meta.schemaVersions.tracks).toBe(12);
    const olderPeer = { ...meta.schemaVersions, tracks: 11 };
    const diff = compareSchemaVersions(meta.schemaVersions, olderPeer);
    expect(scopeVersionDiff(diff, RECORD_KIND_SCHEMA_CATEGORIES.track)).toEqual({
      compatible: false,
      ahead: [{ category: 'tracks', senderV: 12, receiverV: 11 }],
      behind: [],
    });
    // This upgrade pauses only tracks; unrelated artist/album sync still works.
    expect(scopeVersionDiff(diff, RECORD_KIND_SCHEMA_CATEGORIES.artist).compatible).toBe(true);
    expect(scopeVersionDiff(diff, RECORD_KIND_SCHEMA_CATEGORIES.album).compatible).toBe(true);
  });

  it('returns { portosVersion, schemaVersions } with the live registry', async () => {
    const meta = await buildPortosMeta();
    expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
    expect(meta.schemaVersions.universes).toBe(14);
    expect(meta.schemaVersions.pipelineIssues).toBe(4);
    expect(meta.schemaVersions.pipelineSeries).toBe(14);
  });

  it('overrides merge into schemaVersions', async () => {
    const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });
    expect(meta.schemaVersions.universes).toBe(14);
    expect(meta.schemaVersions.future).toBe(1);
  });
});

describe('compareSchemaVersions', () => {
  it('compatible when both sides match exactly', () => {
    const r = compareSchemaVersions({ universes: 5 }, { universes: 5 });
    expect(r.compatible).toBe(true);
    expect(r.ahead).toEqual([]);
    expect(r.behind).toEqual([]);
  });

  it('flags ahead when sender is newer', () => {
    const r = compareSchemaVersions({ universes: 6 }, { universes: 5 });
    expect(r.compatible).toBe(false);
    expect(r.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);
    expect(r.behind).toEqual([]);
  });

  it('flags behind when sender is older', () => {
    const r = compareSchemaVersions({ universes: 4 }, { universes: 5 });
    expect(r.compatible).toBe(false);
    expect(r.ahead).toEqual([]);
    expect(r.behind).toEqual([{ category: 'universes', senderV: 4, receiverV: 5 }]);
  });

  it('handles mixed ahead + behind across categories', () => {
    const r = compareSchemaVersions(
      { universes: 6, series: 1 },
      { universes: 5, series: 3 },
    );
    expect(r.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);
    expect(r.behind).toEqual([{ category: 'series', senderV: 1, receiverV: 3 }]);
    expect(r.compatible).toBe(false);
  });

  it('treats a missing sender field as 0 (sender behind)', () => {
    const r = compareSchemaVersions({}, { universes: 5 });
    expect(r.behind).toEqual([{ category: 'universes', senderV: 0, receiverV: 5 }]);
    expect(r.ahead).toEqual([]);
  });

  it('treats a missing receiver field as 0 (sender ahead)', () => {
    const r = compareSchemaVersions({ universes: 5 }, {});
    expect(r.ahead).toEqual([{ category: 'universes', senderV: 5, receiverV: 0 }]);
    expect(r.behind).toEqual([]);
  });

  it('silently passes legacy peer with no portosMeta at all (sender = {}) when receiver has no version either', () => {
    const r = compareSchemaVersions({}, {});
    expect(r.compatible).toBe(true);
  });

  it('ignores categories where both sides are 0/absent', () => {
    const r = compareSchemaVersions(
      { universes: 5, future: 0 },
      { universes: 5, somethingElse: 0 },
    );
    expect(r.compatible).toBe(true);
  });

  it('treats non-integer entries as 0', () => {
    const r = compareSchemaVersions(
      { universes: 'five', series: 1.5 },
      { universes: 5 },
    );
    // 'five' → 0 → sender behind v5 ; 1.5 → 0 ; receiver has no series → both 0 → skip
    expect(r.behind).toEqual([{ category: 'universes', senderV: 0, receiverV: 5 }]);
    expect(r.ahead).toEqual([]);
  });

  it('handles null/undefined inputs gracefully', () => {
    expect(compareSchemaVersions(null, { universes: 5 }).behind).toHaveLength(1);
    expect(compareSchemaVersions(undefined, { universes: 5 }).behind).toHaveLength(1);
    // Default receiver is PORTOS_SCHEMA_VERSIONS (live).
    expect(compareSchemaVersions(null).behind).toHaveLength(Object.keys(PORTOS_SCHEMA_VERSIONS).length);
  });
});

describe('RECORD_KIND_SCHEMA_CATEGORIES', () => {
  it('maps each federated record kind to its versioned storage categories', () => {
    expect(RECORD_KIND_SCHEMA_CATEGORIES.universe).toEqual(['universes']);
    expect(RECORD_KIND_SCHEMA_CATEGORIES.series).toEqual(['pipelineSeries']);
    expect(RECORD_KIND_SCHEMA_CATEGORIES.issue).toEqual(['pipelineIssues']);
    expect(RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection).toEqual(['mediaCollections']);
  });

  it('only references keys that exist in PORTOS_SCHEMA_VERSIONS', () => {
    for (const keys of Object.values(RECORD_KIND_SCHEMA_CATEGORIES)) {
      for (const k of keys) {
        expect(PORTOS_SCHEMA_VERSIONS[k]).toBeDefined();
      }
    }
  });

  it('is frozen so a kind→category mapping change is deliberate', () => {
    expect(Object.isFrozen(RECORD_KIND_SCHEMA_CATEGORIES)).toBe(true);
  });
});

describe('scopeVersionDiff', () => {
  const diff = {
    ahead: [
      { category: 'universes', senderV: 6, receiverV: 5 },
      { category: 'mediaCollections', senderV: 2, receiverV: 1 },
    ],
    behind: [{ category: 'pipelineSeries', senderV: 1, receiverV: 2 }],
    compatible: false,
  };

  it('keeps only ahead/behind entries within the allowed categories', () => {
    const scoped = scopeVersionDiff(diff, ['universes']);
    expect(scoped.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);
    expect(scoped.behind).toEqual([]);
    expect(scoped.compatible).toBe(false);
  });

  it('drops an unrelated ahead category so it no longer blocks', () => {
    // The crux of the per-category gate: a transfer that only touches
    // `pipelineSeries` is NOT blocked by a sender that bumped `mediaCollections`.
    const scoped = scopeVersionDiff(diff, ['pipelineSeries']);
    expect(scoped.ahead).toEqual([]); // mediaCollections + universes filtered out
    expect(scoped.behind).toEqual([{ category: 'pipelineSeries', senderV: 1, receiverV: 2 }]);
    expect(scoped.compatible).toBe(false);
  });

  it('an empty allow-list makes the scoped diff compatible (no versioned category touched)', () => {
    const scoped = scopeVersionDiff(diff, []);
    expect(scoped.ahead).toEqual([]);
    expect(scoped.behind).toEqual([]);
    expect(scoped.compatible).toBe(true);
  });

  it('a non-array categories arg returns the diff unchanged (whole-payload gate)', () => {
    expect(scopeVersionDiff(diff, null)).toBe(diff);
    expect(scopeVersionDiff(diff, undefined)).toBe(diff);
  });

  it('tolerates a malformed diff (missing ahead/behind arrays)', () => {
    const scoped = scopeVersionDiff({}, ['universes']);
    expect(scoped).toEqual({ ahead: [], behind: [], compatible: true });
  });

  it('composes with compareSchemaVersions for a realistic cross-key scenario', () => {
    // Sender is ahead on mediaCollections only; a universe transfer scopes to
    // ['universes'] and stays compatible even though the union diff is not.
    const union = compareSchemaVersions(
      {
        universes: PORTOS_SCHEMA_VERSIONS.universes,
        pipelineSeries: 2,
        pipelineIssues: 3,
        mediaCollections: PORTOS_SCHEMA_VERSIONS.mediaCollections + 1,
      },
      PORTOS_SCHEMA_VERSIONS,
    );
    expect(union.compatible).toBe(false);
    expect(scopeVersionDiff(union, RECORD_KIND_SCHEMA_CATEGORIES.universe).compatible).toBe(true);
    expect(scopeVersionDiff(union, RECORD_KIND_SCHEMA_CATEGORIES.mediaCollection).compatible).toBe(false);
  });
});

describe('formatVersionGap', () => {
  it('describes a single ahead gap', () => {
    expect(formatVersionGap({ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] }))
      .toBe('sender ahead of receiver on universes (v5 vs v4)');
  });

  it('describes a single behind gap', () => {
    expect(formatVersionGap({ behind: [{ category: 'universes', senderV: 4, receiverV: 5 }] }))
      .toBe('sender behind receiver on universes (v4 vs v5)');
  });

  it('combines ahead + behind across categories', () => {
    expect(formatVersionGap({
      ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],
      behind: [{ category: 'series', senderV: 1, receiverV: 3 }],
    })).toBe('sender ahead of receiver on universes (v6 vs v5); sender behind receiver on series (v1 vs v3)');
  });

  it('returns "compatible" for an empty diff', () => {
    expect(formatVersionGap({ ahead: [], behind: [] })).toBe('compatible');
    expect(formatVersionGap({})).toBe('compatible');
    expect(formatVersionGap()).toBe('compatible');
  });
});