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

10.3 KB
Raw Blame
/**
 * Per-track animation targets (#2985) — the pure precedence chain, the
 * sibling-preserving merge, and drift detection. The service-level wiring
 * (queue-time enforcement, PUT /walk/target, lazy write-back) is covered by
 * walk.test.js; this file pins the rules those depend on.
 */

import { describe, it, expect, vi } from 'vitest';
import {
  WALK_TRACK, resolveAnimationTarget, withTrackTarget, targetDrift, describeTargetSource,
} from './animationTargets.js';
import { getAnimationTrack, SCANNER_TRACK } from './animationTracks.js';

describe('resolveAnimationTarget precedence', () => {
  it('falls back to the documented defaults when nothing is pinned or packaged', () => {
    expect(resolveAnimationTarget()).toMatchObject({
      track: WALK_TRACK, frameCount: 12, fps: 10, source: 'default', frameCountLocked: false,
    });
  });

  it('derives from the FIRST packaged direction, mirroring the compiler\'s first-wins rule', () => {
    expect(resolveAnimationTarget({
      packagedCycles: [
        { direction: 'south', frameCount: 8, fps: 12 },
        { direction: 'east', frameCount: 16, fps: 6 },
      ],
    })).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
  });

  it('prefers an explicit set pin over the derived geometry', () => {
    expect(resolveAnimationTarget({
      animationTargets: { walk: { frameCount: 14, fps: 8, source: 'set' } },
      packagedCycles: [{ direction: 'south', frameCount: 8, fps: 12 }],
    })).toMatchObject({ frameCount: 14, fps: 8, source: 'set' });
  });

  it('reports an auto-pinned block as "derived", not as a user-chosen target', () => {
    // The lazy write-back stamps `source: 'derived'` so a value PortOS inferred
    // never masquerades in the UI as one the user deliberately picked.
    expect(resolveAnimationTarget({
      animationTargets: { walk: { frameCount: 8, fps: 12, source: 'derived' } },
    })).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
  });

  it('treats a legacy pin with no source field as a user-set target', () => {
    expect(resolveAnimationTarget({
      animationTargets: { walk: { frameCount: 14, fps: 8 } },
    })).toMatchObject({ source: 'set' });
  });

  it('lets the app contract beat every other rung and marks the knob locked', () => {
    expect(resolveAnimationTarget({
      runtimeContract: { walkFrameCount: 16 },
      animationTargets: { walk: { frameCount: 14, fps: 8, source: 'set' } },
      packagedCycles: [{ direction: 'south', frameCount: 8, fps: 12 }],
    })).toMatchObject({
      // The contract pins only the frame count today — fps still falls through
      // to the set pin, but the target as a whole reports as app-authored.
      frameCount: 16, fps: 8, source: 'app', frameCountLocked: true, fpsLocked: false,
    });
  });

  it('honors a contract that also pins fps', () => {
    expect(resolveAnimationTarget({
      runtimeContract: { walkFrameCount: 16, walkFps: 24 },
    })).toMatchObject({ frameCount: 16, fps: 24, fpsLocked: true });
  });

  it('ignores out-of-range and non-integer values at every rung instead of clamping them', () => {
    // A hand-edited record must not silently pin something the packer would
    // quietly rewrite — the rung is skipped, not coerced.
    expect(resolveAnimationTarget({
      runtimeContract: { walkFrameCount: 99 },
      animationTargets: { walk: { frameCount: 2, fps: 'fast' } },
      packagedCycles: [{ direction: 'south', frameCount: 12.5, fps: 0 }],
    })).toMatchObject({ frameCount: 12, fps: 10, source: 'default', frameCountLocked: false });
  });

  it('ignores an unrelated track\'s pin when resolving walk', () => {
    expect(resolveAnimationTarget({
      animationTargets: { scanner: { frameCount: 6, fps: 4 } },
    })).toMatchObject({ frameCount: 12, fps: 10, source: 'default' });
  });

  it('reads the app rung through the track\'s declared contract fields (#3015)', () => {
    // The registry row names which runtimeContract fields the track occupies,
    // so the app rung is track-driven rather than hard-coded to walkFrameCount.
    const row = getAnimationTrack(WALK_TRACK);
    expect(resolveAnimationTarget({
      track: WALK_TRACK,
      runtimeContract: { [row.contractFrameCountField]: 16, [row.contractFpsField]: 24 },
    })).toMatchObject({ frameCount: 16, fps: 24, source: 'app' });
  });

  it('ignores the contract\'s fps entirely for a track that declares no fps field', async () => {
    // A registry row may set `contractFpsField: null` — a track whose speed an
    // app has no say in. The app rung must then fall through to
    // set/derived/default and report fpsLocked:false rather than reading some
    // other track's contract key. Only one track exists today, so stand up a
    // null-fps row via a scoped module mock to keep that branch covered.
    vi.resetModules();
    // Mock the LIB registry, not the services/sprites re-export shim: the row
    // this resolver sees comes from animationTrackStore.js, which imports
    // lib/spriteAnimationTracks.js directly (#4901). Mocking the shim would
    // leave the store reading the real table and silently un-discriminate this
    // test.
    const real = await vi.importActual('../../lib/spriteAnimationTracks.js');
    const nullFpsRow = { ...real.ANIMATION_TRACKS.walk, contractFpsField: null };
    vi.doMock('../../lib/spriteAnimationTracks.js', () => ({
      ...real,
      ANIMATION_TRACKS: { walk: nullFpsRow },
      getAnimationTrack: (id) => {
        if (id === undefined || id === null || id === real.WALK_TRACK) return nullFpsRow;
        throw new Error(`Unknown animation track '${String(id)}'`);
      },
    }));
    const { resolveAnimationTarget: resolveWithNullFps } = await import('./animationTargets.js');
    // The literal `null` key is what makes this DISCRIMINATING: without the
    // guard the code would evaluate `runtimeContract[null]`, which coerces to
    // the string key "null" — so a contract carrying that key would resolve
    // fps: 24 / fpsLocked: true. With the guard the rung is skipped entirely.
    expect(resolveWithNullFps({
      runtimeContract: { walkFrameCount: 16, walkFps: 24, null: 24 },
    })).toMatchObject({ frameCount: 16, fps: 10, source: 'app', fpsLocked: false });
    vi.doUnmock('../../lib/spriteAnimationTracks.js');
    vi.resetModules();
  });

  it('resolves scanner against its own range and rejects unknown tracks', () => {
    // Sentinel discipline: absent ⇒ the default track; unrecognized ⇒ an error
    // naming the known tracks, never a silent fall-through to 6–16 / 4–24.
    expect(resolveAnimationTarget({ track: SCANNER_TRACK })).toMatchObject({
      track: SCANNER_TRACK, frameCount: 4, fps: 6, source: 'default',
    });
    expect(() => resolveAnimationTarget({ track: 'unknown' }))
      .toThrow(/Unknown animation track 'unknown'/);
    expect(resolveAnimationTarget({ track: undefined }).track).toBe(WALK_TRACK);
  });
});

describe('withTrackTarget', () => {
  it('preserves an unrecognized sibling track key on write', () => {
    // Forward-compat: a newer PortOS (or a peer) may have written a track this
    // build knows nothing about — a naive overwrite would silently drop it.
    const merged = withTrackTarget(
      { scanner: { frameCount: 4, fps: 6, source: 'set' } },
      WALK_TRACK,
      { frameCount: 12, fps: 10, source: 'set' },
    );
    expect(merged).toEqual({
      scanner: { frameCount: 4, fps: 6, source: 'set' },
      walk: { frameCount: 12, fps: 10, source: 'set' },
    });
  });

  it('tolerates a missing or malformed map', () => {
    expect(withTrackTarget(null, WALK_TRACK, { frameCount: 12, fps: 10, source: 'set' }))
      .toEqual({ walk: { frameCount: 12, fps: 10, source: 'set' } });
    expect(withTrackTarget(['nope'], WALK_TRACK, { frameCount: 12, fps: 10, source: 'set' }))
      .toEqual({ walk: { frameCount: 12, fps: 10, source: 'set' } });
  });

  it('refuses to WRITE a track this build does not know (#3015)', () => {
    // Preserving a sibling key a newer peer wrote and minting a bogus one are
    // different things: the first is forward-compat, the second is a bug that
    // would persist a row nothing can range-check.
    expect(withTrackTarget({}, SCANNER_TRACK, { frameCount: 4, fps: 6, source: 'set' }))
      .toEqual({ scanner: { frameCount: 4, fps: 6, source: 'set' } });
    expect(() => withTrackTarget({}, 'unknown', { frameCount: 4, fps: 6, source: 'set' }))
      .toThrow(/Unknown animation track 'unknown'/);
  });
});

describe('targetDrift', () => {
  const target = { frameCount: 12, fps: 10 };

  it('reports only the directions that disagree, and which knob disagrees', () => {
    expect(targetDrift(target, [
      { direction: 'south', frameCount: 12, fps: 10 },
      { direction: 'east', frameCount: 8, fps: 10 },
      { direction: 'west', frameCount: 12, fps: 24 },
    ])).toEqual([
      {
        direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,
      },
      {
        direction: 'west', frameCount: 12, fps: 24, frameCountDrifts: false, fpsDrifts: true,
      },
    ]);
  });

  it('does not call a direction with no declared geometry "drifted"', () => {
    expect(targetDrift(target, [{ direction: 'south' }])).toEqual([]);
  });

  it('range-checks against the target\'s own track, defaulting when it carries none', () => {
    // A bare `{ frameCount, fps }` target (every pre-#3015 caller) still reads
    // against the walk row; an explicit track is honored.
    expect(targetDrift({ ...target, track: WALK_TRACK }, [
      { direction: 'east', frameCount: 8, fps: 10 },
    ])).toEqual([{
      direction: 'east', frameCount: 8, fps: 10, frameCountDrifts: true, fpsDrifts: false,
    }]);
    expect(targetDrift({ ...target, track: SCANNER_TRACK }, [])).toEqual([]);
    expect(() => targetDrift({ ...target, track: 'unknown' }, []))
      .toThrow(/Unknown animation track 'unknown'/);
  });
});

describe('describeTargetSource', () => {
  it('names the winning rung in the user\'s words', () => {
    expect(describeTargetSource({ source: 'app' }, 'example-game')).toBe('locked by example-game');
    expect(describeTargetSource({ source: 'app' })).toBe('locked by the bound app');
    expect(describeTargetSource({ source: 'set' })).toBe('set target');
    expect(describeTargetSource({ source: 'derived' })).toBe('from the first approved direction');
    expect(describeTargetSource({ source: 'default' })).toBe('default');
  });
});