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): primary canon reference image + fix canon-PATCH stripping
[._.]/ Adam Eivyd71cb717183a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fd704211d0..b6b9e6cacb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,39 @@## Added+- **Canon entries: primary reference image (Cluster A — A3/A4/A5).** Every+ character, place, and object canon entry gains an optional+ `primaryImageRef: filename | null` slot that pins one of its rendered+ `imageRefs[]` thumbnails as the canonical visual anchor. The CanonCard UI+ surfaces a star button per thumbnail (top-right corner) — clicking the+ star pins; clicking the pinned star unpins. The pinned image gets a+ port-accent border + filled star indicator so the visual hierarchy is+ legible across characters / settings / objects. Stale pointers (primary+ names a filename that was later removed from `imageRefs[]`) auto-clear+ to null on sanitization so the UI doesn't render a broken star. Defers+ automatic injection into downstream panel/scene render prompts to the+ multi-reference image-gen follow-up (PLAN.md). Touches:+ `server/lib/storyBible.js` (new `derivePrimaryImageRef` helper ++ `primaryImageRef` line in all three kind sanitizers),+ `client/src/components/pipeline/CanonCard.jsx` (per-thumbnail star+ overlay).++## Fixed++- **Universe canon writes silently dropped at the Zod layer.** The+ `patchSchema` in `server/routes/universeBuilder.js` didn't list+ `characters` / `settings` / `objects` / `origin`, so Zod's default-strip+ behavior dropped them from PATCH bodies before the service layer's+ `PATCHABLE_SCALARS` reader saw them. Means the inline canon-edit flows+ shipped in earlier Cluster A commits (INT/EXT + time-of-day chips,+ wardrobes editor) appeared to work in the optimistic UI but never+ persisted to disk. The patch schema now accepts canon arrays as+ loose record arrays (the service-layer `sanitizeBibleList` is the+ structural validator), with a regression test in+ `routes/universeBuilder.test.js` pinning the end-to-end persistence.++## Added+- **CoS scheduled-task filter (All / Enabled).** The CoS Schedule tab headergains an All/Enabled filter persisted in the URL (`?filter=enabled`) so theselection is bookmarkable. Counts render once per pass, and each filterdiff --git a/client/src/components/pipeline/CanonCard.jsx b/client/src/components/pipeline/CanonCard.jsxindex 369fcb05b6..1af20a9ce2 100644--- a/client/src/components/pipeline/CanonCard.jsx+++ b/client/src/components/pipeline/CanonCard.jsx@@ -8,7 +8,7 @@*/import { useEffect, useRef, useState } from 'react';-import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight } from 'lucide-react';+import { Loader2, ImagePlus, WandSparkles, Lock, Unlock, Shirt, Plus, Trash2, ChevronDown, ChevronRight, Star } from 'lucide-react';import useMediaJobProgress from '../../hooks/useMediaJobProgress';import MediaJobThumb from './MediaJobThumb';@@ -360,22 +360,55 @@ export default function CanonCard({{inFlightJobId ? (<MediaJobThumb jobId={inFlightJobId} label={`${entry.name} reference`} size="sm" />) : null}- {refs.map((ref) => (- <button- key={ref}- type="button"- onClick={() => onPreview?.(ref)}- title={ref}- className="w-16 h-16 bg-port-bg rounded overflow-hidden border border-port-border hover:border-port-accent/50 cursor-zoom-in p-0"- >- <img- src={`/data/images/${ref}`}- alt={`${entry.name} reference`}- className="w-full h-full object-cover"- loading="lazy"- />- </button>- ))}+ {refs.map((ref) => {+ const isPrimary = entry.primaryImageRef === ref;+ const canPin = !!onPatchEntry && !locked;+ return (+ <div key={ref} className="relative w-16 h-16">+ <button+ type="button"+ onClick={() => onPreview?.(ref)}+ title={ref}+ className={`w-full h-full bg-port-bg rounded overflow-hidden border ${+ isPrimary ? 'border-port-accent' : 'border-port-border hover:border-port-accent/50'+ } cursor-zoom-in p-0`}+ >+ <img+ src={`/data/images/${ref}`}+ alt={`${entry.name} reference`}+ className="w-full h-full object-cover"+ loading="lazy"+ />+ </button>+ {canPin ? (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onPatchEntry(entry.id, { primaryImageRef: isPrimary ? null : ref });+ }}+ title={isPrimary+ ? `Unpin ${ref} as primary reference`+ : `Pin ${ref} as ${entry.name}'s primary reference`}+ className={`absolute top-0.5 right-0.5 p-0.5 rounded ${+ isPrimary+ ? 'bg-port-accent text-white'+ : 'bg-port-bg/80 text-gray-400 hover:text-port-accent'+ }`}+ >+ <Star size={10} fill={isPrimary ? 'currentColor' : 'none'} />+ </button>+ ) : isPrimary ? (+ <span+ title="Primary reference image"+ className="absolute top-0.5 right-0.5 p-0.5 rounded bg-port-accent text-white"+ >+ <Star size={10} fill="currentColor" />+ </span>+ ) : null}+ </div>+ );+ })}</div>) : null}{usage && usage.length > 0 ? (diff --git a/server/lib/storyBible.js b/server/lib/storyBible.jsindex 95f356fee6..f92c8bbf08 100644--- a/server/lib/storyBible.js+++ b/server/lib/storyBible.js@@ -181,6 +181,17 @@ function ensureFirstAppearance(raw) {return isStr(raw) && raw.trim() ? raw.trim().slice(0, 200) : null;}+// Primary reference image (A3/A4/A5). User pins one of the canon entry's+// existing `imageRefs[]` as the canonical visual anchor. Stale pointers+// (primary names a filename that was later removed from imageRefs) collapse+// to null so the UI doesn't render a broken star indicator. Returns the+// validated filename or null — never undefined, so the shape stays explicit.+function derivePrimaryImageRef(raw, imageRefs) {+ if (!isStr(raw) || !raw.trim()) return null;+ const trimmed = raw.trim().slice(0, BIBLE_LIMITS.IMAGE_REF_MAX);+ return imageRefs.includes(trimmed) ? trimmed : null;+}+// Wardrobe sanitizer (A2). One entry per outfit/styling variant; the// description is image-gen-ready prose ("worn linen suit, gold pocket watch,// scuffed wingtips"). Reference images per wardrobe land in a follow-up.@@ -236,6 +247,7 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,BIBLE_LIMITS.PHYSICAL_DESCRIPTION_MAX,);const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();+ const imageRefs = cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX);return {id: ensureId(raw.id, idPrefix),name,@@ -248,7 +260,10 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,// Voice binding for VO synthesis (kokoro/piper local OSS, ElevenLabs// when configured). null = use the project default at synth time.voiceId: trimTo(raw.voiceId, BIBLE_LIMITS.VOICE_ID_MAX) || null,- imageRefs: cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX),+ imageRefs,+ // Pinned visual anchor (A3). One of imageRefs marked canonical so+ // downstream renders + the UI know which to lean on.+ primaryImageRef: derivePrimaryImageRef(raw.primaryImageRef, imageRefs),// Wardrobes (A2): outfit/styling variants applied on top of// physicalDescription. Empty array stays the legacy shape — every// existing character keeps rendering through physicalDescription alone.@@ -270,6 +285,7 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, pre// 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();+ const imageRefs = cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX);return {id: ensureId(raw.id, idPrefix),name,@@ -285,7 +301,9 @@ export function sanitizeSetting(raw, { idPrefix = DEFAULT_ID_PREFIX.setting, pretimeOfDay: 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),+ imageRefs,+ // A4: clean-plate / canonical location render pinned for downstream.+ primaryImageRef: derivePrimaryImageRef(raw.primaryImageRef, imageRefs),firstAppearance: ensureFirstAppearance(raw.firstAppearance),evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),@@ -300,6 +318,7 @@ export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, preseconst name = trimTo(raw.name, BIBLE_LIMITS.NAME_MAX);if (!name) return null;const created = preserveTimestamps && isStr(raw.createdAt) ? raw.createdAt : nowIso();+ const imageRefs = cleanStringArray(raw.imageRefs, BIBLE_LIMITS.IMAGE_REF_MAX, BIBLE_LIMITS.IMAGE_REFS_PER_ENTRY_MAX);return {id: ensureId(raw.id, idPrefix),name,@@ -307,7 +326,9 @@ export function sanitizeObject(raw, { idPrefix = DEFAULT_ID_PREFIX.object, presedescription: trimTo(raw.description, BIBLE_LIMITS.OBJECT_DESCRIPTION_MAX),significance: trimTo(raw.significance, BIBLE_LIMITS.SIGNIFICANCE_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),+ imageRefs,+ // A5: canonical prop / hero-object reference render.+ primaryImageRef: derivePrimaryImageRef(raw.primaryImageRef, imageRefs),firstAppearance: ensureFirstAppearance(raw.firstAppearance),evidence: cleanStringArray(raw.evidence, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),missingFromProse: cleanStringArray(raw.missingFromProse, BIBLE_LIMITS.EVIDENCE_ITEM_MAX, BIBLE_LIMITS.EVIDENCE_PER_ENTRY_MAX),diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.jsindex 21d04d0b38..0fa08823db 100644--- a/server/lib/storyBible.test.js+++ b/server/lib/storyBible.test.js@@ -147,6 +147,51 @@ describe('storyBible — sanitizeCharacter', () => {expect(o.source).toBe('manual');});+ describe('primaryImageRef (Cluster A)', () => {+ it('returns null when not set', () => {+ const out = sanitizeCharacter({ name: 'A', imageRefs: ['a.png'] });+ expect(out.primaryImageRef).toBeNull();+ });++ it('persists a valid pointer that matches one of imageRefs[]', () => {+ const out = sanitizeCharacter({+ name: 'A',+ imageRefs: ['a.png', 'b.png'],+ primaryImageRef: 'b.png',+ });+ expect(out.primaryImageRef).toBe('b.png');+ });++ it('auto-clears a stale pointer when the target was removed from imageRefs[]', () => {+ const out = sanitizeCharacter({+ name: 'A',+ imageRefs: ['a.png'],+ primaryImageRef: 'ghost.png',+ });+ expect(out.primaryImageRef).toBeNull();+ });++ it('rejects non-string pointers without throwing', () => {+ const out = sanitizeCharacter({ name: 'A', imageRefs: ['a.png'], primaryImageRef: 123 });+ expect(out.primaryImageRef).toBeNull();+ });++ it('applies identically to settings and objects', () => {+ const s = sanitizeSetting({+ name: 'Bar',+ imageRefs: ['plate.png'],+ primaryImageRef: 'plate.png',+ });+ expect(s.primaryImageRef).toBe('plate.png');+ const o = sanitizeObject({+ name: 'Watch',+ imageRefs: ['watch1.png', 'watch2.png'],+ primaryImageRef: 'watch2.png',+ });+ expect(o.primaryImageRef).toBe('watch2.png');+ });+ });+describe('wardrobes (Cluster A)', () => {it('defaults to an empty array when omitted', () => {const out = sanitizeCharacter({ name: 'A' });diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 8b98d57e34..9aa9a20565 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -102,6 +102,18 @@ const createSchema = z.object({llm: llmSchema,});+// Canon arrays go through `sanitizeBibleList` in the service layer where+// each entry is validated structurally — accept them loosely here so+// patch-the-whole-list flows (e.g. inline canon edits, render-ref hooks)+// don't fail Zod for legitimately rich shapes. Cap at the bible-wide entry+// limit so a malicious payload can't blow up memory.+// Hard cap mirrors BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) with headroom+// — sanitizer truncates anyway, so this just protects the JSON-parse layer.+const canonArrayField = z.array(z.record(z.unknown())).max(500).optional();+// `origin` is a share-bucket provenance block written by the importer + cleared+// to null by the user; structurally an object or null.+const originField = z.record(z.unknown()).nullable().optional();+const patchSchema = z.object({name: z.string().trim().min(1).max(svc.NAME_MAX_LENGTH).optional(),starterPrompt: z.string().trim().max(svc.STARTER_PROMPT_MAX).optional(),@@ -115,6 +127,15 @@ const patchSchema = z.object({influences: influencesSchema.optional(),locked: lockedSchema.optional(),llm: llmSchema,+ // Canon writes — these flow through sanitizeBibleList server-side so+ // schema parity here is just "accept arrays of records." Without these+ // entries Zod's default strip behavior silently drops them from the+ // 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,+ objects: canonArrayField,+ origin: originField,}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });const expandSchema = z.object({diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.jsindex 980e6be51d..027a4d09bd 100644--- a/server/routes/universeBuilder.test.js+++ b/server/routes/universeBuilder.test.js@@ -172,6 +172,28 @@ describe('universe-builder routes', () => {expect(res.body.stylePrompt).toBe('oil painting');});+ it('PATCH /:id persists canon array writes (characters/settings/objects)', async () => {+ // Regression guard for the Zod-default-strips-unknown-keys bug that+ // would silently drop canon-array writes from the inline-edit UI.+ const app = buildApp();+ const c = await request(app).post('/api/universe-builder').send({ name: 'A' });+ const res = await request(app)+ .patch(`/api/universe-builder/${c.body.id}`)+ .send({+ characters: [{ name: 'Jean', physicalDescription: 'tall, dark hair' }],+ settings: [{ 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.objects).toHaveLength(1);+ expect(res.body.objects[0].name).toBe('Gold pocket watch');+ });+it('DELETE /:id removes the universe', async () => {const app = buildApp();const c = await request(app).post('/api/universe-builder').send({ name: 'A' });