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

135 KB
Raw Blame
import { on } from 'node:events';
import { spriteEvents } from './events.js';
/**
 * Walk-animation workflow orchestration (#2897): generation gating on locked
 * anchors, run-record lifecycle through the video completion hook, approval
 * with tamper checks, walk-set finalization + immutability, and the loop
 * trimmer. The queue and the deterministic postprocess are mocked — the
 * postprocess itself is covered by walkPostprocess.test.js.
 *
 * Anchor candidates share the cached PNG encoder in `spriteTestFixtures.js`.
 * Excluded from `npm run test:fast` (`VITEST_FAST=1`).
 */

import { describe, it as vitestIt, expect, vi, beforeEach, afterAll } from 'vitest';
import { existsSync, mkdtempSync, rmSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { mkdir, writeFile, readFile, rm } from 'fs/promises';
import { createHash } from 'crypto';
import { ownTestBodies } from '../../lib/mockPathsDataRoot.js';
import {
  capSharpThreads, lockAllAnchors, lockAllAnchorsReal, expectCarriesCorrection, normalizeManifestForComparison,
  writeCandidatePng,
} from './spriteTestFixtures.js';

const restoreSharpThreads = capSharpThreads();
afterAll(restoreSharpThreads);
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-walk-test-'));
// Fail-fast cancellation (--bail from another worker) settles a test's wrapper
// while its body keeps writing into TEST_ROOT; teardown drains the bodies first
// so the root is not removed under them and recreated by their next write.
const owned = ownTestBodies(vitestIt);
const it = owned.it;

vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
  const actual = await importOriginal();
  Object.assign(actual.PATHS, {
    data: TEST_ROOT,
    sprites: join(TEST_ROOT, 'sprites'),
    images: join(TEST_ROOT, 'images'),
    videos: join(TEST_ROOT, 'videos'),
  });
  return actual;
});

// Walk generation now runs grok as an observable TUI session (executeTuiRun)
// rather than a headless media-job. Default mock returns a promise that never
// resolves, so the fire-and-forget render started by startWalkGeneration does
// NOT race the test with a background attach; a happy-path test overrides it
// with mockImplementationOnce to simulate grok writing the MP4.
const executeTuiRun = vi.fn(() => new Promise(() => {}));
vi.mock('../tuiPromptRunner.js', () => ({
  executeTuiRun: (...args) => executeTuiRun(...args),
}));

vi.mock('../../lib/imageCleanDefaults.js', () => ({
  resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
}));

vi.mock('../settings.js', () => ({
  getSettings: async () => ({
    imageGen: { mode: 'grok', grok: { enabled: true, grokPath: '/usr/local/bin/grok' } },
  }),
}));

// The clip-length contract now comes from the dependency-free lib/grokVideoClip.js
// leaf (#3022), so the videoGen graph is out of this suite by construction — no
// mock needed, and the REAL `[6, 10]` list is what the assertions below exercise.

// ffprobe isn't available to every test environment and the suite's stub clips
// aren't decodable media anyway, so the delivered-clip-length probe is a spy:
// unmocked it resolves null (the real "couldn't measure" path), and a test that
// cares about a measured value primes it with mockResolvedValueOnce.
const probeVideoDuration = vi.fn(async () => null);
vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({
  ...await importOriginal(),
  probeVideoDuration: (...args) => probeVideoDuration(...args),
}));

// The real helper measures the anchor with sharp; the stub reports a fixed
// PORTRAIT size so the local lane's canvas choice is exercised for real (the
// chooser is the production one — only the measurement is stubbed).
const STUB_ANCHOR_SIZE = { width: 512, height: 896 };
const prepareWalkAnchorChromaInput = vi.fn(async (_anchorAbs, destAbs, _chromaKey, chooseCanvas = null) => {
  await mkdir(join(destAbs, '..'), { recursive: true });
  await writeFile(destAbs, 'stub-chroma-anchor');
  const canvas = chooseCanvas ? chooseCanvas(STUB_ANCHOR_SIZE) : null;
  return {
    preparation: canvas
      ? 'composited-over-solid-chroma-matte-padded-to-render-canvas'
      : 'composited-over-solid-chroma-matte',
    canvas,
  };
});
const runWalkPostprocess = vi.fn(async ({
  runRel, runAbs, recordId, direction, frameCount = 8, fps = 12,
}) => {
  // Faithfully land the packed strip AND the packaged manifest on disk (the real
  // postprocess writes both) — getWalkState's missing-strip guard flips a
  // candidate whose strip is absent to an error, and approveWalkDirection
  // re-validates the manifest, so a mock that only returned paths would make a
  // re-derived run look broken and un-approvable.
  const stripBytes = 'packaged-strip-bytes';
  await mkdir(join(runAbs, 'generated'), { recursive: true });
  await writeFile(join(runAbs, 'generated', 'strip.png'), stripBytes);
  await writeFile(join(runAbs, 'generated', 'manifest.json'), JSON.stringify({
    schemaVersion: 1,
    kind: 'deterministically-packaged-grok-walk-video',
    characterId: recordId,
    direction,
    frameCount,
    frameRate: fps,
    stripPath: `${runRel}/generated/strip.png`,
    stripSha256: createHash('sha256').update(Buffer.from(stripBytes)).digest('hex'),
  }));
  return {
    manifestPath: `${runRel}/generated/manifest.json`,
    stripPreview: {
      stripPath: `${runRel}/generated/strip.png`, frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
    },
  };
});
// The real extractor shells out to ffmpeg; the source-frame reader (#2980)
// re-extracts on demand when `raw/` was cleaned, so stand in for it with a mock
// that lands the same `source-NNNN.png` shape on disk and returns the sorted
// names, exactly as the real one does.
const EXTRACTED_FRAME_NAMES = ['source-0001.png', 'source-0002.png', 'source-0003.png'];
const extractVideoFrames = vi.fn(async (_videoPath, rawDir) => {
  await mkdir(rawDir, { recursive: true });
  for (const name of EXTRACTED_FRAME_NAMES) {
    await writeFile(join(rawDir, name), `re-extracted:${name}`);
  }
  return [...EXTRACTED_FRAME_NAMES];
});
vi.mock('./walkPostprocess.js', async (importOriginal) => {
  const actual = await importOriginal();
  return {
    ...actual,
    prepareWalkAnchorChromaInput: (...args) => prepareWalkAnchorChromaInput(...args),
    runWalkPostprocess: (...args) => runWalkPostprocess(...args),
    extractVideoFrames: (...args) => extractVideoFrames(...args),
  };
});

// ── Local render lane (#4876) ───────────────────────────────────────────────
// The lane's own unit coverage lives in localAnimationRender.test.js; what these
// mocks buy HERE is that the real lane logic runs THROUGH walk.js, so the
// dispatch, the run-record provenance, and the job-backed staleness rule are
// exercised end to end. Only the ENVIRONMENT is stubbed — the model catalog, the
// runtime/weight probes, and the job queue — never the lane itself, which would
// make these assertions a restatement of the mock.
const H3_MODEL = {
  id: 'minimax_h3_8bit',
  name: 'MiniMax H3 MLX 8-bit',
  repo: 'pipenetwork/MiniMax-H3-MLX-8bit',
  revision: 'rev-abc',
  runtime: 'minimax_h3',
  defaultFrames: 124,
  frameOptions: [107, 124, 141, 158, 175],
  fpsOptions: [24],
  defaultWidth: 1344,
  defaultHeight: 768,
  resolutionOptions: [
    { w: 1344, h: 768 }, { w: 1024, h: 768 }, { w: 768, h: 768 }, { w: 768, h: 1024 },
  ],
};
let localRuntimeReady = true;
vi.mock('../../lib/mediaModels.js', async (importOriginal) => ({
  ...await importOriginal(),
  getVideoModels: () => [H3_MODEL],
}));
vi.mock('../videoGen/runtimes.js', async (importOriginal) => ({
  ...await importOriginal(),
  BYOV_RUNTIME_INFO: { minimax_h3: { label: 'MiniMax H3 MLX' } },
  isByovRuntimeReady: async () => localRuntimeReady,
}));
vi.mock('../../lib/hfCache.js', async (importOriginal) => ({
  ...await importOriginal(),
  inspectModelCache: async () => ({ cached: true, sizeBytes: 1, snapshotPath: '/snap' }),
  findCachedRepoFiles: async () => ['/snap/a.safetensors'],
}));
const enqueuedVideoJobs = [];
const queuedJobsById = new Map();
vi.mock('../mediaJobQueue/index.js', async (importOriginal) => ({
  ...await importOriginal(),
  enqueueJob: (job) => {
    const id = `mjob-${enqueuedVideoJobs.length + 1}`;
    enqueuedVideoJobs.push({ id, ...job });
    queuedJobsById.set(id, { id, status: 'running' });
    return { jobId: id, position: 1, status: 'queued' };
  },
  getJob: (id) => queuedJobsById.get(id) || null,
}));

const records = await import('./records.js');
const { listSpriteAssets } = await import('./paths.js');
const { lockReference, loadManifest } = await import('./reference.js');
const {
  getWalkState, startWalkGeneration, attachTuiWalkResult, approveWalkDirection, rerunWalkPostprocess, unlockWalkSet,
  reopenWalkDirection, invalidateWalkDirectionForAnchorRevision,
  unlockDirectionalAnchor, unlockMainReference, unlockTurnaroundReference,
  setWalkTarget, importedWalkDirections, getWalkSourceFrames,
} = await import('./walk.js');
const { SPRITE_DIRECTIONS, ANCHOR_DIRECTIONS } = await import('./prompts.js');

let seq = 0;
const newId = () => `walker-${++seq}`;
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');

async function characterWithLockedAnchors(id, directions = ['east']) {
  await records.createRecord({ kind: 'character', name: 'Walker' }, id);
  await lockAllAnchors(TEST_ROOT, id, { lockReference, directions, records });
  return id;
}

// `anchored: true` builds the run the way the source-pipeline importer leaves
// it (#2978): every embedded path stays anchored at the SOURCE repo root
// (`art-source/sprites/<id>/…`) because the importer copies manifests
// byte-for-byte against pinned hashes. Readers must re-anchor at read time.
async function makeCandidateRun(recordId, direction, {
  stripBytes = `strip-${direction}`, anchored = false, frameCount = 8, fps = 12,
  anchorSha256,
} = {}) {
  const runId = `walk-${direction}-${(seq++).toString(16).padStart(8, '0')}`;
  const runDir = join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'generated');
  await mkdir(runDir, { recursive: true });
  const stripName = `${recordId}-walk-${direction}-strip.png`;
  await writeFile(join(runDir, stripName), stripBytes);
  const anchor = (rel) => (anchored ? `art-source/sprites/${recordId}/${rel}` : rel);
  const stripRel = `runs/${runId}/generated/${stripName}`;
  const packaged = {
    schemaVersion: 1,
    kind: 'deterministically-packaged-grok-walk-video',
    characterId: recordId,
    direction,
    frameRate: fps,
    frameCount,
    stripPath: anchor(stripRel),
    stripSha256: sha256(Buffer.from(stripBytes)),
  };
  const manifestRel = `runs/${runId}/generated/${recordId}-walk-${direction}-manifest.json`;
  await writeFile(join(runDir, `${recordId}-walk-${direction}-manifest.json`), JSON.stringify(packaged));
  await writeFile(join(TEST_ROOT, 'sprites', recordId, 'runs', runId, 'animation-run.json'), JSON.stringify({
    schemaVersion: 1,
    kind: 'grok-game-animation-frames-run',
    status: 'candidate',
    id: runId,
    characterId: recordId,
    direction,
    chromaKey: '#FF00FF',
    ...(anchorSha256 ? { anchorSha256 } : {}),
    createdAt: new Date().toISOString(),
    postprocessManifest: anchor(manifestRel),
    // The run's i2v clip — imported alongside the run since #2984, and
    // anchored the same way every other imported path is.
    sourceVideoPath: anchor(`runs/${runId}/generated/source-video.mp4`),
    // Real candidate records carry the packed-strip preview the UI renders.
    // The importer stamps it as `path` (repo-anchored); PortOS uses `stripPath`.
    stripPreview: {
      ...(anchored ? { path: anchor(stripRel) } : { stripPath: stripRel }),
      frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
    },
  }));
  return { runId, manifestRel };
}

/**
 * Build ONE approved direction the way the source-pipeline importer leaves it
 * (#2895/#2984): the run under `<base>/<runId>/` with every embedded path
 * anchored at the SOURCE repo root, no `id` field at all, and — unless
 * `clip: false` — the `source-video.mp4` the importer now copies across.
 *
 * `declaredBase` differs from `base` to reproduce source-tree layout drift: the
 * manifests say one run layout while the files sit under the other, and both
 * spellings denote the same run.
 */
async function makeImportedDirection(recordId, direction, {
  base = 'grok', declaredBase = base, clip = true, frameCount = 8, fps = 12,
  status = 'approved',
} = {}) {
  const runId = `run-${(seq++).toString(16)}`;
  const spriteRoot = join(TEST_ROOT, 'sprites', recordId);
  const genAbs = join(spriteRoot, base, runId, 'generated');
  await mkdir(genAbs, { recursive: true });
  const anchor = (rel) => `art-source/sprites/${recordId}/${rel}`;
  const declaredRun = `${declaredBase}/${runId}`;
  const stripRel = `${declaredRun}/generated/${direction}-strip.png`;
  const manifestRel = `${declaredRun}/generated/${direction}-manifest.json`;
  const stripBytes = `imported-strip-${direction}`;
  await writeFile(join(genAbs, `${direction}-strip.png`), stripBytes);
  await writeFile(join(genAbs, `${direction}-manifest.json`), JSON.stringify({
    schemaVersion: 1,
    kind: 'deterministically-packaged-grok-walk-video',
    characterId: recordId,
    direction,
    frameRate: fps,
    frameCount,
    stripPath: anchor(stripRel),
    stripSha256: sha256(Buffer.from(stripBytes)),
  }));
  if (clip) await writeFile(join(genAbs, 'source-video.mp4'), 'IMPORTED-CLIP');
  await writeFile(join(spriteRoot, base, runId, 'animation-run.json'), JSON.stringify({
    kind: 'grok-walk-animation-run',
    status: 'candidate',
    characterId: recordId,
    direction,
    postprocessManifest: anchor(manifestRel),
    sourceVideoPath: anchor(`${declaredRun}/generated/source-video.mp4`),
    stripPreview: {
      path: anchor(stripRel), frameCount, fps, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
    },
  }));
  return {
    runId,
    entry: { status, runPath: anchor(declaredRun), runManifest: anchor(manifestRel) },
  };
}

// A finalized, imported character: `perDirection` maps each direction to its
// makeImportedDirection options. Both the selection and the frozen walk set are
// copied source-anchored, exactly as the importer leaves them.
async function importedCharacter(id, perDirection) {
  const walkDir = join(TEST_ROOT, 'sprites', id, 'walk');
  await mkdir(walkDir, { recursive: true });
  const directions = {};
  const runIds = {};
  for (const [direction, options] of Object.entries(perDirection)) {
    const made = await makeImportedDirection(id, direction, options);
    directions[direction] = made.entry;
    runIds[direction] = made.runId;
  }
  await writeFile(join(walkDir, `${id}-walk-selection-v1.json`), JSON.stringify({
    schemaVersion: 1,
    kind: 'reviewed-directional-walk-selection',
    characterId: id,
    status: 'complete',
    animationTargets: {},
    directions,
  }));
  await writeFile(join(walkDir, `${id}-walk-set-v1.json`), JSON.stringify({
    schemaVersion: 1,
    kind: 'finalized-eight-direction-walk-set',
    characterId: id,
    status: 'final',
    selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,
    directionOrder: SPRITE_DIRECTIONS,
    directions,
  }));
  return runIds;
}

// #6180 — characterWithLockedAnchors materializes every locked character from
// a single real-locked prototype (spriteTestFixtures.js's lockAllAnchors)
// instead of re-running the real lock pipeline per test. This is the
// acceptance gate for that refactor: it proves a materialized character is
// indistinguishable from one the real pipeline built, for both the full
// anchor set and a partial one — the partial case is the one where the
// reset-to-pending logic could silently drift from a real partial lock.
describe('lockAllAnchors fixture materialization (#6180)', () => {
  it('matches the real lock pipeline byte-for-byte (file names, PNG bytes, manifest, record state) after id normalization', async () => {
    const realId = newId();
    await records.createRecord({ kind: 'character', name: 'Walker' }, realId);
    await lockAllAnchorsReal(TEST_ROOT, realId, { lockReference, directions: ANCHOR_DIRECTIONS });
    const fastId = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);

    const [realAssets, fastAssets] = await Promise.all([
      listSpriteAssets(realId, { subdir: 'reference', metadata: false }),
      listSpriteAssets(fastId, { subdir: 'reference', metadata: false }),
    ]);
    const idNormalizedNames = (id, assets) => assets.map((a) => a.path.split(id).join('<id>')).sort();
    expect(idNormalizedNames(fastId, fastAssets)).toEqual(idNormalizedNames(realId, realAssets));

    for (const asset of realAssets.filter((a) => a.path.endsWith('.png'))) {
      const fastRel = asset.path.split(realId).join(fastId);
      const [realBytes, fastBytes] = await Promise.all([
        readFile(join(TEST_ROOT, 'sprites', realId, asset.path)),
        readFile(join(TEST_ROOT, 'sprites', fastId, fastRel)),
      ]);
      expect(fastBytes.equals(realBytes)).toBe(true);
    }

    const [realManifest, fastManifest] = await Promise.all([loadManifest(realId), loadManifest(fastId)]);
    expect(normalizeManifestForComparison(fastManifest, fastId))
      .toEqual(normalizeManifestForComparison(realManifest, realId));

    const [realRecord, fastRecord] = await Promise.all([records.getRecord(realId), records.getRecord(fastId)]);
    expect(fastRecord.chromaKey).toBe(realRecord.chromaKey);
    expect(fastRecord.status).toBe(realRecord.status);
  });

  it('resets an anchor outside the requested set to the exact seeded-pending shape a fresh partial lock would leave', async () => {
    const realId = newId();
    await records.createRecord({ kind: 'character', name: 'Walker' }, realId);
    await lockAllAnchorsReal(TEST_ROOT, realId, { lockReference, directions: ['east'] });
    const fastId = await characterWithLockedAnchors(newId(), ['east']);

    const [realManifest, fastManifest] = await Promise.all([loadManifest(realId), loadManifest(fastId)]);
    expect(normalizeManifestForComparison(fastManifest, fastId))
      .toEqual(normalizeManifestForComparison(realManifest, realId));

    const west = fastManifest.anchors.find((a) => a.direction === 'west');
    expect(west.status).toBe('pending');
    expect(west.path).toBeUndefined();
    expect(west.sha256).toBeUndefined();
    expect(fastManifest.status).toBe('in-progress');

    const [realRecord, fastRecord] = await Promise.all([records.getRecord(realId), records.getRecord(fastId)]);
    expect(fastRecord.status).toBe(realRecord.status);
    expect(fastRecord.status).toBe('reference');
  });
});

describe('named-track isolation', () => {
  it('does not surface or reprocess a scanner run through the walk workflow', async () => {
    const id = await characterWithLockedAnchors(newId(), []);
    const runId = 'scanner-east-00000001';
    const runDir = join(TEST_ROOT, 'sprites', id, 'runs', runId);
    await mkdir(runDir, { recursive: true });
    await writeFile(join(runDir, 'animation-run.json'), JSON.stringify({
      id: runId,
      track: 'scanner',
      status: 'rendering',
      characterId: id,
      direction: 'east',
      createdAt: new Date().toISOString(),
    }));

    expect((await getWalkState(id)).runs).toEqual([]);
    await expect(rerunWalkPostprocess(id, { runId, frameCount: 8, fps: 12 }))
      .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });
  });
});

beforeEach(() => {
  executeTuiRun.mockClear();
  executeTuiRun.mockImplementation(() => new Promise(() => {}));
  prepareWalkAnchorChromaInput.mockClear();
  runWalkPostprocess.mockClear();
  // Reset the probe too (not just mockClear): a `mockResolvedValueOnce` primed
  // by a test whose run errors before packageRun would otherwise stay queued
  // and leak its value into the next test's first probe.
  probeVideoDuration.mockReset();
  probeVideoDuration.mockResolvedValue(null);
  rmSync(join(TEST_ROOT, 'sprite-records.json'), { force: true });
});
afterAll(async () => {
  try {
    await owned.drain();
  } finally {
    rmSync(TEST_ROOT, { recursive: true, force: true });
  }
});

describe('startWalkGeneration', () => {
  it('409s when the direction anchor is not locked', async () => {
    const id = newId();
    await records.createRecord({ kind: 'character', name: 'Walker' }, id);
    await expect(startWalkGeneration(id, { direction: 'east' }))
      .rejects.toMatchObject({ code: 'ANCHOR_NOT_LOCKED' });
  });

  it('starts an observable grok-tui render off a locked anchor', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const result = await startWalkGeneration(id, { direction: 'east' });
    expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);
    expect(result.duration).toBe(6); // GROK_VIDEO_DEFAULT_DURATION — grok's shortest deliverable clip
    // The shell session id is the run id, so the card can deep-link to /shell/<id>.
    expect(result.shellSession).toBe(result.runId);

    // grok runs as a TUI session (not a media job) so the user can watch it.
    expect(executeTuiRun).toHaveBeenCalledOnce();
    const call = executeTuiRun.mock.calls[0][0];
    expect(call.runId).toBe(result.runId);
    expect(call.provider).toMatchObject({ id: 'grok-tui', type: 'tui', command: '/usr/local/bin/grok' });
    expect(call.workspacePath).toBe(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated'));
    // The task points grok at the chroma-backed input and the exact MP4 path.
    expect(call.prompt).toContain('walking east');
    expect(call.prompt).toContain('magenta (#FF00FF)');
    expect(call.prompt).toContain(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'input-anchor-chroma.png'));
    expect(call.prompt).toContain(join(TEST_ROOT, 'sprites', id, 'runs', result.runId, 'generated', 'source-video.mp4'));
    expect(call.idleMs).toBeGreaterThan(8000); // longer than the default one-shot idle

    // Chroma-backed input prepared from the anchor; run persisted as 'rendering'
    // with the shell session id.
    expect(prepareWalkAnchorChromaInput).toHaveBeenCalledOnce();
    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(1);
    expect(runs[0]).toMatchObject({
      id: result.runId, status: 'rendering', provider: 'grok-tui', shellSession: result.runId,
      direction: 'east', chromaKey: '#FF00FF',
    });
    expect(runs[0].animationInputPreparation).toBe('composited-over-solid-chroma-matte');
  });

  it('appends a trimmed correction note to the motion prompt and stamps it on the run (#3134)', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await startWalkGeneration(id, {
      direction: 'east', correctionPrompt: '  the legs barely lift  ',
    });
    expectCarriesCorrection(expect, executeTuiRun.mock.calls[0][0].prompt, 'the legs barely lift');
    // Persisted on the run so the provenance rebuild can reproduce it.
    const { runs } = await getWalkState(id);
    expect(runs.find((r) => r.id === runId).correctionPrompt).toBe('the legs barely lift');
  });

  it('leaves a blank correction note out of the prompt and the run record (#3134)', async () => {
    // The TUI task is `<motion prompt>\n\n<per-run input/output paths>`, so
    // compare the motion prompt only — the paths legitimately differ per run.
    const motionPrompt = () => executeTuiRun.mock.calls[0][0].prompt.split('\n\n')[0];
    const plain = await characterWithLockedAnchors(newId(), ['east']);
    await startWalkGeneration(plain, { direction: 'east' });
    const blindPrompt = motionPrompt();
    executeTuiRun.mockClear();

    const blank = await characterWithLockedAnchors(newId(), ['east']);
    const { runId: blankRun } = await startWalkGeneration(blank, { direction: 'east', correctionPrompt: '   ' });
    expect(motionPrompt()).toBe(blindPrompt);
    const { runs } = await getWalkState(blank);
    expect(runs.find((r) => r.id === blankRun)).not.toHaveProperty('correctionPrompt');
  });

  it('honors duration 10 (passed to the grok task)', async () => {
    const id = await characterWithLockedAnchors(newId(), []);
    const result = await startWalkGeneration(id, { direction: 'south', duration: 10 });
    expect(result.duration).toBe(10);
    expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 10 seconds');
  });

  // 2s is the length a user reaches for to "save render time"; grok renders 6s
  // for it regardless (#3022), so the prompt must ask for 6 — putting a number
  // in it that the tool silently ignores is what made the old picker a lie.
  // (The full fallback table is unit-tested in lib/grokVideoClip.test.js.)
  for (const duration of [2, 5]) {
    it(`asks grok for 6s when ${duration}s is requested, since ${duration}s is not deliverable`, async () => {
      const id = await characterWithLockedAnchors(newId(), ['east']);
      const result = await startWalkGeneration(id, { direction: 'east', duration });
      expect(result.duration).toBe(6);
      expect(executeTuiRun.mock.calls[0][0].prompt).toContain('for 6 seconds');
      expect(executeTuiRun.mock.calls[0][0].prompt).not.toContain(`for ${duration} seconds`);
    });
  }

  // Own completion through the persisted invalidation stream, not waitFor's
  // one-second polling budget. Subscribe before releasing the fake TUI so a
  // fast attachment cannot publish its terminal event before the test listens.
  async function generateAndWaitForTerminal(id, options, signal, render) {
    let release;
    const released = new Promise(resolve => { release = resolve; });
    executeTuiRun.mockImplementationOnce(async args => { await released; await render(args); });
    const result = await startWalkGeneration(id, options);
    const changes = on(spriteEvents, 'changed', { signal });
    release();
    try {
      for await (const [{ recordId }] of changes) {
        if (recordId !== id) continue;
        const { runs } = await getWalkState(id);
        const run = runs.find(entry => entry.id === result.runId);
        if (run && ['candidate', 'error'].includes(run.status)) return { ...result, run };
      }
      throw new Error('Walk completion event stream ended before a terminal run');
    } finally { await changes.return(); }
  }

  it('stores the chosen frame count + fps on the run and passes them to the packer', async ({ signal }) => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    // Frame count / fps are pinned at the SET level now (#2985) — a render must
    // agree with the target, so pin it first, then generate against it.
    await setWalkTarget(id, { frameCount: 14, fps: 8 });
    const { runId, run } = await generateAndWaitForTerminal(id, { direction: 'east', frameCount: 14, fps: 8 }, signal, async ({ workspacePath }) => {
      await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');
    });
    expect(run.status).toBe('candidate');
    const { runs } = await getWalkState(id);
    expect(runs[0]).toMatchObject({ id: runId, frameCount: 14, fps: 8 });
    expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 14, fps: 8 });
  });

  it('packages the candidate once grok writes the clip (full render→attach)', async ({ signal }) => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    // Simulate grok saving the MP4 to the directed path, then finishing.
    const { runId, run } = await generateAndWaitForTerminal(id, { direction: 'east' }, signal, async ({ workspacePath }) => {
      await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');
    });
    expect(run.status).toBe('candidate');
    expect(runWalkPostprocess).toHaveBeenCalledOnce();
    const { runs } = await getWalkState(id);
    expect(runs[0]).toMatchObject({
      id: runId, status: 'candidate', postprocessManifest: `runs/${runId}/generated/manifest.json`,
    });
    expect(runs[0].sourceVideoSha256).toBe(sha256(Buffer.from('grok-clip-bytes')));
    // The stub clip isn't real media, so ffprobe finds no duration — the field
    // must be ABSENT rather than 0, so "we couldn't measure it" never renders as
    // "grok returned a zero-length clip" (#3022).
    expect(runs[0]).not.toHaveProperty('sourceVideoSeconds');
  });

  it('stamps the DELIVERED clip length, which need not match what was requested', async ({ signal }) => {
    // grok's image_to_video renders 6s for anything shorter than 6s, so the
    // requested length is not a promise — the probe is. Here the request is 10s
    // and the file measures 6s, the exact divergence the field exists to expose.
    probeVideoDuration.mockResolvedValueOnce(6.041667);
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { run } = await generateAndWaitForTerminal(id, { direction: 'east', duration: 10 }, signal, async ({ workspacePath }) => {
      await writeFile(join(workspacePath, 'source-video.mp4'), 'grok-clip-bytes');
    });
    expect(run.status).toBe('candidate');
    const { runs } = await getWalkState(id);
    expect(runs[0].duration).toBe(10);      // what we asked grok for
    expect(runs[0].sourceVideoSeconds).toBe(6.04); // what grok actually delivered
  });

  it('marks the run errored when grok finishes without a clip', async ({ signal }) => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { run } = await generateAndWaitForTerminal(id, { direction: 'east' }, signal, async () => {});
    expect(run.status).toBe('error');
    const { runs } = await getWalkState(id);
    expect(runs[0].postprocessError).toMatch(/without writing the walk video/);
    expect(runWalkPostprocess).not.toHaveBeenCalled();
  });

  it('refuses a second render while one is already in flight for the direction', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    // Default executeTuiRun mock never resolves → the first run stays 'rendering'.
    await startWalkGeneration(id, { direction: 'east' });
    await expect(startWalkGeneration(id, { direction: 'east' }))
      .rejects.toMatchObject({ code: 'WALK_RENDER_IN_PROGRESS' });
    expect(executeTuiRun).toHaveBeenCalledTimes(1); // the second never dispatched
  });

  it('treats a long-stale rendering run as errored and allows regenerating it', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    // A run left 'rendering' by a server that died mid-render, well past the cap.
    const staleId = 'walk-east-deadbeef';
    await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', staleId, 'generated'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', staleId, 'animation-run.json'), JSON.stringify({
      schemaVersion: 1, id: staleId, status: 'rendering', characterId: id, direction: 'east',
      chromaKey: '#FF00FF', createdAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
    }));
    const { runs } = await getWalkState(id);
    const stale = runs.find((r) => r.id === staleId);
    expect(stale.status).toBe('error');
    expect(stale.postprocessError).toMatch(/interrupted/);
    // The in-flight guard must NOT treat a stale run as live — regeneration works.
    const result = await startWalkGeneration(id, { direction: 'east' });
    expect(result.runId).toMatch(/^walk-east-[0-9a-f]{8}$/);
    expect(result.runId).not.toBe(staleId);
  });
});

describe('startWalkGeneration — local render lane (#4876)', () => {
  beforeEach(() => {
    localRuntimeReady = true;
    enqueuedVideoJobs.length = 0;
    queuedJobsById.clear();
  });

  it('defaults to grok when no provider is requested, exactly as before the lane existed', async () => {
    const id = await characterWithLockedAnchors(newId());
    const res = await startWalkGeneration(id, { direction: 'east' });
    expect(res.provider).toBe('grok');
    expect(res.shellSession).toBe(res.runId);
    expect(enqueuedVideoJobs).toHaveLength(0);
    expect(executeTuiRun).toHaveBeenCalled();
    const [run] = (await getWalkState(id)).runs;
    expect(run.provider).toBe('grok-tui');
    expect(run.jobId).toBeUndefined();
  });

  it('queues a MEDIA JOB instead of a TUI session when provider is local', async () => {
    const id = await characterWithLockedAnchors(newId());
    executeTuiRun.mockClear();
    const res = await startWalkGeneration(id, { direction: 'east', provider: 'local', duration: 6 });
    expect(executeTuiRun).not.toHaveBeenCalled();
    expect(res.provider).toBe('local');
    expect(res.jobId).toBe('mjob-1');
    // No PTY exists, so the card must not offer a Shell deep-link.
    expect(res.shellSession).toBeUndefined();
    // owner 'sprites' + the spriteWalk tag is the shipped contract the client's
    // pending-render rehydrate reads; spriteAnimation is what the durable
    // completion hook decodes.
    expect(enqueuedVideoJobs[0]).toMatchObject({ kind: 'video', owner: 'sprites' });
    expect(enqueuedVideoJobs[0].params.spriteWalk).toEqual({ recordId: id, direction: 'east' });
    expect(enqueuedVideoJobs[0].params.spriteAnimation).toMatchObject({ recordId: id, track: 'walk', direction: 'east' });
    expect(enqueuedVideoJobs[0].params).toMatchObject({
      modelId: 'minimax_h3_8bit',
      mode: 'image',
      // 6s at 24fps = 144 requested → 141 is the nearest legal H3 count.
      numFrames: 141,
      fps: 24,
      hidden: true,
    });
    expect(enqueuedVideoJobs[0].params.prompt).toMatch(/walk-in-place/);
  });

  it('renders on the canvas matching the ANCHOR aspect, not the model default', async () => {
    const id = await characterWithLockedAnchors(newId());
    await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    // The stub anchor is 512x896 (portrait). H3 defaults to 1344x768; sending
    // that would center-crop the character's head and feet off.
    expect(enqueuedVideoJobs[0].params).toMatchObject({ width: 768, height: 1024 });
  });

  it('stamps the lane, model, runtime, geometry, and job id on the run record', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local', duration: 6 });
    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run).toMatchObject({
      provider: 'minimax-h3-local',
      videoModelId: 'minimax_h3_8bit',
      videoRuntime: 'minimax_h3',
      renderFrames: 141,
      renderFps: 24,
      renderWidth: 768,
      renderHeight: 1024,
      jobId: 'mjob-1',
      status: 'rendering',
    });
    // The provenance spread must WIN over the grok defaults, not be overwritten.
    expect(run.shellSession).toBeNull();
    // The postprocess knobs stay the SET's target, untouched by the render
    // geometry above — a 141-frame 24fps source clip still packs the pinned cycle.
    const { walkTarget } = await getWalkState(id);
    expect(run.frameCount).toBe(walkTarget.frameCount);
    expect(run.fps).toBe(walkTarget.fps);
    expect(run.frameCount).not.toBe(run.renderFrames);
    expect(run.animationInputPreparation).toBe('composited-over-solid-chroma-matte-padded-to-render-canvas');
  });

  it('409s before writing any run record when the local runtime is not installed', async () => {
    const id = await characterWithLockedAnchors(newId());
    localRuntimeReady = false;
    await expect(startWalkGeneration(id, { direction: 'east', provider: 'local' }))
      .rejects.toMatchObject({ status: 409, code: 'LOCAL_VIDEO_PROVIDER_NOT_READY' });
    expect((await getWalkState(id)).runs).toHaveLength(0);
    expect(enqueuedVideoJobs).toHaveLength(0);
  });

  it('rejects an unknown provider rather than falling back to the paid lane', async () => {
    const id = await characterWithLockedAnchors(newId());
    await expect(startWalkGeneration(id, { direction: 'east', provider: 'minimax' }))
      .rejects.toMatchObject({ status: 400, code: 'ANIMATION_PROVIDER_INVALID' });
    expect(executeTuiRun).not.toHaveBeenCalledWith(expect.objectContaining({ label: expect.stringContaining(id) }));
  });

  it('keeps a long-running local render LIVE past the grok staleness cutoff', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    // Backdate the run well beyond grok's ~31-minute cutoff. A local H3 clip is
    // a multi-hour render, so the wall clock must not decide this.
    const runJson = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
    const stored = JSON.parse(await readFile(runJson, 'utf8'));
    stored.createdAt = new Date(Date.now() - 5 * 60 * 60_000).toISOString();
    await writeFile(runJson, JSON.stringify(stored));
    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run.status).toBe('rendering');
  });

  it('flips a local run to error as soon as its job settles without an attach', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    // Job terminal but the run still says 'rendering' — the server died between
    // the two. Reported immediately rather than after a wall-clock wait.
    queuedJobsById.set('mjob-1', { id: 'mjob-1', status: 'failed', error: 'oom' });
    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run.status).toBe('error');
    expect(run.postprocessError).toMatch(/interrupted/);
  });

  it('leaves a local run alone when the queue has forgotten its job but the clock is young', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    queuedJobsById.delete('mjob-1');
    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run.status).toBe('rendering');
  });

  it('keeps a local run that renders for HOURS then packs looking healthy, and still blocked', async () => {
    // The user-visible shape of the packaging-window bug: `getWalkState` is what
    // the card polls every few seconds while a run packages, and the in-flight
    // guard reads the same normalized state. Anchoring the window on `createdAt`
    // made a successful 3-hour render report "interrupted" the instant it began
    // to pack AND released the guard — so a Regenerate click would start a second
    // multi-hour render for a facing that already had a good candidate.
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    const runJson = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
    const stored = JSON.parse(await readFile(runJson, 'utf8'));
    stored.createdAt = new Date(Date.now() - 3 * 60 * 60_000).toISOString();
    stored.status = 'postprocessing';
    stored.postprocessingStartedAt = new Date().toISOString();
    await writeFile(runJson, JSON.stringify(stored));

    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run.status).toBe('postprocessing');
    expect(run.postprocessError).toBeUndefined();
    await expect(startWalkGeneration(id, { direction: 'east', provider: 'local' }))
      .rejects.toMatchObject({ code: 'WALK_RENDER_IN_PROGRESS' });
  });

  it('errors a run whose PACKAGING itself was interrupted, freeing the direction', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    const runJson = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
    const stored = JSON.parse(await readFile(runJson, 'utf8'));
    stored.status = 'postprocessing';
    stored.postprocessingStartedAt = new Date(Date.now() - 40 * 60_000).toISOString();
    await writeFile(runJson, JSON.stringify(stored));

    const run = (await getWalkState(id)).runs.find((r) => r.id === runId);
    expect(run.status).toBe('error');
    // Both in-flight guards count `postprocessing` as busy, so without the
    // normalization this direction would be unrenderable forever.
    await expect(startWalkGeneration(id, { direction: 'east', provider: 'local' })).resolves.toBeTruthy();
  });

  it('reports a local attach that found no clip in local terms, not grok terms', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    await attachTuiWalkResult(id, runId, join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'));
    const stored = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), 'utf8'));
    expect(stored.status).toBe('error');
    expect(stored.postprocessError).toMatch(/Render Queue/);
    expect(stored.postprocessError).not.toMatch(/shell session/);
  });

  it('runs the SAME deterministic postprocess on a local clip as on a grok one', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await startWalkGeneration(id, { direction: 'east', provider: 'local' });
    const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');
    await writeFile(videoAbs, 'local-rendered-clip');
    runWalkPostprocess.mockClear();
    const persisted = [];
    const onChanged = ({ recordId }) => {
      if (recordId === id) persisted.push(JSON.parse(readFileSync(
        join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), 'utf8',
      )).status);
    };
    spriteEvents.on('changed', onChanged);
    try {
      await attachTuiWalkResult(id, runId, videoAbs);
    } finally {
      spriteEvents.off('changed', onChanged);
    }
    expect(persisted).toEqual(['postprocessing', 'candidate']);
    expect(runWalkPostprocess).toHaveBeenCalledTimes(1);
    const stored = JSON.parse(await readFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), 'utf8'));
    expect(stored.status).toBe('candidate');
    // Provenance survives packaging, so an approved frame set still names the
    // model that produced it.
    expect(stored.provider).toBe('minimax-h3-local');
    expect(stored.videoModelId).toBe('minimax_h3_8bit');
  });
});

describe('attachTuiWalkResult (grok-tui completion)', () => {
  // Write a source video directly into a run's generated dir (grok's TUI run
  // saves it there in production) and return its abs path.
  async function landVideo(id, runId, bytes = 'grok-clip') {
    const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');
    await mkdir(join(videoAbs, '..'), { recursive: true });
    await writeFile(videoAbs, bytes);
    return videoAbs;
  }

  it('refuses to attach onto an approved run (a late render must not overwrite frozen evidence)', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await approveWalkDirection(id, { direction: 'east', runId });
    const videoAbs = await landVideo(id, runId, 'late');
    runWalkPostprocess.mockClear();
    await attachTuiWalkResult(id, runId, videoAbs);
    expect(runWalkPostprocess).not.toHaveBeenCalled();
    const { runs } = await getWalkState(id);
    expect(runs.find((r) => r.id === runId).status).toBe('candidate'); // untouched
  });

  it('refuses to attach after the walk set is finalized', async () => {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      await approveWalkDirection(id, { direction, runId }); // eslint-disable-line no-await-in-loop
    }
    const staleRunId = 'walk-east-0badc0de';
    await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', staleRunId, 'generated'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', staleRunId, 'animation-run.json'), JSON.stringify({
      schemaVersion: 1, id: staleRunId, status: 'rendering', characterId: id, direction: 'east', chromaKey: '#FF00FF',
    }));
    const videoAbs = await landVideo(id, staleRunId, 'late');
    runWalkPostprocess.mockClear();
    await attachTuiWalkResult(id, staleRunId, videoAbs);
    expect(runWalkPostprocess).not.toHaveBeenCalled();
  });

  it('skips silently when the run record is missing', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const videoAbs = await landVideo(id, 'walk-east-deadbeef');
    await attachTuiWalkResult(id, 'walk-east-deadbeef', videoAbs); // no throw
    expect(runWalkPostprocess).not.toHaveBeenCalled();
  });
});

describe('rerunWalkPostprocess', () => {
  it('404s an unknown run and 409s a run with no video', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(rerunWalkPostprocess(id, { runId: 'walk-east-deadbeef' }))
      .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });
    const { runId } = await startWalkGeneration(id, { direction: 'east' });
    await expect(rerunWalkPostprocess(id, { runId }))
      .rejects.toMatchObject({ code: 'VIDEO_NOT_READY' });
  });

  it('re-packages a landed video and 409s an approved run', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await startWalkGeneration(id, { direction: 'east' });
    const videoAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4');
    await writeFile(videoAbs, 'landed');
    const run = await rerunWalkPostprocess(id, { runId });
    expect(run.status).toBe('candidate');

    // Approve it (needs a packaged manifest + strip on disk), then rerun 409s.
    const { runId: approvedRun } = await makeCandidateRun(id, 'east');
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', approvedRun, 'generated', 'source-video.mp4'), 'landed');
    await approveWalkDirection(id, { direction: 'east', runId: approvedRun });
    await expect(rerunWalkPostprocess(id, { runId: approvedRun }))
      .rejects.toMatchObject({ code: 'RUN_APPROVED' });
  });

  it('reprocesses the on-disk clip at a new frame count + fps (no regeneration)', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await setWalkTarget(id, { frameCount: 8, fps: 12 });
    const { runId } = await startWalkGeneration(id, { direction: 'east', frameCount: 8, fps: 12 });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'landed');
    runWalkPostprocess.mockClear();
    // Retargeting the SET is what unlocks a reprocess at a new geometry — the
    // reprocess is how a drifted direction is brought back into line.
    await setWalkTarget(id, { frameCount: 16, fps: 6 });
    const run = await rerunWalkPostprocess(id, { runId, frameCount: 16, fps: 6 });
    // The override reaches the deterministic packer — same clip, new count/fps.
    expect(runWalkPostprocess).toHaveBeenCalledOnce();
    expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 16, fps: 6 });
    // …and is stamped back onto the run record so the card reflects the choice.
    expect(run).toMatchObject({ frameCount: 16, fps: 6 });
  });
});

// #2985: the cycle geometry is pinned per SET and enforced when each render is
// queued, instead of surfacing as an atlas-compile wall eight renders later.
describe('walk cycle target', () => {
  const readSelection = (id) => readFile(
    join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), 'utf8',
  ).then(JSON.parse);

  it('derives the target from the first packaged direction and reports drift', async () => {
    // The exact shape this issue exists for: one direction packed at 12 frames
    // and the rest at 8. It must LOAD, resolve a target, and name the drifted
    // directions — not throw, and not wait until compile to complain.
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    await makeCandidateRun(id, 'south', { frameCount: 12, fps: 10 });
    await makeCandidateRun(id, 'east');
    await makeCandidateRun(id, 'west');
    const { walkTarget } = await getWalkState(id);
    expect(walkTarget).toMatchObject({ frameCount: 12, fps: 10, source: 'derived' });
    expect(walkTarget.drift.map((d) => d.direction).sort()).toEqual(['east', 'west']);
    expect(walkTarget.drift[0]).toMatchObject({ frameCount: 8, fps: 12, frameCountDrifts: true });
  });

  it('resolves the target from the bound app\'s runtime contract and refuses to override it', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await records.updateRecord(id, {
      publishBinding: { appId: 'example-game', runtimeContract: { walkFrameCount: 16 } },
    });
    const { walkTarget } = await getWalkState(id);
    expect(walkTarget).toMatchObject({
      frameCount: 16, source: 'app', frameCountLocked: true, appId: 'example-game',
    });
    // Per-render override → refused; the app decides what its atlas may hold.
    await expect(startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 10 }))
      .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
    // …and so is retargeting the set behind the contract's back.
    await expect(setWalkTarget(id, { frameCount: 12, fps: 10 }))
      .rejects.toMatchObject({ code: 'WALK_TARGET_LOCKED' });
  });

  it('409s a generate whose geometry disagrees with the target, naming both values', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
    await setWalkTarget(id, { frameCount: 12, fps: 10 });
    await expect(startWalkGeneration(id, { direction: 'east', frameCount: 8, fps: 10 }))
      .rejects.toMatchObject({
        code: 'WALK_TARGET_MISMATCH',
        status: 409,
        message: expect.stringContaining('targets 12 frames @ 10fps'),
      });
    await expect(startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 24 }))
      .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
    expect(executeTuiRun).not.toHaveBeenCalled();
    // A matching request goes through, and an omitted geometry adopts the target.
    const matching = await startWalkGeneration(id, { direction: 'east', frameCount: 12, fps: 10 });
    expect(matching.runId).toMatch(/^walk-east-/);
    await startWalkGeneration(id, { direction: 'west' });
    const { runs } = await getWalkState(id);
    expect(runs.every((r) => r.frameCount === 12 && r.fps === 10)).toBe(true);
  });

  it('409s a reprocess whose geometry disagrees with the target', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await startWalkGeneration(id, { direction: 'east' });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'landed');
    runWalkPostprocess.mockClear();
    await expect(rerunWalkPostprocess(id, { runId, frameCount: 6, fps: 10 }))
      .rejects.toMatchObject({ code: 'WALK_TARGET_MISMATCH' });
    expect(runWalkPostprocess).not.toHaveBeenCalled();
    // Omitting the geometry adopts the target rather than 409ing.
    await rerunWalkPostprocess(id, { runId });
    expect(runWalkPostprocess.mock.calls[0][0]).toMatchObject({ frameCount: 12, fps: 10 });
  });

  it('persists an explicit target track-keyed, preserving an unknown sibling track', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await setWalkTarget(id, { frameCount: 12, fps: 10 });
    // Simulate a newer PortOS (or a peer) having written a track this build
    // knows nothing about — it must survive the next write untouched.
    const selection = await readSelection(id);
    selection.animationTargets.scanner = { frameCount: 4, fps: 6, source: 'set' };
    await writeFile(
      join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`),
      JSON.stringify(selection),
    );
    const state = await setWalkTarget(id, { frameCount: 14, fps: 8 });
    expect(state.walkTarget).toMatchObject({ frameCount: 14, fps: 8, source: 'set' });
    expect(await readSelection(id)).toMatchObject({
      animationTargets: {
        walk: { frameCount: 14, fps: 8, source: 'set' },
        scanner: { frameCount: 4, fps: 6, source: 'set' },
      },
    });
  });

  it('lazily pins a derived target on the first write, stamped as derived', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
    await makeCandidateRun(id, 'east');
    // Nothing written yet — a read never mutates the record, so an older peer
    // keeps seeing exactly what it wrote.
    expect((await getWalkState(id)).walkTarget).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
    await expect(readSelection(id)).rejects.toThrow();
    // The first write path resolves it and records it, so it stops being implicit.
    await startWalkGeneration(id, { direction: 'west', frameCount: 8, fps: 12 });
    expect((await readSelection(id)).animationTargets.walk)
      .toEqual({ frameCount: 8, fps: 12, source: 'derived' });
    expect((await getWalkState(id)).walkTarget).toMatchObject({ source: 'derived' });
  });

  it('409s approving a direction that drifts from the target, so a ragged set can\'t finalize', async () => {
    // Retargeting mid-set is a sanctioned action, so the queue-time gate alone
    // leaves a hole: approve one direction at the old target, retarget, approve
    // the rest, and the ragged set only fails at atlas-compile time — exactly
    // the failure this issue moves earlier. Approval is where geometry is frozen
    // into the compiled set, so the target has to hold there too.
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    const { runId } = await makeCandidateRun(id, 'south', { frameCount: 12, fps: 10 });
    await approveWalkDirection(id, { direction: 'south', runId });
    const { runId: eastId } = await makeCandidateRun(id, 'east', { frameCount: 8, fps: 10 });
    await expect(approveWalkDirection(id, { direction: 'east', runId: eastId }))
      .rejects.toMatchObject({
        code: 'WALK_TARGET_MISMATCH',
        message: expect.stringContaining('targets 12 frames @ 10fps'),
      });
    // The drifted direction stays unapproved rather than half-recorded.
    const { selection } = await getWalkState(id);
    expect(selection.directions.east).toBeUndefined();
  });

  it('refuses to FINALIZE a set whose earlier approvals drifted from a retarget', async () => {
    // Retargeting mid-set is sanctioned, so the per-direction gate alone isn't
    // enough: a direction approved under the OLD target stays drifted while
    // every later approval matches the new one, and the 8th approval would
    // otherwise freeze a ragged set for atlas.js to reject.
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    const { runId: southId } = await makeCandidateRun(id, 'south', { frameCount: 12, fps: 10 });
    await approveWalkDirection(id, { direction: 'south', runId: southId });
    await setWalkTarget(id, { frameCount: 8, fps: 10 });
    const rest = SPRITE_DIRECTIONS.filter((d) => d !== 'south');
    for (const direction of rest.slice(0, -1)) {
      const { runId } = await makeCandidateRun(id, direction, { frameCount: 8, fps: 10 });
      await approveWalkDirection(id, { direction, runId });
    }
    const last = rest[rest.length - 1];
    const { runId: lastId } = await makeCandidateRun(id, last, { frameCount: 8, fps: 10 });
    await expect(approveWalkDirection(id, { direction: last, runId: lastId }))
      .rejects.toMatchObject({
        code: 'WALK_TARGET_MISMATCH',
        message: expect.stringContaining('south'),
      });
    // Nothing was frozen, and the drifted direction is still named.
    const { walkSet, walkTarget } = await getWalkState(id);
    expect(walkSet).toBeNull();
    expect(walkTarget.drift.map((d) => d.direction)).toContain('south');
  });

  it('does not derive the target from a direction whose packed strip is gone', async () => {
    // A stripMissing run keeps its stripPreview (only stripPath is dropped), so
    // without an explicit exclusion it could win the first-packaged slot and
    // derive the whole set's target from artwork that no longer exists.
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    const { runId } = await makeCandidateRun(id, 'south', { frameCount: 16, fps: 24 });
    await rm(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-south-strip.png`));
    await makeCandidateRun(id, 'east', { frameCount: 8, fps: 12 });
    const { runs, walkTarget } = await getWalkState(id);
    expect(runs.find((r) => r.direction === 'south').stripMissing).toBe(true);
    // 'east' — the live direction — sets the target, not the dead 'south'.
    expect(walkTarget).toMatchObject({ frameCount: 8, fps: 12, source: 'derived' });
    expect(walkTarget.drift).toEqual([]);
  });

  it('preserves the pinned target across unlock and reopen', async () => {
    // Both paths reseed the selection; dropping animationTargets there would
    // silently re-derive the target from whichever direction is re-approved
    // first, so this pins the preservation the reseeds depend on.
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    await setWalkTarget(id, { frameCount: 8, fps: 12 });
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      await approveWalkDirection(id, { direction, runId });
    }
    await unlockWalkSet(id);
    expect((await readSelection(id)).animationTargets.walk)
      .toEqual({ frameCount: 8, fps: 12, source: 'set' });
    // …and re-approving one direction then reopening it keeps the pin too.
    const { runId } = await makeCandidateRun(id, 'south');
    await approveWalkDirection(id, { direction: 'south', runId });
    await reopenWalkDirection(id, { direction: 'south' });
    expect((await readSelection(id)).animationTargets.walk)
      .toEqual({ frameCount: 8, fps: 12, source: 'set' });
  });

  it('409s a retarget on a finalized set', async () => {
    const id = await characterWithLockedAnchors(newId(), SPRITE_DIRECTIONS);
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      await approveWalkDirection(id, { direction, runId });
    }
    await expect(setWalkTarget(id, { frameCount: 14, fps: 8 }))
      .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
  });
});

describe('approveWalkDirection', () => {
  it('validates run existence, direction, and candidate status', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(approveWalkDirection(id, { direction: 'east', runId: 'walk-east-deadbeef' }))
      .rejects.toMatchObject({ code: 'RUN_NOT_FOUND' });
    const { runId } = await makeCandidateRun(id, 'east');
    await expect(approveWalkDirection(id, { direction: 'west', runId }))
      .rejects.toMatchObject({ code: 'RUN_DIRECTION_MISMATCH' });
    const { runId: queuedId } = await startWalkGeneration(id, { direction: 'east' });
    await expect(approveWalkDirection(id, { direction: 'east', runId: queuedId }))
      .rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });
  });

  it('rejects a strip modified after packaging', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await writeFile(
      join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-east-strip.png`),
      'tampered',
    );
    await expect(approveWalkDirection(id, { direction: 'east', runId }))
      .rejects.toMatchObject({ code: 'RUN_STRIP_INVALID' });
  });

  it('rejects a candidate rendered from a superseded anchor hash', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east', { anchorSha256: '0'.repeat(64) });
    await expect(approveWalkDirection(id, { direction: 'east', runId }))
      .rejects.toMatchObject({ code: 'RUN_ANCHOR_STALE' });
  });

  it('records the approval in the selection', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId, manifestRel } = await makeCandidateRun(id, 'east');
    const state = await approveWalkDirection(id, { direction: 'east', runId });
    expect(state.selection.kind).toBe('reviewed-directional-walk-selection');
    expect(state.selection.status).toBe('in-progress');
    expect(state.selection.directions.east).toMatchObject({
      status: 'approved', runId, runPath: `runs/${runId}`, runManifest: manifestRel,
    });
    expect(state.selection.directions.east.runManifestSha256).toBe(
      sha256(await readFile(join(TEST_ROOT, 'sprites', id, manifestRel))),
    );
    expect(state.walkSet).toBeNull();
  });

  // #2978: an imported run's postprocessManifest and the manifest's own
  // stripPath are both anchored at the source repo root. Resolved raw they
  // produce a doubled non-existent path, so approval 409'd RUN_MANIFEST_INVALID
  // on art that is present and intact.
  it('approves an imported run whose manifest paths are art-source/-anchored', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId, manifestRel } = await makeCandidateRun(id, 'east', { anchored: true });
    const state = await approveWalkDirection(id, { direction: 'east', runId });
    expect(state.selection.directions.east).toMatchObject({
      // The selection stores the RE-ANCHORED path — it's PortOS-owned state,
      // unlike the hash-pinned imported manifest it points at.
      status: 'approved', runId, runManifest: manifestRel,
    });
    // Pin WHICH file was hashed, not merely that something was: the whole bug is
    // that the anchored path resolved to a file that isn't there, so a shape-only
    // assertion would pass over a hash of the wrong (or a missing) manifest.
    expect(state.selection.directions.east.runManifestSha256).toBe(
      sha256(await readFile(join(TEST_ROOT, 'sprites', id, manifestRel))),
    );
  });

  it('finalizes the walk set on the 8th approval and freezes the record', async () => {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    let state;
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      state = await approveWalkDirection(id, { direction, runId });
    }
    expect(state.selection.status).toBe('complete');
    expect(state.walkSet).toMatchObject({
      kind: 'finalized-eight-direction-walk-set',
      status: 'final',
      characterId: id,
      directionOrder: SPRITE_DIRECTIONS,
      // A native walk set is NOT an import, so the client gets its Unlock button.
      imported: false,
    });
    expect(Object.keys(state.walkSet.directions)).toHaveLength(8);
    expect((await records.getRecord(id)).status).toBe('walk-complete');

    // The finalized set is immutable: no new generation, approval, or rerun.
    await expect(startWalkGeneration(id, { direction: 'east' }))
      .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
    const eastRun = state.walkSet.directions.east.runId;
    await expect(approveWalkDirection(id, { direction: 'east', runId: eastRun }))
      .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
    await expect(rerunWalkPostprocess(id, { runId: eastRun }))
      .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
  });
});

describe('unlockWalkSet', () => {
  async function finalizedCharacter() {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      await approveWalkDirection(id, { direction, runId });
    }
    return id;
  }

  it('409s when there is no finalized walk set', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(unlockWalkSet(id)).rejects.toMatchObject({ code: 'WALK_SET_NOT_FINAL' });
  });

  it('un-freezes the set, re-opens every direction, and reverts the record status', async () => {
    const id = await finalizedCharacter();
    expect((await records.getRecord(id)).status).toBe('walk-complete');

    const state = await unlockWalkSet(id);
    // The frozen set is gone and the selection is back to an editable, empty set.
    expect(state.walkSet).toBeNull();
    expect(state.selection.status).toBe('in-progress');
    expect(state.selection.directions).toEqual({});
    expect((await records.getRecord(id)).status).toBe('reference-complete');

    // Regeneration/approval is allowed again (no WALK_SET_FINAL), and the
    // already-rendered clips remain on disk to re-approve.
    const { runId } = await makeCandidateRun(id, 'east');
    const reapproved = await approveWalkDirection(id, { direction: 'east', runId });
    expect(reapproved.selection.directions.east.status).toBe('approved');
  });

  it('preserves the finalized set and status when the selection is unreadable', async () => {
    const id = await finalizedCharacter();
    const walkDir = join(TEST_ROOT, 'sprites', id, 'walk');
    const setPath = join(walkDir, `${id}-walk-set-v1.json`);
    const before = await readFile(setPath, 'utf8');
    await writeFile(join(walkDir, `${id}-walk-selection-v1.json`), '{broken');

    await expect(unlockWalkSet(id)).rejects.toMatchObject({ code: 'UNREADABLE_STORE' });

    expect(await readFile(setPath, 'utf8')).toBe(before);
    expect((await records.getRecord(id)).status).toBe('walk-complete');
  });

  it('refuses to unlock a legacy source-pipeline import', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-set-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'finalized-eight-direction-walk-set',
      characterId: id,
      status: 'final',
      // The importer copies this source-repo-anchored, which marks it legacy.
      selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,
      directions: {},
    }));
    // The client keys its Unlock affordance off this flag: a legacy import
    // must surface imported:true so the button is hidden rather than offered
    // and then 409'd.
    expect((await getWalkState(id)).walkSet.imported).toBe(true);
    await expect(unlockWalkSet(id)).rejects.toMatchObject({ code: 'LEGACY_IMPORTED_WALK_SET' });
  });
});

describe('reopenWalkDirection', () => {
  async function finalizedCharacter() {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      await approveWalkDirection(id, { direction, runId });
    }
    return id;
  }

  it('reopens ONE approved direction, un-finalizes the set, and keeps the others', async () => {
    const id = await finalizedCharacter();
    expect((await records.getRecord(id)).status).toBe('walk-complete');

    const state = await reopenWalkDirection(id, { direction: 'east' });
    // The frozen set is gone (a set is final only when all 8 are approved)…
    expect(state.walkSet).toBeNull();
    expect((await records.getRecord(id)).status).toBe('reference-complete');
    // …east is editable again while every other direction stays approved.
    expect(state.selection.directions.east).toBeUndefined();
    expect(state.selection.directions.north.status).toBe('approved');
    expect(state.selection.status).toBe('in-progress');

    // Re-approving just east re-freezes the set with a single click.
    const { runId } = await makeCandidateRun(id, 'east');
    const reapproved = await approveWalkDirection(id, { direction: 'east', runId });
    expect(reapproved.walkSet).not.toBeNull();
    expect((await records.getRecord(id)).status).toBe('walk-complete');
  });

  it('409s a direction that is not approved', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(reopenWalkDirection(id, { direction: 'east' }))
      .rejects.toMatchObject({ code: 'DIRECTION_NOT_APPROVED' });
  });

  it('refuses to reopen a legacy source-pipeline import', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-set-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'finalized-eight-direction-walk-set',
      characterId: id,
      status: 'final',
      selectionPath: `art-source/sprites/${id}/walk/${id}-walk-selection-v1.json`,
      directions: { east: { status: 'approved' } },
    }));
    await expect(reopenWalkDirection(id, { direction: 'east' }))
      .rejects.toMatchObject({ code: 'LEGACY_IMPORTED_WALK_SET' });
  });
});

describe('invalidateWalkDirectionForAnchorRevision', () => {
  it('invalidates the dependent walk before reopening the anchor for regeneration', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await approveWalkDirection(id, { direction: 'east', runId });

    const result = await unlockDirectionalAnchor(id, { direction: 'east' });
    const state = await getWalkState(id);
    expect(result.walkInvalidated).toBe(true);
    expect(result.manifest.anchors.find((anchor) => anchor.direction === 'east')).toMatchObject({
      status: 'pending',
    });
    expect(state.selection.directions.east).toBeUndefined();
    expect(state.runs.find((run) => run.id === runId)).toMatchObject({
      status: 'superseded-anchor',
      supersededReason: 'directional-anchor-revised',
    });
  });

  it('un-finalizes the set, drops only the stale approval, and preserves every rendered run', async () => {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    const runIds = {};
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      runIds[direction] = runId;
      await approveWalkDirection(id, { direction, runId });
    }

    const invalidated = await invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' });
    const state = await getWalkState(id);
    expect(invalidated).toBe(true);
    expect(state.walkSet).toBeNull();
    expect(state.selection.status).toBe('in-progress');
    expect(state.selection.directions.east).toBeUndefined();
    expect(state.selection.directions.north.status).toBe('approved');
    expect(state.runs.find((run) => run.id === runIds.east)).toMatchObject({
      status: 'superseded-anchor',
      supersededReason: 'directional-anchor-revised',
    });
    await expect(approveWalkDirection(id, { direction: 'east', runId: runIds.east }))
      .rejects.toMatchObject({ code: 'RUN_NOT_CANDIDATE' });
    expect((await records.getRecord(id)).status).toBe('reference');
  });

  it('is a no-op when the direction has no approved walk', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(invalidateWalkDirectionForAnchorRevision(id, { direction: 'east' })).resolves.toBe(false);
  });

  it('reopens the turnaround only after invalidating every dependent approval', async () => {
    const id = await characterWithLockedAnchors(newId(), ANCHOR_DIRECTIONS);
    const runIds = {};
    for (const direction of SPRITE_DIRECTIONS) {
      const { runId } = await makeCandidateRun(id, direction);
      runIds[direction] = runId;
      await approveWalkDirection(id, { direction, runId });
    }

    const result = await unlockTurnaroundReference(id);
    const state = await getWalkState(id);
    expect(result.walkInvalidatedDirections).toEqual(SPRITE_DIRECTIONS);
    expect(result.manifest).toMatchObject({
      status: 'needs-turnaround',
      turnaround: { locked: false, path: null },
      mainReference: { locked: false, path: null },
    });
    expect(result.manifest.anchors.every((anchor) => anchor.status === 'pending')).toBe(true);
    expect(state.walkSet).toBeNull();
    expect(state.selection.directions).toEqual({});
    for (const runId of Object.values(runIds)) {
      expect(state.runs.find((run) => run.id === runId)).toMatchObject({
        status: 'superseded-anchor',
        supersededReason: 'directional-anchor-revised',
      });
    }
    expect((await records.getRecord(id)).status).toBe('reference');
  });

  it('invalidates only south before reopening the main reference', async () => {
    const id = await characterWithLockedAnchors(newId(), ['south', 'east']);
    const south = await makeCandidateRun(id, 'south');
    const east = await makeCandidateRun(id, 'east');
    await approveWalkDirection(id, { direction: 'south', runId: south.runId });
    await approveWalkDirection(id, { direction: 'east', runId: east.runId });

    const result = await unlockMainReference(id);
    const state = await getWalkState(id);
    expect(result.walkInvalidated).toBe(true);
    expect(result.manifest.turnaround.locked).toBe(true);
    expect(result.manifest.mainReference).toMatchObject({ locked: false, path: null });
    expect(result.manifest.anchors.find((anchor) => anchor.direction === 'south')).toMatchObject({ status: 'pending' });
    expect(result.manifest.anchors.find((anchor) => anchor.direction === 'east')).toMatchObject({ status: 'locked' });
    expect(state.selection.directions.south).toBeUndefined();
    expect(state.selection.directions.east.status).toBe('approved');
  });
});

/**
 * #2993 — the un-finalize gate keys on EVIDENCE (is a clip on disk?), not on the
 * set's imported-looking provenance. #2984 made the importer copy each run's
 * source-video.mp4, so an imported direction with its clip present is exactly as
 * re-derivable as a native one; only a direction with nothing behind it is the
 * dead end the original blanket refusal was written for.
 */
describe('imported walk sets — evidence-based re-derive', () => {
  it('unlocks an imported set whose direction still has its clip on disk', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });

    const state = await unlockWalkSet(id);
    expect(state.walkSet).toBeNull();
    expect((await records.getRecord(id)).status).toBe('reference-complete');
    // The imported run must survive losing its index entry — it lives in a
    // directory the source pipeline named freely (`run-…`, not `walk-…`), so a
    // name-prefix scan would have made it vanish exactly when it is needed.
    const run = state.runs.find((r) => r.id === runIds.east);
    expect(run.direction).toBe('east');
    expect(run.sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
    expect(run.sourceClipMissing).toBeUndefined();
  });

  it('still refuses an unacknowledged unlock of an imported set with no clip behind any direction', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: { clip: false } });
    // Regenerable (east's anchor is locked), so the refusal NAMES the way past it
    // — but a caller who did not ask for that still gets refused, under the same
    // code as any other un-re-derivable import (the override rides in the message,
    // per the FORK_SYNC_REQUIRED precedent).
    await expect(unlockWalkSet(id)).rejects.toMatchObject({
      status: 409,
      code: 'LEGACY_IMPORTED_WALK_SET',
      message: expect.stringContaining('acknowledgeNoClips'),
    });
    // …and it does NOT advise reopening "the directions that do have clips", of
    // which there are none.
    await expect(unlockWalkSet(id)).rejects.toMatchObject({
      message: expect.not.stringContaining('one at a time'),
    });
    expect((await getWalkState(id)).walkSet).not.toBeNull();
  });

  /**
   * #3043 — re-deriving is not the only way back. A walk render is conditioned on
   * the direction's LOCKED anchor, so a clipless imported set whose anchors are
   * all locked can still be rebuilt from scratch; before this, such a set (the
   * whole phase-1 import population) had no reachable way to revise anything —
   * not one direction, and not the set's cycle target, which `requireUnfinalized`
   * refuses while the set is frozen.
   */
  it('unlocks a clipless imported set when the caller acknowledges regeneration', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: { clip: false } });

    const state = await unlockWalkSet(id, { acknowledgeNoClips: true });
    expect(state.walkSet).toBeNull();
    expect((await records.getRecord(id)).status).toBe('reference-complete');
    // …and the retarget the whole exercise exists for now succeeds.
    const retargeted = await setWalkTarget(id, { frameCount: 12, fps: 12 });
    expect(retargeted.walkTarget).toMatchObject({ frameCount: 12, fps: 12, source: 'set' });
  });

  /**
   * The importer stamps the chroma key it used on the RECORD and copies a
   * manifest that carries none, so a renderability probe reading only
   * `manifest.chromaKey` reports every fully-locked import as un-regenerable —
   * which made both the acknowledged unlock and Generate itself dead for exactly
   * the population they exist for. The fallback mirrors reference.js's own
   * manifest → record resolution order.
   */
  it('resolves the chroma key off the record when the imported manifest carries none', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: { clip: false } });
    // Drop the manifest key the native lock flow would have frozen, leaving only
    // the record-level key the importer stamps.
    const manifestPath = join(TEST_ROOT, 'sprites', id, 'reference', `${id}-reference-set-v1.json`);
    const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
    delete manifest.chromaKey;
    await writeFile(manifestPath, JSON.stringify(manifest));
    await records.updateRecord(id, { chromaKey: '#FF00FF' });

    expect((await getWalkState(id)).walkSet.unlock).toMatchObject({ acknowledgeable: true });

    // …and with NEITHER key the refusal stands: that is the real "main was never
    // locked" state, where regeneration genuinely can't be promised.
    await records.updateRecord(id, { chromaKey: null });
    expect((await getWalkState(id)).walkSet.unlock).toMatchObject({ acknowledgeable: false });
  });

  /**
   * The same missing rung, in the OTHER path that keys a matte. `packageRun` read
   * `run.chromaKey || manifest.chromaKey` — both absent on an imported run — and
   * handed `undefined` to the un-key step, which surfaced as the parser's own
   * `Invalid hex color: undefined`: a complaint about an argument, naming neither
   * the field nor the record behind it. This is the reprocess a user reaches for
   * the moment their clips ARE on disk, so it has to resolve the record rung too.
   */
  it('reprocesses an imported run using the record-level chroma key', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    const manifestPath = join(TEST_ROOT, 'sprites', id, 'reference', `${id}-reference-set-v1.json`);
    const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
    delete manifest.chromaKey;
    await writeFile(manifestPath, JSON.stringify(manifest));
    await records.updateRecord(id, { chromaKey: '#FF00FF' });
    // Reopen so the frozen set stops refusing the re-derive.
    await reopenWalkDirection(id, { direction: 'east' });

    const run = await rerunWalkPostprocess(id, { runId: runIds.east });
    expect(run.status).toBe('candidate');
    expect(run.postprocessError).toBeUndefined();
    expect(runWalkPostprocess.mock.calls.at(-1)[0]).toMatchObject({ chromaKey: '#FF00FF' });
  });

  it('names the record when NO rung carries a chroma key, instead of failing inside the color parser', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    const manifestPath = join(TEST_ROOT, 'sprites', id, 'reference', `${id}-reference-set-v1.json`);
    const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
    delete manifest.chromaKey;
    await writeFile(manifestPath, JSON.stringify(manifest));
    await records.updateRecord(id, { chromaKey: null });
    await reopenWalkDirection(id, { direction: 'east' });

    await expect(rerunWalkPostprocess(id, { runId: runIds.east })).rejects.toMatchObject({
      message: expect.stringContaining('No chroma key'),
    });
    expect(runWalkPostprocess).not.toHaveBeenCalled();
  });

  /**
   * The stamped read and the unlock gate must agree. `getWalkState` resolves runs
   * only for entries whose status is `approved`, while `importedWalkDirections`
   * filters on provenance alone and so includes entries in any state — so a
   * source-anchored `pending` entry is absent from the clip map the read hands
   * over. Reading absent as "proven clipless" made the read report `blocked` for
   * a set the write path unlocks plainly and for free: the client would quote
   * eight needless renders, or (with any anchor unlocked) render no unlock
   * control at all — the dead end #3043 exists to remove, through another door.
   */
  it('agrees with the unlock gate when an imported entry is not approved', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: {}, north: { status: 'pending' } });

    // north is source-anchored (so `stale` includes it) and HAS its clip on disk,
    // but is not approved — so the read never resolved a run for it.
    expect((await getWalkState(id)).walkSet.unlock).toMatchObject({ blocked: false });
    // …and the gate, which probes disk, agrees: a plain unlock succeeds.
    await expect(unlockWalkSet(id)).resolves.toMatchObject({ walkSet: null });
  });

  // The acknowledgement is an override of the CLIP requirement only — it must
  // never become a way to strand a direction that cannot be rebuilt at all.
  it('refuses an acknowledged unlock when a stranded direction has no locked anchor', async () => {
    // Only east's anchor is locked, so north can be neither re-derived (no clip)
    // nor regenerated (no anchor to condition a render on).
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: { clip: false }, north: { clip: false } });

    await expect(unlockWalkSet(id, { acknowledgeNoClips: true })).rejects.toMatchObject({
      status: 409,
      code: 'LEGACY_IMPORTED_WALK_SET',
    });
    expect((await getWalkState(id)).walkSet).not.toBeNull();
  });

  // What the two clients render their Unlock affordance from (#3043) — stamped by
  // the same resolver the gate uses, so the button offered and the 409 it might
  // hit cannot be computed from two different readings of the set.
  it('stamps the unlock block on the walk state', async () => {
    const clipless = await characterWithLockedAnchors(newId(), ['east']);
    const cliplessRunIds = await importedCharacter(clipless, { east: { clip: false } });
    const cliplessState = await getWalkState(clipless);
    expect(cliplessState.walkSet.unlock).toEqual({
      blocked: true, stranded: ['east'], acknowledgeable: true,
    });
    expect(cliplessState.runs.find((run) => run.id === cliplessRunIds.east).reopen).toEqual({
      blocked: true, stranded: ['east'], acknowledgeable: true,
    });

    const withClip = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(withClip, { east: {} });
    expect((await getWalkState(withClip)).walkSet.unlock).toMatchObject({ blocked: false });
  });

  // Unlock drops EVERY approval, and a source-packaged direction with no clip can
  // be neither reprocessed nor re-approved (its frames were never imported) — so a
  // partial unlock would strand it permanently. The whole-set action refuses; the
  // per-direction one, which leaves the rest frozen, still works.
  it('refuses to unlock a mixed set, naming the direction that would be stranded', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: {}, north: { clip: false } });

    await expect(unlockWalkSet(id)).rejects.toMatchObject({
      status: 409,
      code: 'LEGACY_IMPORTED_WALK_SET',
      message: expect.stringContaining('north would be left with no source clip'),
    });
    // …and the frozen set is untouched by the refusal.
    expect((await getWalkState(id)).walkSet).not.toBeNull();
  });

  it('reopens a clipless imported direction only after acknowledging regeneration', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east', 'north']);
    const runIds = await importedCharacter(id, { east: {}, north: { clip: false } });

    await expect(reopenWalkDirection(id, { direction: 'north' }))
      .rejects.toMatchObject({
        code: 'LEGACY_IMPORTED_WALK_SET',
        message: expect.stringContaining('acknowledgeNoClips'),
      });

    // Reopen is a narrower scope than unlock: reopening east leaves north
    // frozen, then state supplies north's same per-direction recovery block.
    const state = await reopenWalkDirection(id, { direction: 'east' });
    expect(state.walkSet).toBeNull();
    expect(state.selection.directions.east).toBeUndefined();
    expect(state.selection.directions.north.status).toBe('approved');

    // The source-packaged entry for north survives the first reopen in the
    // editable selection, so its per-direction block is still stamped from the
    // same resolver after the frozen set has gone away.
    const afterReopen = await getWalkState(id);
    expect(afterReopen.runs.find((run) => run.id === runIds.north).reopen)
      .toEqual({ blocked: true, stranded: ['north'], acknowledgeable: true });

    const acknowledged = await reopenWalkDirection(id, {
      direction: 'north', acknowledgeNoClips: true,
    });
    expect(acknowledged.selection.directions.north).toBeUndefined();
  });

  it('refuses an acknowledged reopen when its stranded direction cannot render', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await importedCharacter(id, { east: {}, north: { clip: false } });

    await expect(reopenWalkDirection(id, {
      direction: 'north', acknowledgeNoClips: true,
    })).rejects.toMatchObject({
      status: 409,
      code: 'LEGACY_IMPORTED_WALK_SET',
    });
    expect((await getWalkState(id)).selection.directions.north.status).toBe('approved');
  });

  // The acceptance case: an imported 8-frame direction brought up to 12 with no
  // new render call — and, because the run lives under `grok/`, without the
  // regenerated frames or the rewritten record landing in a phantom `runs/` twin.
  it('re-derives a grok/-layout imported run in place at the new set target', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    await unlockWalkSet(id);
    await setWalkTarget(id, { frameCount: 12, fps: 12 });

    runWalkPostprocess.mockClear();
    const run = await rerunWalkPostprocess(id, { runId: runIds.east });

    expect(executeTuiRun).not.toHaveBeenCalled();
    expect(runWalkPostprocess).toHaveBeenCalledWith(expect.objectContaining({
      frameCount: 12,
      runRel: `grok/${runIds.east}`,
      videoAbs: join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated', 'source-video.mp4'),
    }));
    expect(run.status).toBe('candidate');
    expect(run.frameCount).toBe(12);
    // The source anchor is replaced by the record-relative form on the way back
    // to disk, in the directory the run actually came from.
    expect(run.sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
    const savedAbs = join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'animation-run.json');
    expect(JSON.parse(await readFile(savedAbs, 'utf8'))).toMatchObject({ status: 'candidate', frameCount: 12 });
    expect(existsSync(join(TEST_ROOT, 'sprites', id, 'runs'))).toBe(false);
  });

  // Source trees drift: a manifest can name `runs/<id>/…` for a clip stored under
  // `grok/<id>/…`. Both spellings denote the same file, so the reader heals the
  // path and the re-derive finds it — the importer already tolerates the same drift.
  it('resolves a clip whose declared run layout differs from where it is stored', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: { base: 'grok', declaredBase: 'runs' } });

    const { runs } = await getWalkState(id);
    expect(runs[0].sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
    expect(runs[0].sourceClipMissing).toBeUndefined();
    // Drift healing is one fact about imported trees, not one fact about clips:
    // the strip is declared under the other layout too, and must resolve rather
    // than badge "strip missing" over a PNG that is present and intact.
    expect(runs[0].stripPreview.stripPath).toBe(`grok/${runIds.east}/generated/east-strip.png`);
    expect(runs[0].stripMissing).toBeUndefined();
    await expect(reopenWalkDirection(id, { direction: 'east' })).resolves.toBeTruthy();
  });

  // Zero-I/O provenance: a run whose packaged manifest is still named against the
  // source repo was packaged there, so its frames were never imported. The client
  // gates Approve on this rather than offering a button that always 409s.
  it('flags a run whose packaging is still the source pipeline\'s, and clears it on re-derive', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    expect((await getWalkState(id)).runs[0].importedPackaging).toBe(true);

    await unlockWalkSet(id);
    await rerunWalkPostprocess(id, { runId: runIds.east });
    expect((await getWalkState(id)).runs[0].importedPackaging).toBeUndefined();
  });

  // "Declares a clip" and "has a clip" must not read the same: the flag is what
  // lets the client offer reopen/reprocess only where they can actually work.
  // The linkage to the atlas: re-deriving a direction and re-approving it
  // rewrites its entry through PortOS's own approve path, which stores
  // record-relative paths — so the direction stops being "still packaged by the
  // source pipeline" and stops blocking the compile. That is what makes an
  // imported set reachable at all: the refusal clears direction by direction as
  // the user works through them, rather than only for a brand-new character.
  it('drops a re-derived direction out of the set\'s imported provenance', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    await unlockWalkSet(id);
    await rerunWalkPostprocess(id, { runId: runIds.east });

    const state = await approveWalkDirection(id, { direction: 'east', runId: runIds.east });
    const entry = state.selection.directions.east;
    expect(entry.runPath).toBe(`grok/${runIds.east}`);
    expect(entry.runManifest).toBe(`grok/${runIds.east}/generated/manifest.json`);
    expect(importedWalkDirections({ directions: state.selection.directions })).toEqual([]);
  });

  // The complement of the test above: re-approving an imported direction WITHOUT
  // re-deriving it would launder the provenance (approve re-anchors the path it
  // stores), leaving a set the atlas refuses with an unexplained sha mismatch.
  // Approve refuses it up front instead, naming the reprocess as the remedy.
  it('refuses to approve a run whose packaged frames were never written here', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    const manifestAbs = join(
      TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated', 'east-manifest.json',
    );
    const manifest = JSON.parse(await readFile(manifestAbs, 'utf8'));
    // The source pipeline's manifest lists its frames; the importer never copied
    // the images themselves (it skips frames/ to minimize cross-machine copies).
    manifest.frames = Array.from({ length: manifest.frameCount }, (_, i) => ({
      path: `art-source/sprites/${id}/grok/${runIds.east}/generated/frames/f${i}.png`,
    }));
    await writeFile(manifestAbs, JSON.stringify(manifest));
    await unlockWalkSet(id);

    await expect(approveWalkDirection(id, { direction: 'east', runId: runIds.east }))
      .rejects.toMatchObject({ status: 409, code: 'RUN_FRAMES_MISSING' });
  });

  it('flags a run whose declared clip is not on disk without dropping the path', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: { clip: false } });

    const { runs } = await getWalkState(id);
    expect(runs[0].sourceClipMissing).toBe(true);
    expect(runs[0].sourceVideoPath).toBe(`grok/${runIds.east}/generated/source-video.mp4`);
  });
});

// The Loop Trimmer can only DROP columns from a packed strip, so the raw frames
// are the only path back to a HIGHER frame count — and they are invisible
// everywhere else by design. These cover the narrow read that surfaces them.
describe('getWalkSourceFrames', () => {
  // Braced deliberately: `mockClear()` RETURNS the mock, and a beforeEach that
  // returns a function hands vitest a teardown callback — which would then call
  // the extractor with no arguments after every test in this block.
  beforeEach(() => { extractVideoFrames.mockClear(); });

  const rawName = (i) => `source-${String(i).padStart(4, '0')}.png`;

  async function seedRawFrames(runAbs, count) {
    const rawAbs = join(runAbs, 'generated', 'raw');
    await mkdir(rawAbs, { recursive: true });
    for (let i = 1; i <= count; i++) await writeFile(join(rawAbs, rawName(i)), `raw-${i}`);
    return rawAbs;
  }

  // The provenance the packer records: the window it chose out of the usable
  // span, plus which raw frames became packed columns.
  //
  // `windowStart: 2` with a first packed frame at raw index 5 encodes a usable
  // span starting at raw frame 3 (span.start = 2) — deliberately NOT the
  // degenerate span.start = 0 case, where `windowStart + 1` and
  // `frames[0].sourceFrameIndex` coincide and a translation that ignored the
  // packed frames entirely would still look correct.
  async function stampCycleProvenance(id, runId, direction = 'east', {
    sourcePaths = true, shas = true, partial = false,
  } = {}) {
    const manifestAbs = join(
      TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-${direction}-manifest.json`,
    );
    const manifest = JSON.parse(await readFile(manifestAbs, 'utf8'));
    manifest.cycleSelection = {
      windowStart: 2, windowLength: 4, endpointSeamScore: 1.25, medianMotionScore: 3.5,
      periodEstimate: 4, periodAgreement: 'ok',
    };
    manifest.frames = [5, 7].map((index, i) => ({
      sourceFrameIndex: index,
      // `partial` declares a path on only the first frame — evidence about one
      // frame is not evidence about the rest.
      ...(sourcePaths && !(partial && i > 0)
        ? { sourcePath: `runs/${runId}/generated/raw/${rawName(index)}` }
        : {}),
      // The bytes `seedRawFrames` writes, so a matching hash is the healthy case.
      ...(shas && !(partial && i > 0) ? { sourceSha256: sha256(Buffer.from(`raw-${index}`)) } : {}),
    }));
    await writeFile(manifestAbs, JSON.stringify(manifest));
  }

  it('lists every raw frame, the cycle window, and the packed columns', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);
    const rawAbs = await seedRawFrames(runAbs, 8);
    // A non-frame file in the same directory must not be listed as a frame.
    await writeFile(join(rawAbs, 'notes.txt'), 'scratch');
    await writeFile(join(runAbs, 'generated', 'source-video.mp4'), 'CLIP');
    await stampCycleProvenance(id, runId);

    const out = await getWalkSourceFrames(id, runId);
    expect(out.available).toBe(true);
    expect(out.reason).toBeNull();
    expect(out.extractionFps).toBe(12);
    expect(out.frames).toHaveLength(8);
    expect(out.frames[0]).toEqual({ index: 1, path: `runs/${runId}/generated/raw/source-0001.png` });
    expect(out.selectedSourceIndices).toEqual([5, 7]);
    // `windowStart` counts from the usable span the packer kept (here starting at
    // raw frame 3), while the client renders raw 1-based numbering — so the
    // window is re-expressed off the FIRST PACKED frame, not off windowStart+1
    // (which would be 3, four frames to the left of the frames it covers).
    expect(out.cycle).toMatchObject({
      windowStart: 2, windowLength: 4, windowStartFrame: 5, windowEndFrame: 9,
      periodEstimate: 4, periodAgreement: 'ok',
    });
    expect(out.cycleProvenance).toBe('verified');
    // Older records predate run.frameCount/run.fps — the packed preview is the
    // fallback the re-derive control seeds from.
    expect(out.current).toEqual({ frameCount: 8, fps: 12 });
    expect(out.editable).toBe(true);
    expect(out.lockReason).toBeNull();
    // The set target, not a free authoring range, bounds the re-derive.
    expect(out.target).toMatchObject({ frameCount: 8, fps: 12 });
    expect(extractVideoFrames).not.toHaveBeenCalled();
  });

  // The read must stay side-effect free: the importer never copies raw/, so
  // every imported run lands here — extracting from the read would spawn an
  // ffmpeg decode per direction just because the trimmer rendered.
  it('reports raw-frames-cleaned WITHOUT extracting when the clip is on disk', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const generatedAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
    await writeFile(join(generatedAbs, 'source-video.mp4'), 'CLIP');

    const out = await getWalkSourceFrames(id, runId);
    expect(extractVideoFrames).not.toHaveBeenCalled();
    expect(out.available).toBe(false);
    expect(out.reason).toBe('raw-frames-cleaned');
    expect(out.frames).toEqual([]);
    // …and the run is still re-derivable: the clip is what that depends on.
    expect(out.editable).toBe(true);
  });

  it('re-extracts from the clip only when the caller asks for it', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const generatedAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
    await writeFile(join(generatedAbs, 'source-video.mp4'), 'CLIP');

    const out = await getWalkSourceFrames(id, runId, { extract: true });
    expect(extractVideoFrames).toHaveBeenCalledWith(
      join(generatedAbs, 'source-video.mp4'),
      join(generatedAbs, 'raw'),
    );
    expect(out.available).toBe(true);
    expect(out.frames.map((f) => f.index)).toEqual([1, 2, 3]);
    // No packaged provenance stamped on this run: the window and the packed
    // columns report empty rather than inventing a selection.
    expect(out.cycle).toBeNull();
    expect(out.selectedSourceIndices).toEqual([]);
    expect(out.cycleProvenance).toBe('none');
  });

  // A manifest's frame indices were recorded against the extraction that packed
  // the strip; frames re-extracted here may not be the same files. Marking the
  // wrong frames as "the gait cycle" is worse than marking none.
  it('withholds the cycle markers when the manifest\'s source frames are not on disk', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);
    await seedRawFrames(runAbs, 4); // only 1–4 exist; the manifest names 5 and 7
    await stampCycleProvenance(id, runId);

    const out = await getWalkSourceFrames(id, runId);
    expect(out.available).toBe(true);
    expect(out.cycleProvenance).toBe('stale');
    expect(out.cycle).toBeNull();
    expect(out.selectedSourceIndices).toEqual([]);
  });

  // The subtle case a filename check cannot catch: BOTH extractions name their
  // output source-%04d.png, so a source pipeline that sampled at a different fps
  // declares files that all "exist" here while holding different moments of the
  // clip. The bytes are what settle it.
  it('withholds the markers when the declared frames are present but not the same bytes', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const runAbs = join(TEST_ROOT, 'sprites', id, 'runs', runId);
    await seedRawFrames(runAbs, 8);
    await stampCycleProvenance(id, runId);
    // Same filename, different content — exactly a re-extraction at another fps.
    await writeFile(join(runAbs, 'generated', 'raw', rawName(5)), 'a-different-moment');

    const out = await getWalkSourceFrames(id, runId);
    expect(out.cycleProvenance).toBe('stale');
    expect(out.cycle).toBeNull();
    expect(out.selectedSourceIndices).toEqual([]);
  });

  // A minimal manifest that declares no sourcePath has nothing to verify — take
  // it at its word rather than punishing it for being terse. A PARTIALLY
  // declared one is different: evidence about one frame is not evidence about
  // the rest, so it stays unverified.
  it('trusts a manifest that declares no source paths, but not a partial one', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const bare = await makeCandidateRun(id, 'east');
    await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', bare.runId), 8);
    await stampCycleProvenance(id, bare.runId, 'east', { sourcePaths: false, shas: false });
    const bareOut = await getWalkSourceFrames(id, bare.runId);
    expect(bareOut.cycleProvenance).toBe('verified');
    expect(bareOut.selectedSourceIndices).toEqual([5, 7]);

    const half = await makeCandidateRun(id, 'east');
    await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', half.runId), 8);
    await stampCycleProvenance(id, half.runId, 'east', { partial: true });
    const halfOut = await getWalkSourceFrames(id, half.runId);
    expect(halfOut.cycleProvenance).toBe('stale');
    expect(halfOut.selectedSourceIndices).toEqual([]);
  });

  it('reports no-source-video rather than an empty-looking success', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: { clip: false } });

    const out = await getWalkSourceFrames(id, runIds.east);
    expect(out.available).toBe(false);
    expect(out.reason).toBe('no-source-video');
    expect(out.frames).toEqual([]);
    expect(extractVideoFrames).not.toHaveBeenCalled();
  });

  // An imported run's manifest names everything under the SOURCE repo root, and
  // it commonly lives under `grok/` — both must resolve, or the trimmer would
  // show an empty grid for exactly the runs this feature exists for.
  it('re-anchors an imported run\'s frames onto the layout it actually lives in', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });
    await unlockWalkSet(id);
    const generatedAbs = join(TEST_ROOT, 'sprites', id, 'grok', runIds.east, 'generated');

    const out = await getWalkSourceFrames(id, runIds.east, { extract: true });
    expect(extractVideoFrames).toHaveBeenCalledWith(
      join(generatedAbs, 'source-video.mp4'),
      join(generatedAbs, 'raw'),
    );
    expect(out.frames[0].path).toBe(`grok/${runIds.east}/generated/raw/source-0001.png`);
    expect(out.imported).toBe(true);
    expect(out.editable).toBe(true);
    expect(out.lockReason).toBeNull();
  });

  // `editable` answers a different question from `available`: these mirror the
  // guards rerunWalkPostprocess actually applies, so the UI never offers a
  // re-derive the server will 409.
  it('locks a finalized set and names the unlock as the reason', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runIds = await importedCharacter(id, { east: {} });

    const out = await getWalkSourceFrames(id, runIds.east);
    expect(out.editable).toBe(false);
    expect(out.lockReason).toBe('finalized');
    await expect(rerunWalkPostprocess(id, { runId: runIds.east }))
      .rejects.toMatchObject({ code: 'WALK_SET_FINAL' });
  });

  it('locks an approved direction and names the reopen as the reason', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', 'source-video.mp4'), 'CLIP');
    await approveWalkDirection(id, { direction: 'east', runId });

    const out = await getWalkSourceFrames(id, runId);
    expect(out.editable).toBe(false);
    expect(out.lockReason).toBe('approved');
    await expect(rerunWalkPostprocess(id, { runId }))
      .rejects.toMatchObject({ code: 'RUN_APPROVED' });
  });

  // Frames can exist for a run whose clip has since been deleted — listable, but
  // nothing to re-derive from. The two facts must not collapse.
  it('lists frames but refuses the re-derive when only the clip is gone', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await seedRawFrames(join(TEST_ROOT, 'sprites', id, 'runs', runId), 4);

    const out = await getWalkSourceFrames(id, runId);
    expect(out.available).toBe(true);
    expect(out.frames).toHaveLength(4);
    expect(out.editable).toBe(false);
    expect(out.lockReason).toBe('no-source-video');
  });

  // A synthesized redraw cycle (#2924) is a legitimate trimmer source with no
  // run directory behind it — a soft sentinel, not the 404 an unknown id earns.
  it('reports run-not-packaged for an imagegen redraw cycle', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const dir = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19');
    await mkdir(dir, { recursive: true });
    await writeFile(join(dir, 'clean-alpha.png'), 'strip');
    await writeFile(join(dir, 'walk-east-v19-manifest.json'), JSON.stringify({
      schemaVersion: 1,
      characterId: id,
      direction: 'east',
      cellSize: 384,
      cycle: { frameCount: 12, referenceFps: 12, stripAlpha: 'imagegen/v19/clean-alpha.png' },
    }));
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({
      schemaVersion: 1,
      characterId: id,
      status: 'in-progress',
      directions: {
        east: {
          status: 'approved',
          runId: `${id}-v19-east`,
          runPath: 'imagegen/v19',
          runManifest: 'imagegen/v19/walk-east-v19-manifest.json',
        },
      },
    }));

    const out = await getWalkSourceFrames(id, `${id}-v19-east`);
    expect(out.available).toBe(false);
    expect(out.reason).toBe('run-not-packaged');
    expect(out.editable).toBe(false);
    expect(out.current).toEqual({ frameCount: 12, fps: 12 });
    // Not finalized here (no walk-set file), so the clipless reason stands.
    expect(out.lockReason).toBe('no-source-video');

    /**
     * …but a FROZEN set outranks it. This branch hardcoded 'no-source-video',
     * so for a redraw-only direction — the one shape with no run directory —
     * the Loop Trimmer treated a finalized set as merely clipless: it left
     * `CycleTarget` enabled (which 409s on change) and suppressed the lock
     * panel carrying the unlock. Both are the defects #3043 exists to fix,
     * reachable through the single direction that has no run behind it.
     */
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-set-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'finalized-eight-direction-walk-set',
      characterId: id,
      status: 'final',
      directionOrder: SPRITE_DIRECTIONS,
      directions: {
        east: {
          status: 'approved',
          runId: `${id}-v19-east`,
          runPath: 'imagegen/v19',
          runManifest: 'imagegen/v19/walk-east-v19-manifest.json',
        },
      },
    }));
    const frozen = await getWalkSourceFrames(id, `${id}-v19-east`);
    expect(frozen.lockReason).toBe('finalized');
  });

  it('404s an unknown run', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await expect(getWalkSourceFrames(id, 'walk-east-deadbeef'))
      .rejects.toMatchObject({ status: 404, code: 'RUN_NOT_FOUND' });
  });
});

describe('listSpriteAssets run-intermediate exclusion', () => {
  it('omits raw extraction frames but keeps packaged frames and the review sheet', async () => {
    const id = await characterWithLockedAnchors(newId(), []);
    const gen = join(TEST_ROOT, 'sprites', id, 'grok', 'walk-east-00c0ffee', 'generated');
    await mkdir(join(gen, 'raw'), { recursive: true });
    await mkdir(join(gen, 'frames'), { recursive: true });
    await mkdir(join(gen, 'review'), { recursive: true });
    await writeFile(join(gen, 'raw', 'source-0001.png'), 'raw');
    // Included assets are real images: this public listing also probes their
    // headers. Corrupt-image handling belongs to pathsAssets.test.js.
    await writeCandidatePng(join(gen, 'frames', '00-left-contact.png'));
    await writeCandidatePng(join(gen, 'review', 'contrast.png'));
    const assets = await listSpriteAssets(id);
    const paths = assets.map((a) => a.path);
    expect(paths).not.toContain('grok/walk-east-00c0ffee/generated/raw/source-0001.png');
    expect(paths).toContain('grok/walk-east-00c0ffee/generated/frames/00-left-contact.png');
    expect(paths).toContain('grok/walk-east-00c0ffee/generated/review/contrast.png');
    for (const path of [
      'grok/walk-east-00c0ffee/generated/frames/00-left-contact.png',
      'grok/walk-east-00c0ffee/generated/review/contrast.png',
    ]) {
      expect(assets.find(asset => asset.path === path)).toMatchObject({ width: 64, height: 64, format: 'png', frameCount: 1 });
    }
  });
});

describe('getWalkState — run directory with no readable record', () => {
  it('skips the orphan instead of failing the whole read', async () => {
    // A run directory can exist with no `animation-run.json`: the server died
    // between creating it and writing the record, or a partial copy landed. The
    // scan used to keep that null (`isWalkRun(null)` is true, since a run with no
    // `track` IS a walk run) and then dereference `.id` on it — taking the entire
    // walk panel down with a 500 for one stray directory.
    const id = await characterWithLockedAnchors(newId());
    await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', 'walk-east-orphaned', 'generated'), { recursive: true });
    const state = await getWalkState(id);
    expect(state.runs).toEqual([]);
  });

  it('still surfaces the healthy runs alongside an orphan directory', async () => {
    const id = await characterWithLockedAnchors(newId());
    const { runId } = await makeCandidateRun(id, 'east');
    await mkdir(join(TEST_ROOT, 'sprites', id, 'runs', 'walk-east-orphaned2', 'generated'), { recursive: true });
    const state = await getWalkState(id);
    expect(state.runs.map((r) => r.id)).toEqual([runId]);
  });
});

describe('getWalkState', () => {
  it('returns empty state for a fresh character and newest-first runs', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
    expect(await getWalkState(id)).toEqual({
      runs: [],
      selection: null,
      walkSet: null,
      // A fresh set has nothing pinned and nothing packaged, so the target is
      // the documented default with no drift (#2985).
      walkTarget: {
        track: 'walk',
        frameCount: 12,
        fps: 10,
        source: 'default',
        sourceLabel: 'default',
        frameCountLocked: false,
        fpsLocked: false,
        appId: null,
        drift: [],
      },
    });
    await startWalkGeneration(id, { direction: 'east' });
    await new Promise((r) => { setTimeout(r, 5); });
    const second = await startWalkGeneration(id, { direction: 'west' });
    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(2);
    expect(runs[0].id).toBe(second.runId);
  });

  // #2984: an imported run's `sourceVideoPath` is anchored at the SOURCE repo
  // root, like every other path the importer copies byte-for-byte. Left raw it
  // resolves to `data/sprites/<id>/art-source/sprites/<id>/…` — inside the
  // record (so the traversal gate passes) but non-existent — which would make
  // the freshly-imported clip unfindable and re-derivation impossible. It is
  // re-anchored at read time, alongside postprocessManifest, never on disk.
  it('re-anchors an imported run\'s sourceVideoPath to record-relative at read time', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east', { anchored: true });
    const runRecordPath = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
    const bytesBefore = await readFile(runRecordPath);

    const { runs } = await getWalkState(id);
    const run = runs.find((r) => r.id === runId);
    expect(run.sourceVideoPath).toBe(`runs/${runId}/generated/source-video.mp4`);
    // In memory only — the hash-pinned record on disk keeps its source anchor.
    expect(await readFile(runRecordPath)).toEqual(bytesBefore);
  });

  // A PortOS-native run already stamps the record-relative form, so the
  // re-anchor is a no-op there — it must not mangle a path it doesn't own.
  it('leaves a native run\'s already record-relative sourceVideoPath alone', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const { runs } = await getWalkState(id);
    expect(runs.find((r) => r.id === runId).sourceVideoPath).toBe(`runs/${runId}/generated/source-video.mp4`);
  });

  // A candidate/approved run whose packed strip PNG has gone missing on disk
  // (a botched migration or manual cleanup dropped it — how pioneer's north/west
  // strips silently vanished) must NOT surface as a healthy run: the native
  // render path otherwise hands the client a stripPath that 404s into a blank
  // StripLoop. getWalkState flags it with stripMissing and drops the dangling
  // stripPath, WITHOUT flipping status to 'error' (which would mis-drive the
  // client's postprocess-retry UI), and never rewrites the record on disk.
  it('flags a candidate run whose strip is missing on disk with stripMissing', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const runRecordPath = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json');
    const bytesBefore = await readFile(runRecordPath);
    // Drop the packed strip the record advertises.
    await rm(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-east-strip.png`));

    const { runs } = await getWalkState(id);
    const run = runs.find((r) => r.id === runId);
    expect(run.stripMissing).toBe(true);
    // Status is preserved — a missing strip is orthogonal to postprocess status,
    // and flipping to 'error' would offer a Retry that 409s on finalized/approved.
    expect(run.status).toBe('candidate');
    // Dangling stripPath is dropped so StripLoop / the trim button don't render it.
    expect(run.stripPreview.stripPath).toBeUndefined();
    // Read-time only — the record on disk is untouched.
    expect(await readFile(runRecordPath)).toEqual(bytesBefore);
  });

  // The population this guard exists for is an APPROVED direction whose strip
  // vanished (pioneer's north/west — approved, then their strips dropped during a
  // grok/->runs/ relocation). The approved entry resolves through loadRunForEntry,
  // and the flag must ride through that path too — the run stays approved in the
  // selection (recovery there is unlock-then-regenerate, driven client-side off
  // stripMissing + finalized), never mutated to a broken 'error' run.
  it('flags an approved direction whose strip is missing without disturbing its approval', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    await approveWalkDirection(id, { direction: 'east', runId });
    // Approval froze the strip on disk; now it vanishes.
    await rm(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated', `${id}-walk-east-strip.png`));

    const { runs, selection } = await getWalkState(id);
    const run = runs.find((r) => r.id === runId);
    expect(run.stripMissing).toBe(true);
    expect(run.stripPreview.stripPath).toBeUndefined();
    expect(run.status).not.toBe('error');
    // The selection still records the direction as approved — the guard never
    // touches approval state, only the strip preview.
    expect(selection.directions.east.status).toBe('approved');
  });

  // A run whose strip IS on disk stays a healthy candidate — the guard only
  // fires on an actually-missing file, not on every read.
  it('leaves a candidate run with its strip present untouched', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const { runId } = await makeCandidateRun(id, 'east');
    const { runs } = await getWalkState(id);
    const run = runs.find((r) => r.id === runId);
    expect(run.status).toBe('candidate');
    expect(run.stripMissing).toBeUndefined();
    expect(run.stripPreview.stripPath).toBe(`runs/${runId}/generated/${id}-walk-east-strip.png`);
  });

  // Imported run records (issue #2895 importer, ElsewhereAcres source
  // pipeline) stamp createdAt as a Python time.time() epoch-seconds float
  // and stripPreview as { path: <source-repo-relative> } instead of
  // PortOS's own { stripPath: <record-relative> } — sorting the former
  // with .localeCompare threw and 500'd the whole detail endpoint, and
  // rendering the latter through spriteAssetUrl() 404'd. Both must be
  // tolerated without mutating the file on disk (its hash is pinned and
  // verified against the source manifest at import time).
  it('sorts an imported numeric-createdAt run behind a native run and normalizes its stripPreview', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const legacyRunId = 'walk-east-legacy01';
    const legacyStripRel = `grok/${legacyRunId}/generated/${id}-walk-east-strip.png`;
    const legacyDir = join(TEST_ROOT, 'sprites', id, 'grok', legacyRunId, 'generated');
    await mkdir(legacyDir, { recursive: true });
    await writeFile(join(legacyDir, `${id}-walk-east-strip.png`), 'legacy-strip');
    const legacyPath = join(TEST_ROOT, 'sprites', id, 'grok', legacyRunId, 'animation-run.json');
    await writeFile(legacyPath, JSON.stringify({
      schemaVersion: 1,
      kind: 'grok-game-animation-frames-run',
      status: 'candidate',
      id: legacyRunId,
      characterId: id,
      direction: 'east',
      createdAt: 1700000000.123456, // source pipeline epoch-seconds float, well in the past
      stripPreview: {
        path: `art-source/sprites/${id}/${legacyStripRel}`,
        frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
      },
    }));
    const legacyBytesBefore = await readFile(legacyPath);

    const { runId: nativeRunId } = await startWalkGeneration(id, { direction: 'east' });
    const { runs } = await getWalkState(id);

    expect(runs).toHaveLength(2);
    expect(runs[0].id).toBe(nativeRunId); // native ISO createdAt sorts first
    const legacy = runs.find((r) => r.id === legacyRunId);
    expect(legacy.stripPreview.stripPath).toBe(legacyStripRel);
    // Normalization happens in memory only — the imported file (and its
    // hash-pinned provenance) is never rewritten on disk.
    expect(await readFile(legacyPath)).toEqual(legacyBytesBefore);
  });

  // Issue #2928: the importer also lays source-pipeline runs down under
  // `runs/<run-id>/` rather than `grok/<run-id>/`. The selection entry names
  // the layout, so resolving runs off the entry (not off a grok-only
  // directory scan) surfaces it with no per-layout special case.
  it('resolves an approved direction whose runPath is under runs/<run-id>/', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runId = 'walk-east-imported1';
    const stripRel = `runs/${runId}/generated/${id}-walk-east-strip.png`;
    const runDir = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
    await mkdir(runDir, { recursive: true });
    await writeFile(join(runDir, `${id}-walk-east-strip.png`), 'imported-strip');
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), JSON.stringify({
      schemaVersion: 1,
      kind: 'grok-game-animation-frames-run',
      status: 'candidate',
      id: runId,
      characterId: id,
      direction: 'east',
      createdAt: 1700000000.123456,
      stripPreview: {
        // Source-repo-anchored, exactly as the importer copies it.
        path: `art-source/sprites/${id}/${stripRel}`,
        frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
      },
    }));
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'reviewed-directional-walk-selection',
      characterId: id,
      status: 'in-progress',
      directions: {
        east: {
          status: 'approved',
          runId,
          runPath: `art-source/sprites/${id}/runs/${runId}`,
          runManifest: `art-source/sprites/${id}/runs/${runId}/generated/manifest.json`,
          approvedAt: '2026-07-01T00:00:00.000Z',
        },
      },
    }));

    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(1);
    expect(runs[0]).toMatchObject({
      id: runId,
      direction: 'east',
      kind: 'grok-game-animation-frames-run',
      // The record's own source-repo-anchored stripPreview is normalized the
      // same way a grok/-layout imported run's is.
      stripPreview: { stripPath: stripRel, frameCount: 8 },
    });
  });

  // The shape the importer ACTUALLY writes: `runId` is stamped only by
  // approveWalkDirection, so a copied source-pipeline walk set carries just
  // status/runPath/runManifest (see importer.test.js's fixtures). Gating the
  // entry walk on `entry.runId` would filter out every imported direction —
  // exactly the population this read path exists for.
  it('resolves an imported entry that carries no runId, keying the run by its directory', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runId = 'walk-east-noid0001';
    const runDir = join(TEST_ROOT, 'sprites', id, 'runs', runId, 'generated');
    await mkdir(runDir, { recursive: true });
    await writeFile(join(runDir, 'strip.png'), 'imported-strip');
    // Imported run records carry no `id` field either.
    await writeFile(join(TEST_ROOT, 'sprites', id, 'runs', runId, 'animation-run.json'), JSON.stringify({
      kind: 'grok-walk-animation-run',
      status: 'candidate',
      characterId: id,
      direction: 'east',
      stripPreview: {
        path: `art-source/sprites/${id}/runs/${runId}/generated/strip.png`,
        frameCount: 8, fps: 12, cellWidth: 384, cellHeight: 384, row: 0, startColumn: 0,
      },
    }));
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'reviewed-directional-walk-selection',
      characterId: id,
      status: 'in-progress',
      directions: {
        east: {
          status: 'approved',
          runPath: `art-source/sprites/${id}/runs/${runId}`,
          runManifest: `art-source/sprites/${id}/runs/${runId}/generated/manifest.json`,
        },
      },
    }));

    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(1);
    // The run directory IS the run id under both layouts, so an idless
    // imported record still gets a stable key for the client's list.
    expect(runs[0].id).toBe(runId);
    expect(runs[0].stripPreview.stripPath).toBe(`runs/${runId}/generated/strip.png`);
  });

  // A `runs/`-layout entry whose record is missing on disk must surface
  // nothing rather than a half-shaped run — the grok scan can't cover it.
  it('surfaces nothing for a runs/<run-id>/ entry with no run record on disk', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({
      schemaVersion: 1,
      kind: 'reviewed-directional-walk-selection',
      characterId: id,
      status: 'in-progress',
      directions: {
        east: {
          status: 'approved', runId: 'walk-east-ghost001', runPath: 'runs/walk-east-ghost001', approvedAt: 'x',
        },
      },
    }));
    expect((await getWalkState(id)).runs).toEqual([]);
  });

  // The scan path needs the same id fallback: without it an idless scanned
  // run keys off `undefined`, which collapses the server-side dedup and makes
  // the client's `runs.find(r => r.id === sel.runId)` match the wrong
  // direction. Reverting the scan to normalizeStripPreview must fail here.
  it('keys an idless scanned grok run by its directory', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east']);
    const runId = 'walk-east-scanidless';
    await mkdir(join(TEST_ROOT, 'sprites', id, 'grok', runId), { recursive: true });
    await writeFile(join(TEST_ROOT, 'sprites', id, 'grok', runId, 'animation-run.json'), JSON.stringify({
      kind: 'grok-walk-animation-run', status: 'candidate', characterId: id, direction: 'east',
    }));
    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(1);
    expect(runs[0].id).toBe(runId);
  });

  // Unapproved candidates and in-flight generations have no selection entry
  // by definition, so the grok/ scan is still what surfaces them alongside
  // the entry-resolved approved run.
  it('unions entry-resolved approved runs with unapproved scanned grok runs', async () => {
    const id = await characterWithLockedAnchors(newId(), ['east', 'west']);
    const { runId: approvedRunId } = await makeCandidateRun(id, 'east');
    await approveWalkDirection(id, { direction: 'east', runId: approvedRunId });
    const { runId: pendingRunId } = await startWalkGeneration(id, { direction: 'west' });

    const { runs } = await getWalkState(id);
    expect(runs).toHaveLength(2);
    expect(runs.map((r) => r.id).sort()).toEqual([approvedRunId, pendingRunId].sort());
    // The approved run is not duplicated by the scan.
    expect(runs.filter((r) => r.id === approvedRunId)).toHaveLength(1);
  });

  // Issue #2924: a direction approved from the source pipeline's video-first
  // imagegen REDRAW path has no grok/ run directory at all — its selection
  // entry points at imagegen/vN. Synthesize the preview from that manifest's
  // cycle block so the card animates instead of showing a bare badge.
  describe('imagegen-redraw approved directions', () => {
    const REDRAW_MANIFEST_REL = 'imagegen/v19/walk-east-v19-manifest.json';

    async function characterWithRedrawEast(id, { cycle, cellSize = 384, strips = ['clean-alpha.png'] } = {}) {
      await characterWithLockedAnchors(id, ['east']);
      const dir = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19');
      await mkdir(dir, { recursive: true });
      for (const name of strips) await writeFile(join(dir, name), `strip:${name}`);
      await writeFile(join(TEST_ROOT, 'sprites', id, REDRAW_MANIFEST_REL), JSON.stringify({
        schemaVersion: 1,
        characterId: id,
        direction: 'east',
        pipeline: 'game-animation-frames-video-first',
        cellSize,
        cycle: cycle ?? {
          frameCount: 12,
          referenceFps: 12,
          // Source-repo-anchored, exactly as the importer copies it.
          stripAlpha: `art-source/sprites/${id}/imagegen/v19/clean-alpha.png`,
          stripKeyed: `art-source/sprites/${id}/imagegen/v19/keyed.png`,
        },
      }));
      await mkdir(join(TEST_ROOT, 'sprites', id, 'walk'), { recursive: true });
      await writeFile(join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`), JSON.stringify({
        schemaVersion: 1,
        kind: 'reviewed-directional-walk-selection',
        characterId: id,
        status: 'in-progress',
        directions: {
          east: {
            status: 'approved',
            runId: `${id}-v19-east`,
            runPath: `art-source/sprites/${id}/imagegen/v19`,
            runManifest: `art-source/sprites/${id}/${REDRAW_MANIFEST_REL}`,
            approvedAt: 'established-production-v19',
          },
        },
      }));
    }

    it('synthesizes a run with the redraw cycle geometry and the clean-alpha strip', async () => {
      const id = newId();
      await characterWithRedrawEast(id);
      const { runs } = await getWalkState(id);
      expect(runs).toHaveLength(1);
      expect(runs[0]).toMatchObject({
        id: `${id}-v19-east`,
        direction: 'east',
        status: 'approved',
        kind: 'imported-redraw-walk-cycle',
        redrawManifest: REDRAW_MANIFEST_REL,
        // A redraw entry names no run directory, so it has no clip to re-derive
        // from and the server refuses to reopen it. The flag is what still says
        // so once the frozen walk set — the client's other signal — is gone.
        importedPackaging: true,
        stripPreview: {
          stripPath: 'imagegen/v19/clean-alpha.png',
          frameCount: 12,
          fps: 12,
          cellWidth: 384,
          cellHeight: 384,
          row: 0,
          startColumn: 0,
        },
      });
      // toMatchObject asserts presence, not absence: pin that the redraw
      // manifest does NOT land on postprocessManifest, which approve/trim
      // resolve as a packaged grok manifest (frames[] + alignment).
      expect(runs[0].postprocessManifest).toBeUndefined();

      // A redraw manifest carries no strip hash, and this is a read path — so
      // the strip's cache-busting token (#3020) is an mtime-size stand-in. It
      // still has to be PRESENT and well-formed, or the client falls back to an
      // un-versioned URL and an imported strip goes stale after a re-import.
      // The client reads ONE field regardless of which server path produced it.
      expect(runs[0].stripPreview.stripVersion).toMatch(/^\d+-\d+$/);
    });

    // The token must track the bytes: rewriting the strip at its stable path
    // (what a re-import does) has to produce a different token, or the client
    // keeps painting the strip it already decoded. Size is part of the token
    // precisely because mtime resolution can be too coarse to catch a fast
    // rewrite. (The absent-token fallback — a run predating the field — is
    // covered client-side in spriteAssets.test.js, which is where the
    // degradation to an un-versioned URL actually happens.)
    it('changes the strip version when the strip is rewritten in place', async () => {
      const id = newId();
      await characterWithRedrawEast(id);
      const before = (await getWalkState(id)).runs[0].stripPreview.stripVersion;

      const stripAbs = join(TEST_ROOT, 'sprites', id, 'imagegen', 'v19', 'clean-alpha.png');
      await writeFile(stripAbs, Buffer.alloc(4096, 7)); // same path, different bytes
      const after = (await getWalkState(id)).runs[0].stripPreview.stripVersion;

      expect(after).toMatch(/^\d+-\d+$/);
      expect(after).not.toBe(before);
    });

    // Same importer-shape guard as the runs/ layout above: a copied redraw
    // entry has no runId, so the synthesized run keys off its manifest path.
    it('synthesizes a redraw run for an imported entry that carries no runId', async () => {
      const id = newId();
      await characterWithRedrawEast(id);
      const selectionAbs = join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`);
      const selection = JSON.parse(await readFile(selectionAbs, 'utf8'));
      delete selection.directions.east.runId;
      await writeFile(selectionAbs, JSON.stringify(selection));

      const { runs } = await getWalkState(id);
      expect(runs).toHaveLength(1);
      expect(runs[0]).toMatchObject({
        id: REDRAW_MANIFEST_REL,
        kind: 'imported-redraw-walk-cycle',
        stripPreview: { stripPath: 'imagegen/v19/clean-alpha.png', frameCount: 12 },
      });
    });

    it('ignores a traversal-shaped runManifest', async () => {
      const id = newId();
      await characterWithRedrawEast(id);
      const selectionAbs = join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`);
      const selection = JSON.parse(await readFile(selectionAbs, 'utf8'));
      selection.directions.east.runManifest = '../../../etc/passwd.json';
      await writeFile(selectionAbs, JSON.stringify(selection));
      expect((await getWalkState(id)).runs).toEqual([]);
    });

    it('ignores an entry whose direction was not approved', async () => {
      const id = newId();
      await characterWithRedrawEast(id);
      const selectionAbs = join(TEST_ROOT, 'sprites', id, 'walk', `${id}-walk-selection-v1.json`);
      const selection = JSON.parse(await readFile(selectionAbs, 'utf8'));
      selection.directions.east.status = 'rejected';
      await writeFile(selectionAbs, JSON.stringify(selection));
      expect((await getWalkState(id)).runs).toEqual([]);
    });

    it('falls back to the keyed strip when the clean-alpha derivative is absent on disk', async () => {
      const id = newId();
      await characterWithRedrawEast(id, { strips: ['keyed.png'] });
      const { runs } = await getWalkState(id);
      expect(runs[0].stripPreview.stripPath).toBe('imagegen/v19/keyed.png');
    });

    it('surfaces nothing when no strip exists, rather than a broken preview', async () => {
      const id = newId();
      await characterWithRedrawEast(id, { strips: [] });
      expect((await getWalkState(id)).runs).toEqual([]);
    });

    it('ignores a manifest with no usable cycle frame count', async () => {
      const id = newId();
      await characterWithRedrawEast(id, {
        cycle: { frameCount: 1, stripAlpha: 'imagegen/v19/clean-alpha.png' },
      });
      expect((await getWalkState(id)).runs).toEqual([]);
    });

    // The selection is written by the real approval path, so the shadowing
    // check runs against the entry shape production actually produces.
    it('does not shadow a direction that DOES have a scanned grok run', async () => {
      const id = await characterWithLockedAnchors(newId(), ['east']);
      const { runId } = await makeCandidateRun(id, 'east');
      await approveWalkDirection(id, { direction: 'east', runId });
      const { runs } = await getWalkState(id);
      expect(runs).toHaveLength(1);
      expect(runs[0].kind).toBe('grok-game-animation-frames-run');
    });
  });
});

describe('unreadable walk persistence', () => {
  it('refuses to reseed a damaged selection and preserves sibling targets after repair', async () => {
    const id = newId();
    await records.createRecord({ kind: 'character', name: 'Walker' }, id);
    const dir = join(TEST_ROOT, 'sprites', id, 'walk');
    await mkdir(dir, { recursive: true });
    const path = join(dir, `${id}-walk-selection-v1.json`);
    await writeFile(path, '{');
    await expect(setWalkTarget(id, { frameCount: 12, fps: 10 })).rejects.toThrow(/Unreadable/);
    expect(await readFile(path, 'utf8')).toBe('{');
    await writeFile(path, JSON.stringify({ directions: {}, animationTargets: { ambient: { frameCount: 6, fps: 8 } } }));
    await setWalkTarget(id, { frameCount: 12, fps: 10 });
    expect(JSON.parse(await readFile(path, 'utf8')).animationTargets.ambient).toEqual({ frameCount: 6, fps: 8 });
  });
  it('does not bypass a damaged finalized walk set', async () => {
    const id = newId();
    await records.createRecord({ kind: 'character', name: 'Walker' }, id);
    const dir = join(TEST_ROOT, 'sprites', id, 'walk');
    await mkdir(dir, { recursive: true });
    const path = join(dir, `${id}-walk-set-v1.json`);
    await writeFile(path, '{');
    await expect(setWalkTarget(id, { frameCount: 12, fps: 10 })).rejects.toThrow(/Unreadable/);
    expect(await readFile(path, 'utf8')).toBe('{');
  });
});