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

address review: fix Writers Room bible merge dedup + sanity-check robustness

Adam Eivy242968f13854
diff --git a/client/src/components/writers-room/sceneCardHelpers.js b/client/src/components/writers-room/sceneCardHelpers.js
index ede394d3f3..0e35fc39ef 100644
--- a/client/src/components/writers-room/sceneCardHelpers.js
+++ b/client/src/components/writers-room/sceneCardHelpers.js
@@ -4,7 +4,7 @@
// Mirror of server/lib/writersRoomStylePresets.js — kept in sync manually
// since client and server are separate bundles. Curated preset ids come from
-// the /api/writers-room/style-presets endpoint at runtime; only the two
+// the /api/image-gen/style-presets endpoint at runtime; only the two
// special discriminators live here.
export const STYLE_ID = { NONE: 'none', CUSTOM: 'custom' };
export const EMPTY_IMAGE_STYLE = { presetId: STYLE_ID.NONE, prompt: '', negativePrompt: '' };
diff --git a/server/lib/ffmpeg.js b/server/lib/ffmpeg.js
index 4f4da415b2..6b577c72de 100644
--- a/server/lib/ffmpeg.js
+++ b/server/lib/ffmpeg.js
@@ -164,7 +164,17 @@ export const verifyVideoPlayable = async (videoPath) => {
if (!existsSync(videoPath)) {
return { ok: false, reason: `video file missing: ${videoPath}` };
}
- const size = statSync(videoPath).size;
+ // statSync is wrapped because the file can be unlinked or made
+ // inaccessible between the existsSync check above and the stat call (a
+ // TOCTOU race during cleanup or external file moves). We want a clean
+ // structured `{ ok: false, reason }` instead of an unhandled throw that
+ // would surface as a 500.
+ let size = 0;
+ try {
+ size = statSync(videoPath).size;
+ } catch (err) {
+ return { ok: false, reason: `video file unreadable: ${err.message}` };
+ }
if (!size || size <= 0) {
return { ok: false, reason: 'video file is empty (0 bytes)' };
}
diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.js
index f81ed86a47..2e774b426d 100644
--- a/server/routes/writersRoom.test.js
+++ b/server/routes/writersRoom.test.js
@@ -20,9 +20,38 @@ vi.mock('../services/writersRoom/local.js', () => ({
createExercise: vi.fn(async (data) => ({ id: 'wr-ex-new', ...data })),
finishExercise: vi.fn(async (id) => ({ id, status: 'finished' })),
discardExercise: vi.fn(async (id) => ({ id, status: 'discarded' })),
+ ensureWorkMediaCollection: vi.fn(async () => ({ id: 'col-1' })),
+}));
+
+vi.mock('../services/writersRoom/characters.js', () => ({
+ listCharacters: vi.fn(async () => [{ id: 'wr-char-1', name: 'Aria' }]),
+ createCharacter: vi.fn(async (workId, data) => ({ id: 'wr-char-new', name: data.name })),
+ updateCharacter: vi.fn(async (workId, charId, data) => ({ id: charId, ...data })),
+ deleteCharacter: vi.fn(async () => ({ ok: true })),
+}));
+
+vi.mock('../services/writersRoom/settings.js', () => ({
+ listSettings: vi.fn(async () => [{ id: 'wr-setting-1', slugline: 'INT. KITCHEN — NIGHT' }]),
+ createSetting: vi.fn(async (workId, data) => ({ id: 'wr-setting-new', ...data })),
+ updateSetting: vi.fn(async (workId, settingId, data) => ({ id: settingId, ...data })),
+ deleteSetting: vi.fn(async () => ({ ok: true })),
+}));
+
+vi.mock('../services/writersRoom/evaluator.js', () => ({
+ runAnalysis: vi.fn(),
+ listAnalyses: vi.fn(async () => []),
+ getAnalysis: vi.fn(),
+ attachSceneImage: vi.fn(async () => ({})),
+}));
+
+vi.mock('../services/mediaCollections.js', () => ({
+ addItem: vi.fn(async () => ({ ok: true })),
+ ERR_DUPLICATE: 'ERR_DUPLICATE',
}));
import * as svc from '../services/writersRoom/local.js';
+import * as charSvc from '../services/writersRoom/characters.js';
+import * as settingsSvc from '../services/writersRoom/settings.js';
import writersRoomRoutes from './writersRoom.js';
describe('writersRoom routes', () => {
@@ -148,4 +177,105 @@ describe('writersRoom routes', () => {
expect(svc.discardExercise).toHaveBeenCalledWith('wr-ex-1');
});
});
+
+ describe('characters', () => {
+ it('GET /works/:id/characters returns the bible', async () => {
+ const r = await request(app).get('/api/writers-room/works/wr-work-1/characters');
+ expect(r.status).toBe(200);
+ expect(r.body[0].id).toBe('wr-char-1');
+ expect(charSvc.listCharacters).toHaveBeenCalledWith('wr-work-1');
+ });
+
+ it('POST /works/:id/characters rejects empty name (schema validation)', async () => {
+ const r = await request(app).post('/api/writers-room/works/wr-work-1/characters').send({ name: '' });
+ expect(r.status).toBe(400);
+ expect(charSvc.createCharacter).not.toHaveBeenCalled();
+ });
+
+ it('POST /works/:id/characters rejects extra/unknown fields (strict schema)', async () => {
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/characters')
+ .send({ name: 'Mila', wat: 'not allowed' });
+ expect(r.status).toBe(400);
+ });
+
+ it('POST /works/:id/characters accepts a valid payload', async () => {
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/characters')
+ .send({ name: 'Mila', physicalDescription: 'tall, copper hair' });
+ expect(r.status).toBe(201);
+ expect(charSvc.createCharacter).toHaveBeenCalledWith('wr-work-1', {
+ name: 'Mila',
+ physicalDescription: 'tall, copper hair',
+ });
+ });
+
+ it('PATCH /works/:id/characters/:characterId forwards a partial update', async () => {
+ const r = await request(app)
+ .patch('/api/writers-room/works/wr-work-1/characters/wr-char-1')
+ .send({ role: 'protagonist' });
+ expect(r.status).toBe(200);
+ expect(charSvc.updateCharacter).toHaveBeenCalledWith('wr-work-1', 'wr-char-1', { role: 'protagonist' });
+ });
+
+ it('PATCH /works/:id/characters/:characterId rejects empty name', async () => {
+ const r = await request(app)
+ .patch('/api/writers-room/works/wr-work-1/characters/wr-char-1')
+ .send({ name: ' ' });
+ expect(r.status).toBe(400);
+ });
+
+ it('DELETE /works/:id/characters/:characterId forwards to the service', async () => {
+ const r = await request(app).delete('/api/writers-room/works/wr-work-1/characters/wr-char-1');
+ expect(r.status).toBe(200);
+ expect(charSvc.deleteCharacter).toHaveBeenCalledWith('wr-work-1', 'wr-char-1');
+ });
+ });
+
+ describe('settings', () => {
+ it('GET /works/:id/settings returns the bible', async () => {
+ const r = await request(app).get('/api/writers-room/works/wr-work-1/settings');
+ expect(r.status).toBe(200);
+ expect(r.body[0].id).toBe('wr-setting-1');
+ expect(settingsSvc.listSettings).toHaveBeenCalledWith('wr-work-1');
+ });
+
+ it('POST /works/:id/settings rejects payload missing both slugline and name', async () => {
+ const r = await request(app).post('/api/writers-room/works/wr-work-1/settings').send({});
+ expect(r.status).toBe(400);
+ expect(settingsSvc.createSetting).not.toHaveBeenCalled();
+ });
+
+ it('POST /works/:id/settings accepts slugline-only payload', async () => {
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/settings')
+ .send({ slugline: 'INT. KITCHEN — NIGHT', description: 'cozy' });
+ expect(r.status).toBe(201);
+ expect(settingsSvc.createSetting).toHaveBeenCalledWith('wr-work-1', {
+ slugline: 'INT. KITCHEN — NIGHT',
+ description: 'cozy',
+ });
+ });
+
+ it('POST /works/:id/settings rejects unknown extra fields', async () => {
+ const r = await request(app)
+ .post('/api/writers-room/works/wr-work-1/settings')
+ .send({ slugline: 'INT. ATTIC — DUSK', tags: ['a'] });
+ expect(r.status).toBe(400);
+ });
+
+ it('PATCH /works/:id/settings/:settingId forwards a partial update', async () => {
+ const r = await request(app)
+ .patch('/api/writers-room/works/wr-work-1/settings/wr-setting-1')
+ .send({ palette: 'amber and ochre' });
+ expect(r.status).toBe(200);
+ expect(settingsSvc.updateSetting).toHaveBeenCalledWith('wr-work-1', 'wr-setting-1', { palette: 'amber and ochre' });
+ });
+
+ it('DELETE /works/:id/settings/:settingId forwards to the service', async () => {
+ const r = await request(app).delete('/api/writers-room/works/wr-work-1/settings/wr-setting-1');
+ expect(r.status).toBe(200);
+ expect(settingsSvc.deleteSetting).toHaveBeenCalledWith('wr-work-1', 'wr-setting-1');
+ });
+ });
});
diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.js
index 04153d3371..0d8fa875d0 100644
--- a/server/services/writersRoom/characters.js
+++ b/server/services/writersRoom/characters.js
@@ -153,12 +153,18 @@ export async function mergeExtractedCharacters(workId, extracted) {
if (!Array.isArray(extracted)) return listCharacters(workId);
const state = await loadFile(workId);
const byKey = new Map();
- for (const c of state.characters) {
- byKey.set(normalizeName(c.name), c);
+ // Index every character by its name AND every alias so a later batch entry
+ // referencing the same person via any of those tokens resolves to one
+ // canonical profile (no duplicates).
+ const indexCharacter = (c) => {
+ const nameKey = normalizeName(c.name);
+ if (nameKey) byKey.set(nameKey, c);
for (const alias of c.aliases || []) {
- byKey.set(normalizeName(alias), c);
+ const aliasKey = normalizeName(alias);
+ if (aliasKey) byKey.set(aliasKey, c);
}
- }
+ };
+ for (const c of state.characters) indexCharacter(c);
for (const incoming of extracted) {
if (!incoming || !incoming.name) continue;
const key = normalizeName(incoming.name);
@@ -173,6 +179,11 @@ export async function mergeExtractedCharacters(workId, extracted) {
}
if (isBlank(existing.aliases) && Array.isArray(incoming.aliases)) {
existing.aliases = incoming.aliases.map((a) => String(a).trim()).filter(Boolean);
+ // Re-index this character under its newly-filled aliases so later
+ // entries in the same batch that reference the character via one of
+ // those aliases resolve to this profile instead of being inserted
+ // as a duplicate.
+ indexCharacter(existing);
}
existing.firstAppearance = incoming.firstAppearance ?? existing.firstAppearance ?? null;
existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
@@ -194,7 +205,10 @@ export async function mergeExtractedCharacters(workId, extracted) {
source: 'ai',
};
state.characters.push(profile);
- byKey.set(normalizeName(profile.name), profile);
+ // Index the new profile under both its name and any aliases so a
+ // later entry in this batch that uses one of those aliases as its
+ // `name` matches this character instead of creating a second one.
+ indexCharacter(profile);
}
}
await saveFile(workId, state);
diff --git a/server/services/writersRoom/characters.test.js b/server/services/writersRoom/characters.test.js
index 38c30170a4..018dde5df3 100644
--- a/server/services/writersRoom/characters.test.js
+++ b/server/services/writersRoom/characters.test.js
@@ -117,6 +117,35 @@ describe('writers room — characters merge', () => {
expect(merged[0].physicalDescription).toBe('late fifties, gray suit, bald, sharp jaw');
});
+ it('does not duplicate when later batch entries use a new character\'s alias as their name', async () => {
+ // Simulates an extraction batch where the model first introduces a
+ // character with aliases, then references the same character by an
+ // alias as the `name` of a later entry. Both must resolve to one
+ // canonical profile — no duplicate.
+ const id = await newWork();
+ const merged = await mergeExtractedCharacters(id, [
+ { name: 'Mr. Voss', aliases: ['Voss', 'The Director'], role: 'antagonist' },
+ { name: 'The Director', physicalDescription: 'late fifties, gray suit' },
+ ]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].name).toBe('Mr. Voss');
+ expect(merged[0].physicalDescription).toBe('late fifties, gray suit');
+ });
+
+ it('does not duplicate when an existing character has aliases filled in mid-batch', async () => {
+ // An existing character with no aliases gets aliases filled by the
+ // first incoming entry; a later entry in the same batch references the
+ // character via one of those aliases. Must resolve to the same record.
+ const id = await newWork();
+ await createCharacter(id, { name: 'Aria' });
+ const merged = await mergeExtractedCharacters(id, [
+ { name: 'aria', aliases: ['Ari', 'A.'] },
+ { name: 'Ari', physicalDescription: 'thirties, athletic' },
+ ]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].physicalDescription).toBe('thirties, athletic');
+ });
+
it('refreshes prose-derived metadata even when text fields are preserved', async () => {
const id = await newWork();
const c = await createCharacter(id, { name: 'Aria', physicalDescription: 'kept' });
diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/settings.js
index c9512a6d0c..ec5cc0a268 100644
--- a/server/services/writersRoom/settings.js
+++ b/server/services/writersRoom/settings.js
@@ -161,14 +161,23 @@ export async function mergeExtractedSettings(workId, extracted) {
if (!Array.isArray(extracted)) return listSettings(workId);
const state = await loadFile(workId);
const byKey = new Map();
- for (const s of state.settings) {
- const key = normalizeSlugline(s.slugline || s.name);
- if (key) byKey.set(key, s);
- }
+ // Index a setting under BOTH its normalized slugline and its normalized
+ // name so an extracted entry that references the location via either
+ // identifier resolves to one canonical record. Indexing by only one of
+ // those keys lets a slugline-only incoming entry collide with a name-only
+ // existing entry (or vice versa) and create a duplicate setting.
+ const indexSetting = (s) => {
+ const slugKey = normalizeSlugline(s.slugline);
+ const nameKey = normalizeSlugline(s.name);
+ if (slugKey) byKey.set(slugKey, s);
+ if (nameKey) byKey.set(nameKey, s);
+ };
+ for (const s of state.settings) indexSetting(s);
for (const incoming of extracted) {
if (!incoming || (!incoming.slugline && !incoming.name)) continue;
- const key = normalizeSlugline(incoming.slugline || incoming.name);
- const existing = byKey.get(key);
+ const slugKey = normalizeSlugline(incoming.slugline);
+ const nameKey = normalizeSlugline(incoming.name);
+ const existing = (slugKey && byKey.get(slugKey)) || (nameKey && byKey.get(nameKey)) || null;
if (existing) {
for (const field of ['description', 'palette', 'era', 'weather', 'recurringDetails']) {
if (isBlank(existing[field]) && !isBlank(incoming[field])) {
@@ -177,6 +186,9 @@ export async function mergeExtractedSettings(workId, extracted) {
}
if (isBlank(existing.name) && !isBlank(incoming.name)) {
existing.name = String(incoming.name).trim();
+ // Re-index now that name is populated so a subsequent entry in the
+ // same batch keyed by that name resolves to this record.
+ indexSetting(existing);
}
existing.firstAppearance = incoming.firstAppearance ?? existing.firstAppearance ?? null;
existing.evidence = Array.isArray(incoming.evidence) ? incoming.evidence : (existing.evidence || []);
@@ -199,7 +211,7 @@ export async function mergeExtractedSettings(workId, extracted) {
source: 'ai',
};
state.settings.push(profile);
- byKey.set(normalizeSlugline(profile.slugline || profile.name), profile);
+ indexSetting(profile);
}
}
await saveFile(workId, state);
diff --git a/server/services/writersRoom/settings.test.js b/server/services/writersRoom/settings.test.js
new file mode 100644
index 0000000000..cc4970f55d
--- /dev/null
+++ b/server/services/writersRoom/settings.test.js
@@ -0,0 +1,187 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+let tempRoot;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };
+ return target[prop];
+ },
+ });
+});
+
+const local = await import('./local.js');
+const settings = await import('./settings.js');
+const { createWork } = local;
+const {
+ listSettings, createSetting, updateSetting, deleteSetting,
+ mergeExtractedSettings, normalizeSlugline,
+} = settings;
+
+beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-settings-test-'));
+});
+
+afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+});
+
+async function newWork() {
+ const w = await createWork({ title: 'Test Work', kind: 'short-story' });
+ return w.id;
+}
+
+describe('writers room — normalizeSlugline', () => {
+ it('collapses em-dash, en-dash, and hyphen variants to the same key', () => {
+ const a = normalizeSlugline('INT. KITCHEN — NIGHT');
+ const b = normalizeSlugline('INT. KITCHEN – NIGHT');
+ const c = normalizeSlugline('INT. KITCHEN - NIGHT');
+ const d = normalizeSlugline('INT KITCHEN NIGHT');
+ expect(a).toBe(b);
+ expect(b).toBe(c);
+ expect(c).toBe(d);
+ });
+
+ it('is case-insensitive and whitespace-tolerant', () => {
+ expect(normalizeSlugline('int. kitchen — night')).toBe(normalizeSlugline('INT. KITCHEN — NIGHT'));
+ });
+
+ it('returns empty for blank input', () => {
+ expect(normalizeSlugline('')).toBe('');
+ expect(normalizeSlugline(null)).toBe('');
+ expect(normalizeSlugline(undefined)).toBe('');
+ });
+});
+
+describe('writers room — settings CRUD', () => {
+ it('starts with an empty bible', async () => {
+ const id = await newWork();
+ expect(await listSettings(id)).toEqual([]);
+ });
+
+ it('rejects creating a setting with neither slugline nor name', async () => {
+ const id = await newWork();
+ await expect(createSetting(id, {})).rejects.toThrow(/slugline or a name/i);
+ });
+
+ it('rejects duplicate sluglines after normalization', async () => {
+ const id = await newWork();
+ await createSetting(id, { slugline: 'INT. KITCHEN — NIGHT', description: 'cozy' });
+ await expect(createSetting(id, { slugline: 'int. kitchen - night' })).rejects.toThrow(/already exists/i);
+ });
+
+ it('creates and updates a setting profile', async () => {
+ const id = await newWork();
+ const s = await createSetting(id, { slugline: 'EXT. ROOFTOP — DAWN', description: 'pink sky' });
+ expect(s.slugline).toBe('EXT. ROOFTOP — DAWN');
+ expect(s.id).toMatch(/^wr-setting-/);
+
+ const updated = await updateSetting(id, s.id, { description: 'pink sky over a copper city' });
+ expect(updated.description).toBe('pink sky over a copper city');
+ expect(updated.source).toBe('user');
+ });
+
+ it('deletes a setting', async () => {
+ const id = await newWork();
+ const s = await createSetting(id, { slugline: 'INT. ATTIC — DUSK' });
+ await deleteSetting(id, s.id);
+ expect(await listSettings(id)).toHaveLength(0);
+ });
+});
+
+describe('writers room — settings merge', () => {
+ it('adds new settings from extraction', async () => {
+ const id = await newWork();
+ const merged = await mergeExtractedSettings(id, [
+ { slugline: 'INT. KITCHEN — NIGHT', description: 'warm' },
+ { slugline: 'EXT. ROOFTOP — DAWN', name: 'Dawn Rooftop', description: 'pink' },
+ ]);
+ expect(merged).toHaveLength(2);
+ expect(merged.every((s) => s.source === 'ai')).toBe(true);
+ });
+
+ it('preserves user edits when re-merging (fill-blanks-only)', async () => {
+ const id = await newWork();
+ const s = await createSetting(id, {
+ slugline: 'INT. KITCHEN — NIGHT',
+ description: 'USER VERSION — copper kettle on the stove',
+ });
+ expect(s.source).toBe('user');
+
+ const merged = await mergeExtractedSettings(id, [{
+ slugline: 'INT. KITCHEN — NIGHT',
+ description: 'AI VERSION — generic kitchen',
+ palette: 'warm amber and ochre',
+ era: 'modern',
+ }]);
+ const refreshed = merged.find((x) => x.id === s.id);
+ expect(refreshed.description).toBe('USER VERSION — copper kettle on the stove');
+ expect(refreshed.palette).toBe('warm amber and ochre');
+ expect(refreshed.era).toBe('modern');
+ });
+
+ it('matches an existing setting by name when the incoming entry uses slugline', async () => {
+ // A user might create a setting via name only ("Eldritch Library").
+ // A later analysis pass may extract the same place by slugline
+ // ("INT. ELDRITCH LIBRARY — NIGHT"). The merge MUST resolve them to one
+ // record — otherwise the bible silently doubles up on every re-run.
+ const id = await newWork();
+ await createSetting(id, { name: 'Eldritch Library' });
+ const merged = await mergeExtractedSettings(id, [{
+ slugline: 'INT. ELDRITCH LIBRARY — NIGHT',
+ name: 'Eldritch Library',
+ description: 'rows of leather spines, dust motes',
+ }]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].description).toBe('rows of leather spines, dust motes');
+ });
+
+ it('matches an existing slugline-only setting by name on subsequent merges', async () => {
+ // Inverse of the above — initial extraction landed slugline only, a
+ // later extraction adds a `name`. The same place must resolve.
+ const id = await newWork();
+ await mergeExtractedSettings(id, [{ slugline: 'EXT. SEAWALL — DUSK' }]);
+ const merged = await mergeExtractedSettings(id, [{
+ name: 'EXT. SEAWALL — DUSK',
+ description: 'salt-bleached concrete, gulls overhead',
+ }]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].description).toBe('salt-bleached concrete, gulls overhead');
+ });
+
+ it('refreshes prose-derived metadata even when descriptive fields are preserved', async () => {
+ const id = await newWork();
+ const s = await createSetting(id, { slugline: 'INT. ATTIC — DUSK', description: 'kept' });
+ const merged = await mergeExtractedSettings(id, [{
+ slugline: 'INT. ATTIC — DUSK',
+ description: 'ignored',
+ missingFromProse: ['weather', 'palette'],
+ evidence: ['"She climbed the ladder,"'],
+ firstAppearance: 'Chapter 2',
+ }]);
+ const updated = merged.find((x) => x.id === s.id);
+ expect(updated.description).toBe('kept');
+ expect(updated.missingFromProse).toEqual(['weather', 'palette']);
+ expect(updated.firstAppearance).toBe('Chapter 2');
+ });
+
+ it('does not duplicate within a single batch when a new entry is referenced by both slugline and name', async () => {
+ // Within ONE merge call, the AI introduces a new setting with both
+ // slugline and a distinct name, then a later entry in the same batch
+ // references it via name only. Both must collapse to one record —
+ // otherwise re-running analysis would silently double up.
+ const id = await newWork();
+ const merged = await mergeExtractedSettings(id, [
+ { slugline: 'INT. CHAPEL — DAWN', name: 'The Old Chapel', description: 'whitewashed walls' },
+ { name: 'The Old Chapel', palette: 'bone-white and gold' },
+ ]);
+ expect(merged).toHaveLength(1);
+ expect(merged[0].description).toBe('whitewashed walls');
+ expect(merged[0].palette).toBe('bone-white and gold');
+ });
+});