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
refactor(universe-canon): simplify-pass fixes for Phase B.4
[._.]/ Adam Eivy0111043b9745
diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex 58cc066a3c..5416f10693 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -8,12 +8,8 @@* refine / render-reference) target the universe directly.** A series with no `universeId` gets a gate banner directing the user to- * link a universe — the orphan-series legacy flow was removed in Phase B.3b- * since every active series in this install was migrated, and keeping the- * dual-path branching just added complexity. Server-side legacy paths- * remain for now (`extractAndMergeIntoSeries` etc.), but no UI exercises- * them — they're scheduled for a future cleanup once the schema fields- * (`series.{characters,settings,objects}`) get dropped too.+ * link a universe — orphan-series canon was removed in Phase B.4 (the+ * series schema no longer carries `characters` / `settings` / `objects`).*/import { useCallback, useEffect, useMemo, useState } from 'react';@@ -34,6 +30,7 @@ import {} from '../../../lib/scenePrompt';import { composeStyledPrompt } from '../../../lib/composeStyledPrompt';import { composeCleanPlatePrompt } from '../../../lib/cleanPlatePrompt';+import { joinInfluenceList } from '../../../lib/joinInfluenceList';import useMounted from '../../../hooks/useMounted';import CanonCard from '../CanonCard';import MediaPreview from '../../media/MediaPreview';@@ -71,16 +68,18 @@ const KINDS = [},];-// Stitch the series' optional `stylePromptOverride` ahead of the linked-// universe's stylePrompt — mirrors server-side `applyWorldStyle` in-// visualStages.js so client preview renders match comic-page renders.+// Mirrors server-side `applyWorldStyle` (visualStages.js): the series'+// optional `stylePromptOverride` prepends ahead of the universe's embrace+// chip list, joined with the same `'. '` separator the server uses. Without+// this parity, client preview renders drift from comic-page renders.const universeStylePreset = (universe, series) => {if (!universe) return null;- const stylePrompt = [series?.stylePromptOverride, universe.stylePrompt]- .map((s) => (s || '').trim())- .filter(Boolean)- .join('. ');- return { prompt: stylePrompt, negativePrompt: universe.negativePrompt };+ const override = (series?.stylePromptOverride || '').trim();+ const embrace = joinInfluenceList(universe.influences?.embrace);+ const avoid = joinInfluenceList(universe.influences?.avoid);+ const prompt = [override, embrace].filter(Boolean).join('. ');+ if (!prompt && !avoid) return null;+ return { prompt, negativePrompt: avoid };};export default function NounsStage({ issue, series }) {diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex 5bc896517f..7fd00a7e45 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -2,7 +2,7 @@* Pipeline — Series detail page.** Two-pane layout (Phase 1 of the Story Arc Planning redesign):- * - Left : bible sidebar (name, logline, premise, characters, style, world). Sticky,+ * - Left : bible sidebar (name, logline, premise, style, linked universe). Sticky,* internally scrollable, collapsible into a hairline rail at lg+. State* persists in localStorage under PIPELINE_SIDEBAR_KEY.* - Right : structural canvas — today a card grid of issues/episodes; in subsequent@@ -13,7 +13,7 @@import { useEffect, useRef, useState } from 'react';import { Link, useParams, useNavigate } from 'react-router-dom';import {- ArrowLeft, Plus, Save, Trash2, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,+ ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,PanelLeftClose, PanelLeftOpen,} from 'lucide-react';import toast from '../components/ui/Toast';@@ -95,7 +95,6 @@ export default function PipelineSeries() {const saved = lastSavedRef.current || series;const fields = ['name', 'logline', 'premise', 'styleNotes', 'stylePromptOverride', 'issueCountTarget', 'universeId'];const dirty = fields.some((k) => (series[k] ?? '') !== (saved[k] ?? ''))- || JSON.stringify(series.characters || []) !== JSON.stringify(saved.characters || [])|| JSON.stringify(series.llm || {}) !== JSON.stringify(saved.llm || {});if (!dirty) return false;const updated = await updatePipelineSeries(series.id, {@@ -106,7 +105,6 @@ export default function PipelineSeries() {styleNotes: series.styleNotes,stylePromptOverride: series.stylePromptOverride || '',issueCountTarget: series.issueCountTarget,- characters: series.characters,llm: series.llm || { provider: null, model: null },}).catch((err) => {toast.error(`Pre-flush save failed: ${err.message}`);@@ -126,23 +124,6 @@ export default function PipelineSeries() {if (didSave) toast.success('Series saved');};- const handleAddCharacter = () => {- patchSeries({- characters: [- ...(series.characters || []),- { name: '', role: '', physicalDescription: '', personality: '', background: '' },- ],- });- };- const handleUpdateCharacter = (i, patch) => {- const next = [...series.characters];- next[i] = { ...next[i], ...patch };- patchSeries({ characters: next });- };- const handleRemoveCharacter = (i) => {- patchSeries({ characters: series.characters.filter((_, j) => j !== i) });- };-// ArcCanvas mutates issues via a setter-style update (`setState(fn)`-shaped)// so child components can do prev-aware patches without parent intervention.// Plain array updates also work — flatten through `Array.isArray` to keep@@ -191,9 +172,6 @@ export default function PipelineSeries() {series={series}universes={universes}patchSeries={patchSeries}- onAddCharacter={handleAddCharacter}- onUpdateCharacter={handleUpdateCharacter}- onRemoveCharacter={handleRemoveCharacter}onCollapse={toggleSidebar}/></aside>@@ -239,7 +217,7 @@ export default function PipelineSeries() {);}-function BibleSidebar({ series, universes, patchSeries, onAddCharacter, onUpdateCharacter, onRemoveCharacter, onCollapse }) {+function BibleSidebar({ series, universes, patchSeries, onCollapse }) {return (<section className="px-3 py-3 space-y-4"><div className="flex items-center justify-between">@@ -357,73 +335,19 @@ function BibleSidebar({ series, universes, patchSeries, onAddCharacter, onUpdate) : null}<div>- <div className="flex items-center justify-between mb-2">- <h3 className="text-xs uppercase tracking-wider text-gray-500">Characters</h3>- <button- type="button"- onClick={onAddCharacter}- className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline"+ <h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Canon</h3>+ {series.universeId ? (+ <Link+ to={`/universe-builder/${encodeURIComponent(series.universeId)}/canon`}+ className="block text-xs text-port-accent hover:underline">- <Plus size={12} /> Add- </button>- </div>- {(series.characters || []).length === 0 ? (- <p className="text-xs text-gray-600 italic">No characters yet — the bible has more bite once a few are defined.</p>+ Manage characters, places, and objects on the linked Universe →+ </Link>) : (- <ul className="space-y-2">- {series.characters.map((c, i) => (- <li key={i} className="space-y-1 pb-2 border-b border-port-border/40 last:border-b-0 last:pb-0">- <div className="flex gap-2 items-center">- <input- value={c.name || ''}- onChange={(e) => onUpdateCharacter(i, { name: e.target.value })}- placeholder="Name"- className="flex-1 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"- maxLength={200}- />- <input- value={c.role || ''}- onChange={(e) => onUpdateCharacter(i, { role: e.target.value })}- placeholder="Role"- className="w-24 px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs"- maxLength={200}- />- <button- type="button"- onClick={() => onRemoveCharacter(i)}- className="text-gray-500 hover:text-port-error p-1.5"- aria-label="Remove character"- >- <Trash2 size={12} />- </button>- </div>- <textarea- value={c.physicalDescription || ''}- onChange={(e) => onUpdateCharacter(i, { physicalDescription: e.target.value })}- placeholder="Physical description — age, build, hair, eyes, wardrobe; drives image-gen"- rows={3}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"- maxLength={2000}- />- <textarea- value={c.personality || ''}- onChange={(e) => onUpdateCharacter(i, { personality: e.target.value })}- placeholder="Personality — temperament, voice, quirks"- rows={2}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"- maxLength={2000}- />- <textarea- value={c.background || ''}- onChange={(e) => onUpdateCharacter(i, { background: e.target.value })}- placeholder="Background — who they are, where they come from"- rows={2}- className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-xs resize-y"- maxLength={2000}- />- </li>- ))}- </ul>+ <p className="text-xs text-gray-600 italic">+ Link a universe above to author characters, places, and objects shared+ across this series' issues.+ </p>)}</div></section>diff --git a/client/src/pages/UniverseCanon.jsx b/client/src/pages/UniverseCanon.jsxindex 74c3c506c9..e5c3acfe33 100644--- a/client/src/pages/UniverseCanon.jsx+++ b/client/src/pages/UniverseCanon.jsx@@ -135,10 +135,14 @@ export default function UniverseCanon() {// If the URL names a series that isn't in this universe's usage map// (stale bookmark, deleted series), drop the param silently so the page- // doesn't show an empty "filtered" view forever.+ // doesn't show an empty "filtered" view forever. One-shot — runs when+ // usage first resolves; later URL changes are driven by the dropdown+ // (handleSeriesFilterChange) which only sets known-good ids.+ const validatedRef = useRef(false);useEffect(() => {- if (!usage || !seriesFilter) return;- if (!seriesOptions.some((s) => s.id === seriesFilter)) {+ if (!usage || validatedRef.current) return;+ validatedRef.current = true;+ if (seriesFilter && !seriesOptions.some((s) => s.id === seriesFilter)) {const next = new URLSearchParams(searchParams);next.delete('series');setSearchParams(next, { replace: true });diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 7e116c1eb2..c5f4876943 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -645,17 +645,16 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(async}// Resolve voice via the shared priority chain (explicit > line override// > character binding > project default). One source of truth, reused by- // the eventual "render all" flow + unit-tested for priority order.- // Phase B.4: the character binding lives on the linked universe — load- // it and pass its canon into resolveVoiceForLine through the series-- // shaped adapter the helper already accepts.- let canonAdapter = null;- if (line.characterId) {+ // the eventual "render all" flow + unit-tested for priority order. Skip+ // the canon load when a higher-priority resolver will win — otherwise+ // every per-line render pays two file reads it doesn't use.+ const needsCanon = !body.voiceId?.trim() && !line.voiceIdOverride && line.characterId;+ let canon = null;+ if (needsCanon) {const series = await seriesSvc.getSeries(issue.seriesId).catch(() => null);- const canon = series ? await getSeriesCanon(series) : null;- canonAdapter = canon ? { characters: canon.characters } : null;+ if (series) canon = await getSeriesCanon(series);}- const voiceId = resolveVoiceForLine(line, canonAdapter, { explicit: body.voiceId });+ const voiceId = resolveVoiceForLine(line, canon, { explicit: body.voiceId });const synthResult = await synthesizeToFile({ text: line.text, voiceId }).catch((err) => { throw mapServiceError(err); });const nextLines = [...lines];diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex dc45ddc2d2..24f25747ae 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -2,9 +2,10 @@* Pipeline — Series Service** A Series is the long-lived parent record for a narrative arc (comic series,- * TV show, or both). It carries the shared "bible" — premise, characters,- * world ref, style notes — that gets injected into every Issue's stage prompts- * so issues stay visually and tonally consistent.+ * TV show, or both). It carries premise + arc + style notes and links to a+ * Universe (`universeId`) where canon — characters, places, objects — lives;+ * those flow into every Issue's stage prompts so issues stay visually and+ * tonally consistent.** Persisted to data/pipeline-series.json. Issues live in their own file* (server/services/pipeline/issues.js) and reference a series by id.diff --git a/server/services/pipeline/seriesCanon.js b/server/services/pipeline/seriesCanon.jsindex f2dd1a1481..7b483cb5d1 100644--- a/server/services/pipeline/seriesCanon.js+++ b/server/services/pipeline/seriesCanon.js@@ -8,7 +8,13 @@ import { getUniverse } from '../universeBuilder.js';const EMPTY = Object.freeze({ characters: [], settings: [], objects: [] });-const pickCanon = (universe) => ({+/**+ * Shape a universe record into `{ characters, settings, 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 : [],objects: Array.isArray(universe?.objects) ? universe.objects : [],diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 04505e0b4e..a6eda591dc 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -42,6 +42,7 @@ import { resolveVisualStyle } from '../../lib/visualStyles.js';import { getDefaultVideoModelId, getVideoModels } from '../../lib/mediaModels.js';import { runStagedLLM } from '../../lib/stageRunner.js';import { runPromptRefine } from './refineHelpers.js';+import { pickCanon } from './seriesCanon.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';const joinStyleParts = (...parts) =>@@ -141,16 +142,10 @@ const loadBibleContext = async (issueId) => {const issue = await getIssue(issueId);const series = await getSeries(issue.seriesId);const world = series.universeId ? await getUniverse(series.universeId).catch(() => null) : null;- // Canon lives on the linked universe (Phase B.4). An orphan series (no- // universeId or a dangling reference) renders against empty canon arrays- // — the visual prompt still includes scene description, just without- // character/setting/object metadata.- const canon = {- characters: Array.isArray(world?.characters) ? world.characters : [],- settings: Array.isArray(world?.settings) ? world.settings : [],- objects: Array.isArray(world?.objects) ? world.objects : [],- };- return { issue, series, world, canon };+ // Orphan series (no universeId or a dangling reference) render against+ // empty canon — the visual prompt still includes scene description,+ // just without character/setting/object metadata.+ return { issue, series, world, canon: pickCanon(world) };})();const [chain, settings] = await Promise.all([issueChain, getSettings()]);return { ...chain, settings };diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex f02ef8d172..c816b3530c 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -705,8 +705,8 @@ export async function listRuns(universeId = null) {// shape the renderer's `composeStyledPrompt` consumes. Tokens have already// been deduped + capped by `sanitizeInfluenceList` at write time, so this is// just a thin join — exported so downstream consumers (universeCanon,-// pipeline/nounRefine, pipeline/visualStages) read a single helper instead-// of each open-coding `(arr || []).join(', ')`.+// pipeline/visualStages) read a single helper instead of each open-coding+// `(arr || []).join(', ')`.export function joinInfluenceList(structured = []) {if (!Array.isArray(structured)) return '';return structured.filter((t) => typeof t === 'string' && t.trim()).join(', ');