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

refactor(writers-room): collapse character/setting/object stores onto bibleStore factory

Adam Eivy66f455993a73
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index f0e2034a63..878f775b00 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -2,13 +2,20 @@
* Canonical story-bible shapes (Character / Setting / Object) shared by the
* Writers Room (per-work bibles) and the Pipeline (per-series bibles).
*
- * Both surfaces persist their own JSON; this module just owns the shape +
- * sanitization + the merge-extracted-entries algorithm. Per-domain concerns
- * (id prefix, file path, route exposure) stay with the caller.
+ * Owns the shape + sanitization + merge-extracted-entries algorithm AND the
+ * `createBibleStore(...)` factory the writers-room domain files build on for
+ * their CRUD + file I/O. Route exposure stays with the caller.
*/
import { randomUUID } from 'crypto';
+import { join } from 'path';
import { normalizeSlugline } from './scenePrompt.js';
+import { PATHS, atomicWrite, ensureDir, readJSONFile } from './fileUtils.js';
+import { ServerError } from './errorHandler.js';
+
+// Re-export so callers (writers-room domain files) can import a single
+// canonical normalizer when they need to match settings by slugline.
+export { normalizeSlugline };
export const BIBLE_LIMITS = Object.freeze({
NAME_MAX: 200,
@@ -369,3 +376,149 @@ export function mergeExtractedBible(existing, incoming, kind, { idPrefix = DEFAU
return existing.sort((a, b) => keyOf(a).localeCompare(keyOf(b)));
}
+
+/**
+ * createBibleStore — per-work CRUD + merge factory. Collapses the three
+ * writers-room domain files (characters/settings/objects) onto one
+ * implementation parameterized by `opts`:
+ *
+ * kind, idPrefix, idRegex, fileName, listKey
+ * dedupKey(entry) → string — normalize an entry to its dedup key
+ * primaryFields — fields that participate in the dedup key (['name'] for
+ * char/obj, ['slugline', 'name'] for settings)
+ * editableFields — patchable fields that DON'T go through the dedup-aware
+ * path; capped/cleaned by the kind's sanitizer
+ * requireOnCreate(patch) → string|undefined — message if required field
+ * missing (lets char/obj require `name`, settings require name-or-slugline)
+ * validateAfterUpdate(next) — optional; throw if invalid (settings use
+ * this for "both name and slugline blank → reject")
+ * conflictMessage(value), notFoundLabel, invalidIdMessage — error strings
+ *
+ * Returns { list, get, create, update, remove, mergeExtracted }. `remove`
+ * (not `delete`) because the latter is a JS keyword.
+ */
+
+const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;
+const badReq = (message) => new ServerError(message, { status: 400, code: 'VALIDATION_ERROR' });
+const notFoundErr = (what) => new ServerError(`${what} not found`, { status: 404, code: 'NOT_FOUND' });
+const wrDir = (workId) => {
+ if (typeof workId !== 'string' || !WORK_ID_RE.test(workId)) throw badReq('Invalid work id');
+ return join(PATHS.data, 'writers-room', 'works', workId);
+};
+
+export function createBibleStore(opts) {
+ const {
+ kind, idPrefix, idRegex, fileName, listKey, dedupKey, primaryFields,
+ editableFields, requireOnCreate, validateAfterUpdate, conflictMessage,
+ notFoundLabel, invalidIdMessage,
+ } = opts;
+ const sanitizer = SANITIZERS[kind];
+ if (!sanitizer) throw new Error(`createBibleStore: unknown kind "${kind}"`);
+ const sortKeyFn = sortKey(kind);
+ const filePath = (workId) => join(wrDir(workId), fileName);
+ const assertId = (id) => { if (!idRegex.test(id)) throw badReq(invalidIdMessage); };
+
+ async function load(workId) {
+ const fallback = { [listKey]: [], updatedAt: null };
+ const parsed = await readJSONFile(filePath(workId), fallback);
+ if (!parsed || !Array.isArray(parsed[listKey])) return fallback;
+ return { ...parsed, [listKey]: sanitizeBibleList(parsed[listKey], kind, { idPrefix }) };
+ }
+
+ async function save(workId, state) {
+ await ensureDir(wrDir(workId));
+ await atomicWrite(filePath(workId), { ...state, updatedAt: nowIso() });
+ }
+
+ async function list(workId) {
+ const state = await load(workId);
+ return state[listKey].sort((a, b) => sortKeyFn(a).localeCompare(sortKeyFn(b)));
+ }
+
+ async function get(workId, entryId) {
+ assertId(entryId);
+ const state = await load(workId);
+ const found = state[listKey].find((e) => e.id === entryId);
+ if (!found) throw notFoundErr(notFoundLabel);
+ return found;
+ }
+
+ async function create(workId, patch = {}) {
+ const requireErr = requireOnCreate(patch);
+ if (requireErr) throw badReq(requireErr);
+ const state = await load(workId);
+ const keyOfPatch = dedupKey(patch);
+ if (keyOfPatch && state[listKey].some((e) => dedupKey(e) === keyOfPatch)) {
+ throw badReq(conflictMessage(patch));
+ }
+ const draft = { id: `${idPrefix}${randomUUID()}`, source: 'user' };
+ for (const field of primaryFields) {
+ if (patch[field] !== undefined) draft[field] = String(patch[field] || '').trim();
+ }
+ for (const field of editableFields) {
+ if (patch[field] !== undefined) draft[field] = patch[field];
+ }
+ // Settings: if both name and slugline are primary, missing name + present
+ // slugline → mirror slugline → name (preserves old createSetting behavior).
+ if (primaryFields.includes('name') && primaryFields.includes('slugline') && !draft.name && draft.slugline) {
+ draft.name = draft.slugline;
+ }
+ const profile = sanitizer(draft, { idPrefix, preserveTimestamps: false });
+ state[listKey].push(profile);
+ await save(workId, state);
+ return profile;
+ }
+
+ async function update(workId, entryId, patch = {}) {
+ assertId(entryId);
+ const state = await load(workId);
+ const idx = state[listKey].findIndex((e) => e.id === entryId);
+ if (idx < 0) throw notFoundErr(notFoundLabel);
+ const next = { ...state[listKey][idx] };
+ // Primary fields: single-primary kinds reject blank; multi-primary
+ // settings allow blanks here and rely on validateAfterUpdate for the
+ // combined-blank invariant.
+ for (const field of primaryFields) {
+ if (patch[field] === undefined) continue;
+ const newVal = String(patch[field] || '').trim();
+ if (primaryFields.length === 1 && !newVal) {
+ throw badReq(`${notFoundLabel} ${field} cannot be blank`);
+ }
+ if (newVal) {
+ const newKey = dedupKey({ ...next, [field]: newVal });
+ if (newKey && state[listKey].some((e) => e.id !== entryId && dedupKey(e) === newKey)) {
+ throw badReq(conflictMessage({ [field]: newVal }));
+ }
+ }
+ next[field] = newVal;
+ }
+ for (const field of editableFields) {
+ if (patch[field] !== undefined) next[field] = patch[field];
+ }
+ if (validateAfterUpdate) validateAfterUpdate(next);
+ next.source = 'user';
+ state[listKey][idx] = sanitizer({ ...next, updatedAt: nowIso() }, { idPrefix, preserveTimestamps: true });
+ await save(workId, state);
+ return state[listKey][idx];
+ }
+
+ async function remove(workId, entryId) {
+ assertId(entryId);
+ const state = await load(workId);
+ const before = state[listKey].length;
+ state[listKey] = state[listKey].filter((e) => e.id !== entryId);
+ if (state[listKey].length === before) throw notFoundErr(notFoundLabel);
+ await save(workId, state);
+ return { ok: true };
+ }
+
+ async function mergeExtracted(workId, extracted) {
+ if (!Array.isArray(extracted)) return list(workId);
+ const state = await load(workId);
+ state[listKey] = mergeExtractedBible(state[listKey], extracted, kind, { idPrefix });
+ await save(workId, state);
+ return state[listKey];
+ }
+
+ return { list, get, create, update, remove, mergeExtracted };
+}
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 70e1f48710..ab8027ae5f 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -1,5 +1,24 @@
-import { describe, it, expect } from 'vitest';
-import {
+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;
+
+// Mock PATHS.data so the factory writes into a temp dir per test. Mirrors
+// the pattern used by writers-room CRUD tests.
+vi.mock('./fileUtils.js', async () => {
+ const actual = await vi.importActual('./fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return { ...actual.PATHS, data: tempRoot };
+ return target[prop];
+ },
+ });
+});
+
+const storyBible = await import('./storyBible.js');
+const {
sanitizeCharacter,
sanitizeSetting,
sanitizeObject,
@@ -7,8 +26,13 @@ import {
mergeExtractedBible,
isBlank,
normalizeBibleName,
+ normalizeSlugline,
BIBLE_LIMITS,
-} from './storyBible.js';
+ BIBLE_KIND,
+ createBibleStore,
+} = storyBible;
+
+const WORK_ID = 'wr-work-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
describe('storyBible — sanitizeCharacter', () => {
it('returns null when name is blank or input is not an object', () => {
@@ -279,3 +303,176 @@ describe('storyBible — helpers', () => {
expect(normalizeBibleName(null)).toBe('');
});
});
+
+// ---------------------------------------------------------------------------
+// createBibleStore — factory exercised through the three real per-kind
+// configs (so we cover both the single-primary-field path and the multi-
+// primary settings path). Each subgroup gets a fresh temp dir.
+// ---------------------------------------------------------------------------
+
+function characterStore() {
+ return createBibleStore({
+ kind: BIBLE_KIND.CHARACTER,
+ idPrefix: 'wr-char-',
+ idRegex: /^wr-char-[0-9a-f-]+$/i,
+ fileName: 'characters.json',
+ listKey: 'characters',
+ dedupKey: (entry) => normalizeBibleName(entry?.name),
+ primaryFields: ['name'],
+ editableFields: ['aliases', 'role', 'physicalDescription'],
+ requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Character name required'),
+ conflictMessage: ({ name }) => `A character named "${name}" already exists`,
+ notFoundLabel: 'Character',
+ invalidIdMessage: 'Invalid character id',
+ });
+}
+
+function settingStore() {
+ return createBibleStore({
+ kind: BIBLE_KIND.SETTING,
+ idPrefix: 'wr-setting-',
+ idRegex: /^wr-setting-[0-9a-f-]+$/i,
+ fileName: 'settings.json',
+ listKey: 'settings',
+ dedupKey: (entry) => normalizeSlugline(entry?.slugline || entry?.name || ''),
+ primaryFields: ['slugline', 'name'],
+ editableFields: ['description', 'palette'],
+ requireOnCreate: (patch) => {
+ const sl = String(patch?.slugline || '').trim();
+ const nm = String(patch?.name || '').trim();
+ return sl || nm ? null : 'Setting requires either a slugline or a name';
+ },
+ validateAfterUpdate: (next) => {
+ if (!next.slugline && !next.name) {
+ const err = new Error('Setting needs slugline or name');
+ err.status = 400;
+ throw err;
+ }
+ },
+ conflictMessage: ({ slugline, name }) => `A setting matching "${slugline || name}" already exists`,
+ notFoundLabel: 'Setting',
+ invalidIdMessage: 'Invalid setting id',
+ });
+}
+
+describe('storyBible — createBibleStore (single-primary-field kind)', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'bible-factory-test-'));
+ });
+ afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ it('creates, lists, gets, updates, deletes', async () => {
+ const store = characterStore();
+ expect(await store.list(WORK_ID)).toEqual([]);
+
+ const created = await store.create(WORK_ID, { name: 'Aria', role: 'protagonist' });
+ expect(created.id).toMatch(/^wr-char-/);
+ expect(created.name).toBe('Aria');
+ expect(created.source).toBe('user');
+
+ const listed = await store.list(WORK_ID);
+ expect(listed).toHaveLength(1);
+
+ const fetched = await store.get(WORK_ID, created.id);
+ expect(fetched.id).toBe(created.id);
+
+ const updated = await store.update(WORK_ID, created.id, { role: 'antagonist' });
+ expect(updated.role).toBe('antagonist');
+
+ const removed = await store.remove(WORK_ID, created.id);
+ expect(removed).toEqual({ ok: true });
+ expect(await store.list(WORK_ID)).toEqual([]);
+ });
+
+ it('rejects creation without the required identifier', async () => {
+ const store = characterStore();
+ await expect(store.create(WORK_ID, { name: ' ' })).rejects.toThrow(/name required/i);
+ });
+
+ it('rejects duplicate dedup keys at create time (case-insensitive)', async () => {
+ const store = characterStore();
+ await store.create(WORK_ID, { name: 'Aria' });
+ await expect(store.create(WORK_ID, { name: 'aria' })).rejects.toThrow(/already exists/i);
+ });
+
+ it('rejects path-traversal-shaped work ids before any filesystem access', async () => {
+ const store = characterStore();
+ await expect(store.list('../../etc')).rejects.toThrow(/work id/i);
+ await expect(store.create('../../etc', { name: 'X' })).rejects.toThrow(/work id/i);
+ await expect(store.mergeExtracted('../../etc', [{ name: 'X' }])).rejects.toThrow(/work id/i);
+ });
+
+ it('rejects malformed entry ids on get/update/remove', async () => {
+ const store = characterStore();
+ await expect(store.get(WORK_ID, 'nope')).rejects.toThrow(/invalid character id/i);
+ await expect(store.update(WORK_ID, 'nope', {})).rejects.toThrow(/invalid character id/i);
+ await expect(store.remove(WORK_ID, 'nope')).rejects.toThrow(/invalid character id/i);
+ });
+
+ it('rejects blanking the primary identifier on update', async () => {
+ const store = characterStore();
+ const c = await store.create(WORK_ID, { name: 'Aria' });
+ await expect(store.update(WORK_ID, c.id, { name: '' })).rejects.toThrow(/cannot be blank/i);
+ });
+
+ it('mergeExtracted inserts new entries and skips duplicates', async () => {
+ const store = characterStore();
+ const merged = await store.mergeExtracted(WORK_ID, [
+ { name: 'Aria', role: 'protagonist' },
+ { name: 'Voss', role: 'antagonist' },
+ ]);
+ expect(merged).toHaveLength(2);
+ expect(merged.every((e) => e.source === 'ai')).toBe(true);
+ });
+});
+
+describe('storyBible — createBibleStore (multi-primary-field kind / settings)', () => {
+ beforeEach(() => {
+ tempRoot = mkdtempSync(join(tmpdir(), 'bible-factory-settings-test-'));
+ });
+ afterEach(() => {
+ if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
+ it('accepts either slugline or name as the primary identifier at create', async () => {
+ const store = settingStore();
+ const a = await store.create(WORK_ID, { slugline: 'INT. KITCHEN — NIGHT', description: 'cozy' });
+ expect(a.slugline).toBe('INT. KITCHEN — NIGHT');
+ // Auto-fills name from slugline when name omitted.
+ expect(a.name).toBe('INT. KITCHEN — NIGHT');
+
+ const b = await store.create(WORK_ID, { name: 'The Atrium' });
+ expect(b.name).toBe('The Atrium');
+ expect(b.slugline).toBe('');
+ });
+
+ it('rejects creation when both slugline and name are blank', async () => {
+ const store = settingStore();
+ await expect(store.create(WORK_ID, {})).rejects.toThrow(/slugline or a name/i);
+ });
+
+ it('rejects an update that blanks both name and slugline (validateAfterUpdate)', async () => {
+ const store = settingStore();
+ const s = await store.create(WORK_ID, { name: 'The Atrium' });
+ await expect(store.update(WORK_ID, s.id, { name: '' })).rejects.toThrow(/slugline or name/i);
+ });
+
+ it('rejects duplicate-slugline create after normalization', async () => {
+ const store = settingStore();
+ await store.create(WORK_ID, { slugline: 'INT. KITCHEN — NIGHT' });
+ await expect(
+ store.create(WORK_ID, { slugline: 'int. kitchen - night' }),
+ ).rejects.toThrow(/already exists/i);
+ });
+
+ it('rejects an update that would collide with another entry on dedup key', async () => {
+ const store = settingStore();
+ const a = await store.create(WORK_ID, { slugline: 'INT. KITCHEN — NIGHT' });
+ await store.create(WORK_ID, { slugline: 'EXT. ROOFTOP — DAWN' });
+ await expect(
+ store.update(WORK_ID, a.id, { slugline: 'EXT. ROOFTOP — DAWN' }),
+ ).rejects.toThrow(/already exists/i);
+ });
+});
diff --git a/server/services/writersRoom/characters.js b/server/services/writersRoom/characters.js
index 5a120dd105..8ee12bac12 100644
--- a/server/services/writersRoom/characters.js
+++ b/server/services/writersRoom/characters.js
@@ -2,133 +2,30 @@
* Writers Room — editable character profile bible.
*
* Per-work canonical roster stored at data/writers-room/works/<workId>/
- * characters.json. Distinct from the immutable analysis snapshots — the
- * snapshot is history; this file is the working bible that survives across
- * runs and accepts hand-edits.
- *
- * Shape + extraction-merge live in `server/lib/storyBible.js`; this module
- * owns CRUD, file I/O, and the writers-room id prefix (`wr-char-`).
+ * characters.json. CRUD + file I/O + dedup rules all live in the shared
+ * `createBibleStore` factory; this module just supplies the per-kind config.
*/
-import { join } from 'path';
-import { randomUUID } from 'crypto';
-import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
-import {
- sanitizeCharacter,
- sanitizeBibleList,
- mergeExtractedBible,
- normalizeBibleName,
-} from '../../lib/storyBible.js';
-import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
-
-const CHAR_ID_RE = /^wr-char-[0-9a-f-]+$/i;
-const ID_PREFIX = 'wr-char-';
-
-const root = () => join(PATHS.data, 'writers-room');
-const charsFile = (workId) => {
- // Defense-in-depth: routes validate the URL parameter, but this module is
- // also imported directly (mergeExtractedCharacters from the analysis
- // pipeline). Refusing path-traversal-shaped ids here makes workId-as-fs-
- // path safe regardless of caller.
- assertValidWorkId(workId);
- return join(root(), 'works', workId, 'characters.json');
-};
-
-const EDITABLE_FIELDS = ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'];
-
-async function loadFile(workId) {
- const fallback = { characters: [], updatedAt: null };
- const parsed = await readJSONFile(charsFile(workId), fallback);
- if (!parsed || !Array.isArray(parsed.characters)) return fallback;
- return { ...parsed, characters: sanitizeBibleList(parsed.characters, 'character', { idPrefix: ID_PREFIX }) };
-}
-
-async function saveFile(workId, state) {
- assertValidWorkId(workId);
- await ensureDir(join(root(), 'works', workId));
- await atomicWrite(charsFile(workId), { ...state, updatedAt: nowIso() });
-}
-
-export async function listCharacters(workId) {
- const state = await loadFile(workId);
- return state.characters.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
-}
-
-export async function getCharacter(workId, characterId) {
- if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
- const state = await loadFile(workId);
- const found = state.characters.find((c) => c.id === characterId);
- if (!found) throw notFound('Character');
- return found;
-}
-
-export async function createCharacter(workId, patch = {}) {
- const name = String(patch.name || '').trim();
- if (!name) throw badRequest('Character name required');
- const state = await loadFile(workId);
- if (state.characters.some((c) => normalizeBibleName(c.name) === normalizeBibleName(name))) {
- throw badRequest(`A character named "${name}" already exists`);
- }
- // Merge user-supplied editable fields into the canonical empty profile,
- // then route through the shared sanitizer so caps/array-cleanup apply.
- const draft = { id: `${ID_PREFIX}${randomUUID()}`, name, source: 'user' };
- for (const field of EDITABLE_FIELDS) {
- if (field === 'name') continue;
- if (patch[field] !== undefined) draft[field] = patch[field];
- }
- const profile = sanitizeCharacter(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
- state.characters.push(profile);
- await saveFile(workId, state);
- return profile;
-}
-
-export async function updateCharacter(workId, characterId, patch = {}) {
- if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
- const state = await loadFile(workId);
- const idx = state.characters.findIndex((c) => c.id === characterId);
- if (idx < 0) throw notFound('Character');
- const next = { ...state.characters[idx] };
- for (const field of EDITABLE_FIELDS) {
- if (patch[field] === undefined) continue;
- if (field === 'name') {
- const newName = String(patch.name || '').trim();
- if (!newName) throw badRequest('Character name cannot be blank');
- const conflict = state.characters.some((c) => c.id !== characterId && normalizeBibleName(c.name) === normalizeBibleName(newName));
- if (conflict) throw badRequest(`A character named "${newName}" already exists`);
- next.name = newName;
- } else {
- next[field] = patch[field];
- }
- }
- next.source = 'user';
- // Re-sanitize so freshly-supplied fields get capped/cleaned consistently.
- state.characters[idx] = sanitizeCharacter(
- { ...next, updatedAt: nowIso() },
- { idPrefix: ID_PREFIX, preserveTimestamps: true },
- );
- await saveFile(workId, state);
- return state.characters[idx];
-}
-
-export async function deleteCharacter(workId, characterId) {
- if (!CHAR_ID_RE.test(characterId)) throw badRequest('Invalid character id');
- const state = await loadFile(workId);
- const before = state.characters.length;
- state.characters = state.characters.filter((c) => c.id !== characterId);
- if (state.characters.length === before) throw notFound('Character');
- await saveFile(workId, state);
- return { ok: true };
-}
-
-/**
- * Merge an AI-extracted character set into the editable bible. Delegates
- * to `mergeExtractedBible` so the writers-room and pipeline-side merges
- * follow byte-identical rules.
- */
-export async function mergeExtractedCharacters(workId, extracted) {
- if (!Array.isArray(extracted)) return listCharacters(workId);
- const state = await loadFile(workId);
- state.characters = mergeExtractedBible(state.characters, extracted, 'character', { idPrefix: ID_PREFIX });
- await saveFile(workId, state);
- return state.characters;
-}
+import { createBibleStore, BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';
+
+export const {
+ list: listCharacters,
+ get: getCharacter,
+ create: createCharacter,
+ update: updateCharacter,
+ remove: deleteCharacter,
+ mergeExtracted: mergeExtractedCharacters,
+} = createBibleStore({
+ kind: BIBLE_KIND.CHARACTER,
+ idPrefix: 'wr-char-',
+ idRegex: /^wr-char-[0-9a-f-]+$/i,
+ fileName: 'characters.json',
+ listKey: 'characters',
+ dedupKey: (entry) => normalizeBibleName(entry?.name),
+ primaryFields: ['name'],
+ editableFields: ['aliases', 'role', 'physicalDescription', 'personality', 'background', 'notes'],
+ requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Character name required'),
+ conflictMessage: ({ name }) => `A character named "${name}" already exists`,
+ notFoundLabel: 'Character',
+ invalidIdMessage: 'Invalid character id',
+});
diff --git a/server/services/writersRoom/objects.js b/server/services/writersRoom/objects.js
index a33b59cd99..b42cbc052f 100644
--- a/server/services/writersRoom/objects.js
+++ b/server/services/writersRoom/objects.js
@@ -2,118 +2,30 @@
* Writers Room — editable recurring-objects bible.
*
* Per-work canonical roster stored at data/writers-room/works/<workId>/
- * objects.json. Shape + extraction-merge live in `server/lib/storyBible.js`;
- * this module owns CRUD, file I/O, and the writers-room id prefix
- * (`wr-object-`).
+ * objects.json. CRUD + file I/O + dedup rules all live in the shared
+ * `createBibleStore` factory; this module just supplies the per-kind config.
*/
-import { join } from 'path';
-import { randomUUID } from 'crypto';
-import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
-import {
- sanitizeObject,
- sanitizeBibleList,
- mergeExtractedBible,
- normalizeBibleName,
-} from '../../lib/storyBible.js';
-import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
-
-const OBJECT_ID_RE = /^wr-object-[0-9a-f-]+$/i;
-const ID_PREFIX = 'wr-object-';
-
-const root = () => join(PATHS.data, 'writers-room');
-const objectsFile = (workId) => {
- assertValidWorkId(workId);
- return join(root(), 'works', workId, 'objects.json');
-};
-
-const EDITABLE_FIELDS = ['name', 'aliases', 'description', 'significance', 'notes'];
-
-async function loadFile(workId) {
- const fallback = { objects: [], updatedAt: null };
- const parsed = await readJSONFile(objectsFile(workId), fallback);
- if (!parsed || !Array.isArray(parsed.objects)) return fallback;
- return { ...parsed, objects: sanitizeBibleList(parsed.objects, 'object', { idPrefix: ID_PREFIX }) };
-}
-
-async function saveFile(workId, state) {
- assertValidWorkId(workId);
- await ensureDir(join(root(), 'works', workId));
- await atomicWrite(objectsFile(workId), { ...state, updatedAt: nowIso() });
-}
-
-export async function listObjects(workId) {
- const state = await loadFile(workId);
- return state.objects.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
-}
-
-export async function getObject(workId, objectId) {
- if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');
- const state = await loadFile(workId);
- const found = state.objects.find((o) => o.id === objectId);
- if (!found) throw notFound('Object');
- return found;
-}
-
-export async function createObject(workId, patch = {}) {
- const name = String(patch.name || '').trim();
- if (!name) throw badRequest('Object name required');
- const state = await loadFile(workId);
- if (state.objects.some((o) => normalizeBibleName(o.name) === normalizeBibleName(name))) {
- throw badRequest(`An object named "${name}" already exists`);
- }
- const draft = { id: `${ID_PREFIX}${randomUUID()}`, name, source: 'user' };
- for (const field of EDITABLE_FIELDS) {
- if (field === 'name') continue;
- if (patch[field] !== undefined) draft[field] = patch[field];
- }
- const profile = sanitizeObject(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
- state.objects.push(profile);
- await saveFile(workId, state);
- return profile;
-}
-
-export async function updateObject(workId, objectId, patch = {}) {
- if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');
- const state = await loadFile(workId);
- const idx = state.objects.findIndex((o) => o.id === objectId);
- if (idx < 0) throw notFound('Object');
- const next = { ...state.objects[idx] };
- for (const field of EDITABLE_FIELDS) {
- if (patch[field] === undefined) continue;
- if (field === 'name') {
- const newName = String(patch.name || '').trim();
- if (!newName) throw badRequest('Object name cannot be blank');
- const conflict = state.objects.some((o) => o.id !== objectId && normalizeBibleName(o.name) === normalizeBibleName(newName));
- if (conflict) throw badRequest(`An object named "${newName}" already exists`);
- next.name = newName;
- } else {
- next[field] = patch[field];
- }
- }
- next.source = 'user';
- state.objects[idx] = sanitizeObject(
- { ...next, updatedAt: nowIso() },
- { idPrefix: ID_PREFIX, preserveTimestamps: true },
- );
- await saveFile(workId, state);
- return state.objects[idx];
-}
-
-export async function deleteObject(workId, objectId) {
- if (!OBJECT_ID_RE.test(objectId)) throw badRequest('Invalid object id');
- const state = await loadFile(workId);
- const before = state.objects.length;
- state.objects = state.objects.filter((o) => o.id !== objectId);
- if (state.objects.length === before) throw notFound('Object');
- await saveFile(workId, state);
- return { ok: true };
-}
-
-export async function mergeExtractedObjects(workId, extracted) {
- if (!Array.isArray(extracted)) return listObjects(workId);
- const state = await loadFile(workId);
- state.objects = mergeExtractedBible(state.objects, extracted, 'object', { idPrefix: ID_PREFIX });
- await saveFile(workId, state);
- return state.objects;
-}
+import { createBibleStore, BIBLE_KIND, normalizeBibleName } from '../../lib/storyBible.js';
+
+export const {
+ list: listObjects,
+ get: getObject,
+ create: createObject,
+ update: updateObject,
+ remove: deleteObject,
+ mergeExtracted: mergeExtractedObjects,
+} = createBibleStore({
+ kind: BIBLE_KIND.OBJECT,
+ idPrefix: 'wr-object-',
+ idRegex: /^wr-object-[0-9a-f-]+$/i,
+ fileName: 'objects.json',
+ listKey: 'objects',
+ dedupKey: (entry) => normalizeBibleName(entry?.name),
+ primaryFields: ['name'],
+ editableFields: ['aliases', 'description', 'significance', 'notes'],
+ requireOnCreate: (patch) => (String(patch?.name || '').trim() ? null : 'Object name required'),
+ conflictMessage: ({ name }) => `An object named "${name}" already exists`,
+ notFoundLabel: 'Object',
+ invalidIdMessage: 'Invalid object id',
+});
diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/settings.js
index 51602399ad..b29838c00e 100644
--- a/server/services/writersRoom/settings.js
+++ b/server/services/writersRoom/settings.js
@@ -3,139 +3,49 @@
*
* Per-location bible keyed by screenplay slugline so SceneCard can match a
* scene's slugline to its canonical setting and inject the description into
- * the image prompt.
- *
- * Per-work file at data/writers-room/works/<workId>/settings.json. Shape +
- * extraction-merge live in `server/lib/storyBible.js`; this module owns
- * CRUD, file I/O, and the writers-room id prefix (`wr-setting-`).
+ * the image prompt. Per-work file at data/writers-room/works/<workId>/
+ * settings.json. CRUD + file I/O + dedup rules all live in the shared
+ * `createBibleStore` factory; this module supplies the per-kind config and
+ * the name-OR-slugline identifier rule.
*/
-import { join } from 'path';
-import { randomUUID } from 'crypto';
-import { PATHS, atomicWrite, ensureDir, readJSONFile } from '../../lib/fileUtils.js';
-import { normalizeSlugline as canonicalNormalizeSlugline } from '../../lib/scenePrompt.js';
-import {
- sanitizeSetting,
- sanitizeBibleList,
- mergeExtractedBible,
-} from '../../lib/storyBible.js';
-import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';
-
-const SETTING_ID_RE = /^wr-setting-[0-9a-f-]+$/i;
-const ID_PREFIX = 'wr-setting-';
-
-const root = () => join(PATHS.data, 'writers-room');
-const settingsFile = (workId) => {
- // Defense-in-depth: refuse path-traversal-shaped workIds before
- // interpolating them into the on-disk path.
- assertValidWorkId(workId);
- return join(root(), 'works', workId, 'settings.json');
-};
-
-// `name` + `slugline` handled separately (identifier rule + conflict check).
-const EDITABLE_FIELDS = ['description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'];
+import { createBibleStore, BIBLE_KIND, normalizeSlugline } from '../../lib/storyBible.js';
+import { ServerError } from '../../lib/errorHandler.js';
// Re-export under the historical name for the existing test + import surface.
-// Canonical implementation in server/lib/scenePrompt.js.
-export const normalizeSlugline = canonicalNormalizeSlugline;
-
-async function loadFile(workId) {
- const fallback = { settings: [], updatedAt: null };
- const parsed = await readJSONFile(settingsFile(workId), fallback);
- if (!parsed || !Array.isArray(parsed.settings)) return fallback;
- return { ...parsed, settings: sanitizeBibleList(parsed.settings, 'setting', { idPrefix: ID_PREFIX }) };
-}
-
-async function saveFile(workId, state) {
- assertValidWorkId(workId);
- await ensureDir(join(root(), 'works', workId));
- await atomicWrite(settingsFile(workId), { ...state, updatedAt: nowIso() });
-}
-
-export async function listSettings(workId) {
- const state = await loadFile(workId);
- return state.settings.sort((a, b) => (a.slugline || a.name || '').localeCompare(b.slugline || b.name || ''));
-}
-
-export async function getSetting(workId, settingId) {
- if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
- const state = await loadFile(workId);
- const found = state.settings.find((s) => s.id === settingId);
- if (!found) throw notFound('Setting');
- return found;
-}
-
-export async function createSetting(workId, patch = {}) {
- const slugline = String(patch.slugline || '').trim();
- const name = String(patch.name || '').trim();
- if (!slugline && !name) throw badRequest('Setting requires either a slugline or a name');
- const state = await loadFile(workId);
- const key = canonicalNormalizeSlugline(slugline || name);
- if (state.settings.some((s) => canonicalNormalizeSlugline(s.slugline || s.name) === key)) {
- throw badRequest(`A setting matching "${slugline || name}" already exists`);
- }
- const draft = {
- id: `${ID_PREFIX}${randomUUID()}`,
- slugline,
- name: name || slugline,
- source: 'user',
- };
- for (const field of EDITABLE_FIELDS) {
- if (patch[field] !== undefined) draft[field] = patch[field];
- }
- const profile = sanitizeSetting(draft, { idPrefix: ID_PREFIX, preserveTimestamps: false });
- state.settings.push(profile);
- await saveFile(workId, state);
- return profile;
-}
-
-export async function updateSetting(workId, settingId, patch = {}) {
- if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
- const state = await loadFile(workId);
- const idx = state.settings.findIndex((s) => s.id === settingId);
- if (idx < 0) throw notFound('Setting');
- const next = { ...state.settings[idx] };
- for (const field of ['slugline', 'name']) {
- if (patch[field] === undefined) continue;
- const newVal = String(patch[field] || '').trim();
- const key = canonicalNormalizeSlugline(newVal);
- if (key) {
- const conflict = state.settings.some((s) => s.id !== settingId && canonicalNormalizeSlugline(s.slugline || s.name) === key);
- if (conflict) throw badRequest(`A setting matching "${newVal}" already exists`);
+export { normalizeSlugline };
+
+const dedupKey = (entry) => normalizeSlugline(entry?.slugline || entry?.name || '');
+
+export const {
+ list: listSettings,
+ get: getSetting,
+ create: createSetting,
+ update: updateSetting,
+ remove: deleteSetting,
+ mergeExtracted: mergeExtractedSettings,
+} = createBibleStore({
+ kind: BIBLE_KIND.SETTING,
+ idPrefix: 'wr-setting-',
+ idRegex: /^wr-setting-[0-9a-f-]+$/i,
+ fileName: 'settings.json',
+ listKey: 'settings',
+ dedupKey,
+ primaryFields: ['slugline', 'name'],
+ editableFields: ['description', 'palette', 'era', 'weather', 'recurringDetails', 'notes'],
+ requireOnCreate: (patch) => {
+ const slugline = String(patch?.slugline || '').trim();
+ const name = String(patch?.name || '').trim();
+ return slugline || name ? null : 'Setting requires either a slugline or a name';
+ },
+ validateAfterUpdate: (next) => {
+ // A PATCH that blanks the only non-empty identifier (e.g. name-only
+ // setting receiving `{ name: '' }`) would leave the record unaddressable.
+ if (!next.slugline && !next.name) {
+ throw new ServerError('Setting needs slugline or name', { status: 400, code: 'VALIDATION_ERROR' });
}
- next[field] = newVal;
- }
- for (const field of EDITABLE_FIELDS) {
- if (patch[field] !== undefined) next[field] = patch[field];
- }
- // A PATCH that blanks the only non-empty identifier (e.g. name-only
- // setting receiving `{ name: '' }`) would leave the setting unaddressable.
- if (!next.slugline && !next.name) {
- throw badRequest('Setting needs slugline or name');
- }
- next.source = 'user';
- state.settings[idx] = sanitizeSetting(
- { ...next, updatedAt: nowIso() },
- { idPrefix: ID_PREFIX, preserveTimestamps: true },
- );
- await saveFile(workId, state);
- return state.settings[idx];
-}
-
-export async function deleteSetting(workId, settingId) {
- if (!SETTING_ID_RE.test(settingId)) throw badRequest('Invalid setting id');
- const state = await loadFile(workId);
- const before = state.settings.length;
- state.settings = state.settings.filter((s) => s.id !== settingId);
- if (state.settings.length === before) throw notFound('Setting');
- await saveFile(workId, state);
- return { ok: true };
-}
-
-export async function mergeExtractedSettings(workId, extracted) {
- if (!Array.isArray(extracted)) return listSettings(workId);
- const state = await loadFile(workId);
- state.settings = mergeExtractedBible(state.settings, extracted, 'setting', { idPrefix: ID_PREFIX });
- await saveFile(workId, state);
- return state.settings;
-}
+ },
+ conflictMessage: ({ slugline, name }) => `A setting matching "${slugline || name}" already exists`,
+ notFoundLabel: 'Setting',
+ invalidIdMessage: 'Invalid setting id',
+});