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

fix: preserve media and sprite state after unreadable reads (#6976)

[._.]/ Adam Eivy21f153893011
diff --git a/server/services/imageTo3d/sourceKeying.js b/server/services/imageTo3d/sourceKeying.js
index 988601457e..b867833914 100644
--- a/server/services/imageTo3d/sourceKeying.js
+++ b/server/services/imageTo3d/sourceKeying.js
@@ -230,6 +230,7 @@ const freshPreparedSource = async (sourcePath, targetPath, request) => {
const targetStats = await stat(targetPath).catch(() => null);
if (!targetStats?.isFile() || targetStats.mtimeMs <= sourceStats.mtimeMs) return null;
+ // Rebuildable cache: source bytes plus the explicit request fully regenerate this metadata.
const metadata = await readJSONFile(preparedCacheMetadataPath(targetPath), null, { logError: false });
if (metadata?.version !== KEYING_CACHE_VERSION || !metadata.sourceSha256) return null;
// The per-run framing/keying request is part of the cache identity: the same
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.js
index 9bc599d3e9..64db495f31 100644
--- a/server/services/mediaAnnotations.js
+++ b/server/services/mediaAnnotations.js
@@ -75,7 +75,7 @@ function liftLegacyEntry(rawEntry, { localInstanceId, defaultAuthorName }) {
async function readAll() {
await ensureDir(PATHS.data);
- const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false });
+ const raw = await readJSONFile(STATE_PATH, DEFAULT_STATE, { logError: false, strict: true });
const annotations = raw && typeof raw.annotations === 'object' && raw.annotations !== null
? raw.annotations
: {};
diff --git a/server/services/mediaSketches.js b/server/services/mediaSketches.js
index d1de27b980..28a58fbace 100644
--- a/server/services/mediaSketches.js
+++ b/server/services/mediaSketches.js
@@ -116,6 +116,7 @@ export function sanitizeSketchInput(input) {
/** Read the persisted sketch for a key, or null when none exists. */
export async function getSketch(key) {
if (!isValidKey(key)) throw makeErr(`Invalid key: ${key}`, ERR_VALIDATION);
+ // Read-only projection: saveSketch replaces the full canvas from explicit input, never this fallback.
const data = await readJSONFile(jsonPathFor(key), null, { logError: false });
if (!data || typeof data !== 'object' || !Array.isArray(data.strokes)) return null;
return {
diff --git a/server/services/mediaWriteBack.test.js b/server/services/mediaWriteBack.test.js
new file mode 100644
index 0000000000..3d3f760809
--- /dev/null
+++ b/server/services/mediaWriteBack.test.js
@@ -0,0 +1,71 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readFile, writeFile, rm, mkdir } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const faults = vi.hoisted(() => ({ path: null }));
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, readFile: (...args) => args[0] === faults.path
+ ? Promise.reject(Object.assign(new Error('Injected read failure'), { code: 'EACCES' }))
+ : actual.readFile(...args) };
+});
+const root = await mkdtemp(join(tmpdir(), 'media-write-back-'));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, data: root, brain: join(root, 'brain') } };
+});
+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: async () => 'local-test', UNKNOWN_INSTANCE_ID: 'unknown' }));
+vi.mock('./sharing/annotationIdentity.js', () => ({ resolveLocalAuthorName: async () => 'Example' }));
+vi.mock('./apps.js', () => ({ getAppById: vi.fn(), PORTOS_APP_ID: 'portos-default' }));
+vi.mock('./brain.js', () => ({ createLinkFromUrl: vi.fn() }));
+vi.mock('./brainStorage.js', () => ({ getLinkByUrl: vi.fn() }));
+vi.mock('./brainJournal.js', () => ({ getSettings: async () => ({ obsidianVaultId: null }) }));
+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn() }));
+vi.mock('./humanActivity.js', () => ({ recordEvents: vi.fn() }));
+vi.mock('./videoGen/history.js', () => ({ mutateVideoHistory: vi.fn() }));
+vi.mock('./videoGen/events.js', () => ({ videoGenEvents: { emit: vi.fn() } }));
+vi.mock('./videoDownload.js', () => ({ buildDownloadHistoryEntry: vi.fn() }));
+const annotations = await import('./mediaAnnotations.js');
+const records = await import('./sprites/recordsFile.js');
+const ingest = await import('./youtubeIngest.js');
+const stores = [
+ {
+ name: 'annotations', path: join(root, 'media-annotations.json'),
+ mutate: () => annotations.setAnnotation('image:new.png', { starred: true }),
+ prior: { annotations: { 'image:keep.png': { authors: { peer: { starred: true, note: 'keep', updatedAt: '2026-01-01T00:00:00Z' } } } } },
+ assertPreserved: (value) => expect(value.annotations['image:keep.png'].authors.peer.note).toBe('keep'),
+ },
+ {
+ name: 'sprite records', path: join(root, 'sprite-records.json'),
+ mutate: () => records.createRecord({ name: 'New' }, 'new'),
+ prior: [{ id: 'keep', kind: 'character', name: 'Keep', notes: 'keep' }],
+ assertPreserved: (value) => expect(value.find((row) => row.id === 'keep').notes).toBe('keep'),
+ },
+ {
+ name: 'ingest index', path: join(root, 'brain', 'youtube', 'index.json'),
+ mutate: () => ingest.deleteIngest('remove'),
+ prior: { keep: { videoId: 'keep', title: 'Keep' }, remove: { videoId: 'remove' } },
+ assertPreserved: (value) => { expect(value.keep.title).toBe('Keep'); expect(value.remove).toBeUndefined(); },
+ },
+];
+beforeEach(async () => { faults.path = null; await rm(root, { recursive: true, force: true }); await mkdir(root); });
+afterAll(() => rm(root, { recursive: true, force: true }));
+
+describe.each(stores)('$name persistence boundary', (store) => {
+ it.each(['{', '', ' ', 'EACCES'])('preserves unreadable bytes (%j) and retries after repair', async (failure) => {
+ await mkdir(join(store.path, '..'), { recursive: true });
+ const bytes = failure === 'EACCES' ? JSON.stringify(store.prior) : failure;
+ await writeFile(store.path, bytes);
+ if (failure === 'EACCES') faults.path = store.path;
+ await expect(store.mutate()).rejects.toThrow(/Unreadable/);
+ faults.path = null;
+ expect(await readFile(store.path, 'utf8')).toBe(bytes);
+ await writeFile(store.path, JSON.stringify(store.prior));
+ await store.mutate();
+ store.assertPreserved(JSON.parse(await readFile(store.path, 'utf8')));
+ });
+ it('accepts an absent file', async () => {
+ await expect(store.mutate()).resolves.toBeDefined();
+ });
+});
diff --git a/server/services/sprites/atlas.js b/server/services/sprites/atlas.js
index 3adbf76fea..5fd9bd0fbd 100644
--- a/server/services/sprites/atlas.js
+++ b/server/services/sprites/atlas.js
@@ -714,7 +714,7 @@ export async function compileAtlasInTail(recordId, {
// exist — otherwise a deleted runtime/vN PNG would loop forever ("recompile"
// → pointer returned untouched → still missing); falling through re-writes
// the same version (nextAtlasVersion only counts versions whose PNG exists).
- const current = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);
+ const current = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null, { strict: true });
const currentAtlasOnDisk = current ? await pathExists(join(dir, current.atlasPath)) : false;
if (
current
@@ -790,7 +790,7 @@ export async function compileAtlasInTail(recordId, {
// dir. Advance until the slot is empty or its manifest matches these bytes
// (the re-materialize case).
for (;;) {
- const survivor = await readJSONFile(join(runtimeAbs, `v${version}`, `${stem}-v${version}-manifest.json`), null);
+ const survivor = await readJSONFile(join(runtimeAbs, `v${version}`, `${stem}-v${version}-manifest.json`), null, { strict: true });
if (!survivor || (
survivor.atlasSha256 === atlasSha256
&& trackFrameCountsUpToDate(survivor.geometry, frameCountFields)
@@ -808,7 +808,7 @@ export async function compileAtlasInTail(recordId, {
// exact atlas bytes, since a freshly-built one would differ only in
// createdAt and trip the immutable-write refusal.
const manifestAbs = join(dir, manifestRel);
- const survivingManifest = await readJSONFile(manifestAbs, null);
+ const survivingManifest = await readJSONFile(manifestAbs, null, { strict: true });
if (
survivingManifest?.atlasSha256 === atlasSha256
&& trackFrameCountsUpToDate(survivingManifest.geometry, frameCountFields)
@@ -950,8 +950,8 @@ export async function compileAtlasInTail(recordId, {
export async function getAtlasState(recordId) {
const dir = spriteDir(recordId);
const [current, publications] = await Promise.all([
- readJSONFile(join(dir, RUNTIME_POINTER_REL), null),
- readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), []),
+ readJSONFile(join(dir, RUNTIME_POINTER_REL), null, { strict: true }),
+ readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), [], { strict: true }),
]);
return { current, publications: [...publications].reverse() };
}
diff --git a/server/services/sprites/atlas.test.js b/server/services/sprites/atlas.test.js
index d2726190ff..c25ad55a48 100644
--- a/server/services/sprites/atlas.test.js
+++ b/server/services/sprites/atlas.test.js
@@ -953,3 +953,15 @@ describe('compileAtlas', () => {
.rejects.toMatchObject({ status: 400, code: 'INVALID_GEOMETRY' });
});
});
+
+it('preserves an unreadable atlas pointer until it is repaired', async () => {
+ const id = await finalizedCharacter();
+ await compileAtlas(id);
+ const path = join(TEST_ROOT, 'sprites', id, 'runtime', 'current.json');
+ const good = await readFile(path, 'utf8');
+ await writeFile(path, '{');
+ await expect(compileAtlas(id)).rejects.toThrow(/Unreadable/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ await writeFile(path, good);
+ await expect(compileAtlas(id)).resolves.toMatchObject({ created: false });
+});
diff --git a/server/services/sprites/localAnimationJobHook.js b/server/services/sprites/localAnimationJobHook.js
index 60287daee0..013126c37f 100644
--- a/server/services/sprites/localAnimationJobHook.js
+++ b/server/services/sprites/localAnimationJobHook.js
@@ -88,7 +88,7 @@ async function settleSpriteAnimationJob(job) {
// error — so the new id is stamped on the run before the attach, and a later
// sweep of that same job then reads as already-filed.
const recordPath = join(spriteDir(recordId), runRel, RUN_RECORD_NAME);
- const record = await readJSONFile(recordPath, null);
+ const record = await readJSONFile(recordPath, null, { strict: true });
const isRetryOfFiledRun = record?.status === 'error'
&& typeof job.id === 'string' && job.id !== record.jobId;
if (record?.status !== 'rendering' && !isRetryOfFiledRun) return false;
diff --git a/server/services/sprites/localAnimationJobHook.persistence.test.js b/server/services/sprites/localAnimationJobHook.persistence.test.js
new file mode 100644
index 0000000000..70daa0e408
--- /dev/null
+++ b/server/services/sprites/localAnimationJobHook.persistence.test.js
@@ -0,0 +1,36 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+const root = await mkdtemp(join(tmpdir(), 'sprite-hook-store-'));
+vi.mock('./paths.js', async (importOriginal) => ({
+ ...await importOriginal(), spriteDir: (id) => join(root, id),
+}));
+vi.mock('../mediaJobQueue/index.js', () => ({ mediaJobEvents: {}, listJobs: () => [] }));
+const collect = vi.fn();
+vi.mock('./localAnimationRender.js', () => ({ collectLocalAnimationClip: (...args) => collect(...args) }));
+const attach = vi.fn();
+vi.mock('./walk.js', () => ({ attachTuiWalkResult: (...args) => attach(...args) }));
+vi.mock('./animationTrackWorkflow.js', () => ({ attachTrackTuiResult: (...args) => attach(...args) }));
+const { __testing: { settleSpriteAnimationJob } } = await import('./localAnimationJobHook.js');
+afterAll(() => rm(root, { recursive: true, force: true }));
+
+describe('local sprite render retry persistence', () => {
+ it('preserves unreadable runs, then files the repaired retry without losing prior fields', async () => {
+ const path = join(root, 'hero', 'runs', 'run-1', 'animation-run.json');
+ await mkdir(join(path, '..'), { recursive: true });
+ const job = { id: 'job-new', kind: 'video', status: 'completed', params: { spriteAnimation: { recordId: 'hero', runId: 'run-1', track: 'walk', direction: 'east' } } };
+ await writeFile(path, '{');
+ await expect(settleSpriteAnimationJob(job)).rejects.toThrow(/Unreadable/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ expect(collect).not.toHaveBeenCalled();
+ expect(attach).not.toHaveBeenCalled();
+ await writeFile(path, JSON.stringify({ id: 'run-1', status: 'error', jobId: 'old', notes: 'preserve' }));
+ await expect(settleSpriteAnimationJob(job)).resolves.toBe(true);
+ expect(JSON.parse(await readFile(path, 'utf8'))).toMatchObject({ jobId: 'job-new', notes: 'preserve' });
+ expect(attach).toHaveBeenCalledOnce();
+ await rm(path);
+ await expect(settleSpriteAnimationJob(job)).resolves.toBe(false);
+ });
+});
diff --git a/server/services/sprites/publish.js b/server/services/sprites/publish.js
index 8c7323337a..b944c1fd07 100644
--- a/server/services/sprites/publish.js
+++ b/server/services/sprites/publish.js
@@ -286,7 +286,7 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
// Reuse the current pointer's geometry so publish ships the atlas the user
// compiled and previewed — a bare default-geometry recompile would silently
// discard a custom-geometry compile and flip the pointer back to defaults.
- const pointer = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null);
+ const pointer = await readJSONFile(join(dir, RUNTIME_POINTER_REL), null, { strict: true });
const geometryOverride = pointer?.geometry
? {
cellSize: pointer.geometry.cellSize,
@@ -405,7 +405,7 @@ async function publishAtlasImpl(recordId, { acknowledgeOverwrite = false } = {})
throw new ServerError('Compiled atlas bytes no longer match their recorded sha256 — recompile before publishing', { status: 422, code: 'ATLAS_OUTPUT_TAMPERED' });
}
- const publications = await readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), []);
+ const publications = await readJSONFile(join(dir, RUNTIME_PUBLICATIONS_REL), [], { strict: true });
const previous = [...publications].reverse().find(
(p) => p.appId === binding.appId && p.atlasDestPath === binding.atlasDestPath,
);
diff --git a/server/services/sprites/publish.test.js b/server/services/sprites/publish.test.js
index b684035daf..5bc6d19a11 100644
--- a/server/services/sprites/publish.test.js
+++ b/server/services/sprites/publish.test.js
@@ -787,3 +787,15 @@ describe('layout sidecar (#2982)', () => {
expect(await readFile(join(APP_REPO, BINDING.atlasDestPath)).catch(() => null)).toBeNull();
});
});
+
+describe('unreadable publication state', () => {
+ it.each(['current.json', 'publications.json'])('refuses publication with damaged %s', async (name) => {
+ const { id } = await characterWithAtlas();
+ await setPublishBinding(id, BINDING);
+ const path = join(TEST_ROOT, 'sprites', id, 'runtime', name);
+ await writeFile(path, '{');
+ await expect(publishAtlas(id)).rejects.toThrow(/Unreadable/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ await expect(readFile(join(APP_REPO, BINDING.atlasDestPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+});
diff --git a/server/services/sprites/recordsFile.js b/server/services/sprites/recordsFile.js
index 993bc04f4b..ee71350865 100644
--- a/server/services/sprites/recordsFile.js
+++ b/server/services/sprites/recordsFile.js
@@ -15,7 +15,7 @@ import { buildSpriteRecord, applySpriteRecordPatch, mergeImportedRecord } from '
const RECORDS_FILE = join(PATHS.data, 'sprite-records.json');
async function loadAll() {
- const raw = await readJSONFile(RECORDS_FILE, []);
+ const raw = await readJSONFile(RECORDS_FILE, [], { strict: true });
return Array.isArray(raw) ? raw : [];
}
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index a1f1d3980c..d49d006458 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -125,7 +125,7 @@ function upgradeManifestShape(manifest) {
}
export async function loadManifest(recordId) {
- const manifest = await readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null);
+ const manifest = await readJSONFile(join(spriteDir(recordId), manifestRelPath(recordId)), null, { strict: true });
if (!manifest) return null;
upgradeManifestShape(manifest);
if (manifest.mainReference) {
@@ -339,6 +339,7 @@ export async function getReferenceSet(recordId) {
const candidates = (await listDirectoryByExtension(candidatesDir, {
extensions: ['.png'],
mapEntry: async (name) => {
+ // Read-only candidate listing: generation writes a new unique candidate, never this fallback.
const sidecar = await readJSONFile(join(candidatesDir, `${name.replace(/\.png$/, '')}.generation.json`), null);
// Sidecarless (crash between copy and sidecar write): infer the target
// from the filename so the client can't group it under the wrong slot.
@@ -842,7 +843,8 @@ export async function attachReferenceCandidate(ctx) {
}
async function loadCandidateSidecar(candAbs) {
- return readJSONFile(`${candAbs.replace(/\.png$/, '')}.generation.json`, null);
+ // Approval consumes provenance; a corrupt present sidecar must not bypass its target guard.
+ return readJSONFile(`${candAbs.replace(/\.png$/, '')}.generation.json`, null, { strict: true });
}
/**
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index de951c492a..367a415bde 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -1258,3 +1258,18 @@ describe('forkSprite', () => {
expect((await records.listRecords()).length).toBe(before);
});
});
+
+describe('unreadable reference manifest', () => {
+ it('refuses generation without overwriting locked evidence and retries after repair', async () => {
+ const id = newId();
+ await createCharacter(id);
+ const dir = join(TEST_ROOT, 'sprites', id, 'reference');
+ await mkdir(dir, { recursive: true });
+ const path = join(dir, `${id}-reference-set-v1.json`);
+ await writeFile(path, '{');
+ await expect(startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'a ranger' })).rejects.toThrow(/Unreadable/);
+ expect(await readFile(path, 'utf8')).toBe('{');
+ await writeFile(path, JSON.stringify({ schemaVersion: 2, characterId: id, anchors: [], turnaround: { locked: false }, mainReference: { locked: false } }));
+ await expect(startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'a ranger' })).resolves.toMatchObject({ target: 'turnaround' });
+ });
+});
diff --git a/server/services/sprites/walk.js b/server/services/sprites/walk.js
index 6d101320bf..cda0d22822 100644
--- a/server/services/sprites/walk.js
+++ b/server/services/sprites/walk.js
@@ -112,7 +112,7 @@ const walkWriteTail = (recordId, fn) => withAnimationWriteTail(recordId, fn);
export const withWalkWriteTail = walkWriteTail;
async function loadWalkSet(recordId) {
- return readJSONFile(join(spriteDir(recordId), walkSetRelPath(recordId)), null);
+ return readJSONFile(join(spriteDir(recordId), walkSetRelPath(recordId)), null, { strict: true });
}
// A phase-1 imported walk set (#2895) is copied verbatim from the source
@@ -146,7 +146,7 @@ export const isImportedWalkSet = (walkSet) => (
);
async function loadSelection(recordId) {
- return readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null);
+ return readJSONFile(join(spriteDir(recordId), selectionRelPath(recordId)), null, { strict: true });
}
function seedSelection(recordId) {
@@ -167,7 +167,7 @@ function seedSelection(recordId) {
// Read a run record by its directory (record-relative), so `grok/<id>/` and
// the importer's `runs/<id>/` share one reader.
async function loadRunRecordAt(recordId, runDirRel) {
- return readJSONFile(join(spriteDir(recordId), runDirRel, RUN_RECORD_NAME), null);
+ return readJSONFile(join(spriteDir(recordId), runDirRel, RUN_RECORD_NAME), null, { strict: true });
}
async function loadRunRecord(recordId, runId) {
@@ -456,6 +456,7 @@ const REDRAW_STRIP_FIELDS = ['stripAlpha', 'stripAlphaOriginal', 'stripKeyed'];
async function loadRedrawRun(recordId, direction, entry) {
const manifestRel = toRecordRelativeAssetPath(recordId, entry.runManifest);
if (!manifestRel) return null;
+ // Read-only redraw projection; this fallback never enters a manifest write.
const manifest = await readJSONFile(join(spriteDir(recordId), manifestRel), null);
const cycle = manifest?.cycle;
const frameCount = Number(cycle?.frameCount);
@@ -1560,6 +1561,7 @@ export async function getWalkSourceFrames(recordId, runId, { extract = false } =
resolveRunClipRel(recordId, run, runDirRel),
listRawFrameNames(recordId, rawRel),
run.postprocessManifest
+ // Read-only source-frame inspection; postprocess writes a fresh authoritative manifest.
? readJSONFile(join(spriteDir(recordId), run.postprocessManifest), null)
: null,
]);
@@ -2108,6 +2110,7 @@ async function approveWalkDirectionImpl(recordId, { direction, runId }) {
const manifestRel = toRecordRelativeAssetPath(recordId, run.postprocessManifest)
|| run.postprocessManifest;
const manifestAbs = resolveSpriteAssetPath(recordId, manifestRel);
+ // Approval validates this immutable evidence below; it never writes back the fallback.
const packaged = await readJSONFile(manifestAbs, null);
const frameCountValid = Number.isInteger(packaged?.frameCount)
&& packaged.frameCount >= WALK_MIN_FRAME_COUNT && packaged.frameCount <= WALK_MAX_FRAME_COUNT
diff --git a/server/services/sprites/walk.test.js b/server/services/sprites/walk.test.js
index 995dfc164f..a717e9dbd3 100644
--- a/server/services/sprites/walk.test.js
+++ b/server/services/sprites/walk.test.js
@@ -2618,3 +2618,29 @@ describe('getWalkState', () => {
});
});
});
+
+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('{');
+ });
+});
diff --git a/server/services/youtubeIngest.js b/server/services/youtubeIngest.js
index 758090b965..cf0dea919b 100644
--- a/server/services/youtubeIngest.js
+++ b/server/services/youtubeIngest.js
@@ -142,7 +142,7 @@ const indexMutex = createMutex();
async function loadIndex() {
await ensureDir(INGEST_DIR);
- const loaded = await readJSONFile(INDEX_FILE, {});
+ const loaded = await readJSONFile(INDEX_FILE, {}, { strict: true });
return loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};
}