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

7.2 KB
Raw Blame
/**
 * Migration 204 — heal the magenta (old-key) fringe left on main-reference
 * sprites that were locked with a chroma-key SWAP.
 *
 * Background:
 *   Locking the main reference (#2896) runs dynamic chroma-key selection: the
 *   candidate is masked against the key it was GENERATED on and re-composited
 *   onto whichever standard key sits farthest in hue from the character's
 *   palette. When those two keys differ (e.g. a green-clothed character rendered
 *   on the magenta default, then re-keyed onto blue), the pre-fix
 *   `normalizeFromAnalysis` copied every surviving foreground pixel VERBATIM —
 *   so the anti-aliased edge pixels, which are a blend of character + magenta,
 *   kept their magenta tint and showed up as a magenta halo ringing the
 *   character against the new blue background.
 *
 *   The code fix (in normalize.js, shipped with this migration) decontaminates
 *   that fringe at composite time by
 *   shifting each foreground pixel by keyShare·(newKey − oldKey). But locked
 *   references are immutable (409 on relock), so already-locked mains stay
 *   broken until re-normalized from their preserved candidate.
 *
 * What this migration does (per affected record):
 *   Re-normalize the locked main reference from its preserved `lockedFrom`
 *   candidate through the now-fixed normalizer (mask on the generation key,
 *   composite onto the selected key). If the decontaminated bytes differ from
 *   what's on disk, overwrite the locked PNG in place and refresh its content
 *   sha in the manifest (`mainReference.sha256` plus the south anchor that
 *   shares the same file). The candidate, geometry, and selected key are all
 *   unchanged — only the fringe pixels move — so the artifact's identity is
 *   preserved; only the corruption is removed.
 *
 * Scope gate (per record): the main reference is locked, the manifest carries a
 * selected `chromaKey`, the `lockedFrom` candidate + its generation sidecar
 * exist on disk, the generation key differs from the selected key (a swap
 * happened — the only case that could leave fringe), and re-normalizing yields
 * bytes whose sha differs from the stored one. A same-key lock (no swap) never
 * had fringe and is skipped by the key-difference gate; an already-clean lock
 * (post-fix, or nothing to fix) is skipped by the sha comparison.
 *
 * NOT touched: directional anchors (they generate on the ALREADY-selected key,
 * so their mask key equals their canvas key — no swap, no fringe); walk-run
 * `anchorSha256` pins (frozen evidence nothing verifies at read time — a walk
 * built from a fringed anchor is regenerated by the user, not rewritten here);
 * records with no locked main; the selected key itself.
 *
 * Idempotency: after a pass the locked bytes are the decontaminated output, so
 * a re-run re-derives the identical bytes and the sha comparison skips the
 * record. The migration is tracked in data/migrations.applied.json and runs
 * once regardless.
 */

import { readdir, readFile, writeFile, rename, stat, unlink } from 'fs/promises';
import { join } from 'path';
import { createHash } from 'crypto';
import { normalizeAnchorFrame } from '../../server/services/sprites/normalize.js';

const exists = (abs) => stat(abs).then(() => true, () => false);
const sha256File = async (abs) => createHash('sha256').update(await readFile(abs)).digest('hex');
const readJson = async (abs) => { try { return JSON.parse(await readFile(abs, 'utf8')); } catch { return null; } };
// Atomic write (temp + rename) so a crash mid-migration can't leave a torn,
// unparseable manifest behind — mirrors migrations 202/203.
const writeJson = async (abs, obj) => {
  const tmp = `${abs}.204.tmp`;
  await writeFile(tmp, `${JSON.stringify(obj, null, 2)}\n`);
  await rename(tmp, abs);
};

// Resolve a possibly repo-anchored path VALUE (imports embed
// `art-source/sprites/<id>/…`) to the record-relative form used on disk.
// Returns null for a value that doesn't resolve safely inside this record.
const recordRelative = (id, p) => {
  if (typeof p !== 'string' || !p) return null;
  const marker = `art-source/sprites/${id}/`;
  const idx = p.indexOf(marker);
  const rel = idx >= 0 ? p.slice(idx + marker.length) : p.replace(/^\/+/, '');
  if (!rel || rel.split(/[\\/]/).some((seg) => seg === '..' || seg === '')) return null;
  return rel;
};

async function migrateRecord(recDir, recordId) {
  const manifestAbs = join(recDir, 'reference', `${recordId}-reference-set-v1.json`);
  const manifest = await readJson(manifestAbs);
  const main = manifest?.mainReference;
  if (!main?.locked) return false;

  const canvasKey = manifest.chromaKey;
  if (typeof canvasKey !== 'string') return false;

  const lockedFromRel = recordRelative(recordId, main.lockedFrom);
  const lockedRel = recordRelative(recordId, main.path);
  if (!lockedFromRel || !lockedRel) return false;

  const candAbs = join(recDir, lockedFromRel);
  const lockedAbs = join(recDir, lockedRel);
  if (!await exists(candAbs) || !await exists(lockedAbs)) return false;

  const sidecar = await readJson(`${candAbs.replace(/\.png$/, '')}.generation.json`);
  const genKey = sidecar?.chromaKey;
  // Only a genuine key SWAP could have left old-key fringe. Same-key locks
  // (and records whose generation key we can't recover) are already clean.
  if (typeof genKey !== 'string' || genKey.toUpperCase() === canvasKey.toUpperCase()) return false;

  // Re-normalize to a temp file first; only touch the locked artifact if the
  // decontaminated bytes actually differ from what's stored.
  const tmpAbs = `${lockedAbs}.204.tmp.png`;
  const result = await normalizeAnchorFrame(candAbs, tmpAbs, { maskKeyHex: genKey, canvasKeyHex: canvasKey });
  if (result?.copiedThrough) { await unlink(tmpAbs).catch(() => {}); return false; }
  const newSha = await sha256File(tmpAbs);
  if (newSha === main.sha256) { await unlink(tmpAbs).catch(() => {}); return false; }

  await rename(tmpAbs, lockedAbs);
  main.sha256 = newSha;
  // The south anchor shares the main-reference file — refresh any anchor that
  // resolves to the same locked path so its pinned sha stays truthful.
  for (const anchor of manifest.anchors || []) {
    if (recordRelative(recordId, anchor.path) === lockedRel) anchor.sha256 = newSha;
  }
  await writeJson(manifestAbs, manifest);
  return true;
}

export default {
  up: async ({ rootDir }) => {
    const spritesDir = join(rootDir, 'data', 'sprites');
    let records;
    try {
      records = await readdir(spritesDir, { withFileTypes: true });
    } catch {
      return { ok: true, migrated: 0 }; // no sprites tree on this install
    }

    let migrated = 0;
    const failures = [];
    for (const rec of records) {
      if (!rec.isDirectory()) continue;
      try {
        if (await migrateRecord(join(spritesDir, rec.name), rec.name)) {
          migrated++;
          console.log(`🎨 migration 204: healed swapped-key reference fringe for sprite ${rec.name}`);
        }
      } catch (err) {
        failures.push(rec.name);
        console.error(`❌ migration 204 (${rec.name}): ${err.message}`);
      }
    }
    if (failures.length > 0) {
      throw new Error(`migration 204: ${failures.length} sprite record(s) failed to heal (${failures.join(', ')}) — the rest healed; reboot to retry.`);
    }
    return { ok: true, migrated };
  },
};