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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([bible-kind-setting-rename-to-place]): rename bible SETTING kind to PLACE (#309)
[._.]/ Adam Eivye05e4227397e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 145be75d33..21890edd66 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -40,6 +40,8 @@- **Pipeline — comic page lightbox now shows the real generation prompt.** The `Image settings` panel for a rendered series comic page previously displayed `Page 1` (the bare page-index label) instead of the prompt that was actually sent to the image-gen backend. The render slot (`page.proofImage` / `page.finalImage`) always carried `prompt`, but `ComicScriptStage.buildPageItem` was reading `page.prompt` from the page root, which is never populated. Now reads from the slot, and `openPreview` matches the clicked filename against the proof/final slots so the panel surfaces the prompt that produced *this* image (proof and final can diverge when re-rendered independently). `Refine Prompt` now has something real to refine. (`client/src/components/pipeline/stages/ComicScriptStage.jsx`)+- **Bible `SETTING` kind rename to `PLACE` (Phase 0b).** Completes the deferred rename from migration 018 (PR #265): `BIBLE_KIND.SETTING` → `PLACE`, `BIBLE_FIELD[PLACE]` → `'places'`, `sanitizeSetting` → `sanitizePlace`, `matchSettingsInText` → `matchPlacesInText`, `CATEGORY_KINDS` plural `'settings'` → `'places'`, writers-room route `/works/:id/settings` → `/works/:id/places`, service file `writersRoom/settings.js` → `places.js` with `listPlaces/createPlace/updatePlace/deletePlace/mergeExtractedPlaces` exports and `wr-place-` id prefix, validation schema rename. Persisted state (`universe.settings[]` → `universe.places[]`, `series.settings[]` → `series.places[]`, per-work `settings.json` → `places.json`) migrated by `scripts/migrations/022-rename-bible-setting-to-place.js`; the migration also patches `data/prompts/stages/writers-room-places.md` + `_partials/bible-deference.md` to use `{{existingPlacesJson}}` + `"places":` when they match the OLD shipped MD5, and `setup-data.js`'s drift list now treats the post-022 hash as the new shipped baseline with the pre-022 hash auto-updatable. Client UI (`UniverseBuilder.jsx` `TRUNK_TABS`, `NounsStage`, `CanonCard`, `UniverseCanonSection`, `StoryboardPanel`, `WorkEditor`, `ProseReader`, `ProseTokenPopover`, `proseTokenizer`, `apiWritersRoom`) flips to the new vocabulary; non-goals stay untouched (`data/settings.json`, `/api/settings`, Settings page). Existing pipeline canon entry id prefix `set-` is retained — ids are opaque after creation, and changing the prefix would force a second migration over per-entry records. ~30 files, 5499 server tests + 77 client tests passing.+## Refactors- **NounsStage — drop heavy `canon-usage` fetch for a thin series-names lookup.** `NounsStage.jsx` was calling `GET /api/universe-builder/:id/canon-usage` purely to extract `seriesNameMap`, which forces the server to iterate every linked series × every issue × 3 prose matchers (O(series × issues × matchers)) just to label a CanonCard chip. New endpoint `GET /api/universe-builder/:id/series-names` returns `[{id,name}]` for linked series only — no issue scan, no matchers. Backed by `listLinkedSeriesNames` in `server/services/canonUsage.js`. `UniverseCanonSection` still uses the full `canon-usage` endpoint because it needs the per-entry usage counts. +3 vitest cases in `canonUsage.test.js`.diff --git a/DONE.md b/DONE.mdindex 49b9c01b43..747c1e151d 100644--- a/DONE.md+++ b/DONE.md@@ -10,6 +10,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-18+- **[bible-kind-setting-rename-to-place] Bible `SETTING` kind rename to `PLACE`.** Completes the rename deferred from migration 018 (PR #265, 2026-05-17): renames the bible-domain "setting" entity to "place" everywhere it's an identifier. Server: `BIBLE_KIND.SETTING` → `PLACE` (value `'place'`), `BIBLE_FIELD[PLACE]` → `'places'`, `sanitizeSetting` → `sanitizePlace`, `matchSettingsInText` → `matchPlacesInText`, `PLACE_INT_EXT`/`PLACE_TIME_OF_DAY`/`PLACE_DESCRIPTION_MAX` constants, `CATEGORY_KINDS` plural `'settings'` → `'places'`, writers-room route `/works/:id/settings` → `/works/:id/places`, service file `writersRoom/settings.js` → `places.js` with `listPlaces/createPlace/updatePlace/deletePlace/mergeExtractedPlaces` exports and `wr-place-` id prefix, validation schemas (`writersRoomPlaceCreateSchema`/`UpdateSchema`/`placeBibleCreateSchema`/`UpdateSchema`), `canonPrompt` SHORT_SPEC/RICH_SPEC keys (server + client mirror), `seriesCanon.pickCanon` returns `places`, `canonUsage` keys on `places`, importer KIND_MAP, `universeBuilder.compilePrompts` CANON_TRUNKS, `universeBuilderExpand` LLM prompt + envelope key `parsed.places`. Persisted state migrated by `scripts/migrations/022-rename-bible-setting-to-place.js`: walks `data/universe-builder.json` (renames `state.universes[].settings[]` → `places[]`, `categories[k].kind 'settings'` → `'places'`), `data/pipeline-series.json` (legacy `settings[]` → `places[]`), and `data/writers-room/works/<id>/settings.json` → `places.json` with the inner `settings` key rewritten to `places`. The migration also patches `data/prompts/stages/writers-room-places.md` + `_partials/bible-deference.md` to use `{{existingPlacesJson}}` + `"places": [` when they match the OLD shipped MD5; customized templates are left alone (the drift surfaces in `setup-data.js`'s hash-check warning, which now treats the post-022 hash as the new shipped baseline with the pre-022 hash auto-updatable alongside migration 007's pre-007 hash). Client UI flips to the new vocabulary: `UniverseBuilder.jsx` `TRUNK_TABS` `kind: 'places'`, `mergeCanonByName(..., 'place')`, `pendingCanonAdditionsRef.places`, `bucketsByKind.places`, `groupBucketsByKind` returns `{ characters, places, objects, other }`, `WORLD_CATEGORY_DEFAULT_KINDS` `landscapes/environments/structures → 'places'`. Component updates: `NounsStage.jsx` (key/singular/match), `CanonCard.jsx` (`kind.key === 'places'`), `UniverseCanonSection.jsx` (key/apiKind), `StoryboardPanel.jsx` (`places` prop, `onPlacesChange`, `onRunPlaces`, `placesCount`, `BIBLE_KINDS.world.propName: 'places'`), `WorkEditor.jsx` (`ANALYSIS_KIND.PLACES`, `places` state, `listWritersRoomPlaces`), `ProseReader.jsx` + `proseTokenizer.jsx` (`places` prop), `ProseTokenPopover.jsx` (`places` prop), `apiWritersRoom.js` (`listWritersRoomPlaces`/`createWritersRoomPlace`/`updateWritersRoomPlace`/`deleteWritersRoomPlace`), `SettingsBible.jsx` imports updated. Non-goals stay untouched: `data/settings.json`, the Settings page, `/api/settings` routes, app-level user-prefs — all keep "settings" terminology. Existing pipeline canon entry id prefix `set-` is preserved (ids are opaque after creation; changing the prefix would force a second migration over per-entry records — pure churn). All 5499 server tests pass; 77 client tests pass. ~30 files touched.- **[tabpills-pipelineissue-status-dot-trailing-slot] Extend `<TabPills>` with a `trailing` slot to migrate `PipelineIssue.jsx`.** Added an optional `t.trailing` ReactNode to the tab shape, rendered after the count in both `underline` and `pills` variants of `client/src/components/ui/TabPills.jsx`. Migrated `client/src/pages/PipelineIssue.jsx`'s previously-inlined stage tab row (the 11th outlier — its per-tab `STATUS_DOT[status]` indicator didn't fit the prior contract) onto `<TabPills>`, with the status dot supplied via `trailing`. Net 22-line bespoke `<button>` block collapsed onto the shared primitive; the row also picks up the standard mobile touch-target (`min-h-[44px]`) and icon size (16 vs 14) used elsewhere. +1 vitest case in `TabPills.test.jsx` pins the DOM-order contract (`trailing` follows `count`) in both variants; all 78 client tests pass.- **[sharing-inbox-live-subscription-badge] "🔄 live" badge on inbox subscription rows.** Subscription rows in the Sharing → Inbox tab now show a small green "live" pill (spinning RefreshCw icon + label) when `item.subscription` is truthy AND `item.receivedAt` is within the last 5 minutes. Re-exports fire on every record edit with a 3s server-side debounce and propagate via chokidar in <1s, so a row received that recently is a real-time signal that the sender is actively editing. Pure `isLiveSubscription(item, now=Date.now())` helper exported from `client/src/pages/Sharing.jsx` (handles null/undefined inputs + unparseable `receivedAt` + one-shot shares without throwing); 5 new vitest cases in `Sharing.test.jsx` cover all four exit paths. Badge placement is inline in the row's metadata strip alongside source/kind/timestamp; freshness is computed on render so the badge naturally decays when the page re-renders (via socket updates) past the 5-min mark. All 82 client tests pass.- **[nounsstage-cheaper-seriesnamemap-fetch] NounsStage seriesNameMap — avoid the heavy canon-usage fetch.** `NounsStage.jsx` was calling `GET /api/universe-builder/:id/canon-usage` purely to extract `seriesNameMap` for the CanonCard "from <series>" chip, which makes the server iterate every linked series × every issue × 3 prose matchers — O(series × issues × matchers) work for what should be O(series). Picked option (a) from the PLAN: new `GET /api/universe-builder/:id/series-names` endpoint returns `[{id,name}]` for linked series only, with no per-issue prose scan and no matchers. Backed by `listLinkedSeriesNames` in `server/services/canonUsage.js` (validates the universe via `getUniverse` so 404s mirror the heavier endpoint, then `listSeries().filter(s.universeId === id).map(s ⇒ ({id, name}))`). Client helper `getUniverseSeriesNames` in `apiUniverseBuilder.js`; `NounsStage` builds the map locally with `Object.fromEntries(list.map(...))`. `UniverseCanonSection` continues to use `canon-usage` because it actually needs the per-entry usage counts. +3 vitest cases in `canonUsage.test.js` (linked-series filter + ignores issues; empty result for no-linked universe; 404 for missing universe).diff --git a/PLAN.md b/PLAN.mdindex 98114ab591..4e4e306005 100644--- a/PLAN.md+++ b/PLAN.md@@ -26,28 +26,6 @@ _Nothing currently parked — pick the next item from the Backlog._- [x] ~~**Universe expand LLM contract enrichment.**~~ Shipped via the Universe Builder redesign Phase B — expand contract now returns rich canon arrays alongside categories.- [x] ~~**arcPlanner prompt context — include canon characters/places/objects.**~~ Shipped via the Universe Builder redesign Phase B (`renderCanonForPrompt(world)` + `worldCanonText` + migration 019 for `pipeline-arc-overview`, `pipeline-arc-verify`, `pipeline-arc-resolve`, `pipeline-volume-verify`). Follow-up still open: sweep `grep -rn "world\.categories" server/services/pipeline server/services/universeBuilder*.js` for other prompt builders that read categories but not canon.-- [ ] [bible-kind-setting-rename-to-place] **Bible `SETTING` kind rename to `PLACE`.** Rename the bible-domain "setting" entity to "place" everywhere it's an identifier (NOT app settings — `data/settings.json` and `/api/settings` are unrelated and stay). Migration 018 (2026-05-17, PR #265) already renamed the `writers-room-settings` stage-config key + prompt template file; this is the broader enum/field/route/data-shape rename it explicitly deferred.-- **Code changes (~14 files, verified via grep 2026-05-17):**- - `server/lib/storyBible.js` — `BIBLE_KIND.SETTING: 'setting'` → `PLACE: 'place'`; `BIBLE_FIELD[…SETTING]: 'settings'` → `'places'`; `PROMPT_FIELDS` key; constants `SETTING_INT_EXT`, `SETTING_TIME_OF_DAY`, `SETTING_DESCRIPTION_MAX`, `SETTING_INT_EXT_SET`, `SETTING_TIME_OF_DAY_SET` → `PLACE_*`.- - `server/lib/{bibleExtractor,sceneExtractor}.js` — prompt-variable name `existingSettingsJson` → `existingPlacesJson` (5 sites incl. 3 in `server/services/pipeline/arcPlanner.js`).- - `server/services/writersRoom/settings.js` → rename file to `places.js`; function exports `listSettings/createSetting/updateSetting/deleteSetting/mergeExtractedSettings` → `listPlaces/…/mergeExtractedPlaces`; id prefix `'wr-setting-'` → `'wr-place-'`; error labels.- - `server/services/writersRoom/{evaluator,promoteToPipeline}.js` — import sites + `BIBLE_KIND.SETTING` usages.- - `server/services/{universeBuilder,universeBuilderExpand,universeBuilderPromote,universeCanon,importer}.js` + `pipeline/{arcPlanner,visualStages}.js` — `BIBLE_KIND.SETTING` swaps; `canonSelection` key `'settings'` → `'places'`; property accesses `canon.settings`, `universe.settings`.- - `server/routes/writersRoom.js` — route `/works/:id/settings/:settingId` → `/works/:id/places/:placeId`; param + handler renames.- - `client/src/pages/UniverseBuilder.jsx` — `kind === 'setting'` checks, `mergeCanonByName(..., 'setting')` calls (4 sites), `TRUNK_TABS` kind value `'settings'` → `'places'`.- - `client/src/components/pipeline/CanonCard.jsx` — `SETTING_INT_EXT_OPTIONS` / `SETTING_TIME_OF_DAY_OPTIONS` → `PLACE_*`.- - `client/src/components/{pipeline/stages/NounsStage,universe/UniverseCanonSection}.jsx` — `key: 'settings'` / `apiKind: 'setting'` shape.- - All `*.test.js` for the above (`storyBible.test.js`, `bibleExtractor.test.js`, `writersRoom.test.js`, `settings.test.js`, etc. — ~6 test files with fixture ids `'wr-setting-1'`, kind enums, expected error messages).-- **Migration NNN-rename-bible-setting-to-place.js (required — touches persisted state):**- - Walk every `data/universes/*.json`, `data/series/*.json`, and any writers-room work record. For each: rename the `settings: [...]` array key → `places: [...]`, and rewrite each entry's `kind: 'setting'` → `kind: 'place'`. Idempotent guard: skip if `places` is already present.- - Coordinate with migration 018: 018 already renamed the stage-config KEY (`writers-room-settings` → `writers-room-places`) but did NOT touch `BIBLE_KIND.SETTING` values in canon entries; this migration is purely the record-internal rename. No conflict, but they must run in order (018 → NNN).- - The `existingSettingsJson` → `existingPlacesJson` prompt-variable rename also requires updating prompt template files `data.sample/prompts/stages/writers-room-places.md` and `data.sample/prompts/_partials/bible-deference.md` (currently reference `{{existingSettingsJson}}`). Stage-prompt migration pattern (see `scripts/migrations/003-…`) with `OLD_SHIPPED_MD5` / `NEW_SHIPPED_MD5` so user-customized templates aren't clobbered.-- **Non-goals / out of scope:** `data/settings.json`, the Settings page, the `/api/settings` routes, app-level user-prefs — all stay as "settings".-- **Why now:** with the 3-canon-trunks architecture (Cast / Places / Objects) fully shipped (see the Universe Builder redesign in DONE.md, 2026-05-17), the user-facing terminology is "Places" everywhere except inside the bible code. This finishes that alignment so a future contributor doesn't have to mentally translate `setting ↔ place`.- [ ] [use-rendered-reference-images-as-i2i-anchors-in] **Use rendered reference images as i2i anchors in downstream comic-page renders for models that support it.** SDXL/Flux pipelines anchor every panel render on the per-character rendered ref.diff --git a/client/src/components/pipeline/ArcCanvas.jsx b/client/src/components/pipeline/ArcCanvas.jsxindex 6e4e813502..edd38c2a86 100644--- a/client/src/components/pipeline/ArcCanvas.jsx+++ b/client/src/components/pipeline/ArcCanvas.jsx@@ -864,7 +864,7 @@ function SeasonRow({ series, season, seasons, issues, onSeriesUpdate, onIssuesUpconst n = result.createdIssues?.length || 0;const extracted = result.bibleExtracted;const extractedSummary = extracted- ? ` (+${extracted.characters} chars, +${extracted.settings} settings, +${extracted.objects} objects extracted)`+ ? ` (+${extracted.characters} chars, +${extracted.places} places, +${extracted.objects} objects extracted)`: '';toast.success(`Generated ${n} issue${n === 1 ? '' : 's'} / episode${n === 1 ? '' : 's'}${extractedSummary}`);};diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex e912b795c8..90d871c0d9 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -16,8 +16,8 @@ import useMediaJobProgress from '../../hooks/useMediaJobProgress';import MediaJobThumb from './MediaJobThumb';import EntryCard from '../universe/EntryCard';-// Setting metadata enums — kept in lock-step with `SETTING_INT_EXT` and-// `SETTING_TIME_OF_DAY` in `server/lib/storyBible.js`. Mirror is fine: a+// Place metadata enums — kept in lock-step with `PLACE_INT_EXT` and+// `PLACE_TIME_OF_DAY` in `server/lib/storyBible.js`. Mirror is fine: a// drift would surface immediately as a Zod 400 on the next save.const INT_EXT_OPTIONS = ['INT', 'EXT'];const TIME_OF_DAY_OPTIONS = ['dawn', 'day', 'dusk', 'night'];@@ -321,7 +321,7 @@ export default function CanonCard({<p className="text-xs text-gray-400 mt-1 line-clamp-3 whitespace-pre-wrap">{description || <em className="text-gray-600">No description yet.</em>}</p>- {kind.key === 'settings' && onPatchEntry && !locked ? (+ {kind.key === 'places' && onPatchEntry && !locked ? (<div className="flex flex-wrap items-center gap-2 mt-2"><ChipPickerlabel="INT/EXT"@@ -336,7 +336,7 @@ export default function CanonCard({onChange={(v) => onPatchEntry(entry.id, { timeOfDay: v })}/></div>- ) : kind.key === 'settings' && (entry.intExt || entry.timeOfDay) ? (+ ) : kind.key === 'places' && (entry.intExt || entry.timeOfDay) ? (<div className="flex flex-wrap items-center gap-1 mt-2">{entry.intExt ? <ReadonlyChip>{entry.intExt}</ReadonlyChip> : null}{entry.timeOfDay ? <ReadonlyChip>{entry.timeOfDay}</ReadonlyChip> : null}@@ -394,7 +394,7 @@ export default function CanonCard({{inFlightJobId ? <Loader2 size={10} className="animate-spin" /> : <ImagePlus size={10} />}Render reference</button>- {kind.key === 'settings' && onRenderCleanPlate ? (+ {kind.key === 'places' && onRenderCleanPlate ? (<buttontype="button"onClick={() => onRenderCleanPlate(entry)}diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex c47992284b..dd81acb245 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -27,7 +27,7 @@ import {import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';import { listImageModels } from '../../../services/apiImageVideo';import {- matchCharactersInText, matchSettingsInText, matchObjectsInText,+ matchCharactersInText, matchPlacesInText, matchObjectsInText,} from '../../../lib/scenePrompt';import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';@@ -54,13 +54,13 @@ const KINDS = [match: matchCharactersInText,},{- key: 'settings', label: 'Settings', singular: 'setting', icon: MapPin,- descFor: (s) => [- s.description,- s.palette ? `Palette: ${s.palette}` : '',- s.recurringDetails,+ key: 'places', label: 'Places', singular: 'place', icon: MapPin,+ descFor: (p) => [+ p.description,+ p.palette ? `Palette: ${p.palette}` : '',+ p.recurringDetails,].filter(Boolean).join('. '),- match: matchSettingsInText,+ match: matchPlacesInText,},{key: 'objects', label: 'Objects', singular: 'object', icon: Package,diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex 722586740d..3277acd15a 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -42,8 +42,8 @@ const KINDS = [descFor: (c) => descriptorForCanonEntry('characters', c),},{- key: 'settings', apiKind: 'setting', label: 'Places', singular: 'place', icon: MapPin,- descFor: (s) => descriptorForCanonEntry('settings', s),+ key: 'places', apiKind: 'place', label: 'Places', singular: 'place', icon: MapPin,+ descFor: (p) => descriptorForCanonEntry('places', p),},{key: 'objects', apiKind: 'object', label: 'Objects', singular: 'object', icon: Package,@@ -273,7 +273,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseCconst handleRenderCleanPlate = async (entry) => {// Match CanonCard's button-enable predicate (descFor includes palette +- // recurringDetails for settings) — composeCleanPlatePrompt builds a valid+ // recurringDetails for places) — composeCleanPlatePrompt builds a valid// prompt from any of {description, palette, recurringDetails}, so gating// on `description` alone produces a button that fails with this toast// even though the composer would have succeeded.@@ -361,7 +361,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC</h2><p className="text-xs text-gray-500 mt-0.5">{kindFilter === 'characters' && 'Recurring people in this universe. Series share the same canon — issues reference these entries so a character renders consistently across crossovers.'}- {kindFilter === 'settings' && 'Recurring places in this universe. Series share the same canon — slugline-anchored entries can be referenced across issues.'}+ {kindFilter === 'places' && 'Recurring places in this universe. Series share the same canon — slugline-anchored entries can be referenced across issues.'}{kindFilter === 'objects' && 'Recurring objects/items in this universe. Series share the same canon — issues reference these entries for visual continuity.'}{!kindFilter && 'People, places, and things that exist in this universe. Series in this universe share the same canon — episodes/issues reference these entries so a character renders consistently across crossovers.'}</p>@@ -392,7 +392,7 @@ export default function UniverseCanonSection({ universe, universeId, onUniverseC<Library size={12} /> Extract from prose</button>{/* "AI: differentiate cast" is a character-only operation. When the- parent passes `kindFilter` to scope this section to settings or+ parent passes `kindFilter` to scope this section to places orobjects, hide the action so it doesn't look applicable to thecurrent trunk. Keep it visible on the all-kinds view + on thecharacters-filtered view. */}diff --git a/client/src/components/writers-room/ObjectsBible.jsx b/client/src/components/writers-room/ObjectsBible.jsxindex 60d6def59a..3c47ad5b12 100644--- a/client/src/components/writers-room/ObjectsBible.jsx+++ b/client/src/components/writers-room/ObjectsBible.jsx@@ -15,7 +15,7 @@ const OBJECT_FIELDS = [{ key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },];-// Editable recurring-objects bible. Mirrors CharactersBible / SettingsBible.+// Editable recurring-objects bible. Mirrors CharactersBible / PlacesBible.// Distinct from analysis snapshots — this is the canonical roster that// survives across `objects` analysis runs and accepts hand-edits.export default function ObjectsBible({ workId, objects: objectsProp, onObjectsChange, readingTheme = 'dark', hotRefId = null }) {diff --git a/client/src/components/writers-room/SettingsBible.jsx b/client/src/components/writers-room/PlacesBible.jsxsimilarity index 75%rename from client/src/components/writers-room/SettingsBible.jsxrename to client/src/components/writers-room/PlacesBible.jsxindex 45f8e73b71..d5607fef01 100644--- a/client/src/components/writers-room/SettingsBible.jsx+++ b/client/src/components/writers-room/PlacesBible.jsx@@ -2,14 +2,14 @@ import { useEffect, useState } from 'react';import { AlertTriangle, Check, Loader2, MapPin, Pencil, Plus, Trash2, X } from 'lucide-react';import toast from '../ui/Toast';import {- listWritersRoomSettings,- createWritersRoomSetting,- updateWritersRoomSetting,- deleteWritersRoomSetting,+ listWritersRoomPlaces,+ createWritersRoomPlace,+ updateWritersRoomPlace,+ deleteWritersRoomPlace,} from '../../services/apiWritersRoom';import useMounted from '../../hooks/useMounted';-const SETTING_FIELDS = [+const PLACE_FIELDS = [{ key: 'description', label: 'Description', placeholder: 'Architecture, scale, materials, lighting sources, recurring set-dressing. Used directly in image-gen prompts.', kind: 'multiline', rows: 3 },{ key: 'palette', label: 'Palette', placeholder: 'Comma-separated dominant colors / lighting cues', kind: 'text' },{ key: 'era', label: 'Era', placeholder: 'near-future, 1950s noir, present day…', kind: 'text' },@@ -18,29 +18,29 @@ const SETTING_FIELDS = [{ key: 'notes', label: 'Notes', placeholder: 'Anything else worth tracking', kind: 'multiline', rows: 2 },];-// Editable setting/world bible — persistent across analysis runs and consumed+// Editable places/world bible — persistent across analysis runs and consumed// by image gen to inject location descriptions into per-scene prompts.//-// Controlled vs. uncontrolled: caller may pass `settings` to keep multiple+// Controlled vs. uncontrolled: caller may pass `places` to keep multiple// mounts in sync (e.g. drawer + storyboard chip count). When omitted we fetch// and own the list so this can stand alone.-export default function SettingsBible({ workId, settings: settingsProp, onSettingsChange, readingTheme = 'dark', hotRefId = null }) {- const [internalSettings, setInternalSettings] = useState(settingsProp || []);- const settings = settingsProp ?? internalSettings;+export default function PlacesBible({ workId, places: placesProp, onPlacesChange, readingTheme = 'dark', hotRefId = null }) {+ const [internalPlaces, setInternalPlaces] = useState(placesProp || []);+ const places = placesProp ?? internalPlaces;const [editingId, setEditingId] = useState(null);const [creating, setCreating] = useState(false);const [loading, setLoading] = useState(false);const mountedRef = useMounted();useEffect(() => {- if (settingsProp) return;+ if (placesProp) return;if (!workId) return;setLoading(true);- listWritersRoomSettings(workId)- .then((list) => { if (mountedRef.current) setInternalSettings(list); })- .catch(() => { if (mountedRef.current) setInternalSettings([]); })+ listWritersRoomPlaces(workId)+ .then((list) => { if (mountedRef.current) setInternalPlaces(list); })+ .catch(() => { if (mountedRef.current) setInternalPlaces([]); }).finally(() => { if (mountedRef.current) setLoading(false); });- }, [workId, settingsProp, mountedRef]);+ }, [workId, placesProp, mountedRef]);const upsert = (next) => {const update = (prev) => {@@ -51,21 +51,21 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettincopy[idx] = next;return sorted(copy);};- setInternalSettings(update);- onSettingsChange?.(update(settings));+ setInternalPlaces(update);+ onPlacesChange?.(update(places));};const removeOne = (id) => {- const next = settings.filter((s) => s.id !== id);- setInternalSettings(next);- onSettingsChange?.(next);+ const next = places.filter((s) => s.id !== id);+ setInternalPlaces(next);+ onPlacesChange?.(next);};return (<div className="text-xs"><div className="flex items-center justify-between mb-2"><div className="text-[11px] text-gray-500">- {settings.length} location{settings.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.+ {places.length} location{places.length === 1 ? '' : 's'} · Edits persist across re-runs and feed image gen.</div><buttononClick={() => { setCreating(true); setEditingId(null); }}@@ -75,34 +75,34 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettin</button></div>- {loading && settings.length === 0 && (+ {loading && places.length === 0 && (<div className="text-gray-500 italic">Loading…</div>)}- {!loading && settings.length === 0 && !creating && (+ {!loading && places.length === 0 && !creating && (<div className="text-gray-500 italic px-1 mb-2">No locations yet. Click "Refresh from prose" above to extract them, or add one manually.</div>)}{creating && (- <SettingEditor+ <PlaceEditorworkId={workId}- setting={null}+ place={null}onSaved={(s) => { upsert(s); setCreating(false); }}onCancel={() => setCreating(false)}/>)}<ul className="space-y-1.5">- {settings.map((s) => {+ {places.map((s) => {const isEditing = editingId === s.id;if (isEditing) {return (<li key={s.id}>- <SettingEditor+ <PlaceEditorworkId={workId}- setting={s}+ place={s}onSaved={(updated) => { upsert(updated); setEditingId(null); }}onDeleted={() => { removeOne(s.id); setEditingId(null); }}onCancel={() => setEditingId(null)}@@ -120,7 +120,7 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettin: 'border-port-border'}`}>- <SettingRow setting={s} onEdit={() => setEditingId(s.id)} readingTheme={readingTheme} />+ <PlaceRow place={s} onEdit={() => setEditingId(s.id)} readingTheme={readingTheme} /></li>);})}@@ -129,11 +129,11 @@ export default function SettingsBible({ workId, settings: settingsProp, onSettin);}-function SettingRow({ setting, onEdit, readingTheme }) {+function PlaceRow({ place, onEdit, readingTheme }) {const light = readingTheme === 'light';- const blanks = SETTING_FIELDS.filter((f) => {+ const blanks = PLACE_FIELDS.filter((f) => {if (f.key === 'notes') return false;- return !String(setting[f.key] || '').trim();+ return !String(place[f.key] || '').trim();});return (<div className="px-3 py-2">@@ -141,36 +141,36 @@ function SettingRow({ setting, onEdit, readingTheme }) {<div className="flex-1 min-w-0"><div className="flex items-center gap-2 flex-wrap"><MapPin size={11} className="text-port-accent shrink-0" />- {setting.slugline ? (- <span className={`font-mono text-[11px] uppercase ${light ? 'text-gray-900' : 'text-white'}`}>{setting.slugline}</span>+ {place.slugline ? (+ <span className={`font-mono text-[11px] uppercase ${light ? 'text-gray-900' : 'text-white'}`}>{place.slugline}</span>) : (- <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{setting.name}</span>+ <span className={`font-semibold ${light ? 'text-gray-900' : 'text-white'}`}>{place.name}</span>)}- {setting.slugline && setting.name && setting.name !== setting.slugline && (- <span className="text-[10px] text-gray-500 truncate">aka {setting.name}</span>+ {place.slugline && place.name && place.name !== place.slugline && (+ <span className="text-[10px] text-gray-500 truncate">aka {place.name}</span>)}- {setting.era && (- <span className="text-[9px] uppercase tracking-wider text-port-accent">{setting.era}</span>+ {place.era && (+ <span className="text-[9px] uppercase tracking-wider text-port-accent">{place.era}</span>)}- {setting.source === 'ai' && (+ {place.source === 'ai' && (<span className="text-[9px] text-gray-500" title="Created by AI extraction — edit to mark as user-curated">ai</span>)}</div>- {setting.description ? (+ {place.description ? (<div className={`text-[11px] mt-0.5 ${light ? 'text-gray-700' : 'text-gray-400'}`}>- {setting.description}+ {place.description}</div>) : (<div className="text-[11px] mt-0.5 text-port-warning italic">No description — image gen will use the scene's visualPrompt only</div>)}- {setting.palette && (+ {place.palette && (<div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Palette:</span> {setting.palette}+ <span className="uppercase tracking-wider text-[9px]">Palette:</span> {place.palette}</div>)}- {setting.recurringDetails && (+ {place.recurringDetails && (<div className="text-[10px] text-gray-500 mt-0.5">- <span className="uppercase tracking-wider text-[9px]">Anchors:</span> {setting.recurringDetails}+ <span className="uppercase tracking-wider text-[9px]">Anchors:</span> {place.recurringDetails}</div>)}{blanks.length > 0 && (@@ -178,17 +178,17 @@ function SettingRow({ setting, onEdit, readingTheme }) {<AlertTriangle size={9} /> Missing: {blanks.map((f) => f.label.toLowerCase()).join(', ')}</div>)}- {setting.missingFromProse?.length > 0 && (+ {place.missingFromProse?.length > 0 && (<div className="text-[10px] text-gray-500 mt-1">- <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {setting.missingFromProse.join(', ')}+ <span className="uppercase tracking-wider text-[9px]">Prose gaps:</span> {place.missingFromProse.join(', ')}</div>)}</div><buttononClick={onEdit}className="text-gray-500 hover:text-port-accent shrink-0"- title="Edit setting"- aria-label={`Edit ${setting.slugline || setting.name}`}+ title="Edit place"+ aria-label={`Edit ${place.slugline || place.name}`}><Pencil size={11} /></button>@@ -197,15 +197,15 @@ function SettingRow({ setting, onEdit, readingTheme }) {);}-function SettingEditor({ workId, setting, onSaved, onDeleted, onCancel }) {- const isCreate = !setting;+function PlaceEditor({ workId, place, onSaved, onDeleted, onCancel }) {+ const isCreate = !place;const [draft, setDraft] = useState(() => {const seed = {- slugline: setting?.slugline || '',- name: setting?.name || '',+ slugline: place?.slugline || '',+ name: place?.name || '',};- for (const f of SETTING_FIELDS) {- seed[f.key] = setting?.[f.key] || '';+ for (const f of PLACE_FIELDS) {+ seed[f.key] = place?.[f.key] || '';}return seed;});@@ -223,12 +223,12 @@ function SettingEditor({ workId, setting, onSaved, onDeleted, onCancel }) {slugline: draft.slugline.trim(),name: draft.name.trim(),};- for (const f of SETTING_FIELDS) {+ for (const f of PLACE_FIELDS) {payload[f.key] = draft[f.key];}const result = await (isCreate- ? createWritersRoomSetting(workId, payload)- : updateWritersRoomSetting(workId, setting.id, payload)+ ? createWritersRoomPlace(workId, payload)+ : updateWritersRoomPlace(workId, place.id, payload)).catch((err) => {toast.error(`Save failed: ${err.message}`);return null;@@ -240,15 +240,15 @@ function SettingEditor({ workId, setting, onSaved, onDeleted, onCancel }) {};const remove = async () => {- if (!setting) return;+ if (!place) return;setSaving(true);- const ok = await deleteWritersRoomSetting(workId, setting.id).then(() => true).catch((err) => {+ const ok = await deleteWritersRoomPlace(workId, place.id).then(() => true).catch((err) => {toast.error(`Delete failed: ${err.message}`);return false;});setSaving(false);if (ok) {- toast.success(`${setting.slugline || setting.name} removed`);+ toast.success(`${place.slugline || place.name} removed`);onDeleted?.();}};@@ -277,7 +277,7 @@ function SettingEditor({ workId, setting, onSaved, onDeleted, onCancel }) {<span className="text-[9px] uppercase tracking-wider text-gray-500">Name (optional, human-readable)</span><input value={draft.name} onChange={set('name')} placeholder="The Kitchen, Curry O'City…" className={inputCls} /></label>- {SETTING_FIELDS.map((f) => (+ {PLACE_FIELDS.map((f) => (<label key={f.key} className="block"><span className="text-[9px] uppercase tracking-wider text-gray-500">{f.label}</span>{f.kind === 'multiline' ? (diff --git a/client/src/components/writers-room/ProseReader.jsx b/client/src/components/writers-room/ProseReader.jsxindex d3e1f072cf..04fa0533b5 100644--- a/client/src/components/writers-room/ProseReader.jsx+++ b/client/src/components/writers-room/ProseReader.jsx@@ -67,7 +67,7 @@ export default function ProseReader({body,scenes = [],characters = [],- settings = [],+ places = [],objects = [],readingTheme = 'dark',activeSceneId = null,@@ -88,7 +88,7 @@ export default function ProseReader({// change instead of rebuilding per paragraph. ProseReader passes the// pre-built `entries` to renderTokenized so each paragraph only pays the// O(text × entries) scan cost, not the index-build cost.- const entries = useTokenEntries({ characters, settings, objects });+ const entries = useTokenEntries({ characters, places, objects });const light = readingTheme === 'light';diff --git a/client/src/components/writers-room/ProseTokenPopover.jsx b/client/src/components/writers-room/ProseTokenPopover.jsxindex 03d9b64cd2..3d1abbbb1b 100644--- a/client/src/components/writers-room/ProseTokenPopover.jsx+++ b/client/src/components/writers-room/ProseTokenPopover.jsx@@ -7,7 +7,7 @@ import { ExternalLink, X } from 'lucide-react';// re-reads getBoundingClientRect on every reflow (scroll, resize, content// height change) so the card stays attached to the token rather than// freezing at the rect captured on hover. We resolve refId against the-// characters/settings/objects lists prop'd in.+// characters/places/objects lists prop'd in.//// Hover semantics: 200ms open delay, 150ms close grace handled by the parent// (WorkEditor) — this component just renders or doesn't.@@ -40,9 +40,9 @@ function clampToViewport(rect, measuredHeight) {return { left, top, width: w };}-function resolveProfile({ kind, refId, characters, settings, objects }) {+function resolveProfile({ kind, refId, characters, places, objects }) {if (kind === 'char') return characters.find((c) => c.id === refId) || null;- if (kind === 'place') return settings.find((s) => s.id === refId) || null;+ if (kind === 'place') return places.find((p) => p.id === refId) || null;if (kind === 'object') return objects.find((o) => o.id === refId) || null;return null;}@@ -93,7 +93,7 @@ export default function ProseTokenPopover({kind,refId,characters = [],- settings = [],+ places = [],objects = [],onOpenProfile,onClose,@@ -175,7 +175,7 @@ export default function ProseTokenPopover({if (!open || !pos) return null;- const profile = resolveProfile({ kind, refId, characters, settings, objects });+ const profile = resolveProfile({ kind, refId, characters, places, objects });if (!profile) return null;const rows = fieldRows(kind, profile);diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsxindex bc3d8bc618..cc3cffb6d9 100644--- a/client/src/components/writers-room/SceneCard.jsx+++ b/client/src/components/writers-room/SceneCard.jsx@@ -19,7 +19,7 @@ import { WR_IMAGE_DEFAULTS } from '../../lib/wrImageDefaults';import {buildScenePrompt,matchSceneCharacters,- matchSceneSetting,+ matchScenePlace,normCharKey,} from '../../lib/scenePrompt';@@ -34,7 +34,7 @@ const SceneCard = forwardRef(function SceneCard({initialImage = null,readingTheme = 'dark',charByKey = null,- settingByKey = null,+ placeByKey = null,isActive = false,onJumpToProse = null,onDebug = null,@@ -48,9 +48,9 @@ const SceneCard = forwardRef(function SceneCard({() => matchSceneCharacters(scene.characters, charByKey),[scene.characters, charByKey]);- const matchedSetting = useMemo(- () => matchSceneSetting(scene.slugline, settingByKey),- [scene.slugline, settingByKey]+ const matchedPlace = useMemo(+ () => matchScenePlace(scene.slugline, placeByKey),+ [scene.slugline, placeByKey]);// Per-chip lookup map — name/alias keys → matched character profile. Built// once so the chip render is O(1) per chip instead of an O(chars × aliases)@@ -158,7 +158,7 @@ const SceneCard = forwardRef(function SceneCard({setError(null);setProgress(null);setGenerated(null);- const prompt = buildScenePrompt(workTitle, scene, matchedCharacters, imageStyle?.prompt || '', matchedSetting);+ const prompt = buildScenePrompt(workTitle, scene, matchedCharacters, imageStyle?.prompt || '', matchedPlace);const stepsNum = imageCfg.steps ? Number(imageCfg.steps) : undefined;const seedNum = imageCfg.seed && Number(imageCfg.seed) >= 0 ? Number(imageCfg.seed) : undefined;const res = await generateImage({@@ -265,7 +265,7 @@ const SceneCard = forwardRef(function SceneCard({{scene.slugline && (<divclassName={`text-[10px] uppercase tracking-wide truncate transition-all ${- hotPlaceId && matchedSetting?.id === hotPlaceId+ hotPlaceId && matchedPlace?.id === hotPlaceId? 'text-white bg-port-accent/30 ring-1 ring-port-accent rounded px-1 -mx-1': 'text-port-accent'}`}diff --git a/client/src/components/writers-room/StoryboardPanel.jsx b/client/src/components/writers-room/StoryboardPanel.jsxindex 49572647a9..b9787fe5cd 100644--- a/client/src/components/writers-room/StoryboardPanel.jsx+++ b/client/src/components/writers-room/StoryboardPanel.jsx@@ -23,10 +23,10 @@ import { ImageGenTab } from '../settings/ImageGenTab';import SceneCard from './SceneCard';import StagePromptModelPicker from './StagePromptModelPicker';import CharactersBible from './CharactersBible';-import SettingsBible from './SettingsBible';+import PlacesBible from './PlacesBible';import ObjectsBible from './ObjectsBible';import { WR_IMAGE_DEFAULTS, readWrImageSettings, STYLE_ID, EMPTY_IMAGE_STYLE } from '../../lib/wrImageDefaults';-import { buildCharByKey, buildSettingByKey } from '../../lib/scenePrompt';+import { buildCharByKey, buildPlaceByKey } from '../../lib/scenePrompt';const SCRIPT_STAGE = 'writers-room-script';@@ -53,7 +53,7 @@ export const STORYBOARD_TAB_VALUES = Object.values(TAB);const RUN_LABEL = {characters: 'Refreshing characters',- settings: 'Refreshing world',+ places: 'Refreshing world',objects: 'Refreshing objects',script: 'Running Adapt',evaluate: 'Editorial pass',@@ -63,12 +63,12 @@ const RUN_LABEL = {export default function StoryboardPanel({work,characters = [],- settings = [],+ places = [],onJumpToScene,onDebug,onRunAdapt,onRunCharacters,- onRunSettings,+ onRunPlaces,onRunFullPipeline,runningAdapt = false,runningKind = null,@@ -76,7 +76,7 @@ export default function StoryboardPanel({activeSceneId = null,onStyleChange,onCharactersChange,- onSettingsChange,+ onPlacesChange,onScenesChange,objects = [],onObjectsChange,@@ -249,7 +249,7 @@ export default function StoryboardPanel({}, []);const charByKey = useMemo(() => buildCharByKey(characters), [characters]);- const settingByKey = useMemo(() => buildSettingByKey(settings), [settings]);+ const placeByKey = useMemo(() => buildPlaceByKey(places), [places]);const scenesCount = useMemo(() => (activeDraft?.segmentIndex || []).filter((s) => s.kind === 'scene').length,[activeDraft?.segmentIndex]@@ -279,7 +279,7 @@ export default function StoryboardPanel({runningKind={runningKind}tabs={[{ id: TAB.CHARACTERS, label: 'Characters', icon: Users, count: characters.length, runningKind: 'characters' },- { id: TAB.WORLD, label: 'World', icon: MapPinIcon, count: settings.length, runningKind: 'settings' },+ { id: TAB.WORLD, label: 'World', icon: MapPinIcon, count: places.length, runningKind: 'places' },{ id: TAB.OBJECTS, label: 'Objects', icon: Package, count: objects.length, runningKind: 'objects' },{ id: TAB.SCENES, label: 'Scenes', icon: ListTree, count: scenesCount },{ id: TAB.BOARDS, label: 'Boards', icon: Clapperboard, count: scenes.length, runningKind: 'script' },@@ -312,10 +312,10 @@ export default function StoryboardPanel({<BibleTabkind="world"workId={work.id}- items={settings}- onItemsChange={onSettingsChange}- onRefresh={onRunSettings}- running={runningKind === 'settings'}+ items={places}+ onItemsChange={onPlacesChange}+ onRefresh={onRunPlaces}+ running={runningKind === 'places'}anyRunning={!!runningKind}readingTheme={readingTheme}hotRefId={hotRef?.kind === 'place' ? hotRef.refId : null}@@ -350,15 +350,15 @@ export default function StoryboardPanel({imageStyle={imageStyle}stylePresets={stylePresets}charByKey={charByKey}- settingByKey={settingByKey}+ placeByKey={placeByKey}charactersCount={characters.length}- settingsCount={settings.length}+ placesCount={places.length}sceneRefs={sceneRefs}onJumpToScene={onJumpToScene}onDebug={onDebug}onRunAdapt={onRunAdapt}onRunCharacters={onRunCharacters}- onRunSettings={onRunSettings}+ onRunPlaces={onRunPlaces}onRunFullPipeline={onRunFullPipeline}runningAdapt={runningAdapt}runningKind={runningKind}@@ -401,12 +401,12 @@ const BIBLE_KINDS = {changeProp: 'onCharactersChange',},world: {- label: 'World / setting bible',+ label: 'World / places bible',sub: 'Locations keyed by slugline · feeds image-gen prompts',refreshNoun: 'world',- Component: SettingsBible,- propName: 'settings',- changeProp: 'onSettingsChange',+ Component: PlacesBible,+ propName: 'places',+ changeProp: 'onPlacesChange',},objects: {label: 'Recurring objects',@@ -517,15 +517,15 @@ function BoardsTab({imageStyle,stylePresets,charByKey,- settingByKey,+ placeByKey,charactersCount,- settingsCount,+ placesCount,sceneRefs,onJumpToScene,onDebug,onRunAdapt,onRunCharacters,- onRunSettings,+ onRunPlaces,onRunFullPipeline,runningAdapt,runningKind,@@ -575,9 +575,9 @@ function BoardsTab({{!loading && !latestScript && !latestFailure && (<StoryboardSetupcharactersCount={charactersCount}- settingsCount={settingsCount}+ placesCount={placesCount}onRunCharacters={onRunCharacters}- onRunSettings={onRunSettings}+ onRunPlaces={onRunPlaces}onRunAdapt={onRunAdapt}onRunFullPipeline={onRunFullPipeline}runningKind={runningKind}@@ -588,12 +588,12 @@ function BoardsTab({<StaleBanner onRunAdapt={onRunAdapt} runningAdapt={runningAdapt} />)}- {!loading && latestScript && !isStale && !latestFailure && (charactersCount === 0 || settingsCount === 0) && (+ {!loading && latestScript && !isStale && !latestFailure && (charactersCount === 0 || placesCount === 0) && (<BiblesMissingNoticecharactersMissing={charactersCount === 0}- settingsMissing={settingsCount === 0}+ placesMissing={placesCount === 0}onRunCharacters={onRunCharacters}- onRunSettings={onRunSettings}+ onRunPlaces={onRunPlaces}runningKind={runningKind}/>)}@@ -623,7 +623,7 @@ function BoardsTab({initialImage={sceneImages[sceneId] || null}readingTheme={readingTheme}charByKey={charByKey}- settingByKey={settingByKey}+ placeByKey={placeByKey}isActive={sceneId === activeSceneId}onJumpToProse={onJumpToScene ? () => onJumpToScene(scene, i, scenes.length) : null}onDebug={onDebug}@@ -685,20 +685,20 @@ function ConfigTab({ imageCfg, models, availableBackends, onCfgChange, stylePres// click "Run all in order" to fire the sequential pipeline.function StoryboardSetup({charactersCount,- settingsCount,+ placesCount,onRunCharacters,- onRunSettings,+ onRunPlaces,onRunAdapt,onRunFullPipeline,runningKind,}) {const isRunning = !!runningKind;const charDone = charactersCount > 0;- const setDone = settingsCount > 0;+ const setDone = placesCount > 0;const Step = ({ n, kind, done, label, sublabel, hint, onClick, primary = false }) => {const running = runningKind === kind;- const Icon = done ? Check : kind === 'characters' ? Users : kind === 'settings' ? MapPinIcon : Clapperboard;+ const Icon = done ? Check : kind === 'characters' ? Users : kind === 'places' ? MapPinIcon : Clapperboard;return (<div className={`flex items-start gap-2.5 p-2.5 border rounded ${done ? 'border-port-success/40 bg-port-success/5' :@@ -761,12 +761,12 @@ function StoryboardSetup({/><Stepn={2}- kind="settings"+ kind="places"done={setDone}- label="Extract settings / world"- sublabel={`${settingsCount} location${settingsCount === 1 ? '' : 's'}`}+ label="Extract places / world"+ sublabel={`${placesCount} location${placesCount === 1 ? '' : 's'}`}hint="Locations keyed by slugline (description, palette, era, recurring details)"- onClick={onRunSettings}+ onClick={onRunPlaces}/><Stepn={3}@@ -848,11 +848,11 @@ function FailedAdaptBanner({ failure, onRunAdapt, runningAdapt, onOpenConfig, ha// the user gets visual drift across scenes. Inline run buttons let them// fix it without leaving the panel; re-running Adapt afterwards picks up// the populated bibles.-function BiblesMissingNotice({ charactersMissing, settingsMissing, onRunCharacters, onRunSettings, runningKind }) {+function BiblesMissingNotice({ charactersMissing, placesMissing, onRunCharacters, onRunPlaces, runningKind }) {const isRunning = !!runningKind;const missing = [charactersMissing && 'character bible',- settingsMissing && 'setting bible',+ placesMissing && 'places bible',].filter(Boolean);return (<div className="flex items-start gap-2 p-2 mb-1 border border-port-warning/40 bg-port-warning/5 rounded text-[11px]">@@ -875,14 +875,14 @@ function BiblesMissingNotice({ charactersMissing, settingsMissing, onRunCharacteExtract characters</button>)}- {settingsMissing && (+ {placesMissing && (<button- onClick={onRunSettings}- disabled={isRunning || !onRunSettings}+ onClick={onRunPlaces}+ disabled={isRunning || !onRunPlaces}className="flex items-center gap-1 px-2 py-1 border border-port-border text-gray-300 rounded text-[10px] hover:bg-port-border/40 disabled:opacity-50">- {runningKind === 'settings' ? <Loader2 size={10} className="animate-spin" /> : <MapPinIcon size={10} />}- Extract settings+ {runningKind === 'places' ? <Loader2 size={10} className="animate-spin" /> : <MapPinIcon size={10} />}+ Extract places</button>)}</div>diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 0af64dc190..040eb0fad3 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -33,7 +33,7 @@ import {updateWritersRoomWork,runWritersRoomAnalysis,listWritersRoomCharacters,- listWritersRoomSettings,+ listWritersRoomPlaces,listWritersRoomObjects,promoteWritersRoomWorkToPipeline,} from '../../services/apiWritersRoom';@@ -46,14 +46,14 @@ import ProseTokenPopover from './ProseTokenPopover';import WritersRoomDock from './WritersRoomDock';import useImageGenQueue from '../../hooks/useImageGenQueue';-const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', SETTINGS: 'settings', OBJECTS: 'objects', EVALUATE: 'evaluate', FORMAT: 'format' };+const ANALYSIS_KIND = { SCRIPT: 'script', CHARACTERS: 'characters', PLACES: 'places', OBJECTS: 'objects', EVALUATE: 'evaluate', FORMAT: 'format' };const DRAWER = { VERSIONS: 'versions', HISTORY: 'history' };const MOBILE_TAB = { WRITING: 'writing', STORYBOARD: 'storyboard' };const ANALYSIS_LABELS = {[ANALYSIS_KIND.SCRIPT]: 'Adapt',[ANALYSIS_KIND.CHARACTERS]: 'Characters',- [ANALYSIS_KIND.SETTINGS]: 'Settings',+ [ANALYSIS_KIND.PLACES]: 'Places',[ANALYSIS_KIND.OBJECTS]: 'Objects',[ANALYSIS_KIND.EVALUATE]: 'Editorial pass',[ANALYSIS_KIND.FORMAT]: 'Format pass',@@ -100,7 +100,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOconst [saving, setSaving] = useState(false);const [readingTheme, setReadingTheme] = useState(readReadingTheme);const [characters, setCharacters] = useState([]);- const [settings, setSettings] = useState([]);+ const [places, setPlaces] = useState([]);const [objects, setObjects] = useState([]);const [runningKind, setRunningKind] = useState(null);const [drawer, setDrawer] = useState(null);@@ -314,17 +314,17 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOuseEffect(() => { setStatus(work.status); }, [work.status]);useEffect(() => { setTitle(work.title); }, [work.title]);- // The CharactersBible / SettingsBible drawers are the canonical editors;+ // The CharactersBible / PlacesBible drawers are the canonical editors;// mirror their lists here so the storyboard's image-prompt enrichment picks// up edits immediately.useEffect(() => {Promise.all([listWritersRoomCharacters(work.id).catch(() => []),- listWritersRoomSettings(work.id).catch(() => []),+ listWritersRoomPlaces(work.id).catch(() => []),listWritersRoomObjects(work.id).catch(() => []),- ]).then(([chars, sets, objs]) => {+ ]).then(([chars, plcs, objs]) => {setCharacters(chars || []);- setSettings(sets || []);+ setPlaces(plcs || []);setObjects(objs || []);});}, [work.id]);@@ -483,8 +483,8 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOif (kind === 'characters' && Array.isArray(snapshot.result?.mergedProfiles)) {setCharacters(snapshot.result.mergedProfiles);}- if (kind === 'settings' && Array.isArray(snapshot.result?.mergedProfiles)) {- setSettings(snapshot.result.mergedProfiles);+ if (kind === 'places' && Array.isArray(snapshot.result?.mergedProfiles)) {+ setPlaces(snapshot.result.mergedProfiles);}if (kind === 'objects' && Array.isArray(snapshot.result?.mergedProfiles)) {setObjects(snapshot.result.mergedProfiles);@@ -497,14 +497,14 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO}, [runningKind, work.id]);// Sequential pipeline for the 3-step storyboard setup. Run characters →- // settings → script in order so each later step has the earlier bible to+ // places → script in order so each later step has the earlier bible to// reference. Bails on first failure (the failed step's toast already fired).const runFullPipeline = useCallback(async () => {if (runningKind) return;const okChars = await runAnalysis(ANALYSIS_KIND.CHARACTERS);if (!okChars || !mountedRef.current) return;- const okSettings = await runAnalysis(ANALYSIS_KIND.SETTINGS);- if (!okSettings || !mountedRef.current) return;+ const okPlaces = await runAnalysis(ANALYSIS_KIND.PLACES);+ if (!okPlaces || !mountedRef.current) return;await runAnalysis(ANALYSIS_KIND.SCRIPT);}, [runAnalysis, runningKind]);@@ -718,7 +718,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<MenuSection label="AI"><MenuItem icon={Clapperboard} label="Run Adapt (rebuild storyboard)" running={runningKind === ANALYSIS_KIND.SCRIPT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SCRIPT))} /><MenuItem icon={Users} label="Refresh characters" running={runningKind === ANALYSIS_KIND.CHARACTERS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.CHARACTERS))} />- <MenuItem icon={MapPin} label="Refresh settings" running={runningKind === ANALYSIS_KIND.SETTINGS} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.SETTINGS))} />+ <MenuItem icon={MapPin} label="Refresh places" running={runningKind === ANALYSIS_KIND.PLACES} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.PLACES))} /><MenuItem icon={Sparkles} label="Editorial pass" running={runningKind === ANALYSIS_KIND.EVALUATE} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.EVALUATE))} /><MenuItem icon={FileSignature} label="Format pass" running={runningKind === ANALYSIS_KIND.FORMAT} onClick={closeOverflowAnd(() => runAnalysis(ANALYSIS_KIND.FORMAT))} /></MenuSection>@@ -776,7 +776,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseObody={body}scenes={latestScenes}characters={characters}- settings={settings}+ places={places}objects={objects}readingTheme={readingTheme}activeSceneId={activeSceneId}@@ -834,10 +834,10 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO<StoryboardPanelwork={work}characters={characters}- settings={settings}+ places={places}objects={objects}onCharactersChange={setCharacters}- onSettingsChange={setSettings}+ onPlacesChange={setPlaces}onObjectsChange={setObjects}onRunObjects={() => runAnalysis(ANALYSIS_KIND.OBJECTS)}onScenesChange={setLatestScenes}@@ -845,7 +845,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOonDebug={handleDebug}onRunAdapt={() => runAnalysis(ANALYSIS_KIND.SCRIPT)}onRunCharacters={() => runAnalysis(ANALYSIS_KIND.CHARACTERS)}- onRunSettings={() => runAnalysis(ANALYSIS_KIND.SETTINGS)}+ onRunPlaces={() => runAnalysis(ANALYSIS_KIND.PLACES)}onRunFullPipeline={runFullPipeline}runningAdapt={runningKind === ANALYSIS_KIND.SCRIPT}runningKind={runningKind}@@ -868,7 +868,7 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOkind={pop?.kind}refId={pop?.refId}characters={characters}- settings={settings}+ places={places}objects={objects}onOpenProfile={handleOpenProfile}onClose={handlePopClose}diff --git a/client/src/components/writers-room/proseTokenizer.jsx b/client/src/components/writers-room/proseTokenizer.jsxindex cba8244fe3..dc498e8f1b 100644--- a/client/src/components/writers-room/proseTokenizer.jsx+++ b/client/src/components/writers-room/proseTokenizer.jsx@@ -1,10 +1,10 @@import { Fragment, useMemo } from 'react';-// proseTokenizer — finds character / setting / object name occurrences in a+// proseTokenizer — finds character / place / object name occurrences in a// paragraph and wraps them in styled spans.//// Algorithm: leftmost-longest greedy match.-// 1. Flatten characters/settings/objects into a list of {term, kind, refId, label}+// 1. Flatten characters/places/objects into a list of {term, kind, refId, label}// entries. Drop terms < 3 chars to avoid pronoun spam ("It", "An").// 2. For each entry, find every case-insensitive occurrence in the paragraph// via a sliding indexOf.@@ -32,7 +32,7 @@ const TOKEN_CLASS = {},};-export function buildTokenIndex({ characters = [], settings = [], objects = [] } = {}) {+export function buildTokenIndex({ characters = [], places = [], objects = [] } = {}) {const entries = [];const push = (kind, refId, label, term) => {if (!term || typeof term !== 'string') return;@@ -45,11 +45,11 @@ export function buildTokenIndex({ characters = [], settings = [], objects = [] }push('char', c.id, c.name || '', c.name);for (const a of c.aliases || []) push('char', c.id, c.name || a, a);}- for (const s of settings) {- if (!s?.id) continue;- const label = s.name || s.slugline || '';- if (s.name) push('place', s.id, label, s.name);- if (s.slugline && s.slugline !== s.name) push('place', s.id, label, s.slugline);+ for (const p of places) {+ if (!p?.id) continue;+ const label = p.name || p.slugline || '';+ if (p.name) push('place', p.id, label, p.name);+ if (p.slugline && p.slugline !== p.name) push('place', p.id, label, p.slugline);}for (const o of objects) {if (!o?.id) continue;@@ -92,7 +92,7 @@ export function tokenizeParagraph(text, entries) {export function renderTokenized(text, {entries = null,characters = [],- settings = [],+ places = [],objects = [],hotRef = null,onTokenEnter,@@ -103,7 +103,7 @@ export function renderTokenized(text, {// Prefer the caller's pre-built index (paid once per bibles change). Fall// back to building per-call when only raw bible arrays are passed — handy// for ad-hoc renders, but not what ProseReader does.- const idx = entries || buildTokenIndex({ characters, settings, objects });+ const idx = entries || buildTokenIndex({ characters, places, objects });const annotations = tokenizeParagraph(text, idx);if (!annotations.length) return <Fragment>{text}</Fragment>;const out = [];@@ -155,6 +155,6 @@ export function renderTokenized(text, {// Convenience hook: memoize the entries so paragraphs don't rebuild the index// on every render. Pair with paragraph-level useMemo for the annotation pass.-export function useTokenEntries({ characters, settings, objects }) {- return useMemo(() => buildTokenIndex({ characters, settings, objects }), [characters, settings, objects]);+export function useTokenEntries({ characters, places, objects }) {+ return useMemo(() => buildTokenIndex({ characters, places, objects }), [characters, places, objects]);}diff --git a/client/src/lib/canonPrompt.js b/client/src/lib/canonPrompt.jsindex 614d3621e4..43f56163f9 100644--- a/client/src/lib/canonPrompt.js+++ b/client/src/lib/canonPrompt.js@@ -6,11 +6,11 @@const trim = (s) => (typeof s === 'string' ? s.trim() : '');-// SHORT spec: chars/objects use single-with-fallback; settings uses a+// SHORT spec: chars/objects use single-with-fallback; places uses a// sequence so palette can carry its prefix.const SHORT_SPEC = Object.freeze({characters: Object.freeze({ primary: 'physicalDescription', fallback: 'description' }),- settings: Object.freeze({+ places: Object.freeze({sequence: Object.freeze([{ field: 'description' },{ field: 'palette', prefix: 'Palette' },@@ -27,7 +27,7 @@ const RICH_SPEC = Object.freeze({{ field: 'physicalDescription' },{ field: 'role' },]),- settings: Object.freeze([+ places: Object.freeze([{ field: 'description' },{ field: 'palette', prefix: 'Palette' },{ field: 'era', prefix: 'Era' },@@ -43,7 +43,7 @@ const RICH_SPEC = Object.freeze({function normalizeKind(kind) {const k = String(kind || '').toLowerCase();if (k === 'character' || k === 'characters') return 'characters';- if (k === 'setting' || k === 'settings') return 'settings';+ if (k === 'place' || k === 'places') return 'places';if (k === 'object' || k === 'objects') return 'objects';return null;}diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.jsindex bc7802ce8f..0e107d57e9 100644--- a/client/src/lib/scenePrompt.js+++ b/client/src/lib/scenePrompt.js@@ -41,7 +41,7 @@ export function matchCharactersInText(text, allCharacters) {return matchEntriesByCandidates(text, allCharacters, (c) => [c.name, ...(c.aliases || [])]);}-export function buildSettingByKey(allSettings) {+export function buildPlaceByKey(allSettings) {const map = new Map();for (const setting of allSettings || []) {const key = normalizeSlugline(setting.slugline || setting.name);@@ -51,9 +51,9 @@ export function buildSettingByKey(allSettings) {return map;}-export function matchSceneSetting(sceneSlugline, settingByKey) {+export function matchScenePlace(sceneSlugline, placeByKey) {if (!sceneSlugline) return null;- return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;+ return placeByKey?.get(normalizeSlugline(sceneSlugline)) || null;}function matchEntriesByCandidates(text, entries, candidatesFn) {@@ -78,34 +78,34 @@ function matchEntriesByCandidates(text, entries, candidatesFn) {return matched;}-export function matchSettingsInText(text, allSettings) {- return matchEntriesByCandidates(text, allSettings, (s) => [s.name]);+export function matchPlacesInText(text, allPlaces) {+ return matchEntriesByCandidates(text, allPlaces, (p) => [p.name]);}export function matchObjectsInText(text, allObjects) {return matchEntriesByCandidates(text, allObjects, (o) => [o.name, ...(o.aliases || [])]);}-export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {+export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedPlace = null) {const stylePart = worldStyle && worldStyle.trim() ? `${worldStyle.trim()}. ` : '';const titlePart = workTitle ? `${workTitle}. ` : '';const visual = scene?.visualPrompt || scene?.description || '';- const intExtPart = matchedSetting?.intExt === 'INT'+ const intExtPart = matchedPlace?.intExt === 'INT'? 'Interior'- : matchedSetting?.intExt === 'EXT'+ : matchedPlace?.intExt === 'EXT'? 'Exterior': '';- const todPart = typeof matchedSetting?.timeOfDay === 'string' && matchedSetting.timeOfDay- ? matchedSetting.timeOfDay+ const todPart = typeof matchedPlace?.timeOfDay === 'string' && matchedPlace.timeOfDay+ ? matchedPlace.timeOfDay: '';- const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');- const baselineFrags = matchedSetting- ? shortCanonDescriptorFragments('setting', matchedSetting)+ const placeMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');+ const baselineFrags = matchedPlace+ ? shortCanonDescriptorFragments('place', matchedPlace).map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value)): [];- const settingFrags = matchedSetting ? [- settingMetaFrag ? `${settingMetaFrag}.` : '',+ const placeFrags = matchedPlace ? [+ placeMetaFrag ? `${placeMetaFrag}.` : '',...baselineFrags,].filter(Boolean) : [];@@ -121,11 +121,11 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyleconst reserveCore = stylePart.length + titlePart.length + visual.length + 4;let budget = PROMPT_MAX - reserveCore;- const settingFit = [];- for (const frag of settingFrags) {- const cost = (settingFit.length === 0 ? 0 : 1) + frag.length;+ const placeFit = [];+ for (const frag of placeFrags) {+ const cost = (placeFit.length === 0 ? 0 : 1) + frag.length;if (cost > budget) break;- settingFit.push(frag);+ placeFit.push(frag);budget -= cost;}@@ -141,7 +141,7 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyleconst segs = [];if (stylePart) segs.push(stylePart.trim());if (titlePart) segs.push(titlePart.trim());- if (settingFit.length > 0) segs.push(settingFit.join(' '));+ if (placeFit.length > 0) segs.push(placeFit.join(' '));if (charFit.length > 0) segs.push(`${PREFIX}${charFit.join(' ')}`);if (visual) segs.push(visual);return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex d3d93e234e..98ab1076ec 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -68,7 +68,7 @@ const BUCKET_CANON = 'canon';// the canon-trunk identifier the server's `canonSelection` schema accepts.const TRUNK_TABS = [{ id: TAB_CAST, kind: 'characters', label: 'Cast', icon: Users },- { id: TAB_PLACES, kind: 'settings', label: 'Places', icon: MapPin },+ { id: TAB_PLACES, kind: 'places', label: 'Places', icon: MapPin },{ id: TAB_OBJECTS, kind: 'objects', label: 'Objects', icon: Package },];const TRUNK_BY_ID = Object.fromEntries(TRUNK_TABS.map((t) => [t.id, t]));@@ -77,7 +77,7 @@ const TRUNK_BY_KIND = Object.fromEntries(TRUNK_TABS.map((t) => [t.kind, t]));// Group category buckets by their `kind` tag. Buckets with an unknown / missing// kind fall into the `other` bin — that bin drives whether the Other tab shows.const groupBucketsByKind = (categories = {}) => {- const out = { characters: [], settings: [], objects: [], other: [] };+ const out = { characters: [], places: [], objects: [], other: [] };for (const [key, bucket] of Object.entries(categories || {})) {const kind = bucket?.kind || 'other';if (out[kind]) out[kind].push(key);@@ -126,8 +126,8 @@ const mergeVariations = (existing, fresh) => {// character "Ashley" with alias "Ash" would not// collide with an LLM-returned "Ash", producing a// duplicate canon entry the user has to merge by hand.-// - settings → `normalizeSlugline` for BOTH `slugline` AND `name`-// (`storyBible.js` MERGE_CONFIG.setting.keyFields).+// - places → `normalizeSlugline` for BOTH `slugline` AND `name`+// (`storyBible.js` MERGE_CONFIG.place.keyFields).// Without this, sluglines that differ only in dash// style or punctuation ("INT. FOUNDRY CITY — DAY"// vs "INT FOUNDRY CITY - DAY") would land as two@@ -144,16 +144,16 @@ const mergeCanonByName = (existing, fresh, kind = 'character') => {// Empty/missing fresh — return `existing` unchanged (preserve reference so// a no-op expand doesn't trigger downstream identity-comparing effects).if (!fresh?.length) return existing || [];- const isSetting = kind === 'setting';- const normName = isSetting+ const isPlace = kind === 'place';+ const normName = isPlace? (s) => (typeof s === 'string' ? normalizeSlugline(s) : ''): (s) => (typeof s === 'string' ? s.trim().toLowerCase() : '');const normSlug = (s) => (typeof s === 'string' ? normalizeSlugline(s) : '');- // Aliases participate in identity for character/object only — settings use- // slugline collision instead (the server's MERGE_CONFIG.setting has no+ // Aliases participate in identity for character/object only — places use+ // slugline collision instead (the server's MERGE_CONFIG.place has no// aliases field).const aliasKeys = (entry) => {- if (isSetting || !Array.isArray(entry?.aliases)) return [];+ if (isPlace || !Array.isArray(entry?.aliases)) return [];return entry.aliases.map(normName).filter(Boolean);};const seen = new Set();@@ -619,9 +619,9 @@ export default function UniverseBuilder() {// wins because our ledger doesn't contain it, so the refetched canon// (which already lacks the deleted entry) is the final state. Cleared on// successful save and on universe-switch.- const pendingCanonAdditionsRef = useRef({ characters: [], settings: [], objects: [] });+ const pendingCanonAdditionsRef = useRef({ characters: [], places: [], objects: [] });const clearPendingCanonAdditions = () => {- pendingCanonAdditionsRef.current = { characters: [], settings: [], objects: [] };+ pendingCanonAdditionsRef.current = { characters: [], places: [], objects: [] };};// Per-page render knobs. Persisted to localStorage so the user's@@ -813,12 +813,12 @@ export default function UniverseBuilder() {const additions = pendingCanonAdditionsRef.current;const baseCanon = {characters: mergeCanonByName(fresh.characters || [], additions.characters, 'character'),- settings: mergeCanonByName(fresh.settings || [], additions.settings, 'setting'),+ places: mergeCanonByName(fresh.places || [], additions.places, 'place'),objects: mergeCanonByName(fresh.objects || [], additions.objects, 'object'),};payload = { ...basePayload, ...baseCanon };} else {- const baseCanon = { characters: draft.characters || [], settings: draft.settings || [], objects: draft.objects || [] };+ const baseCanon = { characters: draft.characters || [], places: draft.places || [], objects: draft.objects || [] };payload = { ...basePayload, ...baseCanon };}}@@ -936,7 +936,7 @@ export default function UniverseBuilder() {// Allowing a fresh LLM kind to supersede an existing 'other' is intentional:// pre-Phase-B "factions" buckets saved as `other` can be promoted to// `characters` by a re-expand without requiring the user to manually change- // the trunk. User-curated non-`other` kinds (e.g. `settings`) are preserved.+ // the trunk. User-curated non-`other` kinds (e.g. `places`) are preserved.const existingKind = draft.categories?.[cat]?.kind;const freshKind = llmCategories[cat]?.kind;const kind = (existingKind && existingKind !== 'other') ? existingKind : (freshKind || existingKind);@@ -964,8 +964,8 @@ export default function UniverseBuilder() {// clobber hand-authored or series-extracted records. mergeCanonByName// short-circuits when `fresh` is empty so identity is preserved.//- // `kind` is passed so settings use `normalizeSlugline` for both `name` and- // `slugline` (matching the server's MERGE_CONFIG.setting.keyFields) —+ // `kind` is passed so places use `normalizeSlugline` for both `name` and+ // `slugline` (matching the server's MERGE_CONFIG.place.keyFields) —// dash/punct-variant identifiers collide instead of duplicating.const pickCanon = (key, kind) => mergeCanonByName(draft[key] || [],@@ -973,7 +973,7 @@ export default function UniverseBuilder() {kind,);const mergedCharacters = pickCanon('characters', 'character');- const mergedSettings = pickCanon('settings', 'setting');+ const mergedPlaces = pickCanon('places', 'place');const mergedObjects = pickCanon('objects', 'object');// Count NEW canon entries this expand added (post-merge minus pre-existing).// Used by the toast so a re-expand on a populated universe doesn't claim@@ -981,7 +981,7 @@ export default function UniverseBuilder() {// on collision in mergeCanonByName, so the delta is always non-negative.const addedCanonCount =(mergedCharacters.length - (draft.characters?.length || 0))- + (mergedSettings.length - (draft.settings?.length || 0))+ + (mergedPlaces.length - (draft.places?.length || 0))+ (mergedObjects.length - (draft.objects?.length || 0));const expandedDraft = {@@ -994,7 +994,7 @@ export default function UniverseBuilder() {categories: ensureDraftCategories(mergedCategories),compositeSheets: mergedSheets,characters: mergedCharacters,- settings: mergedSettings,+ places: mergedPlaces,objects: mergedObjects,llm: result.llm || draft.llm,};@@ -1018,7 +1018,7 @@ export default function UniverseBuilder() {};pendingCanonAdditionsRef.current = {characters: [...pendingCanonAdditionsRef.current.characters, ...computeAdditions(draft.characters, mergedCharacters)],- settings: [...pendingCanonAdditionsRef.current.settings, ...computeAdditions(draft.settings, mergedSettings)],+ places: [...pendingCanonAdditionsRef.current.places, ...computeAdditions(draft.places, mergedPlaces)],objects: [...pendingCanonAdditionsRef.current.objects, ...computeAdditions(draft.objects, mergedObjects)],};}@@ -1054,7 +1054,7 @@ export default function UniverseBuilder() {// any concurrent deletions/edits.let canonForPayload = {characters: expandedDraft.characters || [],- settings: expandedDraft.settings || [],+ places: expandedDraft.places || [],objects: expandedDraft.objects || [],};if (selectedId) {@@ -1079,7 +1079,7 @@ export default function UniverseBuilder() {// deletions in other tabs/surfaces get resurrected because the// deleted entry is still present in the stale draft.characters: mergeCanonByName(fresh.characters || [], pendingCanonAdditionsRef.current.characters, 'character'),- settings: mergeCanonByName(fresh.settings || [], pendingCanonAdditionsRef.current.settings, 'setting'),+ places: mergeCanonByName(fresh.places || [], pendingCanonAdditionsRef.current.places, 'place'),objects: mergeCanonByName(fresh.objects || [], pendingCanonAdditionsRef.current.objects, 'object'),};}@@ -1343,7 +1343,7 @@ export default function UniverseBuilder() {return {...d,characters: mergeCanonByName(updated.characters || [], additions.characters, 'character'),- settings: mergeCanonByName(updated.settings || [], additions.settings, 'setting'),+ places: mergeCanonByName(updated.places || [], additions.places, 'place'),objects: mergeCanonByName(updated.objects || [], additions.objects, 'object'),updatedAt: updated.updatedAt,};@@ -1351,7 +1351,7 @@ export default function UniverseBuilder() {return {...d,characters: updated.characters,- settings: updated.settings,+ places: updated.places,objects: updated.objects,updatedAt: updated.updatedAt,};@@ -1422,7 +1422,7 @@ export default function UniverseBuilder() {}};// Auto-sort with AI — one LLM call classifies every Other-tab bucket into- // characters/settings/objects. Each bucket's `kind` is reassigned via a+ // characters/places/objects. Each bucket's `kind` is reassigned via a// single atomic patch server-side so the universe ends up consistent or// unchanged. Renames the LLM suggests are surfaced in the toast but not// auto-applied (the user can rename manually if they want it).@@ -1555,7 +1555,7 @@ export default function UniverseBuilder() {const newDraft = {...baseDraft,characters: updated.characters,- settings: updated.settings,+ places: updated.places,objects: updated.objects,categories: { ...baseDraft.categories, [result.removed.category]: updated.categories?.[result.removed.category] },schemaVersion: updated.schemaVersion,@@ -1734,7 +1734,7 @@ export default function UniverseBuilder() {tabs={[{ id: TAB_BIBLE, label: 'Bible', icon: BookOpen },{ id: TAB_CAST, label: 'Cast', icon: Users, count: (draft.characters?.length || 0) + bucketsByKind.characters.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0) },- { id: TAB_PLACES, label: 'Places', icon: MapPin, count: (draft.settings?.length || 0) + bucketsByKind.settings.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0) },+ { id: TAB_PLACES, label: 'Places', icon: MapPin, count: (draft.places?.length || 0) + bucketsByKind.places.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0) },{ id: TAB_OBJECTS, label: 'Objects', icon: Package, count: (draft.objects?.length || 0) + bucketsByKind.objects.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0) },hasOtherBuckets && { id: TAB_OTHER, label: 'Other', icon: FolderTree, count: bucketsByKind.other.reduce((n, k) => n + (draft.categories?.[k]?.variations?.length || 0), 0) },{ id: TAB_COMPOSITES, label: 'Composites', icon: Layers, count: totalSheets },@@ -1893,11 +1893,11 @@ const hasNonBlankString = (v) => typeof v === 'string' && v.trim().length > 0;const canonEntryHasContent = (e, kind) => {if (!e) return false;if (hasNonBlankString(e.prompt)) return true;- // Identifier anchors per kind — settings allow slugline-only entries (bible+ // Identifier anchors per kind — places allow slugline-only entries (bible// sanitizer); characters/objects ignore stray slugline. Mirrors server// synthesizeCanonPrompt's identifier-seed rule.if (hasNonBlankString(e.name)) return true;- if (kind === 'settings' && hasNonBlankString(e.slugline)) return true;+ if (kind === 'places' && hasNonBlankString(e.slugline)) return true;return hasCanonDescriptorContent(kind, e);};@@ -1909,7 +1909,7 @@ function renderPromptCount(world, promptMode = 'variations') {const sheets = world.compositeSheets?.length || 0;if (promptMode === 'sheets') return sheets;const canon = countCanonWithContent(world, 'characters')- + countCanonWithContent(world, 'settings')+ + countCanonWithContent(world, 'places')+ countCanonWithContent(world, 'objects');if (promptMode === 'canon') return canon;return totalVariationCount(world) + sheets + canon;@@ -1959,7 +1959,7 @@ function scopedPromptCount(world, scope) {}if (mode === 'canon' || mode === 'all') {if (scope.canonSelection) {- for (const trunk of ['characters', 'settings', 'objects']) {+ for (const trunk of ['characters', 'places', 'objects']) {const pick = scope.canonSelection[trunk];if (!pick) continue;const entries = Array.isArray(world[trunk]) ? world[trunk] : [];@@ -1967,12 +1967,12 @@ function scopedPromptCount(world, scope) {if (pick === 'all') n += withContent.length;else if (Array.isArray(pick)) {const needles = new Set(pick.map((p) => p.toLowerCase()));- // Mirror server: slugline matching is settings-only — name is the+ // Mirror server: slugline matching is places-only — name is the// shared anchor for characters/objects.n += withContent.filter((e) => {const name = (e.name || '').toLowerCase();if (needles.has(name)) return true;- if (trunk === 'settings') {+ if (trunk === 'places') {const slug = (e.slugline || '').toLowerCase();if (needles.has(slug)) return true;}@@ -2964,7 +2964,7 @@ export function TrunkView({value={newBucketName}onChange={(e) => setNewBucketName(e.target.value)}onKeyDown={(e) => { if (e.key === 'Enter') handleAddBucket(); }}- placeholder={trunk.kind === 'characters' ? 'heroes, villains, factions' : trunk.kind === 'settings' ? 'colonies, ruins' : 'weapons, vehicles'}+ placeholder={trunk.kind === 'characters' ? 'heroes, villains, factions' : trunk.kind === 'places' ? 'colonies, ruins' : 'weapons, vehicles'}className="flex-1 min-w-[160px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-white text-sm focus:outline-none focus:border-port-accent"maxLength={WORLD_CATEGORY_KEY_MAX}autoFocus@@ -3063,7 +3063,7 @@ export function OtherTab({onClick={onAutoSort}disabled={autoSorting}className="text-xs px-2 py-1.5 bg-port-accent/15 hover:bg-port-accent/25 disabled:opacity-50 text-port-accent rounded flex items-center gap-1 min-h-[32px]"- title="Auto-sort with AI — sends every Other-tab bucket to the active LLM and assigns each to characters / settings / objects"+ title="Auto-sort with AI — sends every Other-tab bucket to the active LLM and assigns each to characters / places / objects">{autoSorting ? <Loader2 size={12} className="animate-spin" /> : <Wand2 size={12} />}{autoSorting ? 'Sorting…' : 'Auto-sort with AI'}@@ -3119,7 +3119,7 @@ function RenderTab({const totalSheets = draft.compositeSheets?.length || 0;const totalVariations = totalVariationCount(draft);const totalCanon = countCanonWithContent(draft, 'characters')- + countCanonWithContent(draft, 'settings')+ + countCanonWithContent(draft, 'places')+ countCanonWithContent(draft, 'objects');const otherBuckets = bucketsByKind?.other || [];const totalOtherVariations = otherBuckets.reduce(diff --git a/client/src/pages/UniverseBuilder.test.jsx b/client/src/pages/UniverseBuilder.test.jsxindex ac31365e0f..b3cdfa029c 100644--- a/client/src/pages/UniverseBuilder.test.jsx+++ b/client/src/pages/UniverseBuilder.test.jsx@@ -75,7 +75,7 @@ describe('CategoryEditor — promote wiring', () => {await user.click(screen.getByRole('menuitem', { name: 'Places' }));expect(onPromote).toHaveBeenCalledTimes(1);- expect(onPromote).toHaveBeenCalledWith(sampleVariation, { targetKind: 'settings' });+ expect(onPromote).toHaveBeenCalledWith(sampleVariation, { targetKind: 'places' });});});diff --git a/client/src/services/apiWritersRoom.js b/client/src/services/apiWritersRoom.jsindex 728d92d277..561614d044 100644--- a/client/src/services/apiWritersRoom.js+++ b/client/src/services/apiWritersRoom.js@@ -84,22 +84,22 @@ export const deleteWritersRoomCharacter = (workId, characterId) =>method: 'DELETE',});-// Settings / world bible (editable, persists across analysis runs, drives+// Places / world bible (editable, persists across analysis runs, drives// scene image gen via slugline match in SceneCard)-export const listWritersRoomSettings = (workId) =>- request(`/writers-room/works/${enc(workId)}/settings`);-export const createWritersRoomSetting = (workId, data) =>- request(`/writers-room/works/${enc(workId)}/settings`, {+export const listWritersRoomPlaces = (workId) =>+ request(`/writers-room/works/${enc(workId)}/places`);+export const createWritersRoomPlace = (workId, data) =>+ request(`/writers-room/works/${enc(workId)}/places`, {method: 'POST',body: JSON.stringify(data),});-export const updateWritersRoomSetting = (workId, settingId, patch) =>- request(`/writers-room/works/${enc(workId)}/settings/${enc(settingId)}`, {+export const updateWritersRoomPlace = (workId, placeId, patch) =>+ request(`/writers-room/works/${enc(workId)}/places/${enc(placeId)}`, {method: 'PATCH',body: JSON.stringify(patch),});-export const deleteWritersRoomSetting = (workId, settingId) =>- request(`/writers-room/works/${enc(workId)}/settings/${enc(settingId)}`, {+export const deleteWritersRoomPlace = (workId, placeId) =>+ request(`/writers-room/works/${enc(workId)}/places/${enc(placeId)}`, {method: 'DELETE',});diff --git a/data.sample/prompts/_partials/bible-deference.md b/data.sample/prompts/_partials/bible-deference.mdindex f43013f350..3906af3889 100644--- a/data.sample/prompts/_partials/bible-deference.md+++ b/data.sample/prompts/_partials/bible-deference.md@@ -6,13 +6,13 @@ Each scene's image-gen prompt has to describe characters physically (image model{{existingCharactersJson}}```-## Setting bible (canonical locations — defer to these)+## Places bible (canonical locations — defer to these)When a scene's slugline matches a `slugline` below (case-insensitive, ignoring punctuation), the storyboard pipeline auto-injects the entry's `description` / `palette` / `recurringDetails` into the final image prompt. So:- **Reuse the same slugline string** from the bible verbatim when the scene takes place in that location — even minor wording drift breaks the match.-- Don't restate the setting's baseline description inside `visualPrompt`; the pipeline will prepend it. Use `visualPrompt` for what's *new this beat* (blocking, lighting *changes* from the room's baseline, character action, time-of-day shifts).+- Don't restate the place's baseline description inside `visualPrompt`; the pipeline will prepend it. Use `visualPrompt` for what's *new this beat* (blocking, lighting *changes* from the room's baseline, character action, time-of-day shifts).```json-{{existingSettingsJson}}+{{existingPlacesJson}}```diff --git a/data.sample/prompts/stages/writers-room-places.md b/data.sample/prompts/stages/writers-room-places.mdindex 21a3838b0d..dc26de703d 100644--- a/data.sample/prompts/stages/writers-room-places.md+++ b/data.sample/prompts/stages/writers-room-places.md@@ -1,6 +1,6 @@-# Writers Room — Setting / World Bible Extraction+# Writers Room — Place / World Bible Extraction-You are a production designer building a setting bible for a piece of prose. Each entry you produce will drive image-generation prompts for scenes set in that location, so descriptions must be specific, visually dense, and renderable — not literary.+You are a production designer building a places bible for a piece of prose. Each entry you produce will drive image-generation prompts for scenes set in that location, so descriptions must be specific, visually dense, and renderable — not literary.## Work being analyzed@@ -8,12 +8,12 @@ You are a production designer building a setting bible for a piece of prose. Eac- Kind: {{work.kind}}- Word count: {{work.wordCount}}-## Existing settings (preserve user edits — DO NOT contradict these)+## Existing places (preserve user edits — DO NOT contradict these)The writer may have already edited some entries. Treat any non-empty field below as authoritative — if you would describe the same location differently, defer to the existing value. Your job is to FILL IN the empty fields from prose evidence and ADD any locations the writer hasn't captured yet.```json-{{existingSettingsJson}}+{{existingPlacesJson}}```## Source prose@@ -24,10 +24,10 @@ The writer may have already edited some entries. Treat any non-empty field below## Task-For every distinct *location* the prose stages a scene in (interior or exterior), produce one entry. Use screenplay-slugline keys so the storyboard pipeline can match scenes back to settings automatically.+For every distinct *location* the prose stages a scene in (interior or exterior), produce one entry. Use screenplay-slugline keys so the storyboard pipeline can match scenes back to places automatically.1. Extract or refine these fields:- - `slugline` — screenplay format: `INT./EXT. LOCATION — TIME OF DAY` (uppercase). This is the *match key* the storyboard uses to attach a setting to a scene, so use the same wording every time the prose returns to a place. If the same room appears at different times of day, prefer the most-used variant (or `INT. LOCATION — DAY` as the default). Do not invent locations the prose never visits.+ - `slugline` — screenplay format: `INT./EXT. LOCATION — TIME OF DAY` (uppercase). This is the *match key* the storyboard uses to attach a place to a scene, so use the same wording every time the prose returns to a place. If the same room appears at different times of day, prefer the most-used variant (or `INT. LOCATION — DAY` as the default). Do not invent locations the prose never visits.- `name` — short human-readable name (`Curry O'City`, `The Train Platform`, `Marlowe's Apartment`). May overlap with the slugline's location half. If the prose names the place, use that name verbatim.- `description` — 40–100 words, image-gen-ready. Be specific and visual: architecture, scale, materials, lighting sources, recurring set-dressing, signage, smells/sounds the prose names visually (steam, neon hum). Bake in genre/era cues. Do NOT include character action, dialogue, or plot — just the *place*.- `palette` — short comma-separated list of dominant colors / lighting cues (`oxblood neon, wet asphalt black, sodium-yellow streetlights`). Drives image-gen color consistency.@@ -55,7 +55,7 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c```json{- "settings": [+ "places": [{"slugline": "INT. KITCHEN — NIGHT","name": "string",diff --git a/scripts/migrations/022-rename-bible-setting-to-place.js b/scripts/migrations/022-rename-bible-setting-to-place.jsnew file mode 100644index 0000000000..fbb542f2db--- /dev/null+++ b/scripts/migrations/022-rename-bible-setting-to-place.js@@ -0,0 +1,309 @@+/**+ * Rename the bible-domain `setting` entity to `place` across persisted state.+ *+ * Migration 018 already renamed the stage-config key + prompt file. This+ * migration extends the rename through every other persisted surface so the+ * runtime contract (`BIBLE_KIND.PLACE: 'place'`, `BIBLE_FIELD[PLACE]: 'places'`)+ * matches what's on disk:+ *+ * 1. `data/universe-builder.json`:+ * - `state.universes[].settings: [...]` → `state.universes[].places: [...]`+ * - `categories[k].kind === 'settings'` → `'places'`+ *+ * 2. `data/pipeline-series.json`:+ * - `state.series[].settings: [...]` → `state.series[].places: [...]`+ * (legacy field — canon now lives on the linked universe, but old+ * records may still carry the array; renaming keeps reads consistent.)+ *+ * 3. `data/writers-room/works/<workId>/`:+ * - rename file `settings.json` → `places.json`+ * - rewrite top-level JSON key `settings` → `places` inside+ *+ * 4. `data/prompts/stages/writers-room-places.md`:+ * - rewrite `{{existingSettingsJson}}` → `{{existingPlacesJson}}`+ * - rewrite `"settings": [` → `"places": [`+ *+ * 5. `data/prompts/_partials/bible-deference.md`:+ * - rewrite `{{existingSettingsJson}}` → `{{existingPlacesJson}}`+ *+ * 6. `data/prompts/stages/writers-room-places.md` + bible-deference.md:+ * auto-update the shipped templates when the user hasn't customized+ * them (matches OLD_SHIPPED_MD5). Customized templates are left alone+ * so the user's edits aren't clobbered; the drift surfaces in+ * setup-data.js's hash-check warning.+ *+ * Idempotent: re-runs skip universes/series/works that already carry the+ * post-rename shape, and prompt templates that already match the new+ * shipped MD5.+ *+ * NOT TOUCHED:+ * - The per-entry id prefix `set-` on existing pipeline canon entries+ * (purely cosmetic — ids are opaque after creation).+ * - The per-work file `data/writers-room/works/<id>/places.json` if the+ * user already migrated by hand (we keep their version).+ * - Stage-config key `writers-room-places` (handled by migration 018).+ */++import { readFile, writeFile, unlink, rename, readdir, stat } from 'fs/promises';+import { join } from 'path';+import { createHash } from 'crypto';++const md5 = (str) => {+ const normalized = str.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};++const readJsonOrNull = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+};++const writeJson = async (path, data) => {+ await writeFile(path, `${JSON.stringify(data, null, 2)}\n`);+};++const fileExists = async (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++const readDirOrEmpty = async (path) => readdir(path, { withFileTypes: true }).catch((err) => {+ if (err.code === 'ENOENT') return [];+ throw err;+});++// Pre-rename shipped hashes. Auto-update only matches; customized templates+// are left for the user to merge manually (setup-data.js will flag the drift).+const OLD_PROMPTS_PLACES_MD5 = '24a33628cc94d80fa5ca60831d973daf';+const NEW_PROMPTS_PLACES_MD5 = 'a7f68e51dd6b4421d20f5bd9d855d9b4';+const OLD_PROMPTS_DEFERENCE_MD5 = '218f0e85643609ed85a12b1ccc7b5a8d';+const NEW_PROMPTS_DEFERENCE_MD5 = 'a4681348c27776e414acf6e0be566a99';++// Each template has a sample twin at the same relative path under+// `data.sample/…`. When an installed copy still hashes to the pre-rename+// baseline (`oldHash`), the migration prefers copying the bundled+// `data.sample` file verbatim — that picks up *every* string the rename+// touched (`## Existing settings` → `## Existing places`, etc.) without+// enumerating the full prose diff. If the bundled sample is missing+// (distributions that strip `data.sample/`, or tests that point `rootDir`+// at a relocated data tree), we fall back to a surgical replace covering+// the rename-critical substitutions so the prompt's runtime contract+// (`{{existingPlacesJson}}` envelope variable + `"places":` LLM output+// envelope key) still works — better to leave some stale prose in+// section headers than to break the extractor on the next request.+const RENAME_SUBSTITUTIONS = [+ // Rename-critical: variable + envelope key. The extractor breaks+ // without these, so they MUST land regardless of fallback path.+ [/\{\{existingSettingsJson\}\}/g, '{{existingPlacesJson}}'],+ [/"settings":\s*\[/g, '"places": ['],+ // Cosmetic but cheap and exhaustive over the known shipped templates.+ [/Setting \/ World Bible Extraction/g, 'Place / World Bible Extraction'],+ [/## Existing settings/g, '## Existing places'],+ [/## Setting bible/g, '## Places bible'],+ [/setting bible \(canonical/g, 'places bible (canonical'],+ [/back to settings automatically/g, 'back to places automatically'],+ [/attach a setting to a scene/g, 'attach a place to a scene'],+ [/the setting's baseline description/g, "the place's baseline description"],+];++const PROMPT_TEMPLATES = [+ {+ rel: 'data/prompts/stages/writers-room-places.md',+ sampleRel: 'data.sample/prompts/stages/writers-room-places.md',+ oldHash: OLD_PROMPTS_PLACES_MD5,+ newHash: NEW_PROMPTS_PLACES_MD5,+ },+ {+ rel: 'data/prompts/_partials/bible-deference.md',+ sampleRel: 'data.sample/prompts/_partials/bible-deference.md',+ oldHash: OLD_PROMPTS_DEFERENCE_MD5,+ newHash: NEW_PROMPTS_DEFERENCE_MD5,+ },+];++const migrateUniverseState = async (rootDir) => {+ const path = join(rootDir, 'data/universe-builder.json');+ const state = await readJsonOrNull(path);+ if (!state || !Array.isArray(state.universes)) return;+ let touched = 0;+ for (const u of state.universes) {+ let changed = false;+ if (Array.isArray(u.settings) && !Array.isArray(u.places)) {+ u.places = u.settings;+ delete u.settings;+ changed = true;+ } else if ('settings' in u && Array.isArray(u.places)) {+ // Both keys present (a partial prior migration or hand-edit) —+ // keep the post-rename `places` and drop the legacy `settings`.+ delete u.settings;+ changed = true;+ }+ if (u.categories && typeof u.categories === 'object') {+ for (const cat of Object.values(u.categories)) {+ if (cat && cat.kind === 'settings') {+ cat.kind = 'places';+ changed = true;+ }+ }+ }+ if (changed) touched += 1;+ }+ if (touched > 0) {+ await writeJson(path, state);+ console.log(`📝 data/universe-builder.json: renamed setting→place on ${touched} universe${touched === 1 ? '' : 's'}`);+ } else {+ console.log(`✅ data/universe-builder.json: already on places shape`);+ }+};++const migrateSeriesState = async (rootDir) => {+ const path = join(rootDir, 'data/pipeline-series.json');+ const state = await readJsonOrNull(path);+ if (!state || !Array.isArray(state.series)) return;+ let touched = 0;+ for (const s of state.series) {+ if (Array.isArray(s.settings) && !Array.isArray(s.places)) {+ s.places = s.settings;+ delete s.settings;+ touched += 1;+ } else if ('settings' in s) {+ delete s.settings;+ touched += 1;+ }+ }+ if (touched > 0) {+ await writeJson(path, state);+ console.log(`📝 data/pipeline-series.json: renamed setting→place on ${touched} series record${touched === 1 ? '' : 's'}`);+ } else {+ console.log(`✅ data/pipeline-series.json: already on places shape`);+ }+};++const migrateWritersRoomWorks = async (rootDir) => {+ const worksDir = join(rootDir, 'data/writers-room/works');+ const entries = await readDirOrEmpty(worksDir);+ let renamedFiles = 0;+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const workDir = join(worksDir, entry.name);+ const legacyPath = join(workDir, 'settings.json');+ const newPath = join(workDir, 'places.json');+ const legacyExists = await fileExists(legacyPath);+ if (!legacyExists) continue;+ const newExists = await fileExists(newPath);+ if (newExists) {+ // Both files exist — `places.json` is the post-rename truth (a prior+ // partial migration run or hand-edit produced it). Move the legacy+ // `settings.json` aside as `.bak-022` rather than `unlink`-ing it: if+ // the two diverged (e.g. user hand-created `places.json` from a+ // non-empty subset), the legacy file may contain entries the user+ // would otherwise lose silently. The next migration tick won't re-fire+ // this branch because `settings.json` is gone; the .bak sits as a+ // recovery breadcrumb the user can diff if anything looks missing.+ const backupPath = `${legacyPath}.bak-022`;+ await rename(legacyPath, backupPath).catch((err) => {+ console.warn(`⚠️ ${join('data/writers-room/works', entry.name)}: failed to back up legacy settings.json → settings.json.bak-022 — ${err.message}`);+ });+ console.log(`🧹 ${join('data/writers-room/works', entry.name)}: both settings.json and places.json existed — kept places.json, backed up legacy settings.json → settings.json.bak-022 (diff if anything looks missing)`);+ continue;+ }+ const raw = await readFile(legacyPath, 'utf-8').catch(() => null);+ if (raw == null) continue;+ let parsed;+ try { parsed = JSON.parse(raw); } catch { parsed = null; }+ if (parsed && Array.isArray(parsed.settings)) {+ parsed.places = parsed.settings;+ delete parsed.settings;+ await writeJson(newPath, parsed);+ } else {+ await writeJson(newPath, parsed || { places: [], updatedAt: null });+ }+ // Try unlink first (clean removal of the now-redundant legacy file).+ // If unlink fails (Windows file-lock, EACCES, etc.) the residual+ // `settings.json` would otherwise be re-discovered by the next+ // migration tick as a phantom "both files exist" case — confusing the+ // user with a "diff if anything looks missing" warning even though+ // both files came from the same migration run. Fall back to renaming+ // it aside as `.bak-022` so the next run sees only `places.json` and+ // exits cleanly.+ const unlinkErr = await unlink(legacyPath).then(() => null, (err) => err);+ if (unlinkErr) {+ const backupPath = `${legacyPath}.bak-022`;+ await rename(legacyPath, backupPath).catch((renameErr) => {+ console.warn(+ `⚠️ ${join('data/writers-room/works', entry.name)}: failed to clean up legacy settings.json after writing places.json — ` ++ `unlink: ${unlinkErr.message}; rename to .bak-022: ${renameErr.message}. ` ++ `Next migration run will treat this as a phantom "both files exist" case.`,+ );+ });+ }+ renamedFiles += 1;+ }+ if (renamedFiles > 0) {+ console.log(`📝 data/writers-room/works/: renamed settings.json → places.json in ${renamedFiles} work director${renamedFiles === 1 ? 'y' : 'ies'}`);+ } else if (entries.length > 0) {+ console.log(`✅ data/writers-room/works/: already on places.json shape`);+ }+};++const migratePromptTemplate = async (rootDir, { rel, sampleRel, oldHash, newHash }) => {+ const path = join(rootDir, rel);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return;+ const currentHash = md5(raw);+ if (currentHash === newHash) {+ console.log(`✅ ${rel}: already at new shipped baseline`);+ return;+ }+ if (currentHash !== oldHash) {+ console.log(`⚠️ ${rel}: customized (hash ${currentHash.slice(0, 8)}) — not auto-updating. Diff against data.sample to pick up the {{existingPlacesJson}} rename.`);+ return;+ }+ // Pre-rename baseline. Prefer copying the bundled `data.sample` twin+ // verbatim — it carries every prose substitution the rename touched.+ // When `data.sample` is missing (stripped distribution, relocated+ // rootDir), fall back to a surgical replace covering the+ // rename-critical substitutions enumerated in RENAME_SUBSTITUTIONS,+ // so the prompt's runtime contract still works even if some prose+ // strings stay stale. Hash check above guarantees we only rewrite an+ // unmodified shipped default — customized templates land in the+ // warning branch and the user-customized version is preserved.+ const samplePath = join(rootDir, sampleRel);+ const sample = await readFile(samplePath, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (sample != null) {+ await writeFile(path, sample);+ console.log(`📝 ${rel}: replaced pre-rename shipped default with current data.sample bundle`);+ return;+ }+ const next = RENAME_SUBSTITUTIONS.reduce((acc, [from, to]) => acc.replace(from, to), raw);+ await writeFile(path, next);+ console.warn(+ `⚠️ ${rel}: bundled sample missing at ${sampleRel} — fell back to surgical replace ` ++ `(rename-critical substitutions applied; some stale prose may remain in section headers).`,+ );+};++export default {+ async up({ rootDir }) {+ await migrateUniverseState(rootDir);+ await migrateSeriesState(rootDir);+ await migrateWritersRoomWorks(rootDir);+ for (const tpl of PROMPT_TEMPLATES) {+ await migratePromptTemplate(rootDir, tpl);+ }+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 8954b245cb..827d724b70 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -162,8 +162,11 @@ const SHIPPED_PROMPT_OLD_MD5 = {'pipeline-arc-resolve.md': ['87bc5c01f1a8a97b681727a38b05edc6', 'a8677bbe1eb38f871fb152a5b0fec7c6'],// Shot decomposition additions (migration 006).'pipeline-extract-scenes.md': '59fa5ee305ce53d91eb15224d8b546d3',- // INT/EXT + time-of-day additions to the places extractor (migration 007).- 'writers-room-places.md': '7f1f80eb63d67a21161994cde115045e',+ // setting→place rename, migration 022. Two known auto-updatable hashes:+ // pre-019 (`7f1f80…`, INT/EXT addition) and pre-022 (`24a336…`, the+ // hash that was the NEW shipped before this rename). Both can be+ // auto-bumped to the post-rename shape.+ 'writers-room-places.md': ['7f1f80eb63d67a21161994cde115045e', '24a33628cc94d80fa5ca60831d973daf'],// CoS agent prompt: drop obsolete "# Chief of Staff Agent Briefing" header// and "You are an autonomous agent…" preamble (migration 009). Every// historical shipped hash is auto-updatable to the new sample.@@ -187,28 +190,48 @@ const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940','pipeline-arc-resolve.md': '8e348f3d1894382889f9f0ee7d5c6792','pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',- 'writers-room-places.md': '24a33628cc94d80fa5ca60831d973daf',+ 'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4','cos-agent-briefing.md': 'dccb392a43cbd3dac900fee12c31619a',};const SHIPPED_PROMPT_FILES = Object.keys(SHIPPED_PROMPT_OLD_MD5);-const sampleStagesDir = join(sampleDir, 'prompts', 'stages');-const dataStagesDir = join(dataDir, 'prompts', 'stages');-if (existsSync(sampleStagesDir) && existsSync(dataStagesDir)) {- const md5 = (s) => {- const normalized = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');- return createHash('md5').update(normalized).digest('hex');- };+// Shared `_partials/*.md` fragments are mustache-rendered into multiple+// stage prompts (e.g. `bible-deference.md` is included by every stage+// that references both character + place bibles). They get their own+// drift table so the loop below scans them in parallel with stage+// prompts and warns the user when a migration's pending.+const SHIPPED_PARTIAL_OLD_MD5 = {+ // setting→place rename, migration 022.+ 'bible-deference.md': '218f0e85643609ed85a12b1ccc7b5a8d',+};+const SHIPPED_PARTIAL_NEW_MD5 = {+ 'bible-deference.md': 'a4681348c27776e414acf6e0be566a99',+};+const SHIPPED_PARTIAL_FILES = Object.keys(SHIPPED_PARTIAL_OLD_MD5);++const md5 = (s) => {+ const normalized = s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');+ return createHash('md5').update(normalized).digest('hex');+};+// Walk one directory's worth of shipped prompt files against a hash table+// and partition them into auto-updatable (still on a known old hash) vs.+// customized (hash matches neither old nor new). Used twice — once for+// stage prompts, once for partial fragments.+const collectDrift = ({ sampleSubdir, dataSubdir, files, oldMap, newMap }) => {+ const sampleSubpath = join(sampleDir, ...sampleSubdir);+ const dataSubpath = join(dataDir, ...dataSubdir);+ if (!existsSync(sampleSubpath) || !existsSync(dataSubpath)) {+ return { autoUpdatable: [], customized: [] };+ }const autoUpdatable = [];const customized = [];-- for (const f of SHIPPED_PROMPT_FILES) {- const dataPath = join(dataStagesDir, f);- if (!existsSync(dataPath)) continue; // missing files handled above+ for (const f of files) {+ const dataPath = join(dataSubpath, f);+ if (!existsSync(dataPath)) continue;const dataMd5 = md5(readFileSync(dataPath, 'utf8'));- if (dataMd5 === SHIPPED_PROMPT_NEW_MD5[f]) continue; // already up to date- const oldExpected = SHIPPED_PROMPT_OLD_MD5[f];+ if (dataMd5 === newMap[f]) continue;+ const oldExpected = oldMap[f];const oldHashes = Array.isArray(oldExpected) ? oldExpected : [oldExpected];if (oldHashes.includes(dataMd5)) {autoUpdatable.push(f);@@ -216,22 +239,47 @@ if (existsSync(sampleStagesDir) && existsSync(dataStagesDir)) {customized.push(f);}}+ return { autoUpdatable, customized };+};- if (autoUpdatable.length > 0) {- console.warn(- `\n⚠️ ${autoUpdatable.length} pipeline stage prompt(s) have a pending migration — run \`npm run migrations\` to auto-update:\n` +- autoUpdatable.map(f => ` • ${f}`).join('\n') + '\n',- );- }+const stageDrift = collectDrift({+ sampleSubdir: ['prompts', 'stages'],+ dataSubdir: ['prompts', 'stages'],+ files: SHIPPED_PROMPT_FILES,+ oldMap: SHIPPED_PROMPT_OLD_MD5,+ newMap: SHIPPED_PROMPT_NEW_MD5,+});+const partialDrift = collectDrift({+ sampleSubdir: ['prompts', '_partials'],+ dataSubdir: ['prompts', '_partials'],+ files: SHIPPED_PARTIAL_FILES,+ oldMap: SHIPPED_PARTIAL_OLD_MD5,+ newMap: SHIPPED_PARTIAL_NEW_MD5,+});- if (customized.length > 0) {- console.warn(- `\n⚠️ ${customized.length} pipeline stage prompt(s) are customized and cannot be auto-updated.\n` +- ` Manually merge the new template variables into each file:\n` +- customized.map(f =>- ` • data/prompts/stages/${f}\n` +- ` Compare with: data.sample/prompts/stages/${f}`,- ).join('\n') + '\n',- );- }+const autoUpdatable = [+ ...stageDrift.autoUpdatable.map((f) => ({ file: f, relDir: 'data/prompts/stages' })),+ ...partialDrift.autoUpdatable.map((f) => ({ file: f, relDir: 'data/prompts/_partials' })),+];+const customized = [+ ...stageDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/stages', sampleDir: 'data.sample/prompts/stages' })),+ ...partialDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/_partials', sampleDir: 'data.sample/prompts/_partials' })),+];++if (autoUpdatable.length > 0) {+ console.warn(+ `\n⚠️ ${autoUpdatable.length} pipeline prompt(s) have a pending migration — run \`npm run migrations\` to auto-update:\n` ++ autoUpdatable.map(({ file, relDir }) => ` • ${relDir}/${file}`).join('\n') + '\n',+ );+}++if (customized.length > 0) {+ console.warn(+ `\n⚠️ ${customized.length} pipeline prompt(s) are customized and cannot be auto-updated.\n` ++ ` Manually merge the new template variables into each file:\n` ++ customized.map(({ file, relDir, sampleDir: sd }) =>+ ` • ${relDir}/${file}\n` ++ ` Compare with: ${sd}/${file}`,+ ).join('\n') + '\n',+ );}diff --git a/server/lib/bibleExtractor.js b/server/lib/bibleExtractor.jsindex 78ede0521c..d8dac4e1ef 100644--- a/server/lib/bibleExtractor.js+++ b/server/lib/bibleExtractor.js@@ -6,13 +6,13 @@ import { sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, pickPromptFields } from './const KIND_STAGE = Object.freeze({[BIBLE_KIND.CHARACTER]: 'writers-room-characters',- [BIBLE_KIND.SETTING]: 'writers-room-places',+ [BIBLE_KIND.PLACE]: 'writers-room-places',[BIBLE_KIND.OBJECT]: 'writers-room-objects',});const EXISTING_VAR = Object.freeze({[BIBLE_KIND.CHARACTER]: 'existingCharactersJson',- [BIBLE_KIND.SETTING]: 'existingSettingsJson',+ [BIBLE_KIND.PLACE]: 'existingPlacesJson',[BIBLE_KIND.OBJECT]: 'existingObjectsJson',});diff --git a/server/lib/bibleExtractor.test.js b/server/lib/bibleExtractor.test.jsindex 921dfbeeea..e2922683ab 100644--- a/server/lib/bibleExtractor.test.js+++ b/server/lib/bibleExtractor.test.js@@ -75,13 +75,13 @@ describe('bibleExtractor — extractBible (characters)', () => {});});-describe('bibleExtractor — extractBible (settings + objects)', () => {- it('settings: pulls inner array, sanitizes via setting shape', async () => {+describe('bibleExtractor — extractBible (places + objects)', () => {+ it('places: pulls inner array, sanitizes via place shape', async () => {stageRunner.runStagedLLM.mockResolvedValue({- content: { settings: [{ slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: 'amber' }] },+ content: { places: [{ slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: 'amber' }] },runId: '', providerId: '', model: '',});- const out = await extractBible({ kind: 'setting', corpus: 'prose' });+ const out = await extractBible({ kind: 'place', corpus: 'prose' });expect(out.extracted).toHaveLength(1);expect(out.extracted[0].slugline).toBe('INT. BAR — NIGHT');expect(out.extracted[0].palette).toBe('amber');diff --git a/server/lib/canonPrompt.js b/server/lib/canonPrompt.jsindex 8d2ec3feac..dcec2b4578 100644--- a/server/lib/canonPrompt.js+++ b/server/lib/canonPrompt.js@@ -12,25 +12,25 @@* - `KINDS[].descFor` (client/src/components/universe/UniverseCanonSection.jsx) →* UI summary + handleRenderRef button-enable predicate (SHORT fields)* - `settingFrags` (server/lib/scenePrompt.js) → scene-prompt framing- * for settings (SHORT fields)+ * for places (SHORT fields)** SHORT vs RICH:* - SHORT = the visual descriptor subset shown in UI cards. For* chars/objects: single primary field with a single fallback (mirrors- * the legacy `descFor` `||` chain). For settings: description +- * palette + recurringDetails (the "setting baseline" from scenePrompt).+ * the legacy `descFor` `||` chain). For places: description ++ * palette + recurringDetails (the "place baseline" from scenePrompt).* - RICH = every descriptive field that contributes to a render prompt.- * Adds `role` (chars), `era`+`weather` (settings), additive+ * Adds `role` (chars), `era`+`weather` (places), additive* `significance` (objects).*/const trim = (s) => (typeof s === 'string' ? s.trim() : '');-// SHORT spec: chars/objects use single-with-fallback; settings uses a+// SHORT spec: chars/objects use single-with-fallback; places uses a// sequence so palette can carry its prefix.const SHORT_SPEC = Object.freeze({characters: Object.freeze({ primary: 'physicalDescription', fallback: 'description' }),- settings: Object.freeze({+ places: Object.freeze({sequence: Object.freeze([{ field: 'description' },{ field: 'palette', prefix: 'Palette' },@@ -47,7 +47,7 @@ const RICH_SPEC = Object.freeze({{ field: 'physicalDescription' },{ field: 'role' },]),- settings: Object.freeze([+ places: Object.freeze([{ field: 'description' },{ field: 'palette', prefix: 'Palette' },{ field: 'era', prefix: 'Era' },@@ -63,7 +63,7 @@ const RICH_SPEC = Object.freeze({function normalizeKind(kind) {const k = String(kind || '').toLowerCase();if (k === 'character' || k === 'characters') return 'characters';- if (k === 'setting' || k === 'settings') return 'settings';+ if (k === 'place' || k === 'places') return 'places';if (k === 'object' || k === 'objects') return 'objects';return null;}@@ -124,7 +124,7 @@ export function richCanonDescriptorFragments(kind, entry) {* Flatten SHORT fragments into a sentence-style descriptor string.* Matches the legacy `KINDS[].descFor` output:* characters: "physicalDescription" else "description"- * settings: "description. Palette: <palette>. recurringDetails"+ * places: "description. Palette: <palette>. recurringDetails"* objects: "description" else "significance"*/export function descriptorForCanonEntry(kind, entry) {diff --git a/server/lib/canonPrompt.test.js b/server/lib/canonPrompt.test.jsindex fbaedce9bb..68303da648 100644--- a/server/lib/canonPrompt.test.js+++ b/server/lib/canonPrompt.test.js@@ -56,9 +56,9 @@ describe('canonPrompt.js', () => {});});- describe('settings', () => {+ describe('places', () => {it('joins description + palette + recurringDetails in order', () => {- expect(descriptorForCanonEntry('settings', {+ expect(descriptorForCanonEntry('places', {description: 'a dusty plaza',palette: 'ochre and copper',recurringDetails: 'cracked statue at center',@@ -66,18 +66,18 @@ describe('canonPrompt.js', () => {});it('prefixes palette with "Palette:"', () => {- expect(descriptorForCanonEntry('settings', { palette: 'noir' })).toBe('Palette: noir');+ expect(descriptorForCanonEntry('places', { palette: 'noir' })).toBe('Palette: noir');});it('omits missing fields', () => {- expect(descriptorForCanonEntry('settings', {+ expect(descriptorForCanonEntry('places', {description: 'plaza',recurringDetails: 'statue',})).toBe('plaza. statue');});it('does NOT include era or weather (rich-only)', () => {- expect(descriptorForCanonEntry('settings', {+ expect(descriptorForCanonEntry('places', {description: 'plaza',era: '2099',weather: 'foggy',@@ -85,7 +85,7 @@ describe('canonPrompt.js', () => {});it('trims whitespace-only fields', () => {- expect(descriptorForCanonEntry('settings', {+ expect(descriptorForCanonEntry('places', {description: ' plaza ',palette: ' ',recurringDetails: 'statue',@@ -117,8 +117,8 @@ describe('canonPrompt.js', () => {expect(shortCanonDescriptorFragments('unknown', { description: 'x' })).toEqual([]);});- it('returns ordered fragments for settings', () => {- const frags = shortCanonDescriptorFragments('settings', {+ it('returns ordered fragments for places', () => {+ const frags = shortCanonDescriptorFragments('places', {description: 'plaza',palette: 'noir',recurringDetails: 'statue',@@ -153,8 +153,8 @@ describe('canonPrompt.js', () => {]);});- it('includes era and weather for settings', () => {- const frags = richCanonDescriptorFragments('settings', {+ it('includes era and weather for places', () => {+ const frags = richCanonDescriptorFragments('places', {description: 'plaza',palette: 'noir',era: '2099',@@ -190,14 +190,14 @@ describe('canonPrompt.js', () => {it('is true when any rich field is set', () => {expect(hasCanonDescriptorContent('characters', { physicalDescription: 'tall' })).toBe(true);expect(hasCanonDescriptorContent('characters', { role: 'protagonist' })).toBe(true);- expect(hasCanonDescriptorContent('settings', { palette: 'noir' })).toBe(true);- expect(hasCanonDescriptorContent('settings', { weather: 'foggy' })).toBe(true);+ expect(hasCanonDescriptorContent('places', { palette: 'noir' })).toBe(true);+ expect(hasCanonDescriptorContent('places', { weather: 'foggy' })).toBe(true);expect(hasCanonDescriptorContent('objects', { significance: 'x' })).toBe(true);});it('is false when no rich field is set', () => {expect(hasCanonDescriptorContent('characters', { name: 'Alice' })).toBe(false);- expect(hasCanonDescriptorContent('settings', { name: 'Plaza' })).toBe(false);+ expect(hasCanonDescriptorContent('places', { name: 'Plaza' })).toBe(false);expect(hasCanonDescriptorContent('objects', {})).toBe(false);});@@ -217,7 +217,7 @@ describe('canonPrompt.js', () => {// Sanity-check that adding extra blank fields after the first hit// doesn't change the result — guards against accidental regression// back to length-of-array-based implementation.- expect(hasCanonDescriptorContent('settings', {+ expect(hasCanonDescriptorContent('places', {description: 'plaza',palette: '',era: '',@@ -228,8 +228,8 @@ describe('canonPrompt.js', () => {});describe('richCanonDescriptorFragments edge cases', () => {- it('returns [] for empty settings entry', () => {- expect(richCanonDescriptorFragments('settings', {})).toEqual([]);+ it('returns [] for empty places entry', () => {+ expect(richCanonDescriptorFragments('places', {})).toEqual([]);});it('coerces non-string field values to empty (no fragment)', () => {diff --git a/server/lib/sceneExtractor.js b/server/lib/sceneExtractor.jsindex 4c6552381e..368dcd353a 100644--- a/server/lib/sceneExtractor.js+++ b/server/lib/sceneExtractor.js@@ -153,7 +153,7 @@ export function sanitizeSceneList(raw, { maxScenes = 200 } = {}) {* @param {string} args.source prose body OR teleplay markdown* @param {string} args.sourceKind 'prose' | 'teleplay'* @param {Array} [args.characters] bible entries (for deference)- * @param {Array} [args.settings] bible entries (for deference)+ * @param {Array} [args.places] bible entries (for deference)* @param {Array} [args.objects] bible entries (for deference)* @param {object} [args.work] variables consumed by writers-room-script (`work.title`, `work.kind`, `work.wordCount`)* @param {object} [args.series] variables consumed by pipeline-extract-scenes (`series.name`, `series.styleNotes`)@@ -166,7 +166,7 @@ export async function extractScenes({source,sourceKind = SOURCE_KIND.PROSE,characters = [],- settings = [],+ places = [],objects = [],work,series,@@ -182,14 +182,14 @@ export async function extractScenes({}// Both prompts read the same `existing<X>Json` envelope so the model can- // defer to canonical character/setting names instead of re-improvising.+ // defer to canonical character/place names instead of re-improvising.// Pipeline's series.characters and Writers Room's per-work characters both// sanitize through `pickPromptFields` to strip ids/timestamps/source/notes.const variables = {returnsJson: true,sourceKind,existingCharactersJson: JSON.stringify((characters || []).map((c) => pickPromptFields(BIBLE_KIND.CHARACTER, c))),- existingSettingsJson: JSON.stringify((settings || []).map((s) => pickPromptFields(BIBLE_KIND.SETTING, s))),+ existingPlacesJson: JSON.stringify((places || []).map((p) => pickPromptFields(BIBLE_KIND.PLACE, p))),existingObjectsJson: JSON.stringify((objects || []).map((o) => pickPromptFields(BIBLE_KIND.OBJECT, o))),};// Variable-shape compat: writers-room-script.md reads `{{draftBody}}` +diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.jsindex f3f6fbc432..efd5352bb8 100644--- a/server/lib/scenePrompt.js+++ b/server/lib/scenePrompt.js@@ -54,7 +54,7 @@ export function matchCharactersInText(text, allCharacters) {return matchEntriesByCandidates(text, allCharacters, (c) => [c.name, ...(c.aliases || [])]);}-export function buildSettingByKey(allSettings) {+export function buildPlaceByKey(allSettings) {const map = new Map();for (const setting of allSettings || []) {const key = normalizeSlugline(setting.slugline || setting.name);@@ -64,9 +64,9 @@ export function buildSettingByKey(allSettings) {return map;}-export function matchSceneSetting(sceneSlugline, settingByKey) {+export function matchScenePlace(sceneSlugline, placeByKey) {if (!sceneSlugline) return null;- return settingByKey?.get(normalizeSlugline(sceneSlugline)) || null;+ return placeByKey?.get(normalizeSlugline(sceneSlugline)) || null;}// Shared word-boundary scanner used by the *-InText helpers below. Returns@@ -93,11 +93,11 @@ function matchEntriesByCandidates(text, entries, candidatesFn) {return matched;}-// Scan free-form prose for bible-canonical settings. Mirrors-// `matchCharactersInText` but tests against `name` (settings have no aliases+// Scan free-form prose for bible-canonical places. Mirrors+// `matchCharactersInText` but tests against `name` (places have no aliases// in the canonical schema — slugline is for screenplay matching, not prose).-export function matchSettingsInText(text, allSettings) {- return matchEntriesByCandidates(text, allSettings, (s) => [s.name]);+export function matchPlacesInText(text, allPlaces) {+ return matchEntriesByCandidates(text, allPlaces, (p) => [p.name]);}// Scan free-form prose for bible-canonical objects. Mirrors@@ -124,7 +124,7 @@ export function matchObjectsInText(text, allObjects) {* Positional API kept for parity with the long-running Writers Room caller* (`SceneCard.jsx`) — adding new optional kwargs at the tail is fine.*/-export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedSetting = null) {+export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle = '', matchedPlace = null) {const stylePart = worldStyle && worldStyle.trim() ? `${worldStyle.trim()}. ` : '';const titlePart = workTitle ? `${workTitle}. ` : '';const visual = scene?.visualPrompt || scene?.description || '';@@ -132,15 +132,15 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle// INT/EXT + time-of-day claim the first setting slot — they're cheap// (≤30 chars combined) and load-bearing for lighting/composition cues// diffusion models actually weight.- const intExtPart = matchedSetting?.intExt === 'INT'+ const intExtPart = matchedPlace?.intExt === 'INT'? 'Interior'- : matchedSetting?.intExt === 'EXT'+ : matchedPlace?.intExt === 'EXT'? 'Exterior': '';- const todPart = typeof matchedSetting?.timeOfDay === 'string' && matchedSetting.timeOfDay- ? matchedSetting.timeOfDay+ const todPart = typeof matchedPlace?.timeOfDay === 'string' && matchedPlace.timeOfDay+ ? matchedPlace.timeOfDay: '';- const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');+ const placeMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');// Pull descriptor fragments via the shared canon-prompt helper so the// setting baseline shares the *SHORT* spec subset (description / Palette /// recurringDetails) with `KINDS[].descFor` (UI summary). Note:@@ -150,12 +150,12 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle// on prefixed fragments preserves the pre-extraction "Palette: X." sentence// boundary so palette + recurringDetails don't run together when the// budget-truncation join collapses fragments with a single space.- const baselineFrags = matchedSetting- ? shortCanonDescriptorFragments('setting', matchedSetting)+ const baselineFrags = matchedPlace+ ? shortCanonDescriptorFragments('place', matchedPlace).map((f) => (f.prefix ? `${f.prefix}: ${f.value}.` : f.value)): [];- const settingFrags = matchedSetting ? [- settingMetaFrag ? `${settingMetaFrag}.` : '',+ const placeFrags = matchedPlace ? [+ placeMetaFrag ? `${placeMetaFrag}.` : '',...baselineFrags,].filter(Boolean) : [];@@ -173,11 +173,11 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyle// Setting first claim on remaining budget (place baseline > characters// for visual continuity across scenes).- const settingFit = [];- for (const frag of settingFrags) {- const cost = (settingFit.length === 0 ? 0 : 1) + frag.length;+ const placeFit = [];+ for (const frag of placeFrags) {+ const cost = (placeFit.length === 0 ? 0 : 1) + frag.length;if (cost > budget) break;- settingFit.push(frag);+ placeFit.push(frag);budget -= cost;}@@ -194,7 +194,7 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyleconst segs = [];if (stylePart) segs.push(stylePart.trim());if (titlePart) segs.push(titlePart.trim());- if (settingFit.length > 0) segs.push(settingFit.join(' '));+ if (placeFit.length > 0) segs.push(placeFit.join(' '));if (charFit.length > 0) segs.push(`${PREFIX}${charFit.join(' ')}`);if (visual) segs.push(visual);return segs.filter(Boolean).join(' ').slice(0, PROMPT_MAX);diff --git a/server/lib/scenePrompt.test.js b/server/lib/scenePrompt.test.jsindex 95f2ed456b..b709ee2a3f 100644--- a/server/lib/scenePrompt.test.js+++ b/server/lib/scenePrompt.test.js@@ -4,8 +4,8 @@ import {normCharKey,buildCharByKey,matchSceneCharacters,- buildSettingByKey,- matchSceneSetting,+ buildPlaceByKey,+ matchScenePlace,buildScenePrompt,__testing,} from './scenePrompt.js';@@ -68,28 +68,28 @@ describe('scenePrompt — buildCharByKey + matchSceneCharacters', () => {});});-describe('scenePrompt — buildSettingByKey + matchSceneSetting', () => {+describe('scenePrompt — buildPlaceByKey + matchScenePlace', () => {const settings = [{ id: 's1', slugline: 'INT. KITCHEN — NIGHT', description: 'cramped tile', palette: 'amber' },{ id: 's2', name: 'EXT. ROOFTOP', slugline: '', description: 'wind-swept' },];it('keys by slugline (preferred) then name (fallback)', () => {- const map = buildSettingByKey(settings);+ const map = buildPlaceByKey(settings);expect(map.get(normalizeSlugline('INT. KITCHEN — NIGHT'))?.id).toBe('s1');expect(map.get(normalizeSlugline('EXT. ROOFTOP'))?.id).toBe('s2');});it('matches with em-dash / hyphen drift', () => {- const map = buildSettingByKey(settings);- expect(matchSceneSetting('INT KITCHEN - NIGHT', map)?.id).toBe('s1');- expect(matchSceneSetting('int kitchen — night', map)?.id).toBe('s1');+ const map = buildPlaceByKey(settings);+ expect(matchScenePlace('INT KITCHEN - NIGHT', map)?.id).toBe('s1');+ expect(matchScenePlace('int kitchen — night', map)?.id).toBe('s1');});it('returns null when slugline is empty or unmatched', () => {- const map = buildSettingByKey(settings);- expect(matchSceneSetting('', map)).toBeNull();- expect(matchSceneSetting('INT. SUBMARINE — DAWN', map)).toBeNull();+ const map = buildPlaceByKey(settings);+ expect(matchScenePlace('', map)).toBeNull();+ expect(matchScenePlace('INT. SUBMARINE — DAWN', map)).toBeNull();});});diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 75221a5d34..0ec5cc87dd 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -1,5 +1,5 @@/**- * Canonical story-bible shapes (Character / Setting / Object) shared by the+ * Canonical story-bible shapes (Character / Place / Object) shared by the* Writers Room (per-work bibles) and the Pipeline (per-series bibles).** Owns the shape + sanitization + merge-extracted-entries algorithm AND the@@ -14,7 +14,7 @@ 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.+// canonical normalizer when they need to match places by slugline.export { normalizeSlugline };export const BIBLE_LIMITS = Object.freeze({@@ -35,13 +35,13 @@ export const BIBLE_LIMITS = Object.freeze({WARDROBES_PER_CHARACTER_MAX: 10,EVIDENCE_ITEM_MAX: 500,EVIDENCE_PER_ENTRY_MAX: 20,- // Settings+ // PlacesSLUGLINE_MAX: 200,PALETTE_MAX: 200,ERA_MAX: 200,WEATHER_MAX: 200,RECURRING_DETAILS_MAX: 1000,- SETTING_DESCRIPTION_MAX: 2000,+ PLACE_DESCRIPTION_MAX: 2000,// ObjectsOBJECT_DESCRIPTION_MAX: 2000,SIGNIFICANCE_MAX: 1000,@@ -74,17 +74,17 @@ const SOURCES = new Set([export const BIBLE_KIND = Object.freeze({CHARACTER: 'character',- SETTING: 'setting',+ PLACE: 'place',OBJECT: 'object',});-// Enums for the location-classification fields on Setting canon entries.+// Enums for the location-classification fields on Place canon entries.// Mirrors AnyFilm's INT/EXT + time-of-day taxonomy so generated panels and// scene starts inherit lighting/composition cues for free.-export const SETTING_INT_EXT = Object.freeze(['INT', 'EXT']);-export const SETTING_TIME_OF_DAY = Object.freeze(['dawn', 'day', 'dusk', 'night']);-const SETTING_INT_EXT_SET = new Set(SETTING_INT_EXT);-const SETTING_TIME_OF_DAY_SET = new Set(SETTING_TIME_OF_DAY);+export const PLACE_INT_EXT = Object.freeze(['INT', 'EXT']);+export const PLACE_TIME_OF_DAY = Object.freeze(['dawn', 'day', 'dusk', 'night']);+const PLACE_INT_EXT_SET = new Set(PLACE_INT_EXT);+const PLACE_TIME_OF_DAY_SET = new Set(PLACE_TIME_OF_DAY);const trimEnum = (raw, allowed) => {if (typeof raw !== 'string') return null;@@ -101,7 +101,7 @@ const trimEnum = (raw, allowed) => {// extractor LLM envelope key — all the same string, consolidated here.export const BIBLE_FIELD = Object.freeze({[BIBLE_KIND.CHARACTER]: 'characters',- [BIBLE_KIND.SETTING]: 'settings',+ [BIBLE_KIND.PLACE]: 'places',[BIBLE_KIND.OBJECT]: 'objects',});@@ -119,7 +119,7 @@ export const BIBLE_KINDS = Object.freeze(Object.values(BIBLE_KIND));// stage's bibles context (evaluator). Excludes ids/timestamps/source/notes.export const PROMPT_FIELDS = Object.freeze({[BIBLE_KIND.CHARACTER]: ['name', 'aliases', 'role', 'physicalDescription', 'personality', 'background', 'voiceId', 'wardrobes', 'prompt', 'tags'],- [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],+ [BIBLE_KIND.PLACE]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],});@@ -131,12 +131,22 @@ export function pickPromptFields(kind, entry) {return out;}+// Pipeline retains the legacy `'set-'` id prefix for places so every+// pre-rename `set-<uuid>` id on disk still round-trips through the+// sanitizer without a per-record id-rewrite migration. The bible-domain+// SETTING→PLACE rename is terminology only — ids are opaque after+// creation, and changing the prefix would force a second migration over+// every persisted canon entry for zero functional gain. Named here so a+// future reader doesn't mistake `place: 'set-'` for a typo introduced by+// the rename and "fix" it (which would silently break id round-tripping).+const LEGACY_PLACE_ID_PREFIX = 'set-';+// Default id prefix per kind. Pipeline accepts these defaults; writers-room-// passes its own `wr-char-` / `wr-setting-` / `wr-object-` prefixes via the+// passes its own `wr-char-` / `wr-place-` / `wr-object-` prefixes via the// sanitizer options.const DEFAULT_ID_PREFIX = Object.freeze({character: 'chr-',- setting: 'set-',+ place: LEGACY_PLACE_ID_PREFIX,object: 'obj-',});@@ -177,7 +187,7 @@ export const normalizeBibleName = (name) => String(name || '').trim().toLowerCas/*** Case-insensitive lookup by `name` OR `aliases[]` (using* `normalizeBibleName`). Returns the first match or undefined; tolerates a- * non-array list, blank needle, and null entries. Settings use sluglines+ * non-array list, blank needle, and null entries. Places use sluglines* for their primary identity; use `normalizeSlugline` + a Map lookup for* those instead — this helper is name-keyed.*/@@ -315,11 +325,11 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,};}-export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, preserveTimestamps = true } = {}) {+export function sanitizePlace(raw, { idPrefix = DEFAULT_ID_PREFIX.place, preserveTimestamps = true } = {}) {if (!raw || typeof raw !== 'object') return null;const name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);const slugline = trimTo(raw.slugline, BIBLE_LIMITS.SLUGLINE_MAX);- // A setting needs at least one identifier (name OR slugline). Without+ // A place needs at least one identifier (name OR slugline). Without// either there's nothing for a scene matcher to key on.if (!name && !slugline) return null;const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();@@ -328,15 +338,15 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, preid: ensureId(raw.id, idPrefix),name,slugline,- description: trimTo(raw.description, BIBLE_LIMITS.SETTING_DESCRIPTION_MAX),+ description: trimTo(raw.description, BIBLE_LIMITS.PLACE_DESCRIPTION_MAX),palette: trimTo(raw.palette, BIBLE_LIMITS.PALETTE_MAX),era: trimTo(raw.era, BIBLE_LIMITS.ERA_MAX),weather: trimTo(raw.weather, BIBLE_LIMITS.WEATHER_MAX),// INT/EXT + time-of-day enums (Cluster A). null when unset — scene-prompt- // composer skips the metadata fragment in that case so legacy settings+ // composer skips the metadata fragment in that case so legacy places// keep rendering with description-only prompts.- intExt: trimEnum(raw.intExt, SETTING_INT_EXT_SET),- timeOfDay: trimEnum(raw.timeOfDay, SETTING_TIME_OF_DAY_SET),+ intExt: trimEnum(raw.intExt, PLACE_INT_EXT_SET),+ timeOfDay: trimEnum(raw.timeOfDay, PLACE_TIME_OF_DAY_SET),recurringDetails: trimTo(raw.recurringDetails, BIBLE_LIMITS.RECURRING_DETAILS_MAX),notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),imageRefs,@@ -394,7 +404,7 @@ export function sanitizeBibleList(rawList, kind, opts = {}) {const SANITIZERS = Object.freeze({character: sanitizeCharacter,- setting: sanitizeSetting,+ place: sanitizePlace,object: sanitizeObject,});@@ -413,7 +423,7 @@ const MERGE_CONFIG = Object.freeze({{ field: 'aliases', normalize: normalizeBibleName },],},- setting: {+ place: {userEditable: ['description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails'],keyFields: [{ field: 'slugline', normalize: normalizeSlugline },@@ -461,20 +471,20 @@ function lookupExisting(map, incoming, keyFields) {return null;}-// Sort key per kind. Settings can legitimately have an empty `name` while+// Sort key per kind. Places can legitimately have an empty `name` while// `slugline` is the primary identifier (scene-matcher keys on it), so a// pure name-sort drifts all slugline-only entries to the top of the list-// AND diverges from `writersRoom/settings.js#listSettings` which uses+// AND diverges from `writersRoom/places.js#listPlaces` which uses// `slugline || name`. Characters / objects always have a name; key on it.const sortKey = (kind) => (entry) => {- if (kind === BIBLE_KIND.SETTING) return (entry.slugline || entry.name || '').toLowerCase();+ if (kind === BIBLE_KIND.PLACE) return (entry.slugline || entry.name || '').toLowerCase();return (entry.name || '').toLowerCase();};/*** Merge AI-extracted entries into a bible array. Mutates and returns* `existing`, sorted by the kind-specific key (`slugline || name` for- * settings, `name` for characters/objects — matches the per-kind list+ * places, `name` for characters/objects — matches the per-kind list* helpers so callers don't observe an ordering flip after a merge).* Per-kind rules in `MERGE_CONFIG`:* - match by case-insensitive name/alias/slugline@@ -583,14 +593,14 @@ export function mergeExtractedBible(existing, incoming, kind, {/*** createBibleStore — per-work CRUD + merge factory. Collapses the three- * writers-room domain files (characters/settings/objects) onto one+ * writers-room domain files (characters/places/objects) onto one* implementation. `remove` (not `delete`) because the latter is a JS keyword.*/const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;const ID_SUFFIX_RE = /^[0-9a-f-]+$/i;-const FILE_NAME = Object.freeze({ character: 'characters.json', setting: 'settings.json', object: 'objects.json' });-const LIST_KEY = Object.freeze({ character: 'characters', setting: 'settings', object: 'objects' });+const FILE_NAME = Object.freeze({ character: 'characters.json', place: 'places.json', object: 'objects.json' });+const LIST_KEY = Object.freeze({ character: 'characters', place: 'places', object: 'objects' });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) => {@@ -656,8 +666,8 @@ export function createBibleStore(opts) {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).+ // Places: if both name and slugline are primary, missing name + present+ // slugline → mirror slugline → name (preserves old createPlace behavior).if (primaryFields.includes('name') && primaryFields.includes('slugline') && !draft.name && draft.slugline) {draft.name = draft.slugline;}@@ -674,7 +684,7 @@ export function createBibleStore(opts) {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+ // places allow blanks here and rely on validateAfterUpdate for the// combined-blank invariant.for (const field of primaryFields) {if (patch[field] === undefined) continue;diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex c10bfd9e47..55d96436c3 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -17,7 +17,7 @@ vi.mock('./fileUtils.js', async () => {const storyBible = await import('./storyBible.js');const {sanitizeCharacter,- sanitizeSetting,+ sanitizePlace,sanitizeObject,sanitizeBibleList,mergeExtractedBible,@@ -136,7 +136,7 @@ describe('storyBible — sanitizeCharacter', () => {});it('extras apply identically to settings + objects', () => {- const s = sanitizeSetting({ name: 'Bubble Room', tags: ['indoor'], prompt: 'pastel lab', locked: true });+ const s = sanitizePlace({ name: 'Bubble Room', tags: ['indoor'], prompt: 'pastel lab', locked: true });expect(s.tags).toEqual(['indoor']);expect(s.prompt).toBe('pastel lab');expect(s.locked).toBe(true);@@ -176,7 +176,7 @@ describe('storyBible — sanitizeCharacter', () => {});it('applies identically to settings and objects', () => {- const s = sanitizeSetting({+ const s = sanitizePlace({name: 'Bar',imageRefs: ['plate.png'],primaryImageRef: 'plate.png',@@ -259,15 +259,15 @@ describe('storyBible — sanitizeCharacter', () => {});});-describe('storyBible — sanitizeSetting', () => {+describe('storyBible — sanitizePlace', () => {it('requires either name or slugline', () => {- expect(sanitizeSetting({ description: 'x' })).toBeNull();- expect(sanitizeSetting({ name: 'A bar' }).name).toBe('A bar');- expect(sanitizeSetting({ slugline: 'INT. BAR — NIGHT' }).slugline).toBe('INT. BAR — NIGHT');+ expect(sanitizePlace({ description: 'x' })).toBeNull();+ expect(sanitizePlace({ name: 'A bar' }).name).toBe('A bar');+ expect(sanitizePlace({ slugline: 'INT. BAR — NIGHT' }).slugline).toBe('INT. BAR — NIGHT');});it('preserves all fields and caps lengths', () => {- const out = sanitizeSetting({+ const out = sanitizePlace({slugline: 'INT. BAR — NIGHT',name: 'The Foundry',description: 'cramped chrome bar',@@ -285,25 +285,25 @@ describe('storyBible — sanitizeSetting', () => {describe('intExt + timeOfDay (Cluster A)', () => {it('persists valid enums', () => {- const out = sanitizeSetting({ name: 'Bar', intExt: 'INT', timeOfDay: 'night' });+ const out = sanitizePlace({ name: 'Bar', intExt: 'INT', timeOfDay: 'night' });expect(out.intExt).toBe('INT');expect(out.timeOfDay).toBe('night');});it('normalizes case on both fields', () => {- const out = sanitizeSetting({ name: 'Bar', intExt: 'ext', timeOfDay: 'DUSK' });+ const out = sanitizePlace({ name: 'Bar', intExt: 'ext', timeOfDay: 'DUSK' });expect(out.intExt).toBe('EXT');expect(out.timeOfDay).toBe('dusk');});it('drops invalid enum values to null instead of throwing', () => {- const out = sanitizeSetting({ name: 'Bar', intExt: 'underwater', timeOfDay: 'midnight-snack' });+ const out = sanitizePlace({ name: 'Bar', intExt: 'underwater', timeOfDay: 'midnight-snack' });expect(out.intExt).toBeNull();expect(out.timeOfDay).toBeNull();});it('treats missing/empty as null (legacy settings)', () => {- const out = sanitizeSetting({ name: 'Bar' });+ const out = sanitizePlace({ name: 'Bar' });expect(out.intExt).toBeNull();expect(out.timeOfDay).toBeNull();});@@ -457,36 +457,36 @@ describe('storyBible — mergeExtractedBible (characters)', () => {});});-describe('storyBible — mergeExtractedBible (settings)', () => {+describe('storyBible — mergeExtractedBible (places)', () => {it('matches by slugline, fills blank fields only', () => {- const existing = [sanitizeSetting({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: '', recurringDetails: '' })];+ const existing = [sanitizePlace({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped chrome bar', palette: '', recurringDetails: '' })];const merged = mergeExtractedBible(existing, [{ slugline: 'INT. BAR — NIGHT', description: 'overwrite attempt', palette: 'amber', recurringDetails: 'jukebox' },- ], 'setting');+ ], 'place');expect(merged[0].description).toBe('cramped chrome bar'); // user winsexpect(merged[0].palette).toBe('amber');expect(merged[0].recurringDetails).toBe('jukebox');});it('matches with em-dash / hyphen drift on the slugline', () => {- const existing = [sanitizeSetting({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped' })];- const merged = mergeExtractedBible(existing, [{ slugline: 'INT BAR - NIGHT', recurringDetails: 'jukebox' }], 'setting');+ const existing = [sanitizePlace({ id: 's1', slugline: 'INT. BAR — NIGHT', description: 'cramped' })];+ const merged = mergeExtractedBible(existing, [{ slugline: 'INT BAR - NIGHT', recurringDetails: 'jukebox' }], 'place');expect(merged.length).toBe(1);expect(merged[0].recurringDetails).toBe('jukebox');});- // Settings can legitimately have an empty `name` (slugline is the primary+ // Places can legitimately have an empty `name` (slugline is the primary// identifier). Sorting by `name` would float every slugline-only entry to- // the top AND diverge from `writersRoom/settings.js#listSettings`'s+ // the top AND diverge from `writersRoom/places.js#listPlaces`'s// `slugline || name` order. Keep the merge sort kind-aware so the API is// consistent and callers don't observe an ordering flip after a merge.- it('sorts settings by slugline (or name as fallback), not by name alone', () => {+ it('sorts places by slugline (or name as fallback), not by name alone', () => {const existing = [- sanitizeSetting({ id: 's1', slugline: 'INT. ZINC FOUNDRY — NIGHT' }),- sanitizeSetting({ id: 's2', name: 'Alpha Lab' }), // name-only- sanitizeSetting({ id: 's3', slugline: 'EXT. BEACH — DAWN' }),+ sanitizePlace({ id: 's1', slugline: 'INT. ZINC FOUNDRY — NIGHT' }),+ sanitizePlace({ id: 's2', name: 'Alpha Lab' }), // name-only+ sanitizePlace({ id: 's3', slugline: 'EXT. BEACH — DAWN' }),];- const merged = mergeExtractedBible(existing, [], 'setting');+ const merged = mergeExtractedBible(existing, [], 'place');// Keys (slugline || name) → 'alpha lab', 'ext. beach — dawn', 'int. zinc foundry — night'expect(merged.map((e) => e.slugline || e.name)).toEqual(['Alpha Lab',@@ -592,8 +592,8 @@ function characterStore() {function settingStore() {return createBibleStore({- kind: BIBLE_KIND.SETTING,- idPrefix: 'wr-setting-',+ kind: BIBLE_KIND.PLACE,+ idPrefix: 'wr-place-',dedupKey: (entry) => normalizeSlugline(entry?.slugline || entry?.name || ''),primaryFields: ['slugline', 'name'],editableFields: ['description', 'palette'],diff --git a/server/lib/universePromptRenderers.js b/server/lib/universePromptRenderers.jsindex 8162b7da95..e246c61222 100644--- a/server/lib/universePromptRenderers.js+++ b/server/lib/universePromptRenderers.js@@ -70,13 +70,13 @@ const formatCharacter = (c) => {// Place: prefer name; show slugline when present (screenplay-style location// header used by scene matchers); include recurringDetails — the expand// contract collects all three and the LLM uses them as continuity anchors.-const formatSetting = (s) => {- const label = s.name || s.slugline || '(unnamed)';- const sluglineTag = s.name && s.slugline ? ` (${s.slugline})` : '';- const palette = s.palette ? ` palette: ${s.palette}` : '';+const formatPlace = (p) => {+ const label = p.name || p.slugline || '(unnamed)';+ const sluglineTag = p.name && p.slugline ? ` (${p.slugline})` : '';+ const palette = p.palette ? ` palette: ${p.palette}` : '';const parts = [- truncDesc(s.description || ''),- s.recurringDetails ? `recurring: ${truncDesc(s.recurringDetails)}` : '',+ truncDesc(p.description || ''),+ p.recurringDetails ? `recurring: ${truncDesc(p.recurringDetails)}` : '',].filter(Boolean);const body = parts.length ? `: ${parts.join('. ')}` : '';return ` - ${label}${sluglineTag}${body}${palette}`;@@ -90,11 +90,11 @@ const formatObject = (o) => {const CANON_SECTIONS = [{ field: 'characters', header: 'characters', formatEntry: formatCharacter },- { field: 'settings', header: 'places', formatEntry: formatSetting },+ { field: 'places', header: 'places', formatEntry: formatPlace },{ field: 'objects', header: 'objects', formatEntry: formatObject },];-// Render the universe's canon arrays (characters/settings/objects) into a+// Render the universe's canon arrays (characters/places/objects) into a// prompt-friendly text block. Distinct from renderCategoriesForPrompt because// canon entries are first-class named entities with rich metadata, not// exploratory variations — the arc planner references them by name.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 84c93bac48..af13e211d9 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -666,18 +666,18 @@ export const writersRoomCharacterUpdateSchema = z.object({wardrobes: wrWardrobeField.optional(),}).strict();-const wrSettingTextField = z.string().max(2000);+const wrPlaceTextField = z.string().max(2000);// Inner ZodObject (without refine) — exposed so the Pipeline can `.extend()`// it; `.refine()` returns a ZodEffects which has no `.extend()`.-const writersRoomSettingCreateObject = z.object({+const writersRoomPlaceCreateObject = z.object({name: z.string().trim().max(200).optional(),slugline: z.string().trim().max(200).optional(),- description: wrSettingTextField.optional(),- palette: wrSettingTextField.optional(),- era: wrSettingTextField.optional(),- weather: wrSettingTextField.optional(),- recurringDetails: wrSettingTextField.optional(),- notes: wrSettingTextField.optional(),+ description: wrPlaceTextField.optional(),+ palette: wrPlaceTextField.optional(),+ era: wrPlaceTextField.optional(),+ weather: wrPlaceTextField.optional(),+ recurringDetails: wrPlaceTextField.optional(),+ notes: wrPlaceTextField.optional(),// Cluster A — INT/EXT + time-of-day taxonomy. Case-insensitive accept// mirrors the sanitizer (`INT`/`int` both normalize to `INT`).intExt: z.preprocess(@@ -689,21 +689,21 @@ const writersRoomSettingCreateObject = z.object({z.enum(['dawn', 'day', 'dusk', 'night']),).nullable().optional(),}).strict();-const settingHasIdentifier = (v) =>+const placeHasIdentifier = (v) =>(v.name && v.name.trim()) || (v.slugline && v.slugline.trim());-export const writersRoomSettingCreateSchema = writersRoomSettingCreateObject.refine(- settingHasIdentifier,- { message: 'Setting requires either a slugline or a name' },+export const writersRoomPlaceCreateSchema = writersRoomPlaceCreateObject.refine(+ placeHasIdentifier,+ { message: 'Place requires either a slugline or a name' },);-export const writersRoomSettingUpdateSchema = z.object({+export const writersRoomPlaceUpdateSchema = z.object({name: z.string().trim().max(200).optional(),slugline: z.string().trim().max(200).optional(),- description: wrSettingTextField.optional(),- palette: wrSettingTextField.optional(),- era: wrSettingTextField.optional(),- weather: wrSettingTextField.optional(),- recurringDetails: wrSettingTextField.optional(),- notes: wrSettingTextField.optional(),+ description: wrPlaceTextField.optional(),+ palette: wrPlaceTextField.optional(),+ era: wrPlaceTextField.optional(),+ weather: wrPlaceTextField.optional(),+ recurringDetails: wrPlaceTextField.optional(),+ notes: wrPlaceTextField.optional(),// Cluster A — INT/EXT + time-of-day taxonomy. Case-insensitive accept// mirrors the sanitizer (`INT`/`int` both normalize to `INT`).intExt: z.preprocess(@@ -735,12 +735,12 @@ export const writersRoomObjectUpdateSchema = z.object({// Generic bible-entry schemas — re-exports of the writers-room schemas under// kind-neutral names so the Pipeline routes share the same validation// surface and funnel through the canonical sanitizer in storyBible.js.-// `settingBibleCreateSchema` is the un-refined ZodObject (not the refined-// `writersRoomSettingCreateSchema`) so Pipeline can `.extend()` it.+// `placeBibleCreateSchema` is the un-refined ZodObject (not the refined+// `writersRoomPlaceCreateSchema`) so Pipeline can `.extend()` it.export const characterBibleCreateSchema = writersRoomCharacterCreateSchema;export const characterBibleUpdateSchema = writersRoomCharacterUpdateSchema;-export const settingBibleCreateSchema = writersRoomSettingCreateObject;-export const settingBibleUpdateSchema = writersRoomSettingUpdateSchema;+export const placeBibleCreateSchema = writersRoomPlaceCreateObject;+export const placeBibleUpdateSchema = writersRoomPlaceUpdateSchema;export const objectBibleCreateSchema = writersRoomObjectCreateSchema;export const objectBibleUpdateSchema = writersRoomObjectUpdateSchema;diff --git a/server/lib/writersRoomPresets.js b/server/lib/writersRoomPresets.jsindex cb62dae5ec..e10a10d32f 100644--- a/server/lib/writersRoomPresets.js+++ b/server/lib/writersRoomPresets.js@@ -5,4 +5,4 @@export const WORK_KINDS = ['novel', 'short-story', 'screenplay', 'essay', 'treatment', 'other'];export const WORK_STATUSES = ['idea', 'drafting', 'revision', 'adaptation', 'rendering', 'complete', 'archived'];export const EXERCISE_STATUSES = ['running', 'finished', 'discarded'];-export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters', 'settings', 'objects'];+export const ANALYSIS_KINDS = ['evaluate', 'format', 'script', 'characters', 'places', 'objects'];diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 068e3847d3..a043c9c8de 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -109,7 +109,7 @@ const mapServiceError = (err) => {// ---- Series schemas ----//-// Canon (characters / settings / objects) is no longer carried on a series+// Canon (characters / places / objects) is no longer carried on a series// payload — it lives on the linked universe (Phase B.4). The bible-entry// Zod shapes (`characterSchema` et al.) and the `BIBLE_KIND` plumbing moved// out of this file when the series-side canon routes were retired.@@ -328,7 +328,7 @@ const generateSchema = z.object({const visualGenerateSchema = z.object({description: z.string().trim().min(1).max(8000),- // Matched against the series settings bible when present.+ // Matched against the series places bible when present.slugline: z.string().trim().max(200).optional(),negativePrompt: z.string().trim().max(2000).optional(),extraStyle: z.string().trim().max(2000).optional(),@@ -980,7 +980,7 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asynif (extractRes) {bibleExtracted = {characters: extractRes.results.characters?.extracted?.length || 0,- settings: extractRes.results.settings?.extracted?.length || 0,+ places: extractRes.results.places?.extracted?.length || 0,objects: extractRes.results.objects?.extracted?.length || 0,universe: extractRes.universe,};@@ -1251,13 +1251,13 @@ router.post('/issues/:id/stages/storyboards/extract-scenes', asyncHandler(async// provider/model picked in the issue header (which mirrors series.llm).// Canon lives on the linked universe (Phase B.4). Orphan series render// with empty canon — extractScenes can still produce scenes from the- // source text alone, just without character/setting/object grounding.+ // source text alone, just without character/place/object grounding.const canon = await getSeriesCanon(series);const result = await extractScenes({source,sourceKind,characters: canon.characters,- settings: canon.settings,+ places: canon.places,objects: canon.objects,work: { title: issue.title, kind: 'tv-episode' },series: { name: series.name, styleNotes: series.styleNotes },diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 1283059264..03ecd26cad 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -6,7 +6,7 @@* GET /api/universe-builder/:id → Universe* PATCH /api/universe-builder/:id → Universe* DELETE /api/universe-builder/:id → { id }- * POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, settings, objects, llm }+ * POST /api/universe-builder/expand → { logline, premise, styleNotes, influences, categories, compositeSheets, characters, places, objects, llm }* POST /api/universe-builder/:id/render → { runId, collectionId, jobIds, promptCount }* GET /api/universe-builder/:id/runs → Run[]*/@@ -62,7 +62,7 @@ const compositeSheetSchema = z.object({const categoryShape = z.object({// Tags this bucket to one of the 3 canon trunks (or 'other' as the// un-classified sink). Optional on input — sanitizeCategories resolves a- // sensible default from the built-in map (landscapes→settings etc.) or+ // sensible default from the built-in map (landscapes→places etc.) or// falls to 'other'. Added in schema v4.kind: z.enum(svc.CATEGORY_KINDS).optional(),variations: z.array(variationSchema).max(svc.VARIATIONS_PER_CATEGORY_MAX),@@ -131,7 +131,7 @@ const createSchema = z.object({// import, and tests can seed a universe with canon at create time instead// of needing a second PATCH round-trip.characters: canonArrayField,- settings: canonArrayField,+ places: canonArrayField,objects: canonArrayField,});// `origin` is a share-bucket provenance block written by the importer + cleared@@ -159,7 +159,7 @@ const patchSchema = z.object({// patch (PATCHABLE_SCALARS in services/universeBuilder.js reads them// from the post-Zod body, so they'd never reach the writer).characters: canonArrayField,- settings: canonArrayField,+ places: canonArrayField,objects: canonArrayField,origin: originField,}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });@@ -264,9 +264,9 @@ const selectionSchema = z.record(// tab can target an entry the user filed by slugline ("INT. FOUNDRY — DAY").// Per-trunk cap mirrors the bible sanitizer (`ENTRIES_PER_BIBLE_MAX`) so this// can't enqueue more entries than the server actually persists; per-string cap-// uses the looser of `NAME_MAX` / `SLUGLINE_MAX` so a settings entry filed by+// uses the looser of `NAME_MAX` / `SLUGLINE_MAX` so a places entry filed by// slugline isn't rejected if those limits ever diverge (both 200 today).-const CANON_TRUNK_KEYS = ['characters', 'settings', 'objects'];+const CANON_TRUNK_KEYS = ['characters', 'places', 'objects'];const CANON_NEEDLE_MAX = Math.max(BIBLE_LIMITS.NAME_MAX, BIBLE_LIMITS.SLUGLINE_MAX);const canonSelectionValueSchema = z.union([z.literal('all'),diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex d4cf63e41d..3d5f5df489 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -23,7 +23,7 @@ vi.mock('crypto', async () => {// Default mock just echoes back a minimal canon entry shape so the route// returns 200 and the schema/validation paths get exercised end-to-end.const promoteVariationToCanonMock = vi.fn(async (_universeId, body = {}) => ({- universe: { id: _universeId, characters: [], settings: [], objects: [] },+ universe: { id: _universeId, characters: [], places: [], objects: [] },entry: { id: 'mock-entry', name: body.label },targetKind: body.targetKind || 'characters',removed: { category: body.category, label: body.label },@@ -45,7 +45,7 @@ vi.mock('../services/universeBuilderPromote.js', async () => {// exercised without shelling out to a real LLM.const autoSortOtherBucketsMock = vi.fn(async (universeId, body = {}) => ({universe: { id: universeId, categories: {} },- results: [{ sourceKey: 'colonies', kind: 'settings', suggestedKey: null }],+ results: [{ sourceKey: 'colonies', kind: 'places', suggestedKey: null }],llm: { provider: 'mock', model: body.model || null },runId: 'mock-autosort-run',}));@@ -174,7 +174,7 @@ describe('universe-builder routes', () => {expect(Object.keys(res.body.categories).sort()).toEqual(['environments', 'landscapes', 'structures', 'vehicles'],);- expect(res.body.categories.landscapes.kind).toBe('settings');+ expect(res.body.categories.landscapes.kind).toBe('places');expect(res.body.categories.vehicles.kind).toBe('objects');});@@ -185,12 +185,12 @@ describe('universe-builder routes', () => {name: 'Kinded',categories: {factions: { kind: 'characters', variations: [{ label: 'Iron Reach', prompt: 'x' }] },- colonies: { kind: 'settings', variations: [{ label: 'Tycho', prompt: 'y' }] },+ colonies: { kind: 'places', variations: [{ label: 'Tycho', prompt: 'y' }] },},});expect(res.status).toBe(201);expect(res.body.categories.factions.kind).toBe('characters');- expect(res.body.categories.colonies.kind).toBe('settings');+ expect(res.body.categories.colonies.kind).toBe('places');});it('POST / rejects an invalid `kind` enum value via Zod', async () => {@@ -339,15 +339,15 @@ describe('universe-builder routes', () => {.patch(`/api/universe-builder/${c.body.id}`).send({characters: [{ name: 'Jean', physicalDescription: 'tall, dark hair' }],- settings: [{ slugline: 'INT. BAR — NIGHT', intExt: 'INT', timeOfDay: 'night' }],+ places: [{ slugline: 'INT. BAR — NIGHT', intExt: 'INT', timeOfDay: 'night' }],objects: [{ name: 'Gold pocket watch', description: 'tarnished brass casing' }],});expect(res.status).toBe(200);expect(res.body.characters).toHaveLength(1);expect(res.body.characters[0].name).toBe('Jean');- expect(res.body.settings).toHaveLength(1);- expect(res.body.settings[0].intExt).toBe('INT');- expect(res.body.settings[0].timeOfDay).toBe('night');+ expect(res.body.places).toHaveLength(1);+ expect(res.body.places[0].intExt).toBe('INT');+ expect(res.body.places[0].timeOfDay).toBe('night');expect(res.body.objects).toHaveLength(1);expect(res.body.objects[0].name).toBe('Gold pocket watch');});@@ -622,7 +622,7 @@ describe('universe-builder routes', () => {providerId: 'p1',model: 'm1',}));- expect(res.body.results[0].kind).toBe('settings');+ expect(res.body.results[0].kind).toBe('places');expect(res.body.runId).toBe('mock-autosort-run');});diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.jsindex be7f3a66e1..80bf0f72c9 100644--- a/server/routes/writersRoom.js+++ b/server/routes/writersRoom.js@@ -18,8 +18,8 @@ import {writersRoomAnalysisCreateSchema,writersRoomCharacterCreateSchema,writersRoomCharacterUpdateSchema,- writersRoomSettingCreateSchema,- writersRoomSettingUpdateSchema,+ writersRoomPlaceCreateSchema,+ writersRoomPlaceUpdateSchema,writersRoomObjectCreateSchema,writersRoomObjectUpdateSchema,} from '../lib/validation.js';@@ -37,8 +37,8 @@ import {listCharacters, createCharacter, updateCharacter, deleteCharacter,} from '../services/writersRoom/characters.js';import {- listSettings, createSetting, updateSetting, deleteSetting,-} from '../services/writersRoom/settings.js';+ listPlaces, createPlace, updatePlace, deletePlace,+} from '../services/writersRoom/places.js';import {listObjects, createObject, updateObject, deleteObject,} from '../services/writersRoom/objects.js';@@ -194,24 +194,24 @@ router.delete('/works/:id/characters/:characterId', asyncHandler(async (req, resres.json(await deleteCharacter(req.params.id, req.params.characterId));}));-// ---------- settings (locations / universe bible) ----------+// ---------- places (locations / universe bible) -----------router.get('/works/:id/settings', asyncHandler(async (req, res) => {- res.json(await listSettings(req.params.id));+router.get('/works/:id/places', asyncHandler(async (req, res) => {+ res.json(await listPlaces(req.params.id));}));-router.post('/works/:id/settings', asyncHandler(async (req, res) => {- const data = validateRequest(writersRoomSettingCreateSchema, req.body || {});- res.status(201).json(await createSetting(req.params.id, data));+router.post('/works/:id/places', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomPlaceCreateSchema, req.body || {});+ res.status(201).json(await createPlace(req.params.id, data));}));-router.patch('/works/:id/settings/:settingId', asyncHandler(async (req, res) => {- const data = validateRequest(writersRoomSettingUpdateSchema, req.body || {});- res.json(await updateSetting(req.params.id, req.params.settingId, data));+router.patch('/works/:id/places/:placeId', asyncHandler(async (req, res) => {+ const data = validateRequest(writersRoomPlaceUpdateSchema, req.body || {});+ res.json(await updatePlace(req.params.id, req.params.placeId, data));}));-router.delete('/works/:id/settings/:settingId', asyncHandler(async (req, res) => {- res.json(await deleteSetting(req.params.id, req.params.settingId));+router.delete('/works/:id/places/:placeId', asyncHandler(async (req, res) => {+ res.json(await deletePlace(req.params.id, req.params.placeId));}));// ---------- objects (recurring symbolic items) ----------diff --git a/server/routes/writersRoom.test.js b/server/routes/writersRoom.test.jsindex ff794a39a2..57a6305e0c 100644--- a/server/routes/writersRoom.test.js+++ b/server/routes/writersRoom.test.js@@ -30,11 +30,11 @@ vi.mock('../services/writersRoom/characters.js', () => ({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/places.js', () => ({+ listPlaces: vi.fn(async () => [{ id: 'wr-place-1', slugline: 'INT. KITCHEN — NIGHT' }]),+ createPlace: vi.fn(async (workId, data) => ({ id: 'wr-place-new', ...data })),+ updatePlace: vi.fn(async (workId, placeId, data) => ({ id: placeId, ...data })),+ deletePlace: vi.fn(async () => ({ ok: true })),}));vi.mock('../services/writersRoom/evaluator.js', () => ({@@ -56,7 +56,7 @@ vi.mock('../services/writersRoom/promoteToPipeline.js', () => ({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 * as placesSvc from '../services/writersRoom/places.js';import writersRoomRoutes from './writersRoom.js';describe('writersRoom routes', () => {@@ -237,50 +237,50 @@ describe('writersRoom routes', () => {});});- 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');+ describe('places', () => {+ it('GET /works/:id/places returns the bible', async () => {+ const r = await request(app).get('/api/writers-room/works/wr-work-1/places');expect(r.status).toBe(200);- expect(r.body[0].id).toBe('wr-setting-1');- expect(settingsSvc.listSettings).toHaveBeenCalledWith('wr-work-1');+ expect(r.body[0].id).toBe('wr-place-1');+ expect(placesSvc.listPlaces).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({});+ it('POST /works/:id/places rejects payload missing both slugline and name', async () => {+ const r = await request(app).post('/api/writers-room/works/wr-work-1/places').send({});expect(r.status).toBe(400);- expect(settingsSvc.createSetting).not.toHaveBeenCalled();+ expect(placesSvc.createPlace).not.toHaveBeenCalled();});- it('POST /works/:id/settings accepts slugline-only payload', async () => {+ it('POST /works/:id/places accepts slugline-only payload', async () => {const r = await request(app)- .post('/api/writers-room/works/wr-work-1/settings')+ .post('/api/writers-room/works/wr-work-1/places').send({ slugline: 'INT. KITCHEN — NIGHT', description: 'cozy' });expect(r.status).toBe(201);- expect(settingsSvc.createSetting).toHaveBeenCalledWith('wr-work-1', {+ expect(placesSvc.createPlace).toHaveBeenCalledWith('wr-work-1', {slugline: 'INT. KITCHEN — NIGHT',description: 'cozy',});});- it('POST /works/:id/settings rejects unknown extra fields', async () => {+ it('POST /works/:id/places rejects unknown extra fields', async () => {const r = await request(app)- .post('/api/writers-room/works/wr-work-1/settings')+ .post('/api/writers-room/works/wr-work-1/places').send({ slugline: 'INT. ATTIC — DUSK', tags: ['a'] });expect(r.status).toBe(400);});- it('PATCH /works/:id/settings/:settingId forwards a partial update', async () => {+ it('PATCH /works/:id/places/:placeId forwards a partial update', async () => {const r = await request(app)- .patch('/api/writers-room/works/wr-work-1/settings/wr-setting-1')+ .patch('/api/writers-room/works/wr-work-1/places/wr-place-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' });+ expect(placesSvc.updatePlace).toHaveBeenCalledWith('wr-work-1', 'wr-place-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');+ it('DELETE /works/:id/places/:placeId forwards to the service', async () => {+ const r = await request(app).delete('/api/writers-room/works/wr-work-1/places/wr-place-1');expect(r.status).toBe(200);- expect(settingsSvc.deleteSetting).toHaveBeenCalledWith('wr-work-1', 'wr-setting-1');+ expect(placesSvc.deletePlace).toHaveBeenCalledWith('wr-work-1', 'wr-place-1');});});diff --git a/server/services/canonUsage.js b/server/services/canonUsage.jsindex eba4689027..a09f371bc7 100644--- a/server/services/canonUsage.js+++ b/server/services/canonUsage.js@@ -8,13 +8,13 @@ import { getUniverse, ERR_NOT_FOUND } from './universeBuilder.js';import { listSeries } from './pipeline/series.js';import { listIssues } from './pipeline/issues.js';import {- matchCharactersInText, matchSettingsInText, matchObjectsInText,+ matchCharactersInText, matchPlacesInText, matchObjectsInText,} from '../lib/scenePrompt.js';import { ServerError } from '../lib/errorHandler.js';const MATCHERS = Object.freeze({characters: matchCharactersInText,- settings: matchSettingsInText,+ places: matchPlacesInText,objects: matchObjectsInText,});@@ -64,7 +64,7 @@ export async function listLinkedSeriesNames(universeId) {* Shape:* {* characters: { [entryId]: [{ seriesId, seriesName, issueIds, issueCount }, ...] },- * settings: { [entryId]: [...] },+ * places: { [entryId]: [...] },* objects: { [entryId]: [...] },* seriesNameMap: { [seriesId]: seriesName }, // every linked series, even ones with no prose match* seriesCount, // how many series link to this universe@@ -84,7 +84,7 @@ export async function getUniverseCanonUsage(universeId) {const seriesNameMap = Object.fromEntries(linkedSeries.map((s) => [s.id, s.name]));// Per (kind, entryId) → Map(seriesId → { seriesName, issueIds: Set })- const tally = { characters: new Map(), settings: new Map(), objects: new Map() };+ const tally = { characters: new Map(), places: new Map(), objects: new Map() };let issueCount = 0;for (const series of linkedSeries) {@@ -133,7 +133,7 @@ export async function getUniverseCanonUsage(universeId) {return {characters: shape(tally.characters),- settings: shape(tally.settings),+ places: shape(tally.places),objects: shape(tally.objects),seriesNameMap,seriesCount: linkedSeries.length,diff --git a/server/services/importer.js b/server/services/importer.jsindex 0a68f5a075..d900f7bac4 100644--- a/server/services/importer.js+++ b/server/services/importer.js@@ -4,11 +4,10 @@* Reverse-engineers a finished short story / novel / screenplay / comic* script into universe canon + series arc + prose-seeded issues.*- * Canon kind mapping: the prompts + wire shape use the forward-looking- * `places` label (matches the in-flight Phase 0b SETTING→PLACE rename),- * but the on-disk universe schema still stores them under `settings`.- * Mapping happens at the orchestrator boundary so the UI + LLM never see- * the legacy field name.+ * Canon kind mapping: the prompts, wire shape, AND on-disk universe schema+ * all use `places` after the bible-kind SETTING→PLACE rename. The mapping+ * table below preserves the orchestrator's wire-vs-storage tuple so a+ * future schema change only has to flip the third column.*/import { runStagedLLM } from '../lib/stageRunner.js';@@ -292,8 +291,8 @@ function compactCanonForPrompt(universe) {// name variant.const characters = (universe.characters || []).map((c) =>slim(c, ['name', 'aliases', 'role', 'physicalDescription']));- const places = (universe.settings || []).map((s) =>- slim(s, ['name', 'aliases', 'slugline', 'description']));+ const places = (universe.places || []).map((p) =>+ slim(p, ['name', 'aliases', 'slugline', 'description']));const objects = (universe.objects || []).map((o) =>slim(o, ['name', 'aliases', 'description']));if (!characters.length && !places.length && !objects.length) return null;@@ -817,12 +816,11 @@ export async function commitImport({}}- // Wire field `places` maps to storage field `settings` until the- // Phase 0b rename lands; the table keeps the three near-identical- // merge calls + universe.update payload in one place.+ // Wire field, BIBLE_KIND, and storage field collapsed to one row per kind+ // so a future schema change updates one tuple instead of three call sites.const KIND_MAP = [['characters', BIBLE_KIND.CHARACTER, 'characters'],- ['places', BIBLE_KIND.SETTING, 'settings'],+ ['places', BIBLE_KIND.PLACE, 'places'],['objects', BIBLE_KIND.OBJECT, 'objects'],];// Only merge kinds the user actually supplied entries for — callingdiff --git a/server/services/importer.test.js b/server/services/importer.test.jsindex 763469cff9..31df16222f 100644--- a/server/services/importer.test.js+++ b/server/services/importer.test.js@@ -512,7 +512,7 @@ describe('commitImport', () => {// Universe canon was merged.expect(result.universe.characters.find((c) => c.name === 'Aria')).toBeDefined();- expect(result.universe.settings.find((s) => s.name === 'The Foundry')).toBeDefined();+ expect(result.universe.places.find((s) => s.name === 'The Foundry')).toBeDefined();expect(result.universe.objects.find((o) => o.name === 'The Locket')).toBeDefined();// Series got arc + seasons.expect(result.series.arc.shape).toBe('man-in-hole');diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.jsindex 201f221acb..43f6f1bfef 100644--- a/server/services/pipeline/arcPlanner.js+++ b/server/services/pipeline/arcPlanner.js@@ -76,7 +76,7 @@ function renderPriorSeason(s, priorIssues) {// The world is the canonical source for factions, characters, environments,// etc. — without this, the arc planner would only see the series' own-// characters/settings/objects which are usually empty pre-prose.+// characters/places/objects which are usually empty pre-prose.async function loadWorldContext(universeId) {if (!universeId) return null;const world = await getUniverse(universeId).catch(() => null);@@ -199,7 +199,7 @@ async function buildArcOverviewContext(series, preloadedWorld) {pickedShapeId: arc.shape || '',allowedShapeIdsCsv: ARC_SHAPE_IDS.join(', '),existingCharactersJson: JSON.stringify(canon.characters, null, 2),- existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingPlacesJson: JSON.stringify(canon.places, null, 2),existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}@@ -315,7 +315,7 @@ async function buildSeasonEpisodesContext(series, season, priorSeasons, priorIssepisodeCountTarget: season.episodeCountTarget,},existingCharactersJson: JSON.stringify(canon.characters, null, 2),- existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingPlacesJson: JSON.stringify(canon.places, null, 2),existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}@@ -651,7 +651,7 @@ async function buildVerifyContext(series, preloadedWorld) {...base,seasonsTreeJson: JSON.stringify(tree, null, 2),existingCharactersJson: JSON.stringify(canon.characters, null, 2),- existingSettingsJson: JSON.stringify(canon.settings, null, 2),+ existingPlacesJson: JSON.stringify(canon.places, null, 2),existingObjectsJson: JSON.stringify(canon.objects, null, 2),};}diff --git a/server/services/pipeline/episodeVideo.js b/server/services/pipeline/episodeVideo.jsindex ddf60ce8f7..f2b63d560f 100644--- a/server/services/pipeline/episodeVideo.js+++ b/server/services/pipeline/episodeVideo.js@@ -20,7 +20,7 @@ import { getSeriesCanon } from './seriesCanon.js';import { createProject as createCDProject, setTreatment as setCDTreatment } from '../creativeDirector/local.js';import { startCreativeDirectorProject } from '../creativeDirector/completionHook.js';import { getDefaultVideoModelId } from '../../lib/mediaModels.js';-import { buildSettingByKey } from '../../lib/scenePrompt.js';+import { buildPlaceByKey } from '../../lib/scenePrompt.js';import { getSettings } from '../settings.js';export const ERR_NO_STORYBOARDS = 'PIPELINE_EPISODE_NO_STORYBOARDS';@@ -90,12 +90,12 @@ export function buildTreatmentFromStoryboards({ issue, series, canon = null }) {);}const shortIssueId = issue.id.slice(-8);- // Canon settings live on the linked universe (Phase B.4). Build the- // settingByKey once and reuse across every scene's composeVisualPrompt+ // Canon places live on the linked universe (Phase B.4). Build the+ // placeByKey once and reuse across every scene's composeVisualPrompt// call rather than rebuilding per-call.- const settingByKey = buildSettingByKey(canon?.settings);+ const placeByKey = buildPlaceByKey(canon?.places);const baselinePrompt = (description, slugline) =>- composeVisualPrompt({ series, description, slugline: slugline || '', settingByKey });+ composeVisualPrompt({ series, description, slugline: slugline || '', placeByKey });const flattened = [];for (let idx = 0; idx < usable.length; idx += 1) {@@ -138,8 +138,8 @@ export async function startEpisodeVideoForIssue(issueId, options = {}) {const existing = issue.stages?.episodeVideo?.cdProjectId;const series = await getSeries(issue.seriesId);- // Canon (characters / settings / objects) lives on the linked universe- // — load it so the per-scene baseline prompt can inject setting baseline+ // Canon (characters / places / objects) lives on the linked universe+ // — load it so the per-scene baseline prompt can inject place baseline// context (INT/EXT, timeOfDay, palette, recurring details) for matched// sluglines. Orphan series render with empty canon.const canon = await getSeriesCanon(series);diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.jsindex 61b0cb4034..4f8d48d29a 100644--- a/server/services/pipeline/seriesCanon.js+++ b/server/services/pipeline/seriesCanon.js@@ -1,4 +1,4 @@-// Resolves a series's effective canon (characters, settings, objects) by+// Resolves a series's effective canon (characters, places, objects) by// reading the linked universe. Series no longer carries canon arrays of its// own (Phase B.4) — every active series is universe-linked, so this is just// a thin async lookup that returns empty arrays when the series has no@@ -10,19 +10,19 @@ import { getUniverse } from '../universeBuilder.js';// at a caller would silently pollute every future orphan-series read.const EMPTY = Object.freeze({characters: Object.freeze([]),- settings: Object.freeze([]),+ places: Object.freeze([]),objects: Object.freeze([]),});/**- * Shape a universe record into `{ characters, settings, objects }` arrays,+ * Shape a universe record into `{ characters, places, objects }` arrays,* tolerating missing/non-array fields. Exposed so callers that already have* a universe in scope (e.g. `visualStages.loadBibleContext`) can avoid the* round-trip through `getSeriesCanon`.*/export const pickCanon = (universe) => ({characters: Array.isArray(universe?.characters) ? universe.characters : [],- settings: Array.isArray(universe?.settings) ? universe.settings : [],+ places: Array.isArray(universe?.places) ? universe.places : [],objects: Array.isArray(universe?.objects) ? universe.objects : [],});@@ -31,7 +31,7 @@ export const pickCanon = (universe) => ({* universe record in scope. Returns frozen-empty when the series is orphan* (no universeId) or the linked universe is missing.*- * @returns {Promise<{ characters, settings, objects }>}+ * @returns {Promise<{ characters, places, objects }>}*/export async function getSeriesCanon(series) {if (!series?.universeId) return EMPTY;diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex f2c3a76e95..200bdc32aa 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -32,9 +32,9 @@ import { buildComicPagesOwner, buildSeasonCoverOwner, buildStoryboardsShotOwnerimport { getUniverse, joinInfluenceList } from '../universeBuilder.js';import { ServerError } from '../../lib/errorHandler.js';import {- buildScenePrompt, buildSettingByKey, matchSceneSetting,+ buildScenePrompt, buildPlaceByKey, matchScenePlace,buildCharByKey, matchSceneCharacters, matchCharactersInText,- matchSettingsInText, matchObjectsInText,+ matchPlacesInText, matchObjectsInText,} from '../../lib/scenePrompt.js';import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';import { resolveVisualStyle } from '../../lib/visualStyles.js';@@ -185,19 +185,19 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLinreturn jobId;};-// Canon settings now live on the linked universe (Phase B.4). Callers can-// either pass a pre-built `settingByKey` (when they've already computed it+// Canon places now live on the linked universe (Phase B.4). Callers can+// either pass a pre-built `placeByKey` (when they've already computed it// for reuse across many scenes — see episodeVideo) or pass `canon` and let-// us build the map here. `series?.settings` is no longer read — that field+// us build the map here. `series?.places` is no longer read — that field// was retired with the series-side canon teardown.-export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', settingByKey = null, matchedCharacters = [], world = null, canon = null }) {- const map = settingByKey || buildSettingByKey(canon?.settings);+export function composeVisualPrompt({ series, description, slugline = '', extraStyle = '', placeByKey = null, matchedCharacters = [], world = null, canon = null }) {+ const map = placeByKey || buildPlaceByKey(canon?.places);const scenePrompt = buildScenePrompt(series?.name || '',{ visualPrompt: description || '', slugline },matchedCharacters,stackStyle(series, extraStyle),- matchSceneSetting(slugline, map),+ matchScenePlace(slugline, map),);return applyWorldStyle(scenePrompt, world, series);}@@ -587,7 +587,7 @@ export async function enqueueVolumeBackCover(seriesId, seasonId, options = {}) {export function composeComicPagePrompt({series, world, page, pageNumber, extraStyle = '',- matchedCharacters = [], matchedSettings = [], matchedObjects = [],+ matchedCharacters = [], matchedPlaces = [], matchedObjects = [],}) {const panels = Array.isArray(page?.panels) ? page.panels : [];if (panels.length === 0) return '';@@ -600,16 +600,16 @@ export function composeComicPagePrompt({.map((c) => `${c.name}: ${c.desc}`).join('; ');- // Setting baseline: pull description + palette + recurringDetails per matched- // setting. Same pattern as buildScenePrompt's settingFrags, but multi-setting+ // Place baseline: pull description + palette + recurringDetails per matched+ // place. Same pattern as buildScenePrompt's placeFrags, but multi-place// (a single comic page can span more than one location).- const settingsClause = (matchedSettings || [])- .map((s) => {- const parts = [s.name && `${s.name}:`, (s.description || '').trim()].filter(Boolean);+ const placesClause = (matchedPlaces || [])+ .map((p) => {+ const parts = [p.name && `${p.name}:`, (p.description || '').trim()].filter(Boolean);const head = parts.join(' ');const tail = [- s.palette ? `palette: ${s.palette.trim()}` : '',- (s.recurringDetails || '').trim(),+ p.palette ? `palette: ${p.palette.trim()}` : '',+ (p.recurringDetails || '').trim(),].filter(Boolean).join('; ');return [head, tail].filter(Boolean).join('. ');})@@ -664,10 +664,10 @@ export function composeComicPagePrompt({const layout = `A single full printable comic book page${seriesClause}, page ${pageNumber}. Render a balanced multi-panel comic page layout with ${panels.length} clearly bordered panel${panels.length === 1 ? '' : 's'} arranged for left-to-right, top-to-bottom reading. Include lettered speech balloons for dialogue, rectangular narration boxes for captions, and stylized SFX where indicated. **Balloon lettering rule: each speech balloon contains ONLY the quoted text shown after "Speech balloon reads:". NEVER letter the speaker's name, role, or any parenthetical attribution (e.g. "(EARPIECE)", "(WHISPERED)", "(OFF-PANEL)") inside the balloon — those are tail-direction and balloon-styling cues for the artist, not lettered content.** Each panel must be visually distinct, with consistent character designs across panels.${styleClause}`;const featuringClause = featuring ? `\n\nFeaturing — ${featuring}` : '';- const settingClause = settingsClause ? `\n\nSetting — ${settingsClause}` : '';+ const placeClause = placesClause ? `\n\nSetting — ${placesClause}` : '';const notableClause = notable ? `\n\nNotable — ${notable}` : '';- return applyWorldStyle(`${layout}${featuringClause}${settingClause}${notableClause}\n\n${panelLines.join('\n\n')}`, world, series);+ return applyWorldStyle(`${layout}${featuringClause}${placeClause}${notableClause}\n\n${panelLines.join('\n\n')}`, world, series);}/**@@ -740,10 +740,10 @@ export async function enqueueVisualComicPage(issueId, options = {}) {return true;});- // Settings + objects: text-match against the panel prose. Codex can't take+ // Places + objects: text-match against the panel prose. Codex can't take// reference images, so rich text descriptions in the prompt are how we// keep environments and signature props visually consistent page-to-page.- const matchedSettings = matchSettingsInText(proseHaystack, canon.settings);+ const matchedPlaces = matchPlacesInText(proseHaystack, canon.places);const matchedObjects = matchObjectsInText(proseHaystack, canon.objects);// composeComicPagePrompt only returns '' when panels.length === 0, which is@@ -752,7 +752,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {const prompt = composeComicPagePrompt({series, world, page, pageNumber: pageIndex + 1,extraStyle: composeExtraStyle(series, issue, 'comicPages', options.extraStyle),- matchedCharacters, matchedSettings, matchedObjects,+ matchedCharacters, matchedPlaces, matchedObjects,});const jobId = enqueueImageJob({diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 096fbdf3c3..87d7061b59 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -45,7 +45,7 @@ import { renameCollectionForUniverse, unlinkCollectionsForUniverse } from './med// split on commas and merged into influences.embrace / influences.avoid// so there is a single token-list editing surface.// v4 — categories carry a `kind` field tagging them to one of the 3 canon-// trunks (characters/settings/objects/other); the default `characters`+// trunks (characters/places/objects/other); the default `characters`// category is retired and any variations get folded into canon// characters[]. See "Categories vs canon — decision" in PLAN.md.export const CURRENT_SCHEMA_VERSION = 4;@@ -153,7 +153,7 @@ export const WORLD_CATEGORIES = Object.freeze([// knows which canon trunk to render it under. `other` is the sink for// un-classified custom buckets; an "Auto-sort" UI action LLM-classifies them// into one of the 3 real kinds.-export const CATEGORY_KINDS = Object.freeze(['characters', 'settings', 'objects', 'other']);+export const CATEGORY_KINDS = Object.freeze(['characters', 'places', 'objects', 'other']);export const DEFAULT_CATEGORY_KIND = 'other';@@ -162,9 +162,9 @@ export const DEFAULT_CATEGORY_KIND = 'other';// to DEFAULT_CATEGORY_KIND ('other') unless the input carries an explicit// valid `kind`.export const WORLD_CATEGORY_DEFAULT_KINDS = Object.freeze({- landscapes: 'settings',- environments: 'settings',- structures: 'settings',+ landscapes: 'places',+ environments: 'places',+ structures: 'places',vehicles: 'objects',});@@ -181,8 +181,8 @@ const resolveCategoryKind = (key, rawKind) => {// by the optional pre-v4 backfill for legacy `landscapes/vehicles/etc` buckets.const CATEGORY_TO_CANON = Object.freeze({characters: { kind: BIBLE_KIND.CHARACTER, tags: [] },- landscapes: { kind: BIBLE_KIND.SETTING, tags: ['landscape'] },- environments: { kind: BIBLE_KIND.SETTING, tags: ['environment'] },+ landscapes: { kind: BIBLE_KIND.PLACE, tags: ['landscape'] },+ environments: { kind: BIBLE_KIND.PLACE, tags: ['environment'] },structures: { kind: BIBLE_KIND.OBJECT, tags: ['structure'] },vehicles: { kind: BIBLE_KIND.OBJECT, tags: ['vehicle'] },});@@ -240,7 +240,7 @@ const sanitizeCompositeSheet = (raw) => {const sanitizeCategory = (raw, key) => {// Per-category structure: { kind, variations: [{ label, prompt }] }. Cap so a// runaway LLM can't blow up the universe template; matches the route schema.- // `kind` tags the bucket to one of the 3 canon trunks (characters/settings/+ // `kind` tags the bucket to one of the 3 canon trunks (characters/places/// objects) or 'other'; resolveCategoryKind picks the best value from// (explicit input || built-in default || 'other').if (!raw || typeof raw !== 'object') {@@ -474,7 +474,7 @@ function foldRetiredCharactersBucket(raw, canon) {if (!variations) return canon;const next = {characters: Array.isArray(canon.characters) ? [...canon.characters] : [],- settings: canon.settings,+ places: canon.places,objects: canon.objects,};// Index existing canon character names AND aliases — server-side@@ -526,14 +526,14 @@ function foldRetiredCharactersBucket(raw, canon) {// retired `characters` bucket is handled by foldRetiredCharactersBucket// before this runs; here we only fold the *other* legacy categories// (landscapes/environments/structures/vehicles + customs) into-// settings/objects for the v3→v4 transition.+// places/objects for the v3→v4 transition.function backfillCanonFromCategories(raw, existingCanon) {// v4 hot path — already backfilled. Sanitize through the kind sanitizers// once and return; no category scan needed.if (raw.schemaVersion >= CURRENT_SCHEMA_VERSION) {return {characters: sanitizeBibleList(existingCanon.characters, BIBLE_KIND.CHARACTER),- settings: sanitizeBibleList(existingCanon.settings, BIBLE_KIND.SETTING),+ places: sanitizeBibleList(existingCanon.places, BIBLE_KIND.PLACE),objects: sanitizeBibleList(existingCanon.objects, BIBLE_KIND.OBJECT),schemaVersion: raw.schemaVersion,};@@ -541,12 +541,12 @@ function backfillCanonFromCategories(raw, existingCanon) {const next = {characters: Array.isArray(existingCanon.characters) ? [...existingCanon.characters] : [],- settings: Array.isArray(existingCanon.settings) ? [...existingCanon.settings] : [],+ places: Array.isArray(existingCanon.places) ? [...existingCanon.places] : [],objects: Array.isArray(existingCanon.objects) ? [...existingCanon.objects] : [],};const nameSeen = {characters: new Set(next.characters.map((e) => normalizeBibleName(e?.name))),- settings: new Set(next.settings.map((e) => normalizeBibleName(e?.name))),+ places: new Set(next.places.map((e) => normalizeBibleName(e?.name))),objects: new Set(next.objects.map((e) => normalizeBibleName(e?.name))),};@@ -572,9 +572,9 @@ function backfillCanonFromCategories(raw, existingCanon) {source: BIBLE_SOURCE.UNIVERSE_EXPAND,};if (variation?.locked === true) entry.locked = true;- // Setting sanitizer requires a name OR slugline; planting the label as+ // Place sanitizer requires a name OR slugline; planting the label as// both preserves the variation identity for scene-matchers.- if (kind === BIBLE_KIND.SETTING) entry.slugline = label;+ if (kind === BIBLE_KIND.PLACE) entry.slugline = label;next[targetField].push(entry);nameSeen[targetField].add(nameKey);}@@ -582,7 +582,7 @@ function backfillCanonFromCategories(raw, existingCanon) {return {characters: sanitizeBibleList(next.characters, BIBLE_KIND.CHARACTER),- settings: sanitizeBibleList(next.settings, BIBLE_KIND.SETTING),+ places: sanitizeBibleList(next.places, BIBLE_KIND.PLACE),objects: sanitizeBibleList(next.objects, BIBLE_KIND.OBJECT),schemaVersion: CURRENT_SCHEMA_VERSION,};@@ -615,16 +615,16 @@ const sanitizeTemplate = (raw) => {// bucket arriving from any write path folds into universe.characters[].// 2. backfillCanonFromCategories — legacy v3→v4 migration. Runs ONLY for// pre-v4 reads, folds all OTHER category buckets (landscapes/vehicles/- // custom) into settings/objects. New v4 universes skip this so Phase+ // custom) into places/objects. New v4 universes skip this so Phase// B's separation of canon (named entities) and categories (exploratory// variations) stays clean.const foldedCanon = foldRetiredCharactersBucket(raw, {characters: raw.characters,- settings: raw.settings,+ places: raw.places,objects: raw.objects,});const canonBackfill = backfillCanonFromCategories(raw, foldedCanon);- const { characters, settings, objects, schemaVersion } = canonBackfill;+ const { characters, places, objects, schemaVersion } = canonBackfill;const llm = raw.llm && typeof raw.llm === 'object'? {provider: trimTo(raw.llm.provider, 80) || null,@@ -645,7 +645,7 @@ const sanitizeTemplate = (raw) => {influences,locked,characters,- settings,+ places,objects,schemaVersion,llm,@@ -736,12 +736,12 @@ export async function createUniverse(input = {}) {// (writers-room promote, share-bucket import). sanitizeTemplate runs// each through sanitizeBibleList, so per-entry shape is enforced.characters: input.characters || [],- settings: input.settings || [],+ places: input.places || [],objects: input.objects || [],// Stamp the current schema so backfillCanonFromCategories takes its// hot-path skip on first read. Without this, the legacy categories→// canon backfill fires on every brand-new universe and re-pollutes- // `characters/settings/objects` with every category variation —+ // `characters/places/objects` with every category variation —// counter to Phase B's separation of canon (named entities) from// categories (exploratory variations). New universes are always at// CURRENT_SCHEMA_VERSION; the backfill exists only for legacy reads.@@ -847,7 +847,7 @@ export async function updateUniverse(id, patchOrMutator = {}) {'logline', 'premise', 'styleNotes', 'compositeSheets',// Canon entity arrays — patched wholesale (the sanitizer reruns// sanitizeBibleList so per-entry shape is enforced on every save).- 'characters', 'settings', 'objects',+ 'characters', 'places', 'objects',// Share-bucket origin metadata (importer sets it; user clears via wholesale null).'origin',];@@ -1049,7 +1049,7 @@ export function buildUniverseStyleContext(universe, options = {}) {// the compiled-prompts list is stable across renders.const CANON_TRUNKS = Object.freeze([{ key: 'characters', category: 'canon:characters' },- { key: 'settings', category: 'canon:settings' },+ { key: 'places', category: 'canon:places' },{ key: 'objects', category: 'canon:objects' },]);@@ -1061,12 +1061,12 @@ export function synthesizeCanonPrompt(kind, entry) {if (!entry) return '';if (typeof entry.prompt === 'string' && entry.prompt.trim()) return entry.prompt.trim();// Identifier seed: `name` is the shared anchor for all kinds. For- // `settings`, the bible sanitizer allows entries whose ONLY identifier is+ // `places`, the bible sanitizer allows entries whose ONLY identifier is// a slugline (e.g. "EXT. FOUNDRY CITY — DAY") with no separate name — fall// back to slugline so those entries don't synthesize to an empty seed and// get silently skipped at render time.const name = typeof entry.name === 'string' ? entry.name.trim() : '';- const sluglineId = (kind === 'settings' && typeof entry.slugline === 'string')+ const sluglineId = (kind === 'places' && typeof entry.slugline === 'string')? entry.slugline.trim(): '';const identifier = name || sluglineId;@@ -1089,10 +1089,10 @@ export function synthesizeCanonPrompt(kind, entry) {* - array of labels → only those labels (case-insensitive match)* - missing key → skip the category entirely*- * canonSelection: { characters?: 'all' | string[], settings?: ..., objects?: ... }+ * canonSelection: { characters?: 'all' | string[], places?: ..., objects?: ... }* - 'all' → render every entry in that canon trunk* - array of names → only those names (case-insensitive match against- * `name` and, for settings, `slugline`)+ * `name` and, for places, `slugline`)* - missing key → skip the trunk entirely** batchPerVariation: how many renders per variation (1..20)@@ -1190,11 +1190,11 @@ export function compilePrompts(universe, options = {}) {: entries.filter((e) => Array.isArray(sel) && sel.some((s) => {const needle = s.toLowerCase();if (typeof e.name === 'string' && e.name.toLowerCase() === needle) return true;- // Slugline is settings-only (see canonSelection docstring above+ // Slugline is places-only (see canonSelection docstring above// and BIBLE_FIELD_WHITELIST). Avoid matching a stray slugline// field on a character/object payload — that field isn't part of// the canon contract for those kinds.- if (trunk.key === 'settings'+ if (trunk.key === 'places'&& typeof e.slugline === 'string'&& e.slugline.toLowerCase() === needle) return true;return false;diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex a4311742b2..e2b4828b21 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -77,7 +77,7 @@ describe("universeBuilder service", () => {expect(svc.CATEGORY_KINDS).toContain(w.categories[c].kind);}expect(w.categories.landscapes.variations).toHaveLength(2);- expect(w.categories.landscapes.kind).toBe("settings");+ expect(w.categories.landscapes.kind).toBe("places");expect(w.categories.vehicles.kind).toBe("objects");expect(w.categories.environments.variations).toHaveLength(0);// Custom (un-defaulted) bucket falls to 'other'.@@ -391,7 +391,7 @@ describe("universeBuilder service", () => {});it("synthesizes from identifier + RICH descriptor for settings (capitalized prefixes)", () => {- expect(svc.synthesizeCanonPrompt("settings", {+ expect(svc.synthesizeCanonPrompt("places", {name: "Foundry City",description: "vast smelting works",palette: "rust + bone",@@ -402,7 +402,7 @@ describe("universeBuilder service", () => {});it("falls back to slugline as identifier for settings without name", () => {- expect(svc.synthesizeCanonPrompt("settings", {+ expect(svc.synthesizeCanonPrompt("places", {slugline: "INT. FOUNDRY — DAY",description: "ore furnace",})).toBe("INT. FOUNDRY — DAY — ore furnace");@@ -706,7 +706,7 @@ describe("universeBuilder service", () => {},{ name: "Vex", physicalDescription: "tall, scarred, plate-armor smith" },],- settings: [+ places: [{name: "Foundry City",slugline: "EXT. FOUNDRY CITY — DAY",@@ -723,7 +723,7 @@ describe("universeBuilder service", () => {const w = canonWorld();const compiled = svc.compilePrompts(w, {promptMode: "canon",- canonSelection: { characters: "all", settings: "all", objects: "all" },+ canonSelection: { characters: "all", places: "all", objects: "all" },});// 2 characters + 1 setting + 1 object = 4expect(compiled).toHaveLength(4);@@ -734,7 +734,7 @@ describe("universeBuilder service", () => {);expect(mira.negativePrompt).toBe("blurry");const place = compiled.find((c) => c.label === "Foundry City");- expect(place.category).toBe("canon:settings");+ expect(place.category).toBe("canon:places");expect(place.prompt).toContain("Foundry City");expect(place.prompt).toContain("Palette: rust + bone");});@@ -743,10 +743,10 @@ describe("universeBuilder service", () => {const w = canonWorld();const compiled = svc.compilePrompts(w, {promptMode: "canon",- canonSelection: { settings: "all" },+ canonSelection: { places: "all" },});expect(compiled).toHaveLength(1);- expect(compiled[0].category).toBe("canon:settings");+ expect(compiled[0].category).toBe("canon:places");});it("canonSelection: array filters by name (case-insensitive)", () => {@@ -765,14 +765,14 @@ describe("universeBuilder service", () => {// to slugline as the identifier seed so such entries don't silently// synthesize to '' and get skipped at render time.const w = canonWorld();- w.settings.push({+ w.places.push({// No name — only a slugline identifier + description.slugline: "INT. OLD ARCHIVE — NIGHT",description: "lantern-lit shelves of ledgers",});const compiled = svc.compilePrompts(w, {promptMode: "canon",- canonSelection: { settings: "all" },+ canonSelection: { places: "all" },});// Two settings now: the named Foundry City + the slugline-only Archive.expect(compiled).toHaveLength(2);@@ -786,7 +786,7 @@ describe("universeBuilder service", () => {const w = canonWorld();const compiled = svc.compilePrompts(w, {promptMode: "canon",- canonSelection: { settings: ["EXT. FOUNDRY CITY — DAY"] },+ canonSelection: { places: ["EXT. FOUNDRY CITY — DAY"] },});expect(compiled).toHaveLength(1);expect(compiled[0].label).toBe("Foundry City");@@ -1135,12 +1135,12 @@ describe("universeBuilder service", () => {expect(alex.prompt).toBe("field lead detective");expect(alex.tags).toEqual([]);expect(alex.source).toBe("universe-expand");- // Settings — landscape + environment- const canyon = w.settings.find((s) => s.name === "Crystal Canyon");+ // Places — landscape + environment+ const canyon = w.places.find((s) => s.name === "Crystal Canyon");expect(canyon.tags).toEqual(["landscape"]);expect(canyon.locked).toBe(true); // variation lock carries through- expect(canyon.slugline).toBe("Crystal Canyon"); // settings need slugline- const bubble = w.settings.find((s) => s.name === "Bubble Room");+ expect(canyon.slugline).toBe("Crystal Canyon"); // places need slugline+ const bubble = w.places.find((s) => s.name === "Bubble Room");expect(bubble.tags).toEqual(["environment"]);// Objects — vehicle + structure + custom 'factions'const rover = w.objects.find((o) => o.name === "Rover");@@ -1216,9 +1216,9 @@ describe("universeBuilder service", () => {describe("category kind (schema v4)", () => {it("assigns built-in default kinds (landscapes/environments/structures→settings, vehicles→objects)", async () => {const w = await seedWorld();- expect(w.categories.landscapes.kind).toBe("settings");- expect(w.categories.environments.kind).toBe("settings");- expect(w.categories.structures.kind).toBe("settings");+ expect(w.categories.landscapes.kind).toBe("places");+ expect(w.categories.environments.kind).toBe("places");+ expect(w.categories.structures.kind).toBe("places");expect(w.categories.vehicles.kind).toBe("objects");});@@ -1252,7 +1252,7 @@ describe("universeBuilder service", () => {colonies: { kind: null, variations: [{ label: "Tycho", prompt: "x" }] },},});- expect(w.categories.landscapes.kind).toBe("settings"); // built-in default+ expect(w.categories.landscapes.kind).toBe("places"); // built-in defaultexpect(w.categories.vehicles.kind).toBe("objects"); // built-in defaultexpect(w.categories.colonies.kind).toBe("other"); // custom fallback});diff --git a/server/services/universeBuilderAutoSort.test.js b/server/services/universeBuilderAutoSort.test.jsindex ac15cbae00..dcb3baf5b3 100644--- a/server/services/universeBuilderAutoSort.test.js+++ b/server/services/universeBuilderAutoSort.test.js@@ -76,7 +76,7 @@ describe('universeBuilderAutoSort — happy path', () => {expect(w.categories.relics.kind).toBe('other');mockLlmClassifications([- { key: 'colonies', kind: 'settings' },+ { key: 'colonies', kind: 'places' },{ key: 'factions', kind: 'characters' },{ key: 'relics', kind: 'objects' },]);@@ -88,11 +88,11 @@ describe('universeBuilderAutoSort — happy path', () => {expect(resolveProviderAndModelMock).toHaveBeenCalledWith({ providerId: 'p-explicit', model: 'm-explicit' });expect(result.results).toEqual([- { sourceKey: 'colonies', kind: 'settings', suggestedKey: null },+ { sourceKey: 'colonies', kind: 'places', suggestedKey: null },{ sourceKey: 'factions', kind: 'characters', suggestedKey: null },{ sourceKey: 'relics', kind: 'objects', suggestedKey: null },]);- expect(result.universe.categories.colonies.kind).toBe('settings');+ expect(result.universe.categories.colonies.kind).toBe('places');expect(result.universe.categories.factions.kind).toBe('characters');expect(result.universe.categories.relics.kind).toBe('objects');// Variations are preserved through the patch — the bucket itself moves@@ -106,7 +106,7 @@ describe('universeBuilderAutoSort — happy path', () => {it('short-circuits with no LLM call when no other-kinded buckets exist', async () => {const w = await seedUniverseWithBuckets({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Crystalline canyon', prompt: 'salt flats' }],},});@@ -120,7 +120,7 @@ describe('universeBuilderAutoSort — happy path', () => {it('leaves non-other buckets untouched in the patch', async () => {const w = await seedUniverseWithBuckets({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Crystalline canyon', prompt: 'salt flats' }],},colonies: {@@ -128,15 +128,15 @@ describe('universeBuilderAutoSort — happy path', () => {},});mockLlmClassifications([- { key: 'colonies', kind: 'settings' },+ { key: 'colonies', kind: 'places' },]);const result = await autoSortSvc.autoSortOtherBuckets(w.id);// The settings-kinded `landscapes` bucket is preserved exactly.- expect(result.universe.categories.landscapes.kind).toBe('settings');+ expect(result.universe.categories.landscapes.kind).toBe('places');expect(result.universe.categories.landscapes.variations[0].label).toBe('Crystalline canyon');- expect(result.universe.categories.colonies.kind).toBe('settings');+ expect(result.universe.categories.colonies.kind).toBe('places');});});@@ -186,7 +186,7 @@ describe('universeBuilderAutoSort — LLM-shaped failures', () => {},});mockLlmClassifications([- { key: 'colonies', kind: 'settings' },+ { key: 'colonies', kind: 'places' },{ key: 'hallucinated_bucket', kind: 'characters' },]);@@ -202,7 +202,7 @@ describe('universeBuilderAutoSort — LLM-shaped failures', () => {},});mockLlmClassifications([- { key: 'hallucinated_only', kind: 'settings' },+ { key: 'hallucinated_only', kind: 'places' },]);await expect(autoSortSvc.autoSortOtherBuckets(w.id),diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex e51499cd1e..8221b58c62 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -130,7 +130,7 @@ Return a SINGLE JSON object. NO markdown, NO commentary. The object MUST have th- styleNotes: string. A prose paragraph (≤4000 chars) describing the visual + tonal style for the story bible — references (artists, films, comics, games), mood, palette, pacing, narrative voice. This is read by writers + creative directors, not the image model, so use full sentences instead of comma-separated tokens.- influences: object { "embrace": [string], "avoid": [string] }. THIS IS THE UNIVERSE'S STYLE + NEGATIVE PROMPT. Each list is a set of short prompt tokens (max 120 chars each, max 30 per list). The "embrace" list is joined verbatim as the positive style prompt prepended to every render (palette, lighting, render quality, artist references — e.g. "moebius linework", "cel-shading", "dust palette"). The "avoid" list is joined verbatim as the negative prompt (e.g. "blurry", "lowres", "watermark", "extra fingers"). Use short token-style labels, NOT full sentences. When influence input is provided above, preserve those entries unless the starter idea explicitly contradicts them.- characters: array. Named cast members central to this universe. Each item has { "name": string (max 120 chars), "physicalDescription": string (max 1000 chars, what they look like — face, build, age range, distinguishing marks), "personality": string (max 600 chars), "background": string (max 800 chars, where they come from + role in the world), "prompt": string (max 400 chars, the render-prompt fragment used for reference images), "tags": [string] (1-3 short labels like "protagonist", "antagonist", "supporting") }. Generate 0-8 leads. Distinct from category "variations" (which are exploratory render prompts) — these are first-class entities that downstream pipeline stages address by name.-- settings: array. Named recurring places in this universe. Each item has { "name": string (max 120 chars, human label like "Foundry City"), "slugline": string (max 120 chars, screenplay-style location header like "EXT. FOUNDRY CITY — DAY"), "description": string (max 1000 chars), "palette": string (max 300 chars, dominant colors), "recurringDetails": string (max 600 chars, recognizable motifs that recur across scenes), "prompt": string (max 400 chars, render-prompt fragment), "tags": [string] }. Generate 0-8 key places.+- places: array. Named recurring places in this universe. Each item has { "name": string (max 120 chars, human label like "Foundry City"), "slugline": string (max 120 chars, screenplay-style location header like "EXT. FOUNDRY CITY — DAY"), "description": string (max 1000 chars), "palette": string (max 300 chars, dominant colors), "recurringDetails": string (max 600 chars, recognizable motifs that recur across scenes), "prompt": string (max 400 chars, render-prompt fragment), "tags": [string] }. Generate 0-8 key places.- objects: array. Named props / vehicles / artifacts with story weight. Each item has { "name": string (max 120 chars), "description": string (max 1000 chars, what it looks like + what it does), "significance": string (max 600 chars, why it matters to the story), "prompt": string (max 400 chars, render-prompt fragment), "tags": [string] }. Generate 0-5 hero objects.- categories: object. Atomic reusable buckets for VISUAL EXPLORATION — bulk-render N variations to see a range of options. Use snake_case keys. Start from these common buckets when useful:${WORLD_CATEGORIES.map((c) => ` - ${c}`).join("\n")}@@ -138,14 +138,14 @@ ${WORLD_CATEGORIES.map((c) => ` - ${c}`).join("\n")}Useful extra buckets include colonies, factions, tribes, species, cultures, clothing_styles, material_palettes, fasteners_and_closures, tools, rituals, raider_clans, vehicles, settlements, and artifacts.- compositeSheets: array. Complete, ready-to-render composite board prompts. Each item has { "kind": "reference_sheet" | "world_pitch_poster", "label": string, "prompt": string up to 4000 chars }. These are NOT atomic fragments; each prompt must describe one complete board/poster that combines multiple buckets into a single image.-Each category value is an object with TWO fields: { "kind": one of ${CATEGORY_KINDS.map((k) => `"${k}"`).join(" | ")}, "variations": array }. The "kind" tags which canon trunk the bucket belongs to — use "characters" for buckets of people/groups (factions, tribes, clans), "settings" for places (landscapes, environments, colonies, structures), "objects" for things (vehicles, tools, artifacts), and "other" when nothing else fits. Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }. Concrete example for one category:- "landscapes": { "kind": "settings", "variations": [+Each category value is an object with TWO fields: { "kind": one of ${CATEGORY_KINDS.map((k) => `"${k}"`).join(" | ")}, "variations": array }. The "kind" tags which canon trunk the bucket belongs to — use "characters" for buckets of people/groups (factions, tribes, clans), "places" for locations (landscapes, environments, colonies, structures), "objects" for things (vehicles, tools, artifacts), and "other" when nothing else fits. Each variation has the shape { "label": string (max 80 chars), "prompt": string (max 400 chars, comma-separated tokens describing ONE specific subject in this category) }. Concrete example for one category:+ "landscapes": { "kind": "places", "variations": [{ "label": "Crystalline canyon basin", "prompt": "vast crystalline canyon, salt flats, low horizon" },{ "label": "Scrap-iron dune sea", "prompt": "rolling dunes of rusted scrap, half-buried machinery" }] }Do NOT use \`[...]\`, \`…\`, or any other placeholder/elision tokens — every array MUST contain real variation objects.-Canon vs categories: a single named entity belongs in CANON (characters/settings/objects) — the protagonist "Ash" goes in characters[], not in a category. A bucket of N exploratory looks belongs in categories — "what could 5 different faction outfit styles look like" goes in a "factions" category with variations[]. The user will iterate on each surface separately.+Canon vs categories: a single named entity belongs in CANON (characters/places/objects) — the protagonist "Ash" goes in characters[], not in a category. A bucket of N exploratory looks belongs in categories — "what could 5 different faction outfit styles look like" goes in a "factions" category with variations[]. The user will iterate on each surface separately.Concrete compositeSheets examples:{ "kind": "reference_sheet", "label": "Gas-Giant Drifters costume sheet", "prompt": "Create a clean illustrated costume reference sheet for Gas-Giant Drifters, a human colony living on floating platforms and balloon settlements high in a gas giant atmosphere. Show a simplified character lineup with five figures: kite child, storm scout, main hero, sky elder, and rig worker. Include material swatches for sailcloth, balloon-skin, rubberized algae fabric, salvaged foil, flex-ceramic patches, storm-glass lenses, braided tether cord, and copper wire ornament. Include fastener/accessory icons for buckles, spring clips, pressure rings, carabiner hooks, breathing collar, goggles, tether belt, strapped sky boots, and wind streamer tabs. Include a color strip: storm blue, saffron, hot coral, orange, slate gray, cream, electric cyan, copper, cloud white. Minimal readable layout, elegant negative space, light background hints of balloon platforms and storm clouds, not baroque, not hyper-detailed." }@@ -185,7 +185,7 @@ const isExpansionShape = (o) =>(o.categories && typeof o.categories === "object") ||Array.isArray(o.compositeSheets) ||Array.isArray(o.characters) ||- Array.isArray(o.settings) ||+ Array.isArray(o.places) ||Array.isArray(o.objects));const extractJson = (raw) => {@@ -307,11 +307,11 @@ const normalizeCanonArray = (raw, kind) => {/*** Expand a starter prompt into a structured universe template draft.* Returns { logline, premise, styleNotes, influences, categories, compositeSheets,- * characters, settings, objects, llm: { provider, model } }.+ * characters, places, objects, llm: { provider, model } }.*- * Canon arrays (characters/settings/objects) are sanitized through+ * Canon arrays (characters/places/objects) are sanitized through* sanitizeBibleList so they're shape-compatible with universe.characters[],- * universe.settings[], universe.objects[] — the client merges them into the+ * universe.places[], universe.objects[] — the client merges them into the* draft's canon arrays alongside the category merge.** @param {object} options@@ -450,7 +450,7 @@ export async function expandWorldTemplate({// entry before sanitize, so provenance lands on disk consistently with the// existing categories→canon backfill in universeBuilder.js.const characters = normalizeCanonArray(rawCharacters, BIBLE_KIND.CHARACTER);- const settings = normalizeCanonArray(parsed.settings, BIBLE_KIND.SETTING);+ const places = normalizeCanonArray(parsed.places, BIBLE_KIND.PLACE);const objects = normalizeCanonArray(parsed.objects, BIBLE_KIND.OBJECT);// sanitizeInfluences enforces the same per-entry cap, list cap, and// case-insensitive dedupe used everywhere else. Distinguish "LLM omitted@@ -473,9 +473,9 @@ export async function expandWorldTemplate({0,);console.log(- `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, canon=${characters.length}/${settings.length}/${objects.length} (chars/places/objs), bible=${logline ? "yes" : "no"} (${perCat})`,+ `🌍 Universe Builder expansion complete — runId=${runId} ${totalVariations} variations, ${compositeSheets.length} composite sheets, canon=${characters.length}/${places.length}/${objects.length} (chars/places/objs), bible=${logline ? "yes" : "no"} (${perCat})`,);- if (totalVariations === 0 && compositeSheets.length === 0 && characters.length === 0 && settings.length === 0 && objects.length === 0) {+ if (totalVariations === 0 && compositeSheets.length === 0 && characters.length === 0 && places.length === 0 && objects.length === 0) {console.warn(`⚠️ Universe Builder expansion produced 0 variations + 0 canon — inspect data/runs/${runId}/output.txt for the raw LLM response`,);@@ -489,7 +489,7 @@ export async function expandWorldTemplate({categories,compositeSheets,characters,- settings,+ places,objects,llm: { provider: provider.id, model: selectedModel || null },};diff --git a/server/services/universeBuilderExpand.test.js b/server/services/universeBuilderExpand.test.jsindex b405938eaa..2fde0a65f6 100644--- a/server/services/universeBuilderExpand.test.js+++ b/server/services/universeBuilderExpand.test.js@@ -336,7 +336,7 @@ describe("universeBuilderExpand.normalizeCanonArray", () => {{ slugline: "INT. FOUNDRY CITY — DAY" },{ description: "no name no slugline — dropped" },],- "setting",+ "place",);expect(out).toHaveLength(2);expect(out[0].name).toBe("Foundry City");@@ -387,15 +387,15 @@ describe("universeBuilderExpand.EXPANSION_PROMPT", () => {expect(EXPANSION_PROMPT).toContain('"avoid"');});- it("asks the LLM to emit canon arrays (characters / settings / objects) with rich metadata", () => {+ it("asks the LLM to emit canon arrays (characters / places / objects) with rich metadata", () => {// Phase B contract: canon arrays are first-class outputs of the expand- // call. The client merges them into universe.characters[]/.settings[]/.objects[]+ // call. The client merges them into universe.characters[]/.places[]/.objects[]// and the redesigned UI surfaces them under their canon trunks. If this// assertion fails, also verify normalizeCanonArray + expandWorldTemplate// still surface the returned values in the response payload.expect(EXPANSION_PROMPT).toContain("characters:");expect(EXPANSION_PROMPT).toContain("physicalDescription");- expect(EXPANSION_PROMPT).toContain("settings:");+ expect(EXPANSION_PROMPT).toContain("places:");expect(EXPANSION_PROMPT).toContain("slugline");expect(EXPANSION_PROMPT).toContain("recurringDetails");expect(EXPANSION_PROMPT).toContain("objects:");@@ -407,7 +407,7 @@ describe("universeBuilderExpand.EXPANSION_PROMPT", () => {// new bucket under 'other' until the user hand-sorts.expect(EXPANSION_PROMPT).toContain('"kind"');expect(EXPANSION_PROMPT).toContain('"characters"');- expect(EXPANSION_PROMPT).toContain('"settings"');+ expect(EXPANSION_PROMPT).toContain('"places"');expect(EXPANSION_PROMPT).toContain('"objects"');expect(EXPANSION_PROMPT).toContain('"other"');});diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.jsindex 99333661ae..dfc02db918 100644--- a/server/services/universeBuilderPromote.js+++ b/server/services/universeBuilderPromote.js@@ -38,13 +38,13 @@ export const VALID_TARGET_KINDS = Object.freeze(Object.keys(KIND_TO_BIBLE));const isCharacterShape = (o) =>o && typeof o === 'object' && typeof o.name === 'string';-const isSettingShape = (o) =>+const isPlaceShape = (o) =>o && typeof o === 'object' && (typeof o.name === 'string' || typeof o.slugline === 'string');const isObjectShape = isCharacterShape;const SHAPE_PREDICATE = {characters: isCharacterShape,- settings: isSettingShape,+ places: isPlaceShape,objects: isObjectShape,};@@ -70,11 +70,11 @@ const buildPromotePrompt = ({- role: string (max ${BIBLE_LIMITS.ROLE_MAX} chars). Their function in the story (protagonist / mentor / faction lead / etc).- prompt: string (max ${BIBLE_LIMITS.PROMPT_MAX} chars). Render-prompt fragment for reference images — comma-separated tokens; do NOT repeat universe style tokens (they're prepended at render time).- tags: array of 1-3 short labels (e.g. "protagonist", "antagonist", "supporting").`;- } else if (targetKind === 'settings') {- outputContract = `Return a SINGLE JSON object describing one SETTING / PLACE. Required fields:+ } else if (targetKind === 'places') {+ outputContract = `Return a SINGLE JSON object describing one PLACE. Required fields:- name: string (max ${BIBLE_LIMITS.NAME_MAX} chars). Human label like "Foundry City". Default the variation label when no clearer name is implied.- slugline: string (max ${BIBLE_LIMITS.SLUGLINE_MAX} chars). Screenplay-style location header like "EXT. FOUNDRY CITY — DAY". Leave empty string when no obvious slugline applies.-- description: string (max ${BIBLE_LIMITS.SETTING_DESCRIPTION_MAX} chars). What the place looks like + feels like.+- description: string (max ${BIBLE_LIMITS.PLACE_DESCRIPTION_MAX} chars). What the place looks like + feels like.- palette: string (max ${BIBLE_LIMITS.PALETTE_MAX} chars). Dominant colors.- era: string (max ${BIBLE_LIMITS.ERA_MAX} chars). Time period / technology level.- weather: string (max ${BIBLE_LIMITS.WEATHER_MAX} chars). Typical conditions.@@ -105,14 +105,14 @@ ${outputContract}- Stay tonally consistent with the LOGLINE / STYLE NOTES / EMBRACE INFLUENCES above when present.`;};-// Find a canon entry that collides with `label` (and, for settings, the+// Find a canon entry that collides with `label` (and, for places, the// slugline derived from `label` or `secondarySlug`). Run pre-LLM against// the prompt-building snapshot AND post-LLM against the latest persisted// canon — keeps the duplicate-detection logic in one place.const findCanonCollision = (canon, label, targetKind, secondarySlug = '') => {const direct = findBibleEntryByName(canon, label);if (direct) return direct;- if (targetKind !== 'settings') return null;+ if (targetKind !== 'places') return null;const needleSlug = normalizeSlugline(label);const secondary = normalizeSlugline(secondarySlug);if (!needleSlug && !secondary) return null;@@ -158,7 +158,7 @@ const extractEntryJson = (raw, kind) => {* @param {string} options.category — bucket key (case-insensitive)* @param {string} options.label — variation label (case-insensitive); the* first matching variation in the bucket is promoted.- * @param {'characters'|'settings'|'objects'} [options.targetKind] — required+ * @param {'characters'|'places'|'objects'} [options.targetKind] — required* when the source category's `kind` is 'other'; ignored otherwise.* @param {string} [options.providerId]* @param {string} [options.model]@@ -196,7 +196,7 @@ export async function promoteVariationToCanon(universeId, options = {}) {if (targetKind === 'other' || !VALID_TARGET_KINDS.includes(targetKind)) {if (!VALID_TARGET_KINDS.includes(rawTargetKind)) {throw new ServerError(- `Bucket "${categoryKey}" has kind "${bucket.kind || 'other'}" — pass targetKind (characters|settings|objects) to promote variations from it`,+ `Bucket "${categoryKey}" has kind "${bucket.kind || 'other'}" — pass targetKind (characters|places|objects) to promote variations from it`,{ status: 400, code: 'UNIVERSE_PROMOTE_NO_TARGET_KIND' },);}@@ -220,7 +220,7 @@ export async function promoteVariationToCanon(universeId, options = {}) {// label already exists, surface a 409 so the UI can suggest "open the// existing entry" or "rename then promote" rather than producing a second// record that the merge logic would silently swallow on next save. For- // settings (kind whose identity is slugline-keyed via MERGE_CONFIG), also+ // places (kind whose identity is slugline-keyed via MERGE_CONFIG), also// match the variation label against existing entries' `slugline` so a// dash-variant or slug-vs-name promotion doesn't slip past name-only// matching.@@ -318,7 +318,7 @@ export async function promoteVariationToCanon(universeId, options = {}) {// concurrent promote (or manual canon add) in another tab could have// landed an entry with the same name while the LLM was thinking. The// sanitized entry's slugline is included as a secondary key for the- // settings case, since the LLM might have emitted a clean slugline+ // places case, since the LLM might have emitted a clean slugline// that collides with an existing entry whose name doesn't match.const latestCanon = Array.isArray(latest[bibleField]) ? latest[bibleField] : [];const lateCollision = findCanonCollision(latestCanon, sanitized.name, targetKind, sanitized.slugline);diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.jsindex 1029dfb83e..34a268d226 100644--- a/server/services/universeBuilderPromote.test.js+++ b/server/services/universeBuilderPromote.test.js@@ -68,10 +68,10 @@ beforeEach(() => {});describe('universeBuilderPromote — happy path', () => {- it('promotes a variation from a settings-kinded bucket into universe.settings[]', async () => {+ it('promotes a variation from a settings-kinded bucket into universe.places[]', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Crystalline canyon', prompt: 'vast crystalline canyon, salt flats' },{ label: 'Scrap dune sea', prompt: 'rolling dunes of rusted scrap' },@@ -99,10 +99,10 @@ describe('universeBuilderPromote — happy path', () => {// Arg-shape pin: a future typo (provider/Provider/etc.) would silently// pass under a flat resolver mock without this assertion.expect(resolveProviderAndModelMock).toHaveBeenCalledWith({ providerId: 'p-explicit', model: 'm-explicit' });- expect(result.targetKind).toBe('settings');+ expect(result.targetKind).toBe('places');expect(result.entry.name).toBe('Crystalline Canyon');expect(result.entry.palette).toContain('pale violet');- expect(result.universe.settings.some((e) => e.name === 'Crystalline Canyon')).toBe(true);+ expect(result.universe.places.some((e) => e.name === 'Crystalline Canyon')).toBe(true);// The source variation is removed from its bucket.const remainingLabels = result.universe.categories.landscapes.variations.map((v) => v.label);expect(remainingLabels).toEqual(['Scrap dune sea']);@@ -141,7 +141,7 @@ describe('universeBuilderPromote — happy path', () => {it('matches variation labels case-insensitively', async () => {const w = await seedUniverseWithBucket({colonies: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Gas-Giant Drifters', prompt: 'balloon settlements in the upper atmosphere' }],},});@@ -152,7 +152,7 @@ describe('universeBuilderPromote — happy path', () => {label: 'gas-giant drifters', // lowercase});- expect(result.universe.settings.find((s) => s.name === 'Gas-Giant Drifters')).toBeTruthy();+ expect(result.universe.places.find((s) => s.name === 'Gas-Giant Drifters')).toBeTruthy();});it('seeds entry.name from the variation label when the LLM omits name', async () => {@@ -233,11 +233,11 @@ describe('universeBuilderPromote — targetKind override + other-bucket gate', (it('rejects invalid targetKind even for non-other buckets', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Salt flats', prompt: 'horizon-spanning salt flats' }],},});- // The bucket kind is 'settings', so the server should ignore an+ // The bucket kind is 'places', so the server should ignore an// ill-typed targetKind and proceed with the bucket-derived kind. (The// route schema would reject the bad value before reaching here in prod.)mockLlm({ name: 'Salt Flats', description: 'A flat expanse.', prompt: 'horizon salt flats' });@@ -246,7 +246,7 @@ describe('universeBuilderPromote — targetKind override + other-bucket gate', (label: 'Salt flats',targetKind: 'invalid',});- expect(result.targetKind).toBe('settings');+ expect(result.targetKind).toBe('places');});});@@ -254,7 +254,7 @@ describe('universeBuilderPromote — error paths', () => {it('404s when the category does not exist', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'A', prompt: 'a' }],},});@@ -266,7 +266,7 @@ describe('universeBuilderPromote — error paths', () => {it('404s when the variation label does not match', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'A', prompt: 'a' }],},});@@ -296,11 +296,11 @@ describe('universeBuilderPromote — error paths', () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Crystalline Canyon', prompt: 'salt-crystal walls' }],},},- { settings: existing },+ { places: existing },);await expect(promoteSvc.promoteVariationToCanon(w.id, {@@ -325,11 +325,11 @@ describe('universeBuilderPromote — error paths', () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'EXT. FOUNDRY CITY - DAY', prompt: 'dawn light over docks' }],},},- { settings: existing },+ { places: existing },);await expect(promoteSvc.promoteVariationToCanon(w.id, {@@ -343,7 +343,7 @@ describe('universeBuilderPromote — error paths', () => {it('throws 502 when the LLM returns invalid JSON', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'A', prompt: 'a' }],},});@@ -387,7 +387,7 @@ describe('universeBuilderPromote — control field stripping', () => {it('drops hallucinated id / locked / imageRefs from the LLM response', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'Salt Flats', prompt: 'horizon salt flats' }],},});@@ -418,7 +418,7 @@ describe('universeBuilderPromote — atomicity', () => {it('writes the canon entry and variation removal in a single atomicWrite', async () => {const w = await seedUniverseWithBucket({landscapes: {- kind: 'settings',+ kind: 'places',variations: [{ label: 'A', prompt: 'a' },{ label: 'B', prompt: 'b' },@@ -439,7 +439,7 @@ describe('universeBuilderPromote — atomicity', () => {// Re-read from the persistence layer (mirrors what a sibling tab would// see): canon has the new entry AND the bucket has lost the variation.const reread = (await svc.listUniverses())[0];- expect(reread.settings.find((s) => s.name === 'Place A')).toBeTruthy();+ expect(reread.places.find((s) => s.name === 'Place A')).toBeTruthy();expect(reread.categories.landscapes.variations.map((v) => v.label)).toEqual(['B']);});});@@ -476,7 +476,7 @@ describe('universeBuilderPromote — prompt content', () => {expect(charPrompt).toContain('personality');const settingPrompt = promoteSvc.__testing.buildPromotePrompt({- targetKind: 'settings',+ targetKind: 'places',variation: { label: 'x', prompt: 'x' },category: 'h',universe: {},diff --git a/server/services/universeCanon.js b/server/services/universeCanon.jsindex 006e6ee90d..e2b271445c 100644--- a/server/services/universeCanon.js+++ b/server/services/universeCanon.js@@ -1,4 +1,4 @@-// Canon entities on the universe — characters, settings, objects. Mirrors+// Canon entities on the universe — characters, places, objects. Mirrors// `pipeline/series.js`'s extract+refine paths but writes into the universe// so multiple series can share a cast (Phase A of the Universe-as-canon// refactor). The series-side helpers stay live until Phase B migrates@@ -49,7 +49,7 @@ export async function extractCanonFromProse(universeId, opts = {}) {const universe = await getUniverse(universeId);const rawKinds = (opts.kinds && opts.kinds.length)? opts.kinds- : [BIBLE_KIND.CHARACTER, BIBLE_KIND.SETTING, BIBLE_KIND.OBJECT];+ : [BIBLE_KIND.CHARACTER, BIBLE_KIND.PLACE, BIBLE_KIND.OBJECT];const kinds = [...new Set(rawKinds)];if (typeof opts.corpus !== 'string' || !opts.corpus.trim()) {throw new ServerError('extractCanonFromProse: corpus is required', {@@ -257,7 +257,7 @@ export async function setCanonEntryLock(universeId, kind, entryId, locked) {/*** Strip a filename from every `imageRefs[]` across every universe's- * characters/settings/objects. Mirror of the series-side purge so the image-+ * characters/places/objects. Mirror of the series-side purge so the image-* delete route can clean both stores in one pass.*/export async function purgeImageRefFromAllUniverses(filename) {diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.jsindex b0b6c4fa11..88b453834b 100644--- a/server/services/writersRoom/evaluator.js+++ b/server/services/writersRoom/evaluator.js@@ -16,7 +16,7 @@ import { BIBLE_KIND } from '../../lib/storyBible.js';import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';import { getWorkWithBody } from './local.js';import { listCharacters, mergeExtractedCharacters } from './characters.js';-import { listSettings, mergeExtractedSettings } from './settings.js';+import { listPlaces, mergeExtractedPlaces } from './places.js';import { listObjects, mergeExtractedObjects } from './objects.js';import { nowIso, badRequest, notFound, assertValidWorkId } from './_shared.js';@@ -27,7 +27,7 @@ const KIND_META = {format: { stage: 'writers-room-format', returnsJson: false },script: { stage: 'writers-room-script', returnsJson: true },characters: { stage: 'writers-room-characters', returnsJson: true },- settings: { stage: 'writers-room-places', returnsJson: true },+ places: { stage: 'writers-room-places', returnsJson: true },objects: { stage: 'writers-room-objects', returnsJson: true },};@@ -40,7 +40,7 @@ const root = () => join(PATHS.data, 'writers-room');const analysisDir = (workId) => {// Defense-in-depth: refuse path-traversal-shaped workIds before// interpolating them into the on-disk path. Mirrors the guard in- // characters.js / settings.js.+ // characters.js / places.js.assertValidWorkId(workId);return join(root(), 'works', workId, 'analysis');};@@ -75,14 +75,14 @@ const SHAPERS = {suggestions: Array.isArray(parsed.suggestions) ? parsed.suggestions.filter((s) => s && typeof s === 'object') : [],};},- // characters / settings / objects route through `extractBible`,+ // characters / places / objects route through `extractBible`,// and `script` routes through `extractScenes` — no per-kind shaper here.};const BIBLE_ANALYSIS = Object.freeze({- characters: { kind: BIBLE_KIND.CHARACTER, list: listCharacters, merge: mergeExtractedCharacters },- settings: { kind: BIBLE_KIND.SETTING, list: listSettings, merge: mergeExtractedSettings },- objects: { kind: BIBLE_KIND.OBJECT, list: listObjects, merge: mergeExtractedObjects },+ characters: { kind: BIBLE_KIND.CHARACTER, list: listCharacters, merge: mergeExtractedCharacters },+ places: { kind: BIBLE_KIND.PLACE, list: listPlaces, merge: mergeExtractedPlaces },+ objects: { kind: BIBLE_KIND.OBJECT, list: listObjects, merge: mergeExtractedObjects },});const isBibleKind = (k) => k in BIBLE_ANALYSIS;@@ -312,13 +312,13 @@ export async function runAnalysis(workId, { kind } = {}) {}if (kind === 'script') {- const [characters, settings, objects] = await Promise.all([- listCharacters(workId), listSettings(workId), listObjects(workId),+ const [characters, places, objects] = await Promise.all([+ listCharacters(workId), listPlaces(workId), listObjects(workId),]);const { extracted, runId, providerId, model } = await extractScenes({source: body,sourceKind: SOURCE_KIND.PROSE,- characters, settings, objects,+ characters, places, objects,work: workCtx,tag: 'writers-room-script',});diff --git a/server/services/writersRoom/settings.js b/server/services/writersRoom/places.jssimilarity index 56%rename from server/services/writersRoom/settings.jsrename to server/services/writersRoom/places.jsindex c0b69269ee..3aaddc7b2e 100644--- a/server/services/writersRoom/settings.js+++ b/server/services/writersRoom/places.js@@ -1,10 +1,10 @@/**- * Writers Room — editable setting/world bible.+ * Writers Room — editable place/world bible.** Per-location bible keyed by screenplay slugline so SceneCard can match a- * scene's slugline to its canonical setting and inject the description into+ * scene's slugline to its canonical place and inject the description into* 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+ * places.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.*/@@ -18,31 +18,31 @@ export { normalizeSlugline };const dedupKey = (entry) => normalizeSlugline(entry?.slugline || entry?.name || '');export const {- list: listSettings,- get: getSetting,- create: createSetting,- update: updateSetting,- remove: deleteSetting,- mergeExtracted: mergeExtractedSettings,+ list: listPlaces,+ get: getPlace,+ create: createPlace,+ update: updatePlace,+ remove: deletePlace,+ mergeExtracted: mergeExtractedPlaces,} = createBibleStore({- kind: BIBLE_KIND.SETTING,- idPrefix: 'wr-setting-',+ kind: BIBLE_KIND.PLACE,+ idPrefix: 'wr-place-',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';+ return slugline || name ? null : 'Place 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.+ // place 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' });+ throw new ServerError('Place needs slugline or name', { status: 400, code: 'VALIDATION_ERROR' });}},- conflictMessage: ({ slugline, name }) => `A setting matching "${slugline || name}" already exists`,- notFoundLabel: 'Setting',- invalidIdMessage: 'Invalid setting id',+ conflictMessage: ({ slugline, name }) => `A place matching "${slugline || name}" already exists`,+ notFoundLabel: 'Place',+ invalidIdMessage: 'Invalid place id',});diff --git a/server/services/writersRoom/settings.test.js b/server/services/writersRoom/places.test.jssimilarity index 53%rename from server/services/writersRoom/settings.test.jsrename to server/services/writersRoom/places.test.jsindex 99e67cbd36..2f727e379c 100644--- a/server/services/writersRoom/settings.test.js+++ b/server/services/writersRoom/places.test.js@@ -12,15 +12,15 @@ vi.mock('../../lib/fileUtils.js', async () => {});const local = await import('./local.js');-const settings = await import('./settings.js');+const places = await import('./places.js');const { createWork } = local;const {- listSettings, createSetting, updateSetting, deleteSetting,- mergeExtractedSettings, normalizeSlugline,-} = settings;+ listPlaces, createPlace, updatePlace, deletePlace,+ mergeExtractedPlaces, normalizeSlugline,+} = places;beforeEach(() => {- tempRoot = mkdtempSync(join(tmpdir(), 'wr-settings-test-'));+ tempRoot = mkdtempSync(join(tmpdir(), 'wr-places-test-'));});afterEach(() => {@@ -54,108 +54,96 @@ describe('writers room — normalizeSlugline', () => {});});-describe('writers room — settings CRUD', () => {+describe('writers room — places CRUD', () => {it('starts with an empty bible', async () => {const id = await newWork();- expect(await listSettings(id)).toEqual([]);+ expect(await listPlaces(id)).toEqual([]);});it('rejects path-traversal-shaped work ids on every read/write helper', async () => {- // Mirrors the characters.js guard. Every helper that interpolates- // workId into the on-disk path must refuse a traversal-shaped id- // with a 400 before any I/O happens.- await expect(listSettings('../../etc')).rejects.toThrow(/work id/i);- await expect(createSetting('../../etc', { slugline: 'X' })).rejects.toThrow(/work id/i);- await expect(mergeExtractedSettings('../../etc', [{ slugline: 'X' }])).rejects.toThrow(/work id/i);+ await expect(listPlaces('../../etc')).rejects.toThrow(/work id/i);+ await expect(createPlace('../../etc', { slugline: 'X' })).rejects.toThrow(/work id/i);+ await expect(mergeExtractedPlaces('../../etc', [{ slugline: 'X' }])).rejects.toThrow(/work id/i);});- it('rejects creating a setting with neither slugline nor name', async () => {+ it('rejects creating a place with neither slugline nor name', async () => {const id = await newWork();- await expect(createSetting(id, {})).rejects.toThrow(/slugline or a name/i);+ await expect(createPlace(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);+ await createPlace(id, { slugline: 'INT. KITCHEN — NIGHT', description: 'cozy' });+ await expect(createPlace(id, { slugline: 'int. kitchen - night' })).rejects.toThrow(/already exists/i);});- it('creates and updates a setting profile', async () => {+ it('creates and updates a place 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 p = await createPlace(id, { slugline: 'EXT. ROOFTOP — DAWN', description: 'pink sky' });+ expect(p.slugline).toBe('EXT. ROOFTOP — DAWN');+ expect(p.id).toMatch(/^wr-place-/);- const updated = await updateSetting(id, s.id, { description: 'pink sky over a copper city' });+ const updated = await updatePlace(id, p.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 () => {+ it('deletes a place', 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);+ const p = await createPlace(id, { slugline: 'INT. ATTIC — DUSK' });+ await deletePlace(id, p.id);+ expect(await listPlaces(id)).toHaveLength(0);});it('rejects an update that would leave both slugline and name blank (name-only created)', async () => {- // Setting was created via name only — slugline=''. Blanking the name- // would leave the record unaddressable; the update must reject.const id = await newWork();- const s = await createSetting(id, { name: 'The Glass Atrium' });- await expect(updateSetting(id, s.id, { name: '' })).rejects.toThrow(/slugline or name/i);+ const p = await createPlace(id, { name: 'The Glass Atrium' });+ await expect(updatePlace(id, p.id, { name: '' })).rejects.toThrow(/slugline or name/i);});it('rejects an update that would leave both slugline and name blank (slugline-only created)', async () => {const id = await newWork();- const s = await createSetting(id, { slugline: 'INT. ATTIC — DUSK' });- // Note: createSetting auto-fills name from slugline when name is omitted,- // so we explicitly clear name first via update, then attempt to clear- // slugline. The combined-blank invariant must still fire.- await updateSetting(id, s.id, { name: '' });- await expect(updateSetting(id, s.id, { slugline: '' })).rejects.toThrow(/slugline or name/i);+ const p = await createPlace(id, { slugline: 'INT. ATTIC — DUSK' });+ await updatePlace(id, p.id, { name: '' });+ await expect(updatePlace(id, p.id, { slugline: '' })).rejects.toThrow(/slugline or name/i);});});-describe('writers room — settings merge', () => {- it('adds new settings from extraction', async () => {+describe('writers room — places merge', () => {+ it('adds new places from extraction', async () => {const id = await newWork();- const merged = await mergeExtractedSettings(id, [+ const merged = await mergeExtractedPlaces(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);+ expect(merged.every((p) => p.source === 'ai')).toBe(true);});it('preserves user edits when re-merging (fill-blanks-only)', async () => {const id = await newWork();- const s = await createSetting(id, {+ const p = await createPlace(id, {slugline: 'INT. KITCHEN — NIGHT',description: 'USER VERSION — copper kettle on the stove',});- expect(s.source).toBe('user');+ expect(p.source).toBe('user');- const merged = await mergeExtractedSettings(id, [{+ const merged = await mergeExtractedPlaces(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);+ const refreshed = merged.find((x) => x.id === p.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.+ it('matches an existing place by name when the incoming entry uses slugline', async () => {const id = await newWork();- await createSetting(id, { name: 'Eldritch Library' });- const merged = await mergeExtractedSettings(id, [{+ await createPlace(id, { name: 'Eldritch Library' });+ const merged = await mergeExtractedPlaces(id, [{slugline: 'INT. ELDRITCH LIBRARY — NIGHT',name: 'Eldritch Library',description: 'rows of leather spines, dust motes',@@ -164,12 +152,10 @@ describe('writers room — settings merge', () => {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.+ it('matches an existing slugline-only place by name on subsequent merges', async () => {const id = await newWork();- await mergeExtractedSettings(id, [{ slugline: 'EXT. SEAWALL — DUSK' }]);- const merged = await mergeExtractedSettings(id, [{+ await mergeExtractedPlaces(id, [{ slugline: 'EXT. SEAWALL — DUSK' }]);+ const merged = await mergeExtractedPlaces(id, [{name: 'EXT. SEAWALL — DUSK',description: 'salt-bleached concrete, gulls overhead',}]);@@ -179,29 +165,25 @@ describe('writers room — settings merge', () => {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, [{+ const p = await createPlace(id, { slugline: 'INT. ATTIC — DUSK', description: 'kept' });+ const merged = await mergeExtractedPlaces(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);+ const updated = merged.find((x) => x.id === p.id);expect(updated.description).toBe('kept');expect(updated.missingFromProse).toEqual(['weather', 'palette']);expect(updated.firstAppearance).toBe('Chapter 2');});- it('back-fills slugline on a name-only existing setting when extraction supplies one', async () => {- // User created a setting via name only ("The Atrium"). A later analysis- // pass extracts the same place with a slugline. The merge MUST- // back-fill `slugline` so storyboard scenes can match this entry by- // slugline; otherwise setting injection silently fails.+ it('back-fills slugline on a name-only existing place when extraction supplies one', async () => {const id = await newWork();- const s = await createSetting(id, { name: 'The Atrium' });- expect(s.slugline).toBe('');- const merged = await mergeExtractedSettings(id, [{+ const p = await createPlace(id, { name: 'The Atrium' });+ expect(p.slugline).toBe('');+ const merged = await mergeExtractedPlaces(id, [{slugline: 'INT. THE ATRIUM — DAY',name: 'The Atrium',description: 'glass dome, copper rails',@@ -213,8 +195,8 @@ describe('writers room — settings merge', () => {it('re-indexes after slugline back-fill so a later batch entry keyed by slugline matches', async () => {const id = await newWork();- await createSetting(id, { name: 'The Vault' });- const merged = await mergeExtractedSettings(id, [+ await createPlace(id, { name: 'The Vault' });+ const merged = await mergeExtractedPlaces(id, [{ slugline: 'INT. THE VAULT — NIGHT', name: 'The Vault', description: 'heavy steel doors' },{ slugline: 'INT. THE VAULT — NIGHT', palette: 'pewter and oxblood' },]);@@ -224,12 +206,8 @@ describe('writers room — settings merge', () => {});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, [+ const merged = await mergeExtractedPlaces(id, [{ slugline: 'INT. CHAPEL — DAWN', name: 'The Old Chapel', description: 'whitewashed walls' },{ name: 'The Old Chapel', palette: 'bone-white and gold' },]);diff --git a/server/services/writersRoom/promoteToPipeline.js b/server/services/writersRoom/promoteToPipeline.jsindex d09d7936c5..8cee95d944 100644--- a/server/services/writersRoom/promoteToPipeline.js+++ b/server/services/writersRoom/promoteToPipeline.js@@ -2,7 +2,7 @@* Writers Room ↔ Pipeline bridge (item 6 of the DRY unification).** `promoteWorkToPipeline(workId)` creates a Pipeline Series + first Issue from- * a Writers Room work — carrying over bibles (characters / settings / objects),+ * a Writers Room work — carrying over bibles (characters / places / objects),* the active draft body, and the latest script-analysis scenes — then records* the bidirectional id link on both sides.*@@ -26,7 +26,7 @@import * as wrLocal from './local.js';import { listCharacters } from './characters.js';-import { listSettings } from './settings.js';+import { listPlaces } from './places.js';import { listObjects } from './objects.js';import { getAnalysis } from './evaluator.js';import * as seriesSvc from '../pipeline/series.js';@@ -91,9 +91,9 @@ export async function promoteWorkToPipeline(workId, { force = false } = {}) {await wrLocal.linkToPipeline(workId, { seriesId: null, issueId: null });}- const [characters, settings, objects, scriptScenes] = await Promise.all([+ const [characters, places, objects, scriptScenes] = await Promise.all([listCharacters(workId),- listSettings(workId),+ listPlaces(workId),listObjects(workId),loadScriptScenes(workId),]);@@ -108,7 +108,7 @@ export async function promoteWorkToPipeline(workId, { force = false } = {}) {const universe = await createUniverse({name: manifest.title,characters,- settings,+ places,objects,});diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.jsindex c4ea1c0886..c1d5946796 100644--- a/server/services/writersRoom/promoteToPipeline.test.js+++ b/server/services/writersRoom/promoteToPipeline.test.js@@ -14,7 +14,7 @@ vi.mock('../../lib/fileUtils.js', async () => {const wrLocal = await import('./local.js');const { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } = await import('./promoteToPipeline.js');const { createCharacter } = await import('./characters.js');-const { createSetting } = await import('./settings.js');+const { createPlace } = await import('./places.js');const { createObject } = await import('./objects.js');const seriesSvc = await import('../pipeline/series.js');const issuesSvc = await import('../pipeline/issues.js');@@ -77,10 +77,10 @@ describe('promoteWorkToPipeline', () => {expect(reloadedSeries.writersRoomWorkId).toBe(work.id);});- it('carries over characters / settings / objects bibles into the linked universe (Phase B.4)', async () => {+ it('carries over characters / places / objects bibles into the linked universe (Phase B.4)', async () => {const work = await seedWorkWithProse();await createCharacter(work.id, { name: 'Aria', physicalDescription: 'tall, freckles' });- await createSetting(work.id, { name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' });+ await createPlace(work.id, { name: 'The Foundry', slugline: 'INT. FOUNDRY — NIGHT', description: 'molten light' });await createObject(work.id, { name: 'The Locket', significance: "mother's keepsake" });const { series } = await promoteWorkToPipeline(work.id);@@ -94,8 +94,8 @@ describe('promoteWorkToPipeline', () => {expect(universe.characters).toHaveLength(1);expect(universe.characters[0].name).toBe('Aria');expect(universe.characters[0].physicalDescription).toBe('tall, freckles');- expect(universe.settings).toHaveLength(1);- expect(universe.settings[0].slugline).toBe('INT. FOUNDRY — NIGHT');+ expect(universe.places).toHaveLength(1);+ expect(universe.places[0].slugline).toBe('INT. FOUNDRY — NIGHT');expect(universe.objects).toHaveLength(1);expect(universe.objects[0].name).toBe('The Locket');});