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(pipeline): setting canon INT/EXT + time-of-day metadata
[._.]/ Adam Eivy57777e8fdc21
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 40788bd878..0cf5f68008 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,32 @@## Added+- **Setting canon: INT/EXT + time-of-day metadata (Cluster A).** Every entry+ under `universe.settings[]` gains two new optional fields — `intExt`+ (`'INT'`/`'EXT'`/null) and `timeOfDay` (`'dawn'`/`'day'`/`'dusk'`/`'night'`+ /null) — that flow through the scene-prompt composer ahead of the description+ fragment so downstream image-gen calls inherit lighting / composition cues+ for free. Sanitizer normalizes case (`int` → `INT`); invalid values fall+ through to null without throwing, so legacy settings keep rendering. The+ scene-prompt builder prepends `Interior, night.` (or whichever subset is+ set) ahead of the existing description / palette / recurring-details+ fragments. Universe Canon + Nouns stage cards surface the new fields as+ inline chip pickers (single-click to set, click again to clear) that PATCH+ via the existing `updateUniverse` write path; reads stay through optimistic+ state so chips feel instant. The places-extraction LLM prompt asks for+ the two new fields in its JSON contract, with an idempotent migration+ (`007-places-int-ext-time-of-day.js`) auto-updating un-customized+ installs. Touches: `server/lib/storyBible.js` (sanitizer + enum+ normalizer + `SETTING_INT_EXT` / `SETTING_TIME_OF_DAY` exports ++ `PROMPT_FIELDS` + `MERGE_CONFIG.userEditable`),+ `server/lib/validation.js` (Zod parity with case-insensitive preprocessing),+ `server/lib/scenePrompt.js` + `client/src/lib/scenePrompt.js` (composer+ metadata fragment), `client/src/components/pipeline/CanonCard.jsx`+ (chip pickers + read-only chips), `client/src/pages/UniverseCanon.jsx`,+ `client/src/components/pipeline/stages/NounsStage.jsx` (optimistic+ PATCH wiring), `data.sample/prompts/stages/writers-room-places.md`,+ `data/migrations/007-places-int-ext-time-of-day.js`, `scripts/setup-data.js`.+- **Pipeline audio stage: music bed muxed into the episode video (Phase 4d).**When the Creative Director stitch step finishes the timeline render, asecond ffmpeg pass overlays the issue's `stages.audio.music.trackFilename`diff --git a/PLAN.md b/PLAN.mdindex b53d3ae6dd..215f26318f 100644--- a/PLAN.md+++ b/PLAN.md@@ -244,6 +244,7 @@ Skeleton landed in `server/services/pipeline/` + `client/src/pages/Pipeline*.jsx- **4c.3: 3rd-party music engine stubs.** Same UI affordance as the VO engines — once 4c.2 lands the abstraction, 3rd-party engines plug in as sibling sources.- **4d.2: VO line muxing into the CD stitch.** Today's mux only lays the music bed; per-line VO is unmixed. Walk `storyboards.scenes[].dialogue` to map each audio line to a scene, compute scene-start offsets from the per-clip durations (already in `buildTimelineClips`), then build an ffmpeg filter_complex that places each line at `sceneStart + lineOffsetInScene` and ducks the music bed underneath. Open question worth real-world testing: gap-between-lines heuristic (fixed 800ms? scene-length-aware? based on prose pacing?). Touch sites: `server/services/pipeline/audioMux.js` (extend `muxMusicBed` to `muxPipelineAudio` or add a sibling export), `server/services/creativeDirector/stitchRunner.js#maybeMuxPipelineAudio` (compute timing from `clips[]` + storyboards mapping).- [ ] **Lift `runFfmpegProcess({ args, signal, stderrTailBytes }) → { ok, reason }` into `server/lib/ffmpeg.js`.** Three call sites today share the spawn → stderr-tail → close → SIGTERM-on-abort pattern: `audioMux.js#runFfmpeg`, `server/lib/ffmpeg.js#upscaleVideo2x`, `server/lib/ffmpeg.js#optimizeForStreaming`. `videoTimeline/local.js` has a fourth variant with per-line broadcast that complicates a full migration — leave that one local. The two simpler call sites collapse to one-liners. Surfaced from /simplify on Phase 4d.+- [ ] **Extract `useCanonPatch(universe, setUniverse, universeId, mountedRef)` if a third caller appears.** Today `UniverseCanon.jsx#handlePatchEntry` and `NounsStage.jsx#handlePatchEntry` are 95% identical (optimistic UI update + `updateUniverse` PATCH + on-success reconcile). Extract into `client/src/hooks/useCanonPatch.js` so the third caller doesn't fork the pattern. YAGNI at two call sites today. Surfaced from /simplify on the Cluster A setting-metadata work.- [ ] **AbortSignal listener cleanup in `audioMux.js#runFfmpeg`.** Today the `signal.addEventListener('abort', kill, { once: true })` is never removed on normal completion. Only a leak if the same `AbortController` is reused across many calls — the stitch step doesn't yet pass a signal, so this is theoretical. Fix when wiring real cancellation: capture the handler ref + `signal.removeEventListener('abort', handler)` in both `close` and `error` paths. Surfaced from /simplify on Phase 4d.- [ ] **Extract `listDirectoryByExtension(dir, { extensions, mapEntry })` helper in `server/lib/fileUtils.js`.** Three call sites today follow the same readdir + filter-by-extension + stat-per-entry shape: `server/services/loras.js#listLoras` (sidecar reads), `server/services/imageGen/local.js#listGallery` (civitai-aware fields), `server/services/pipeline/musicLibrary.js#listMusicLibrary`. Each carries domain-specific per-entry mapping, so the shared helper takes a `mapEntry(dirent, statResult) → entry|null` callback. Saves ~15 LOC at each site plus a single fix-point for future "use `readdir(withFileTypes:true)` to skip the stat when only `.isFile()` is needed" optimization. Surfaced from the /simplify pass on Phase 4c.- [ ] **Teach `request()` in `client/src/services/apiCore.js` about FormData.** Two helpers today bypass `request()` because it hard-codes `Content-Type: application/json`: `apiHealth.js#uploadAppleHealthXml` and `apiPipeline.js#uploadPipelineMusicTrack`. Each re-implements the error-shape extraction (`{ error, code, status }`) inline. Fix: in `request()`, when `body instanceof FormData`, omit the `Content-Type` header so the browser sets `multipart/form-data; boundary=...` automatically. Both call sites then collapse to a single `request()` call. Surfaced from the /simplify pass on Phase 4c.diff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 44d51364bc..e8e2fd6c96 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -12,6 +12,46 @@ import { Loader2, ImagePlus, WandSparkles, Lock, Unlock } from 'lucide-react';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import MediaJobThumb from './MediaJobThumb';+// 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+// 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'];++function ChipPicker({ label, value, options, onChange }) {+ return (+ <div className="flex items-center gap-1">+ <span className="text-[10px] uppercase tracking-wider text-gray-500">{label}:</span>+ {options.map((opt) => {+ const active = value === opt;+ return (+ <button+ key={opt}+ type="button"+ onClick={() => onChange(active ? null : opt)}+ className={`px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider border ${+ active+ ? 'bg-port-accent/20 border-port-accent text-port-accent'+ : 'border-port-border text-gray-400 hover:text-white hover:border-gray-500'+ }`}+ title={active ? `Clear ${label}` : `Set ${label} to ${opt}`}+ >+ {opt}+ </button>+ );+ })}+ </div>+ );+}++function ReadonlyChip({ children }) {+ return (+ <span className="px-1.5 py-0.5 rounded text-[10px] uppercase tracking-wider bg-port-card border border-port-border text-gray-400">+ {children}+ </span>+ );+}+export default function CanonCard({kind, entry,inFlightJobId,@@ -24,6 +64,9 @@ export default function CanonCard({// unlockable-only at the universe level. Called with `(entryId, nextLocked)`.onToggleLock = null,togglingLock = false,+ // Optional — when provided + kind is settings, surfaces inline chip pickers+ // for `intExt` / `timeOfDay`. Called with `(entryId, { intExt?, timeOfDay? })`.+ onPatchEntry = null,}) {const description = kind.descFor(entry);const refs = Array.isArray(entry.imageRefs) ? entry.imageRefs : [];@@ -89,6 +132,27 @@ 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 ? (+ <div className="flex flex-wrap items-center gap-2 mt-2">+ <ChipPicker+ label="INT/EXT"+ value={entry.intExt}+ options={INT_EXT_OPTIONS}+ onChange={(v) => onPatchEntry(entry.id, { intExt: v })}+ />+ <ChipPicker+ label="Time"+ value={entry.timeOfDay}+ options={TIME_OF_DAY_OPTIONS}+ onChange={(v) => onPatchEntry(entry.id, { timeOfDay: v })}+ />+ </div>+ ) : kind.key === 'settings' && (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}+ </div>+ ) : null}</div><div className="shrink-0 flex flex-col gap-1 items-stretch">{onToggleLock ? (diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex ad46b332ef..0667223c80 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -265,6 +265,21 @@ export default function NounsStage({ issue, series }) {if (updated && mountedRef.current) setUniverse(updated);}, [universe, mountedRef]);+ // Inline-edit channel for canon fields the user picks directly (today:+ // setting intExt + timeOfDay chips). Optimistic — UI updates before the+ // server roundtrip so chip clicks feel instant.+ const handlePatchEntry = useCallback(async (kind, entryId, patch) => {+ if (!universe || !patch || typeof patch !== 'object') return;+ const kindKey = kind.key;+ const list = (universe[kindKey] || []).map((e) =>+ e.id === entryId ? { ...e, ...patch } : e,+ );+ setUniverse((prev) => prev ? { ...prev, [kindKey]: list } : prev);+ const updated = await updateUniverse(universe.id, { [kindKey]: list })+ .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });+ if (updated && mountedRef.current) setUniverse(updated);+ }, [universe, mountedRef]);+const handleRefFailed = useCallback((entryId, errMsg) => {setRenderingJobs((prev) => {if (!prev[entryId]) return prev;@@ -350,6 +365,7 @@ export default function NounsStage({ issue, series }) {onPreview={openPreview}onRefine={handleRefineCharacter}refiningCharacterId={refiningCharacterId}+ onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}/>))}@@ -367,7 +383,7 @@ export default function NounsStage({ issue, series }) {);}-function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId }) {+function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningCharacterId, onPatchEntry }) {const Icon = kind.icon;const inIssue = useMemo(() => kind.match(prose, all), [prose, all, kind]);const inIssueIds = useMemo(() => new Set(inIssue.map((e) => e.id || e.name)), [inIssue]);@@ -411,6 +427,7 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompletedonRefine={onRefine}refining={refiningCharacterId === entry.id}refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}+ onPatchEntry={onPatchEntry}/>))}</ul>@@ -437,6 +454,7 @@ function KindSection({ kind, all, prose, renderingJobs, onRender, onJobCompletedonRefine={onRefine}refining={refiningCharacterId === entry.id}refineDisabled={!!refiningCharacterId && refiningCharacterId !== entry.id}+ onPatchEntry={onPatchEntry}/>))}</ul>diff --git a/client/src/lib/scenePrompt.js b/client/src/lib/scenePrompt.jsindex 65f947cbae..6c294df4ad 100644--- a/client/src/lib/scenePrompt.js+++ b/client/src/lib/scenePrompt.js@@ -89,7 +89,17 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyleconst titlePart = workTitle ? `${workTitle}. ` : '';const visual = scene?.visualPrompt || scene?.description || '';+ const intExtPart = matchedSetting?.intExt === 'INT'+ ? 'Interior'+ : matchedSetting?.intExt === 'EXT'+ ? 'Exterior'+ : '';+ const todPart = typeof matchedSetting?.timeOfDay === 'string' && matchedSetting.timeOfDay+ ? matchedSetting.timeOfDay+ : '';+ const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');const settingFrags = matchedSetting ? [+ settingMetaFrag ? `${settingMetaFrag}.` : '',matchedSetting.description?.trim() || '',matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',matchedSetting.recurringDetails?.trim() || '',diff --git a/client/src/pages/UniverseCanon.jsx b/client/src/pages/UniverseCanon.jsxindex 7c1a0b4f8f..41a17cdc3d 100644--- a/client/src/pages/UniverseCanon.jsx+++ b/client/src/pages/UniverseCanon.jsx@@ -237,6 +237,21 @@ export default function UniverseCanon() {if (errMsg) toast.error(`Render failed: ${errMsg}`);}, []);+ // Inline-edit channel for canon fields the user types/picks directly+ // (today: setting intExt + timeOfDay chips). Optimistic — UI updates+ // before the server roundtrip so chip clicks feel instant.+ const handlePatchEntry = useCallback(async (kind, entryId, patch) => {+ if (!universe || !patch || typeof patch !== 'object') return;+ const kindKey = kind.key;+ const list = (universe[kindKey] || []).map((e) =>+ e.id === entryId ? { ...e, ...patch } : e+ );+ setUniverse((prev) => prev ? { ...prev, [kindKey]: list } : prev);+ const updated = await updateUniverse(universeId, { [kindKey]: list })+ .catch((err) => { toast.error(`Save failed: ${err.message}`); return null; });+ if (updated && mountedRef.current) setUniverse(updated);+ }, [universe, universeId, mountedRef]);+if (loadErr) return <div className="p-4 text-port-error">{loadErr}</div>;if (!universe) return <div className="p-4 text-gray-500 italic">Loading universe…</div>;@@ -329,6 +344,7 @@ export default function UniverseCanon() {refiningId={refiningId}onToggleLock={(entryId, nextLocked) => handleToggleLock(kind, entryId, nextLocked)}togglingLockId={togglingLockId}+ onPatchEntry={(entryId, patch) => handlePatchEntry(kind, entryId, patch)}/>))}@@ -337,7 +353,7 @@ export default function UniverseCanon() {);}-function KindSection({ kind, all, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId }) {+function KindSection({ kind, all, usage, renderingJobs, onRender, onJobCompleted, onJobFailed, onPreview, onRefine, refiningId, onToggleLock, togglingLockId, onPatchEntry }) {const Icon = kind.icon;return (<section className="rounded-lg border border-port-border bg-port-card/40">@@ -367,6 +383,7 @@ function KindSection({ kind, all, usage, renderingJobs, onRender, onJobCompletedusage={usage?.[entry.id] || null}onToggleLock={onToggleLock}togglingLock={togglingLockId === entry.id}+ onPatchEntry={onPatchEntry}/>))}</ul>diff --git a/data.sample/prompts/stages/writers-room-places.md b/data.sample/prompts/stages/writers-room-places.mdindex 2598ccc9b0..21a3838b0d 100644--- a/data.sample/prompts/stages/writers-room-places.md+++ b/data.sample/prompts/stages/writers-room-places.md@@ -34,6 +34,8 @@ For every distinct *location* the prose stages a scene in (interior or exterior)- `era` — short tag (`near-future`, `1950s noir`, `present day`, `Victorian`). One phrase. Skip if the prose is ambiguous.- `weather` — recurring atmospheric conditions inside this place (`muggy curry-steam`, `dust motes in shafts of sun`, `permanent drizzle out the window`). Skip if the prose doesn't establish one.- `recurringDetails` — 1–2 sentences listing distinctive props or fixtures the prose returns to (`three tiny tables and standing room only`, `a dead jukebox in the corner`). These are the visual anchors that keep scenes in the same place looking the same.+ - `intExt` — `"INT"` for interiors, `"EXT"` for exteriors. Drives lighting + composition cues in downstream renders. Omit only if the prose genuinely doesn't settle one way (rare).+ - `timeOfDay` — one of `"dawn"`, `"day"`, `"dusk"`, `"night"` when the prose stages the place at a consistent time. Skip if the location appears across multiple times of day without a dominant.- `firstAppearance` — short quote (≤ 120 chars) from the prose where the location first shows up, or null if not clear.- `evidence` — array of 1–3 short verbatim quotes (≤ 120 chars each) from the prose that support the description specifically.@@ -62,6 +64,8 @@ Return ONLY valid JSON matching this shape — no prose, no markdown fence, no c"era": "string","weather": "string","recurringDetails": "string",+ "intExt": "INT or EXT or null",+ "timeOfDay": "dawn or day or dusk or night or null","firstAppearance": "string or null","evidence": ["string", ...],"missingFromProse": ["palette", "weather", ...]diff --git a/data/migrations/007-places-int-ext-time-of-day.js b/data/migrations/007-places-int-ext-time-of-day.jsnew file mode 100644index 0000000000..60fbd0a23e--- /dev/null+++ b/data/migrations/007-places-int-ext-time-of-day.js@@ -0,0 +1,86 @@+/**+ * Augment `writers-room-places.md` with `intExt` + `timeOfDay` fields in the+ * extraction schema. Adds two new bullet items in the field list and two new+ * keys in the JSON output contract so downstream scene-prompt composition+ * gets first-class lighting/composition cues.+ *+ * Strategy mirrors migration 004: replace the installed file only when its+ * hash still matches the previously-shipped version. Customized files are+ * skipped with a manual-merge warning.+ */++import { readFile, writeFile } 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 OLD_SHIPPED_MD5 = {+ 'writers-room-places.md': '7f1f80eb63d67a21161994cde115045e',+};++const NEW_SHIPPED_MD5 = {+ 'writers-room-places.md': '24a33628cc94d80fa5ca60831d973daf',+};++export default {+ async up({ rootDir }) {+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');++ let updated = 0;+ let alreadyCurrent = 0;+ let skipped = 0;++ for (const filename of Object.keys(OLD_SHIPPED_MD5)) {+ const dataPath = join(stagesDir, filename);+ const samplePath = join(sampleDir, filename);++ const existing = await readFile(dataPath, 'utf-8').catch((err) => {+ if (err.code !== 'ENOENT') throw err;+ return null;+ });++ if (existing === null) {+ console.log(`📄 writers-room places prompt ${filename}: not present in data/, will be created by setup-data.js`);+ continue;+ }++ const existingMd5 = md5(existing);++ if (existingMd5 === NEW_SHIPPED_MD5[filename]) {+ alreadyCurrent++;+ continue;+ }++ if (existingMd5 !== OLD_SHIPPED_MD5[filename]) {+ console.warn(+ `⚠️ places extraction prompt ${filename} has been customized — skipping auto-update.\n` ++ ` To pick up the new intExt / timeOfDay fields, diff:\n` ++ ` data.sample/prompts/stages/${filename}\n` ++ ` against your current:\n` ++ ` data/prompts/stages/${filename}\n` ++ ` and add the two new field bullets + two new JSON keys.`,+ );+ skipped++;+ continue;+ }++ const sampleContent = await readFile(samplePath, 'utf-8');+ await writeFile(dataPath, sampleContent);+ console.log(`✅ updated places extraction prompt: ${filename}`);+ updated++;+ }++ if (updated > 0) {+ console.log(`📝 places int-ext/time-of-day migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);+ } else if (skipped > 0) {+ console.log(`📝 places int-ext/time-of-day migration: file customized (${skipped} skipped)`);+ } else {+ console.log(`📝 places int-ext/time-of-day migration: already up to date`);+ }+ },+};diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex edcb0b609a..90473dc6f9 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -142,6 +142,8 @@ const SHIPPED_PROMPT_OLD_MD5 = {'pipeline-arc-resolve.md': '87bc5c01f1a8a97b681727a38b05edc6',// 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',};const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-idea-expansion.md': '1ee44cf95851ff8debf18729ebcd40b4',@@ -154,6 +156,7 @@ const SHIPPED_PROMPT_NEW_MD5 = {'pipeline-volume-verify.md': '03f3c874cb80e1c98abcf03168fa7a92','pipeline-arc-resolve.md': 'a8677bbe1eb38f871fb152a5b0fec7c6','pipeline-extract-scenes.md': 'c51fb208568d0d903eb43b437478b0ba',+ 'writers-room-places.md': '24a33628cc94d80fa5ca60831d973daf',};const SHIPPED_PROMPT_FILES = Object.keys(SHIPPED_PROMPT_OLD_MD5);diff --git a/server/lib/scenePrompt.js b/server/lib/scenePrompt.jsindex b73db757e5..9ff8496fb2 100644--- a/server/lib/scenePrompt.js+++ b/server/lib/scenePrompt.js@@ -127,7 +127,20 @@ export function buildScenePrompt(workTitle, scene, matchedCharacters, worldStyleconst titlePart = workTitle ? `${workTitle}. ` : '';const visual = scene?.visualPrompt || scene?.description || '';+ // 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'+ ? 'Interior'+ : matchedSetting?.intExt === 'EXT'+ ? 'Exterior'+ : '';+ const todPart = typeof matchedSetting?.timeOfDay === 'string' && matchedSetting.timeOfDay+ ? matchedSetting.timeOfDay+ : '';+ const settingMetaFrag = [intExtPart, todPart].filter(Boolean).join(', ');const settingFrags = matchedSetting ? [+ settingMetaFrag ? `${settingMetaFrag}.` : '',matchedSetting.description?.trim() || '',matchedSetting.palette ? `Palette: ${matchedSetting.palette.trim()}.` : '',matchedSetting.recurringDetails?.trim() || '',diff --git a/server/lib/scenePrompt.test.js b/server/lib/scenePrompt.test.jsindex 24a0a5125a..95f2ed456b 100644--- a/server/lib/scenePrompt.test.js+++ b/server/lib/scenePrompt.test.js@@ -114,6 +114,36 @@ describe('scenePrompt — buildScenePrompt', () => {.toBeLessThan(out.indexOf('wide shot of two figures'));});+ it('prepends INT/EXT + time-of-day before the setting description (Cluster A)', () => {+ const out = buildScenePrompt(+ '',+ baseScene,+ [],+ '',+ { description: 'cramped chrome bar', intExt: 'INT', timeOfDay: 'night' },+ );+ expect(out).toContain('Interior, night.');+ expect(out.indexOf('Interior, night.'))+ .toBeLessThan(out.indexOf('cramped chrome bar'));+ });++ it('honors only one of intExt / timeOfDay if the other is null', () => {+ const intOnly = buildScenePrompt('', baseScene, [], '', { description: 'bar', intExt: 'EXT', timeOfDay: null });+ expect(intOnly).toContain('Exterior.');+ expect(intOnly).not.toContain(',');++ const todOnly = buildScenePrompt('', baseScene, [], '', { description: 'bar', intExt: null, timeOfDay: 'dawn' });+ expect(todOnly).toContain('dawn.');+ expect(todOnly).not.toContain('Interior');+ expect(todOnly).not.toContain('Exterior');+ });++ it('emits no metadata fragment when both fields are missing (legacy settings)', () => {+ const out = buildScenePrompt('', baseScene, [], '', { description: 'bar' });+ expect(out).not.toContain('Interior');+ expect(out).not.toContain('Exterior');+ });+it('accepts pipeline-flavored characters (description in lieu of physicalDescription)', () => {const out = buildScenePrompt('Series',diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 815ead5e3d..7763626aca 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -73,6 +73,25 @@ export const BIBLE_KIND = Object.freeze({OBJECT: 'object',});+// Enums for the location-classification fields on Setting 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);++const trimEnum = (raw, allowed) => {+ if (typeof raw !== 'string') return null;+ const trimmed = raw.trim();+ if (!trimmed) return null;+ const upper = trimmed.toUpperCase();+ if (allowed.has(upper)) return upper;+ const lower = trimmed.toLowerCase();+ if (allowed.has(lower)) return lower;+ return null;+};+// Canonical pluralization: pipeline series.<field>, evaluator analysis kind,// extractor LLM envelope key — all the same string, consolidated here.export const BIBLE_FIELD = Object.freeze({@@ -95,7 +114,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', 'prompt', 'tags'],- [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'recurringDetails', 'prompt', 'tags'],+ [BIBLE_KIND.SETTING]: ['name', 'slugline', 'description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails', 'prompt', 'tags'],[BIBLE_KIND.OBJECT]: ['name', 'aliases', 'description', 'significance', 'prompt', 'tags'],});@@ -222,6 +241,11 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, prepalette: 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+ // keep rendering with description-only prompts.+ intExt: trimEnum(raw.intExt, SETTING_INT_EXT_SET),+ timeOfDay: trimEnum(raw.timeOfDay, SETTING_TIME_OF_DAY_SET),recurringDetails: trimTo(raw.recurringDetails, BIBLE_LIMITS.RECURRING_DETAILS_MAX),notes: trimTo(raw.notes, BIBLE_LIMITS.NOTES_MAX),imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),@@ -298,7 +322,7 @@ const MERGE_CONFIG = Object.freeze({],},setting: {- userEditable: ['description', 'palette', 'era', 'weather', 'recurringDetails'],+ userEditable: ['description', 'palette', 'era', 'weather', 'intExt', 'timeOfDay', 'recurringDetails'],keyFields: [{ field: 'slugline', normalize: normalizeSlugline },{ field: 'name', normalize: normalizeSlugline },diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex e3f0fc4c73..b21e2d6dd8 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -171,6 +171,32 @@ describe('storyBible — sanitizeSetting', () => {expect(out.palette).toBe('amber, neon-red');expect(out.evidence).toEqual(['ch1: opens here']);});++ describe('intExt + timeOfDay (Cluster A)', () => {+ it('persists valid enums', () => {+ const out = sanitizeSetting({ 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' });+ 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' });+ expect(out.intExt).toBeNull();+ expect(out.timeOfDay).toBeNull();+ });++ it('treats missing/empty as null (legacy settings)', () => {+ const out = sanitizeSetting({ name: 'Bar' });+ expect(out.intExt).toBeNull();+ expect(out.timeOfDay).toBeNull();+ });+ });});describe('storyBible — sanitizeObject', () => {diff --git a/server/lib/validation.js b/server/lib/validation.jsindex a0c4b80ad4..d0b041df77 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -664,6 +664,16 @@ const writersRoomSettingCreateObject = z.object({weather: wrSettingTextField.optional(),recurringDetails: wrSettingTextField.optional(),notes: wrSettingTextField.optional(),+ // Cluster A — INT/EXT + time-of-day taxonomy. Case-insensitive accept+ // mirrors the sanitizer (`INT`/`int` both normalize to `INT`).+ intExt: z.preprocess(+ (v) => (typeof v === 'string' ? v.trim().toUpperCase() : v),+ z.enum(['INT', 'EXT']),+ ).nullable().optional(),+ timeOfDay: z.preprocess(+ (v) => (typeof v === 'string' ? v.trim().toLowerCase() : v),+ z.enum(['dawn', 'day', 'dusk', 'night']),+ ).nullable().optional(),}).strict();const settingHasIdentifier = (v) =>(v.name && v.name.trim()) || (v.slugline && v.slugline.trim());@@ -680,6 +690,16 @@ export const writersRoomSettingUpdateSchema = z.object({weather: wrSettingTextField.optional(),recurringDetails: wrSettingTextField.optional(),notes: wrSettingTextField.optional(),+ // Cluster A — INT/EXT + time-of-day taxonomy. Case-insensitive accept+ // mirrors the sanitizer (`INT`/`int` both normalize to `INT`).+ intExt: z.preprocess(+ (v) => (typeof v === 'string' ? v.trim().toUpperCase() : v),+ z.enum(['INT', 'EXT']),+ ).nullable().optional(),+ timeOfDay: z.preprocess(+ (v) => (typeof v === 'string' ? v.trim().toLowerCase() : v),+ z.enum(['dawn', 'day', 'dusk', 'night']),+ ).nullable().optional(),}).strict();const wrObjectTextField = z.string().max(2000);