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: add Author persona management and a series author picker
[._.]/ Adam Eivy05edf2d83c0f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2553ced5c5..2a4681c1f5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Author personas — manage reusable authors and pick one for a series** — Create gains an **Authors** page (`/authors`, reachable from the sidebar and ⌘K) for managing reusable author personas: each carries a **name**, **writing style**, **bio**, a **physical description** and a **headshot style** (the prompt inputs for generating a book-cover author headshot), plus an optional headshot image URL. The Series Pipeline's author field — previously a free-text byline on both the create form and the series bible — is now an **author picker** that lists your personas: selecting one stores the persona link (`authorId`) **and** the denormalized byline string on the series, so covers and title screens still render the right name. Picking "— No author —" clears it; a legacy free-text byline with no linked persona is shown as a hint until you link one. Authors are stored in PostgreSQL (`authors` table, `db-primary`); they're local-only for now (a federated peer renders a synced series' byline from the string it carries) — cross-machine sync of the personas themselves is tracked as a follow-up. (`server/services/authors/`, `server/routes/authors.js`, `server/scripts/init-db.sql`, `server/lib/db.js`, `server/services/pipeline/series.js`, `client/src/pages/Authors.jsx`, `client/src/components/pipeline/AuthorPicker.jsx`, `client/src/services/apiAuthors.js`, `client/src/components/Layout.jsx`, `server/lib/navManifest.js`)+- **LoRA dataset grid: collapse captions, click-to-preview, and full-height thumbnails** — The dataset workbench image grid (`/media/training/:id`) gets three usability fixes. A **Hide captions / Show captions** toggle collapses every card's caption editor and action row at once, so you can scan the whole dataset as a clean thumbnail wall. Clicking any thumbnail now opens a **full-size preview lightbox** (← / → to step through the ready images, Esc to close) — the same affordance the media galleries already have. And thumbnails render at their **natural aspect ratio** (fixed column width, full relative height) instead of a fixed square crop, so portrait and landscape training images are no longer sliced off at the top and bottom. (`client/src/components/loraTraining/DatasetImageGrid.jsx`)- **Describe a canon character / place / object from reference image(s)** — Each canon card in the Universe editor (Cast, Places, Objects) gains a **Describe from image(s)** button (the scan-text icon next to Render). Upload one reference image to turn it into an image-gen-ready prose description, or several images of the *same* subject (a character from multiple angles, a location across lighting conditions) and a vision model returns the description **common to all of them** — ignoring incidental differences like pose, background, and framing. You pick the **provider + model on demand** in the modal (only API/vision-capable providers are offered), edit the generated prose before applying, and it writes straight into the entry's descriptor field (`physicalDescription` for characters, `description` for places/objects) — the same field the render prompt reads. Vision runs through the existing API runner's `image_url` content-block path; the new `runPromptThroughProvider({ screenshots })` arg threads images through the shared runner, and the stateless `POST /api/universe-builder/describe-from-images` endpoint resolves an API provider (clear `NO_API_PROVIDER` error if none is configured) and builds the per-kind vision prompt. (`server/services/universeVisionDescribe.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/components/pipeline/CanonCard.jsx`, `client/src/components/universe/UniverseCanonSection.jsx`)diff --git a/PLAN.md b/PLAN.mdindex 7d95dddc31..d8e0c778db 100644--- a/PLAN.md+++ b/PLAN.md@@ -28,6 +28,8 @@ independently.- [ ] [ref-watch-phosphene-i2v-snap-dims-to-source-aspect] **Auto-snap I2V default width×height to the uploaded source image's aspect ratio.** From `reference-watch` review of Phosphene (commit `0b98a5bd`, 2026-06-12). Upstream keeps custom W×H inputs editable for image flows but auto-snaps the *default* dimensions to the uploaded image via `snapAspectToImage()`, because the common case can't cover-crop a 16:9 photo into a 9:16 frame without losing content. PortOS already exposes editable W×H plus presets, but on I2V it ffmpeg cover-crops the source to the chosen size (`server/services/videoGen/local.js#resizeImage()` uses `force_original_aspect_ratio=increase,crop`), so a mismatched preset silently crops away the subject. Fix: when a source/keyframe image is selected in `client/src/pages/VideoGen.jsx`, read its natural dimensions and snap the width/height fields to the nearest 64-aligned preset that matches the image's aspect ratio (only when the user hasn't manually overridden), leaving the inputs editable for power users; keep the existing server-side 64-grid clamp. Estimated scope: small.+- [ ] [authors-federation-sync-category] **Federate the `authors` table as a dataSync category (like universes).** Author personas (`server/services/authors/`, `authors` table) shipped `db-primary` but LOCAL-ONLY — a series carries `authorId` (FK) + a denormalized `author` byline so a federated peer renders the cover correctly without the author record, but the persona itself (writing style, bio, headshot description/style) does NOT sync, so a user's other federated machines don't see their authors. Make authors a first-class sync category mirroring the universe pattern: add an `author` case to `server/lib/syncWire.js` (`sanitizeRecordForWire` + `sanitizeStateForWire`), register `getAuthorSnapshot`/`applyAuthorRemote` + a `mergeAuthorsFromSync` merge entry in `server/services/dataSync.js`, give the table soft-delete tombstones on the wire (already has `deleted`/`deleted_at` columns) + a mutation-epoch fingerprint (`server/services/changeToken.js`) so a PG-backed edit invalidates the snapshot cache, wire the per-record push path + auto-subscribe (`server/services/sharing/recordEvents.js`) the way `createSeries` does, and mind the test peer-fan-out mocks (`mockNoPeers`/`mockNoPeerSync`). Additive field on series (`authorId`) already crosses the wire via the series passthrough; no series schema-version bump needed. Estimated scope: medium-large (federation surface + checksum-stability + tests). Deferred from the Authors-management PR as genuinely-large work needing its own PR.+### Trigger-gated (waiting for a precondition)- [ ] [ref-watch-phosphene-spaced-lora-id-decode-validate] **Harden trained-character/LoRA id handling for spaced filenames + percent-encoded path segments.** From `reference-watch` review of Phosphene (commit `ce031395`, 2026-06-12). Upstream's character-id validation regex was a hard gate that ran *before* the sidecar was read, so a LoRA whose trigger/filename contained a space (e.g. `Annie Phosphene_v2.safetensors`) was misclassified as style-only and vanished from the Characters tab; the fix widened the id class to allow spaces and made the route `unquote()`-then-validate (staying traversal-safe because an encoded `../` or `/` decodes to chars the class still rejects). PortOS's equivalent is `server/services/loras.js#assertSafeLoraFilename()` plus the trained-LoRA `character` classification it surfaces. Fix (if applicable): audit whether any PortOS LoRA/character id route 404s or misclassifies spaced filenames and whether percent-encoded id segments are decoded before validation; if so, widen the allowed id class to permit spaces and decode-then-validate in the route. **Decision needed:** confirm PortOS actually exposes id-addressed character/LoRA routes (not just filename-addressed ones) and reproduces the spaced-name misclassification before investing — it may already be covered by `assertSafeLoraFilename`'s filename-only model. Estimated scope: small.diff --git a/client/src/App.jsx b/client/src/App.jsxindex fc8a7600c7..06825fc968 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -46,6 +46,7 @@ const LoraTraining = lazyWithReload(() => import('./pages/LoraTraining'));const LoraDatasetDetail = lazyWithReload(() => import('./pages/LoraDatasetDetail'));const UniverseBuilder = lazyWithReload(() => import('./pages/UniverseBuilder'));const Universes = lazyWithReload(() => import('./pages/Universes'));+const Authors = lazyWithReload(() => import('./pages/Authors'));const Catalog = lazyWithReload(() => import('./pages/Catalog'));const Songs = lazyWithReload(() => import('./pages/Songs'));const SongEditor = lazyWithReload(() => import('./pages/SongEditor'));@@ -306,6 +307,7 @@ export default function App() {<Route path="story-builder" element={<StoryBuilder />} /><Route path="story-builder/:storyId" element={<Navigate to="idea" replace />} /><Route path="story-builder/:storyId/:step" element={<StoryBuilder />} />+ <Route path="authors" element={<Authors />} /><Route path="pipeline" element={<Pipeline />} /><Route path="pipeline/series/:seriesId" element={<PipelineSeries />} /><Route path="pipeline/series/:seriesId/roadmap" element={<PipelineSeriesRoadmap />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 5b98ba3d50..90315fe863 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -197,6 +197,7 @@ const navItems = [icon: Sparkles,defaultTo: '/media',children: [+ { to: '/authors', label: 'Authors', icon: FilePen },{ to: '/catalog', label: 'Catalog', icon: Sparkles },{ to: '/importer', label: 'Importer', icon: FileInput },{ to: '/media', label: 'Media Gen', icon: Layers },diff --git a/client/src/components/pipeline/AuthorPicker.jsx b/client/src/components/pipeline/AuthorPicker.jsxnew file mode 100644index 0000000000..7fbacf3d97--- /dev/null+++ b/client/src/components/pipeline/AuthorPicker.jsx@@ -0,0 +1,69 @@+/**+ * AuthorPicker — pick an Author persona for a series.+ *+ * Replaces the free-text "author byline" input. Selecting an author calls+ * `onChange(authorId, authorName)` so the caller can store BOTH the FK+ * (`authorId`) and the denormalized byline string (`author`) on the series —+ * the byline is what cover/title prompts render, and keeping it on the series+ * means a federated peer renders correctly even without the (local-only) author+ * record. Selecting "— No author —" calls `onChange(null, '')`.+ *+ * Self-contained: fetches the author list on mount. A series carrying a legacy+ * byline string with no matching `authorId` keeps showing that byline as a hint+ * until the user picks a persona.+ */++import { useEffect, useState } from 'react';+import { Link } from 'react-router-dom';+import { listAuthors } from '../../services/api';++export default function AuthorPicker({ id = 'series-author', value, byline, onChange, disabled = false }) {+ const [authors, setAuthors] = useState([]);+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ let alive = true;+ listAuthors({ silent: true })+ .then((list) => { if (alive) setAuthors(Array.isArray(list) ? list : []); })+ .catch(() => { if (alive) setAuthors([]); })+ .finally(() => { if (alive) setLoading(false); });+ return () => { alive = false; };+ }, []);++ const handleChange = (e) => {+ const authorId = e.target.value || null;+ const picked = authors.find((a) => a.id === authorId);+ onChange(authorId, picked ? picked.name : '');+ };++ // An authorId that isn't in the fetched list (deleted persona) shouldn't make+ // the select silently snap to "none" — surface it so the link isn't lost.+ const unknownLink = value && !authors.some((a) => a.id === value);++ return (+ <div>+ <select+ id={id}+ value={value || ''}+ onChange={handleChange}+ disabled={disabled || loading}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white disabled:opacity-50"+ >+ <option value="">— No author —</option>+ {authors.map((a) => (+ <option key={a.id} value={a.id}>{a.name}</option>+ ))}+ {unknownLink ? <option value={value}>{byline || 'Linked author (unavailable)'}</option> : null}+ </select>+ <p className="text-[11px] text-gray-500 mt-1">+ {authors.length === 0 && !loading ? (+ <>No author personas yet — <Link to="/authors" className="text-port-accent hover:underline">create one</Link>.</>+ ) : !value && byline ? (+ <>Unlinked byline: <span className="text-gray-400">{byline}</span> — pick a persona to link it.</>+ ) : (+ <>Manage personas in <Link to="/authors" className="text-port-accent hover:underline">Authors</Link>.</>+ )}+ </p>+ </div>+ );+}diff --git a/client/src/pages/Authors.jsx b/client/src/pages/Authors.jsxnew file mode 100644index 0000000000..cc202b0c28--- /dev/null+++ b/client/src/pages/Authors.jsx@@ -0,0 +1,271 @@+/**+ * Authors page — manage reusable author personas.+ *+ * An Author is a creative persona used as a series' cover byline and as the+ * prompt source for a book-cover author headshot. Each carries a name, writing+ * style, bio, a physical description + style direction for the headshot, and an+ * optional headshot image pointer.+ *+ * Master-detail: a selectable list on the left, an editor on the right. Picking+ * an author loads it into the editor; "New Author" opens a blank create form.+ */++import { useEffect, useMemo, useState } from 'react';+import { FilePen, Plus, Loader2, Trash2, Save } from 'lucide-react';+import toast from '../components/ui/Toast';+import {+ listAuthors, createAuthor, updateAuthor, deleteAuthor,+ AUTHOR_NAME_MAX, AUTHOR_WRITING_STYLE_MAX, AUTHOR_BIO_MAX,+ AUTHOR_PHYSICAL_DESCRIPTION_MAX, AUTHOR_HEADSHOT_STYLE_MAX, AUTHOR_HEADSHOT_IMAGE_URL_MAX,+} from '../services/api';++const emptyForm = () => ({+ name: '', writingStyle: '', bio: '', physicalDescription: '', headshotStyle: '', headshotImageUrl: '',+});++const formFromAuthor = (a) => ({+ name: a.name || '',+ writingStyle: a.writingStyle || '',+ bio: a.bio || '',+ physicalDescription: a.physicalDescription || '',+ headshotStyle: a.headshotStyle || '',+ headshotImageUrl: a.headshotImageUrl || '',+});++function Field({ label, hint, children }) {+ return (+ <label className="block">+ <span className="block text-xs uppercase tracking-wider text-gray-500 mb-1">{label}</span>+ {children}+ {hint ? <span className="block text-[11px] text-gray-500 mt-1">{hint}</span> : null}+ </label>+ );+}++export default function Authors() {+ const [authors, setAuthors] = useState([]);+ const [loading, setLoading] = useState(true);+ // selectedId === 'new' is create mode; a real id is edit mode; null is idle.+ const [selectedId, setSelectedId] = useState(null);+ const [form, setForm] = useState(emptyForm);+ const [saving, setSaving] = useState(false);+ const [confirmDelete, setConfirmDelete] = useState(false);++ useEffect(() => {+ listAuthors()+ .then((list) => setAuthors(Array.isArray(list) ? list : []))+ .catch((err) => toast.error(err.message || 'Failed to load authors'))+ .finally(() => setLoading(false));+ }, []);++ const isCreate = selectedId === 'new';+ const selected = useMemo(+ () => (isCreate || !selectedId ? null : authors.find((a) => a.id === selectedId) || null),+ [authors, selectedId, isCreate],+ );++ const selectAuthor = (a) => {+ setSelectedId(a.id);+ setForm(formFromAuthor(a));+ setConfirmDelete(false);+ };++ const startCreate = () => {+ setSelectedId('new');+ setForm(emptyForm());+ setConfirmDelete(false);+ };++ const handleSave = async () => {+ const name = form.name.trim();+ if (!name) { toast.error('Author name is required'); return; }+ setSaving(true);+ const payload = { ...form, name };+ if (isCreate) {+ const created = await createAuthor(payload).catch((err) => {+ toast.error(err.message || 'Failed to create author');+ return null;+ });+ setSaving(false);+ if (!created) return;+ setAuthors((prev) => [...prev, created].sort((a, b) => (a.name || '').localeCompare(b.name || '')));+ setSelectedId(created.id);+ toast.success(`Created "${created.name}"`);+ } else {+ const updated = await updateAuthor(selectedId, payload).catch((err) => {+ toast.error(err.message || 'Failed to save author');+ return null;+ });+ setSaving(false);+ if (!updated) return;+ setAuthors((prev) => prev+ .map((a) => (a.id === updated.id ? updated : a))+ .sort((a, b) => (a.name || '').localeCompare(b.name || '')));+ toast.success('Saved');+ }+ };++ const handleDelete = async () => {+ if (!selected) return;+ const prior = authors;+ setAuthors((prev) => prev.filter((a) => a.id !== selected.id));+ setSelectedId(null);+ setConfirmDelete(false);+ await deleteAuthor(selected.id).catch((err) => {+ toast.error(err.message || 'Delete failed');+ setAuthors(prior);+ });+ };++ return (+ <div>+ <div className="flex items-center justify-between mb-6 flex-wrap gap-3">+ <div className="flex items-center gap-3">+ <FilePen className="w-6 h-6 text-port-accent" />+ <h1 className="text-2xl font-bold text-white">Authors</h1>+ </div>+ <button+ type="button"+ onClick={startCreate}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"+ >+ <Plus size={16} aria-hidden="true" />+ New Author+ </button>+ </div>++ <p className="text-sm text-gray-400 mb-6">+ Author personas are reusable across series — the cover byline plus the writing voice, bio, and the+ physical description + style used to generate a book-cover author headshot. Link one to a series from+ the Series Pipeline.+ </p>++ <div className="grid grid-cols-1 md:grid-cols-[260px_1fr] gap-4">+ <div className="bg-port-card border border-port-border rounded-lg p-2">+ {loading ? (+ <div className="text-gray-500 text-sm p-2">Loading…</div>+ ) : authors.length === 0 ? (+ <div className="text-gray-500 text-sm p-2">No authors yet. Click <span className="text-port-accent">New Author</span>.</div>+ ) : (+ <ul className="space-y-1">+ {authors.map((a) => (+ <li key={a.id}>+ <button+ type="button"+ onClick={() => selectAuthor(a)}+ className={`w-full text-left px-3 py-2 rounded text-sm truncate ${+ a.id === selectedId ? 'bg-port-accent/20 text-white' : 'text-gray-300 hover:bg-port-bg'+ }`}+ >+ {a.name}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>++ <div className="bg-port-card border border-port-border rounded-lg p-4">+ {!isCreate && !selected ? (+ <div className="text-gray-500 text-sm">Select an author to edit, or create a new one.</div>+ ) : (+ <div className="space-y-3">+ <Field label="Name">+ <input+ value={form.name}+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}+ placeholder="Jane Doe"+ maxLength={AUTHOR_NAME_MAX}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ autoFocus+ />+ </Field>+ <Field label="Writing style" hint="Voice / tone / craft notes — fed into stage prompts.">+ <textarea+ value={form.writingStyle}+ onChange={(e) => setForm((f) => ({ ...f, writingStyle: e.target.value }))}+ rows={4}+ maxLength={AUTHOR_WRITING_STYLE_MAX}+ placeholder="Spare, noir-tinged prose; short declarative sentences; dry wit."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Bio" hint="About-the-author blurb for the back cover.">+ <textarea+ value={form.bio}+ onChange={(e) => setForm((f) => ({ ...f, bio: e.target.value }))}+ rows={4}+ maxLength={AUTHOR_BIO_MAX}+ placeholder="Jane Doe is the author of…"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Physical description" hint="Subject of the cover headshot — appearance, age, expression.">+ <textarea+ value={form.physicalDescription}+ onChange={(e) => setForm((f) => ({ ...f, physicalDescription: e.target.value }))}+ rows={3}+ maxLength={AUTHOR_PHYSICAL_DESCRIPTION_MAX}+ placeholder="Woman in her 40s, silver-streaked dark hair, warm gaze, slight smile."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Headshot style" hint="Art / photography direction for the headshot render.">+ <textarea+ value={form.headshotStyle}+ onChange={(e) => setForm((f) => ({ ...f, headshotStyle: e.target.value }))}+ rows={3}+ maxLength={AUTHOR_HEADSHOT_STYLE_MAX}+ placeholder="Studio portrait, soft Rembrandt lighting, muted background, 85mm."+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </Field>+ <Field label="Headshot image URL" hint="Optional — a chosen/generated headshot to use on covers.">+ <input+ value={form.headshotImageUrl}+ onChange={(e) => setForm((f) => ({ ...f, headshotImageUrl: e.target.value }))}+ placeholder="/images/… or https://…"+ maxLength={AUTHOR_HEADSHOT_IMAGE_URL_MAX}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"+ />+ </Field>++ <div className="flex items-center gap-2 pt-1 flex-wrap">+ <button+ type="button"+ onClick={handleSave}+ disabled={saving || !form.name.trim()}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ >+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ {isCreate ? 'Create' : 'Save'}+ </button>+ {!isCreate && selected ? (+ confirmDelete ? (+ <span className="inline-flex items-center gap-2 text-sm">+ <span className="text-port-error">Delete this author?</span>+ <button type="button" onClick={handleDelete} className="px-2 py-1 rounded bg-port-error/20 text-port-error hover:bg-port-error/30">+ Yes, delete+ </button>+ <button type="button" onClick={() => setConfirmDelete(false)} className="px-2 py-1 rounded text-gray-400 hover:text-white">+ Cancel+ </button>+ </span>+ ) : (+ <button+ type="button"+ onClick={() => setConfirmDelete(true)}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-gray-400 hover:text-port-error text-sm"+ >+ <Trash2 size={14} /> Delete+ </button>+ )+ ) : null}+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 5b68b37a51..a5e7e8fd08 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -22,12 +22,12 @@ import {deletePipelineSeries,generateSeriesTitleLogo,listUniverses,- SERIES_AUTHOR_MAX,WORLD_LOGLINE_MAX,WORLD_PREMISE_MAX,WORLD_STYLE_NOTES_MAX,} from '../services/api';import { ArcShapePicker, ArcShapeSparkline, getStoryShape } from '../components/pipeline/StoryShapes';+import AuthorPicker from '../components/pipeline/AuthorPicker';const emptyForm = () => ({name: '',@@ -36,6 +36,7 @@ const emptyForm = () => ({premise: '',styleNotes: '',author: '',+ authorId: '',shape: null,issueCountTarget: '',});@@ -109,6 +110,7 @@ export default function Pipeline() {premise: form.premise.trim(),styleNotes: form.styleNotes.trim(),author: form.author.trim(),+ authorId: form.authorId || null,universeId: form.universeId,issueCountTarget: Number.isFinite(target) && target > 0 ? target : undefined,arc: form.shape ? { shape: form.shape } : undefined,@@ -238,14 +240,11 @@ export default function Pipeline() {<label htmlFor="series-author" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Author (cover byline)</label>- <input+ <AuthorPickerid="series-author"- type="text"- value={form.author}- onChange={(e) => setForm((f) => ({ ...f, author: e.target.value }))}- placeholder="Jane Doe"- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- maxLength={SERIES_AUTHOR_MAX}+ value={form.authorId}+ byline={form.author}+ onChange={(authorId, name) => setForm((f) => ({ ...f, authorId: authorId || '', author: name }))}/></div></div>diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex bc632e6993..d536440d5d 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -25,8 +25,9 @@ import {listPipelineIssues,listUniverses,generateSeriesTitleLogo,- SERIES_TITLE_LOGO_MAX, SERIES_AUTHOR_MAX,+ SERIES_TITLE_LOGO_MAX,} from '../services/api';+import AuthorPicker from '../components/pipeline/AuthorPicker';import { recommendStructure, describeStructure } from '../lib/seasonStructure';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import { useArcCanvasSync } from '../hooks/useArcCanvasSync';@@ -46,12 +47,13 @@ const STYLE_OVERRIDE_MODE_TABS = [// empty-value defaults the server expects for the optional ones. Module-level// constants so the `useArcCanvasSync` callbacks keep a stable identity.const ARC_FLUSH_FIELDS = [- 'name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author',+ 'name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author', 'authorId','stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId',];const ARC_PAYLOAD_DEFAULTS = {titleLogo: '',author: '',+ authorId: null,stylePromptOverride: '',stylePromptOverrideMode: STYLE_OVERRIDE_MODE_DEFAULT,};@@ -248,12 +250,10 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP/></Field><Field label="Author (cover byline + title screen)">- <input- value={series.author || ''}- onChange={(e) => patchSeries({ author: e.target.value })}- placeholder="Jane Doe"- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"- maxLength={SERIES_AUTHOR_MAX}+ <AuthorPicker+ value={series.authorId}+ byline={series.author}+ onChange={(authorId, name) => patchSeries({ authorId: authorId || null, author: name })}/></Field><Field label="Logline">diff --git a/client/src/services/README.md b/client/src/services/README.mdindex e1efa6531e..890d67fe3e 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -86,6 +86,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCreativeDirector.js` | Creative Director (video production). || `apiPipeline.js` | Pipeline (issues + stages + canon). || `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |+| `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). || `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). || `apiSharing.js` | Share buckets + federation sync. || `apiSongs.js` | Songs workbench CRUD (a cappella song writing + arranging voice layers + learning tracking). |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 43db3f4500..a137391802 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -45,6 +45,7 @@ export * from './apiLoraTraining.js';export * from './apiMediaJobs.js';export * from './apiWritersRoom.js';export * from './apiUniverseBuilder.js';+export * from './apiAuthors.js';export * from './apiPipeline.js';export * from './apiSharing.js';export * from './apiSongs.js';diff --git a/client/src/services/apiAuthors.js b/client/src/services/apiAuthors.jsnew file mode 100644index 0000000000..8675e86777--- /dev/null+++ b/client/src/services/apiAuthors.js@@ -0,0 +1,30 @@+import { request } from './apiCore.js';++// ---- Author personas ----+// Reusable author/byline personas: name, writing style, bio, plus a physical+// description + headshot style used to generate a book-cover author headshot.+// `options` lets a caller suppress request()'s auto-toast with `{ silent: true }`.+export const listAuthors = (options = {}) => request('/authors', options);+export const getAuthor = (id, options = {}) => request(`/authors/${encodeURIComponent(id)}`, options);+export const createAuthor = (data, requestOptions = {}) => request('/authors', {+ method: 'POST',+ body: JSON.stringify(data),+ ...requestOptions,+});+export const updateAuthor = (id, patch, requestOptions = {}) => request(`/authors/${encodeURIComponent(id)}`, {+ method: 'PATCH',+ body: JSON.stringify(patch),+ ...requestOptions,+});+export const deleteAuthor = (id, requestOptions = {}) => request(`/authors/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...requestOptions,+});++// Mirror server caps in server/services/authors/logic.js — bump both sides.+export const AUTHOR_NAME_MAX = 120;+export const AUTHOR_WRITING_STYLE_MAX = 4000;+export const AUTHOR_BIO_MAX = 4000;+export const AUTHOR_PHYSICAL_DESCRIPTION_MAX = 2000;+export const AUTHOR_HEADSHOT_STYLE_MAX = 2000;+export const AUTHOR_HEADSHOT_IMAGE_URL_MAX = 1000;diff --git a/server/index.js b/server/index.jsindex 0d8e6ed05d..49561ed214 100644--- a/server/index.js+++ b/server/index.js@@ -105,6 +105,7 @@ import mediaJobsRoutes from './routes/mediaJobs.js';import creativeDirectorRoutes from './routes/creativeDirector.js';import writersRoomRoutes from './routes/writersRoom.js';import universeBuilderRoutes from './routes/universeBuilder.js';+import authorsRoutes from './routes/authors.js';import conflictJournalRoutes from './routes/conflictJournal.js';import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';@@ -518,6 +519,7 @@ app.use('/api/media-jobs', mediaJobsRoutes);app.use('/api/creative-director', creativeDirectorRoutes);app.use('/api/writers-room', writersRoomRoutes);app.use('/api/universe-builder', universeBuilderRoutes);+app.use('/api/authors', authorsRoutes);app.use('/api/pipeline', pipelineRoutes);app.use('/api/conflict-journal', conflictJournalRoutes);app.use('/api/importer', importerRoutes);diff --git a/server/lib/db.js b/server/lib/db.jsindex 424ca4c04d..82ff94702b 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -762,6 +762,25 @@ async function ensureSchemaImpl() {)`,`CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC)`,+ // Author personas. One row per reusable author/byline persona, the full+ // sanitized record (name, writingStyle, bio, physicalDescription,+ // headshotStyle, headshotImageUrl) in `data` JSONB. `name` mirrors a column+ // for the live-list sort; the LWW/tombstone trio (updated_at/deleted/+ // deleted_at) is populated FROM the record body. Authors are db-primary but+ // LOCAL-ONLY for now (no sync_sequence/wire path) — a federated series keeps+ // its denormalized `author` byline so peers still render the cover+ // correctly. Mirrors the authors block in init-db.sql.+ `CREATE TABLE IF NOT EXISTS authors (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+ )`,+ `CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE`,+// Pipeline series (Phase 3 Create migration, issue #1015). One row per// series, the full sanitized record (arc/seasons/locks/covers/style) in// `data` JSONB, moved out of data/pipeline-series/{id}/index.json@@ -1029,6 +1048,7 @@ async function ensureSchemaImpl() {'story_builder_sessions', 'writers_room_works', 'writers_room_folders','writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps','catalog_user_types', 'creative_director_projects', 'lora_training_runs',+ 'authors',];for (const t of auditedTables) {catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f6dd421bdb..dba3bf3940 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -21,6 +21,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.creative-director', path: '/media/creative-director', label: 'Creative Director', section: 'Create', aliases: ['creative-director', 'creative', 'director', 'long-form', 'episode'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form'] },{ id: 'nav.media.timeline', path: '/media/timeline', label: 'Timeline', section: 'Create', aliases: ['timeline', 'video-timeline', 'editor'], keywords: ['edit', 'trim', 'composite', 'stitch', 'cut', 'compose'] },{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },+ { id: 'nav.create.authors', path: '/authors', label: 'Authors', section: 'Create', aliases: ['authors', 'author', 'byline', 'author-persona', 'writer-persona'], keywords: ['author', 'byline', 'pen name', 'persona', 'writing style', 'bio', 'headshot', 'cover', 'book author'] },{ id: 'nav.create.universe-builder', path: '/universes', label: 'Universes', section: 'Create', aliases: ['universes', 'universe', 'universe-builder', 'worldbuilder', 'worldbuild', 'world', 'lore', 'universe-canon', 'canon'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations', 'characters', 'settings', 'objects', 'canon entries', 'list', 'manage'] },{ id: 'nav.create.importer', path: '/importer', label: 'Importer', section: 'Create', aliases: ['importer', 'import'], keywords: ['paste', 'screenplay', 'novel', 'short story', 'comic script', 'analyze', 'reverse-engineer', 'extract'] },{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Series Pipeline', section: 'Create', aliases: ['series', 'pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },diff --git a/server/routes/authors.js b/server/routes/authors.jsnew file mode 100644index 0000000000..6d9eb7fc7d--- /dev/null+++ b/server/routes/authors.js@@ -0,0 +1,68 @@+/**+ * Author persona routes.+ *+ * GET /api/authors → Author[] (live, sorted by name)+ * POST /api/authors → Author+ * GET /api/authors/:id → Author+ * PATCH /api/authors/:id → Author+ * DELETE /api/authors/:id → { id } (soft delete)+ */++import { Router } from 'express';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import * as authors from '../services/authors/index.js';++const router = Router();++const nameField = z.string().trim().min(1).max(authors.NAME_MAX);+const writingStyleField = z.string().trim().max(authors.WRITING_STYLE_MAX);+const bioField = z.string().trim().max(authors.BIO_MAX);+const physicalDescriptionField = z.string().trim().max(authors.PHYSICAL_DESCRIPTION_MAX);+const headshotStyleField = z.string().trim().max(authors.HEADSHOT_STYLE_MAX);+const headshotImageUrlField = z.string().trim().max(authors.HEADSHOT_IMAGE_URL_MAX);++const createSchema = z.object({+ name: nameField,+ writingStyle: writingStyleField.optional().default(''),+ bio: bioField.optional().default(''),+ physicalDescription: physicalDescriptionField.optional().default(''),+ headshotStyle: headshotStyleField.optional().default(''),+ headshotImageUrl: headshotImageUrlField.optional().default(''),+});++const patchSchema = z.object({+ name: nameField.optional(),+ writingStyle: writingStyleField.optional(),+ bio: bioField.optional(),+ physicalDescription: physicalDescriptionField.optional(),+ headshotStyle: headshotStyleField.optional(),+ headshotImageUrl: headshotImageUrlField.optional(),+}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });++router.get('/', asyncHandler(async (_req, res) => {+ res.json(await authors.listAuthors());+}));++router.post('/', asyncHandler(async (req, res) => {+ const body = validateRequest(createSchema, req.body ?? {});+ res.status(201).json(await authors.createAuthor(body));+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const author = await authors.getAuthor(req.params.id);+ if (!author) throw new ServerError('Author not found', { status: 404, code: 'NOT_FOUND' });+ res.json(author);+}));++router.patch('/:id', asyncHandler(async (req, res) => {+ const body = validateRequest(patchSchema, req.body ?? {});+ res.json(await authors.updateAuthor(req.params.id, body));+}));++router.delete('/:id', asyncHandler(async (req, res) => {+ res.json(await authors.deleteAuthor(req.params.id));+}));++export default router;diff --git a/server/routes/authors.test.js b/server/routes/authors.test.jsnew file mode 100644index 0000000000..ff9955477d--- /dev/null+++ b/server/routes/authors.test.js@@ -0,0 +1,88 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++vi.mock('../services/authors/index.js', () => ({+ NAME_MAX: 120,+ WRITING_STYLE_MAX: 4000,+ BIO_MAX: 4000,+ PHYSICAL_DESCRIPTION_MAX: 2000,+ HEADSHOT_STYLE_MAX: 2000,+ HEADSHOT_IMAGE_URL_MAX: 1000,+ AUTHOR_ID_RE: /^auth-/,+ listAuthors: vi.fn(async () => [{ id: 'auth-1', name: 'Jane' }]),+ getAuthor: vi.fn(),+ createAuthor: vi.fn(async (input) => ({ id: 'auth-new', ...input })),+ updateAuthor: vi.fn(async (id, patch) => ({ id, ...patch })),+ deleteAuthor: vi.fn(async (id) => ({ id })),+}));++import * as authors from '../services/authors/index.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import authorsRoutes from './authors.js';++function makeApp() {+ const app = express();+ app.use(express.json());+ app.use('/api/authors', authorsRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('authors routes', () => {+ let app;+ beforeEach(() => {+ app = makeApp();+ vi.clearAllMocks();+ });++ it('GET / returns the author list', async () => {+ const r = await request(app).get('/api/authors');+ expect(r.status).toBe(200);+ expect(r.body).toEqual([{ id: 'auth-1', name: 'Jane' }]);+ });++ it('POST / creates an author', async () => {+ const r = await request(app).post('/api/authors').send({ name: 'Jane', bio: 'blurb' });+ expect(r.status).toBe(201);+ expect(authors.createAuthor).toHaveBeenCalledWith(expect.objectContaining({ name: 'Jane', bio: 'blurb' }));+ expect(r.body.id).toBe('auth-new');+ });++ it('POST / rejects a missing name', async () => {+ const r = await request(app).post('/api/authors').send({ bio: 'no name' });+ expect(r.status).toBe(400);+ expect(authors.createAuthor).not.toHaveBeenCalled();+ });++ it('GET /:id returns 404 when absent', async () => {+ authors.getAuthor.mockResolvedValueOnce(null);+ const r = await request(app).get('/api/authors/auth-missing');+ expect(r.status).toBe(404);+ });++ it('GET /:id returns the author when found', async () => {+ authors.getAuthor.mockResolvedValueOnce({ id: 'auth-1', name: 'Jane' });+ const r = await request(app).get('/api/authors/auth-1');+ expect(r.status).toBe(200);+ expect(r.body.name).toBe('Jane');+ });++ it('PATCH /:id rejects an empty patch', async () => {+ const r = await request(app).patch('/api/authors/auth-1').send({});+ expect(r.status).toBe(400);+ expect(authors.updateAuthor).not.toHaveBeenCalled();+ });++ it('PATCH /:id updates an author', async () => {+ const r = await request(app).patch('/api/authors/auth-1').send({ name: 'Janet' });+ expect(r.status).toBe(200);+ expect(authors.updateAuthor).toHaveBeenCalledWith('auth-1', { name: 'Janet' });+ });++ it('DELETE /:id soft-deletes an author', async () => {+ const r = await request(app).delete('/api/authors/auth-1');+ expect(r.status).toBe(200);+ expect(r.body).toEqual({ id: 'auth-1' });+ });+});diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex 18297f6e28..f2a239159c 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -117,6 +117,7 @@ const seriesCreateSchema = z.object({styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional().default(''),author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional().default(''),+ authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional().default(''),stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),@@ -139,6 +140,7 @@ const seriesPatchSchema = z.object({styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional(),author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional(),+ authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),stylePromptOverride: z.string().trim().max(seriesSvc.STYLE_PROMPT_OVERRIDE_MAX).optional(),stylePromptOverrideMode: z.enum(seriesSvc.STYLE_PROMPT_OVERRIDE_MODES).optional(),targetFormat: z.enum(seriesSvc.TARGET_FORMATS).optional(),diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex 70f14ecce2..57db2b6a32 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -690,6 +690,26 @@ CREATE TABLE IF NOT EXISTS universe_runs ();CREATE INDEX IF NOT EXISTS idx_universe_runs_universe ON universe_runs (universe_id, created_at DESC);+-- Author personas. One row per reusable author/byline persona, the full+-- sanitized record (name, writingStyle, bio, physicalDescription, headshotStyle,+-- headshotImageUrl) in `data` JSONB. `name` mirrors a column for the live-list+-- sort; the LWW/tombstone trio (updated_at/deleted/deleted_at) is populated FROM+-- the record body. Authors are db-primary but LOCAL-ONLY for now (no+-- sync_sequence/wire path) — a federated series keeps its denormalized `author`+-- byline so peers still render the cover correctly. Mirrors the authors block in+-- db.js ensureSchema().+CREATE TABLE IF NOT EXISTS authors (+ id TEXT PRIMARY KEY,+ name TEXT NOT NULL,+ data JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ DEFAULT NOW(),+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ+);+-- The common path is "live authors sorted by name".+CREATE INDEX IF NOT EXISTS idx_authors_live ON authors (deleted) WHERE deleted = FALSE;+-- Pipeline series (Phase 3 Create migration, issue #1015). One row per series,-- the full sanitized record (arc/seasons/locks/covers/style) in `data` JSONB,-- moved out of data/pipeline-series/{id}/index.json (collectionStore). Only the@@ -946,3 +966,5 @@ DROP TRIGGER IF EXISTS trg_creative_director_projects_audit ON creative_directorCREATE TRIGGER trg_creative_director_projects_audit AFTER UPDATE OR DELETE ON creative_director_projects FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_authors_audit ON authors;+CREATE TRIGGER trg_authors_audit AFTER UPDATE OR DELETE ON authors FOR EACH ROW EXECUTE FUNCTION record_audit_log();diff --git a/server/services/authors/db.js b/server/services/authors/db.jsnew file mode 100644index 0000000000..5e64c534db--- /dev/null+++ b/server/services/authors/db.js@@ -0,0 +1,93 @@+/**+ * Author personas — PostgreSQL leaf I/O.+ *+ * One row per author in `authors`: the full sanitized record in `data` JSONB,+ * with `name` + the LWW/tombstone trio (updated_at/deleted/deleted_at) mirrored+ * into columns for the queries the service runs (live list, delete-guard).+ * Reads return `data` verbatim — the columns are a queryable mirror, never read+ * back. Mutations run inside withTransaction + SELECT … FOR UPDATE so a+ * read-modify-write spanning two pool round-trips can't lose an update.+ *+ * All mutation semantics live in logic.js (shared with file.js) so the two+ * backends can't drift; this module only does row I/O + locking.+ */++import { randomUUID } from 'crypto';+import { query, withTransaction } from '../../lib/db.js';+import { ServerError } from '../../lib/errorHandler.js';+import { mirrorTimestamp } from '../../lib/pgTimestamp.js';+import { buildAuthorRecord, applyAuthorPatch } from './logic.js';++function rowToAuthor(row) {+ return row ? row.data : null;+}++async function persist(exec, author) {+ const now = new Date().toISOString();+ const createdAt = mirrorTimestamp(author.createdAt, now);+ await exec(+ `INSERT INTO authors (id, name, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7)+ ON CONFLICT (id) DO UPDATE SET+ name = EXCLUDED.name,+ data = EXCLUDED.data,+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ author.id,+ typeof author.name === 'string' ? author.name : '',+ JSON.stringify(author),+ createdAt,+ mirrorTimestamp(author.updatedAt, createdAt),+ author.deleted === true,+ mirrorTimestamp(author.deletedAt, null),+ ],+ );+ return author;+}++export async function listAuthors({ includeDeleted = false } = {}) {+ const { rows } = includeDeleted+ ? await query(`SELECT data FROM authors ORDER BY name ASC`)+ : await query(`SELECT data FROM authors WHERE deleted = FALSE ORDER BY name ASC`);+ return rows.map(rowToAuthor);+}++export async function getAuthor(id) {+ const { rows } = await query(`SELECT data FROM authors WHERE id = $1`, [id]);+ const author = rowToAuthor(rows[0]);+ return author && !author.deleted ? author : null;+}++export async function createAuthor(input) {+ const author = buildAuthorRecord(input, { id: `auth-${randomUUID()}`, now: new Date().toISOString() });+ if (!author) throw new ServerError('Invalid author payload', { status: 400, code: 'VALIDATION' });+ await persist(query, author);+ console.log(`✍️ Created author persona: ${author.id} (${author.name})`);+ return author;+}++export async function updateAuthor(id, patch) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM authors WHERE id = $1 FOR UPDATE`, [id]);+ const current = rowToAuthor(sel.rows[0]);+ if (!current || current.deleted) throw new ServerError('Author not found', { status: 404, code: 'NOT_FOUND' });+ const next = applyAuthorPatch(current, patch);+ if (!next) throw new ServerError('Invalid author payload', { status: 400, code: 'VALIDATION' });+ await persist(client.query.bind(client), next);+ return next;+ });+}++export async function deleteAuthor(id) {+ return withTransaction(async (client) => {+ const sel = await client.query(`SELECT data FROM authors WHERE id = $1 FOR UPDATE`, [id]);+ const current = rowToAuthor(sel.rows[0]);+ if (!current || current.deleted) throw new ServerError('Author not found', { status: 404, code: 'NOT_FOUND' });+ const now = new Date().toISOString();+ const next = { ...current, deleted: true, deletedAt: now, updatedAt: now };+ await persist(client.query.bind(client), next);+ return { id };+ });+}diff --git a/server/services/authors/file.js b/server/services/authors/file.jsnew file mode 100644index 0000000000..7f5eb1c43e--- /dev/null+++ b/server/services/authors/file.js@@ -0,0 +1,73 @@+/**+ * Author personas — file-backed store (escape-hatch / test backend).+ *+ * Persists to data/authors.json (array, atomicWrite). PostgreSQL (db.js) is the+ * default; this backend is reachable only via the MEMORY_BACKEND=file escape+ * hatch or NODE_ENV=test — same posture as the memory backend. The dispatcher+ * in index.js picks between this and db.js.+ *+ * All mutation semantics live in logic.js so this backend and the PG backend+ * can't drift; this module only does load/find/persist.+ */++import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, readJSONFile, atomicWrite, ensureDir } from '../../lib/fileUtils.js';+import { ServerError } from '../../lib/errorHandler.js';+import { sanitizeAuthor, buildAuthorRecord, applyAuthorPatch } from './logic.js';++const AUTHORS_FILE = join(PATHS.data, 'authors.json');++async function loadAll() {+ const raw = await readJSONFile(AUTHORS_FILE, []);+ return (Array.isArray(raw) ? raw : []).map(sanitizeAuthor).filter(Boolean);+}++async function saveAll(authors) {+ await ensureDir(PATHS.data);+ await atomicWrite(AUTHORS_FILE, authors);+}++const byName = (a, b) => (a.name || '').localeCompare(b.name || '');++export async function listAuthors({ includeDeleted = false } = {}) {+ const all = await loadAll();+ return (includeDeleted ? all : all.filter((a) => !a.deleted)).sort(byName);+}++export async function getAuthor(id) {+ const all = await loadAll();+ const found = all.find((a) => a.id === id);+ return found && !found.deleted ? found : null;+}++export async function createAuthor(input) {+ const author = buildAuthorRecord(input, { id: `auth-${randomUUID()}`, now: new Date().toISOString() });+ if (!author) throw new ServerError('Invalid author payload', { status: 400, code: 'VALIDATION' });+ const all = await loadAll();+ all.push(author);+ await saveAll(all);+ console.log(`✍️ Created author persona: ${author.id} (${author.name})`);+ return author;+}++export async function updateAuthor(id, patch) {+ const all = await loadAll();+ const idx = all.findIndex((a) => a.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Author not found', { status: 404, code: 'NOT_FOUND' });+ const next = applyAuthorPatch(all[idx], patch);+ if (!next) throw new ServerError('Invalid author payload', { status: 400, code: 'VALIDATION' });+ all[idx] = next;+ await saveAll(all);+ return next;+}++export async function deleteAuthor(id) {+ const all = await loadAll();+ const idx = all.findIndex((a) => a.id === id);+ if (idx < 0 || all[idx].deleted) throw new ServerError('Author not found', { status: 404, code: 'NOT_FOUND' });+ const now = new Date().toISOString();+ all[idx] = { ...all[idx], deleted: true, deletedAt: now, updatedAt: now };+ await saveAll(all);+ return { id };+}diff --git a/server/services/authors/index.js b/server/services/authors/index.jsnew file mode 100644index 0000000000..423bdc3af3--- /dev/null+++ b/server/services/authors/index.js@@ -0,0 +1,81 @@+/**+ * Author personas — storage backend dispatcher.+ *+ * Authors are `db-primary` (PostgreSQL `authors` table). This thin dispatcher+ * mirrors creativeDirector/local.js: select the backend lazily on first call+ * so route imports + tests work regardless of boot ordering.+ *+ * - PostgreSQL (db.js) for normal installs.+ * - File (file.js) only via MEMORY_BACKEND=file (escape hatch) or+ * NODE_ENV=test — both UNSUPPORTED for production. Tests boot without a DB,+ * so they exercise the file backend and need no Postgres.+ *+ * There is no legacy file→DB import: authors are a brand-new store, so the PG+ * path only needs the (idempotent) ensureSchema() that creates the table.+ */++import { checkHealth, ensureSchema } from '../../lib/db.js';++export {+ NAME_MAX,+ WRITING_STYLE_MAX,+ BIO_MAX,+ PHYSICAL_DESCRIPTION_MAX,+ HEADSHOT_STYLE_MAX,+ HEADSHOT_IMAGE_URL_MAX,+ AUTHOR_ID_RE,+} from './logic.js';++let backend = null;+let backendName = null;++async function selectBackend() {+ if (backend) return backend;+ if (process.env.MEMORY_BACKEND === 'file' || process.env.NODE_ENV === 'test') {+ backend = await import('./file.js');+ backendName = 'file';+ return backend;+ }+ // The boot DB gate fail-fasts a required-but-missing DB, but a route can call+ // in before that gate runs ensureSchema(), so bring the schema up here+ // (idempotent) — the authors table is created on first use either way.+ const health = await checkHealth();+ if (!health.connected) {+ throw new Error('Authors require PostgreSQL — run `npm run setup:db` (dev/test only: set PGMODE=file in .env for the unsupported file backend)');+ }+ await ensureSchema();+ backend = await import('./db.js');+ backendName = 'postgres';+ return backend;+}++/** Name of the active backend, or null before first call (for diagnostics/tests). */+export function getAuthorsBackendName() {+ return backendName;+}++/** Test seam — drop the memoized backend so a suite can re-select. */+export function _resetAuthorsBackend() {+ backend = null;+ backendName = null;+}++export async function listAuthors(options = {}) {+ return (await selectBackend()).listAuthors(options);+}++export async function getAuthor(id) {+ return (await selectBackend()).getAuthor(id);+}++export async function createAuthor(input) {+ return (await selectBackend()).createAuthor(input);+}++export async function updateAuthor(id, patch) {+ return (await selectBackend()).updateAuthor(id, patch);+}++export async function deleteAuthor(id) {+ return (await selectBackend()).deleteAuthor(id);+}diff --git a/server/services/authors/logic.js b/server/services/authors/logic.jsnew file mode 100644index 0000000000..8d9313e6d6--- /dev/null+++ b/server/services/authors/logic.js@@ -0,0 +1,100 @@+/**+ * Author personas — shared mutation logic (backend-agnostic).+ *+ * The file backend (file.js) and the PostgreSQL backend (db.js) both import+ * the sanitizer + record builders from here so the two backends can never+ * drift in how an author record is shaped, trimmed, or patched. This module+ * has NO I/O — pure functions only.+ *+ * An Author is a reusable creative persona used as a series' cover byline and+ * as the prompt source for generating an author headshot on the book cover:+ * - name — display name / byline+ * - writingStyle — voice / tone notes fed into stage prompts+ * - bio — back-cover / about-the-author blurb+ * - physicalDescription — subject description for the headshot render+ * - headshotStyle — art/photography direction for the headshot render+ * - headshotImageUrl — optional pointer to a generated/chosen headshot+ *+ * Authors are `db-primary` (PostgreSQL) but LOCAL-ONLY for now — they carry no+ * sync cursor/tombstone wire path. A federated series keeps its denormalized+ * `author` byline string so peers still render the cover correctly even when+ * the author record itself hasn't synced. See PLAN.md for the federation+ * follow-up.+ */++export const AUTHOR_ID_RE = /^auth-[A-Za-z0-9-]{1,64}$/;++export const NAME_MAX = 120;+export const WRITING_STYLE_MAX = 4000;+export const BIO_MAX = 4000;+export const PHYSICAL_DESCRIPTION_MAX = 2000;+export const HEADSHOT_STYLE_MAX = 2000;+export const HEADSHOT_IMAGE_URL_MAX = 1000;++const isStr = (v) => typeof v === 'string';+const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');++/**+ * Normalize a raw author record into the canonical stored shape. Returns null+ * for a non-object or a record without a usable id/name (mirrors the other+ * sanitizers' "drop on the floor" contract so a malformed import can't land).+ */+export function sanitizeAuthor(raw) {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const name = trimTo(raw.name, NAME_MAX);+ if (!name) return null;+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;+ const deleted = raw.deleted === true;+ return {+ id: raw.id,+ name,+ writingStyle: trimTo(raw.writingStyle, WRITING_STYLE_MAX),+ bio: trimTo(raw.bio, BIO_MAX),+ physicalDescription: trimTo(raw.physicalDescription, PHYSICAL_DESCRIPTION_MAX),+ headshotStyle: trimTo(raw.headshotStyle, HEADSHOT_STYLE_MAX),+ // Empty string = no headshot chosen; never null so the on-disk shape is stable.+ headshotImageUrl: trimTo(raw.headshotImageUrl, HEADSHOT_IMAGE_URL_MAX),+ createdAt,+ updatedAt,+ deleted,+ deletedAt: deleted && isStr(raw.deletedAt) && raw.deletedAt.trim() ? raw.deletedAt : null,+ };+}++/** Build a fresh author record from create input. */+export function buildAuthorRecord(input, { id, now }) {+ return sanitizeAuthor({+ id,+ name: input.name,+ writingStyle: input.writingStyle || '',+ bio: input.bio || '',+ physicalDescription: input.physicalDescription || '',+ headshotStyle: input.headshotStyle || '',+ headshotImageUrl: input.headshotImageUrl || '',+ createdAt: now,+ updatedAt: now,+ deleted: false,+ deletedAt: null,+ });+}++const PATCHABLE = [+ 'name', 'writingStyle', 'bio', 'physicalDescription', 'headshotStyle', 'headshotImageUrl',+];++/**+ * Apply a partial patch onto an existing record. Only keys PRESENT in `patch`+ * overwrite — an absent key preserves the current value, while a present+ * empty-string value applies the clear (distinguish-absent-vs-empty per+ * CLAUDE.md). Always bumps `updatedAt`.+ */+export function applyAuthorPatch(current, patch = {}) {+ const next = { ...current };+ for (const key of PATCHABLE) {+ if (key in patch) next[key] = patch[key];+ }+ next.updatedAt = new Date().toISOString();+ return sanitizeAuthor(next);+}diff --git a/server/services/authors/logic.test.js b/server/services/authors/logic.test.jsnew file mode 100644index 0000000000..06ee398c9d--- /dev/null+++ b/server/services/authors/logic.test.js@@ -0,0 +1,74 @@+import { describe, it, expect } from 'vitest';+import {+ sanitizeAuthor, buildAuthorRecord, applyAuthorPatch,+ NAME_MAX, WRITING_STYLE_MAX,+} from './logic.js';++describe('authors logic', () => {+ describe('sanitizeAuthor', () => {+ it('drops records without an id or name', () => {+ expect(sanitizeAuthor(null)).toBeNull();+ expect(sanitizeAuthor({})).toBeNull();+ expect(sanitizeAuthor({ id: 'auth-1' })).toBeNull();+ expect(sanitizeAuthor({ id: 'auth-1', name: ' ' })).toBeNull();+ });++ it('trims fields to their caps and normalizes the shape', () => {+ const a = sanitizeAuthor({+ id: 'auth-1',+ name: ` ${'n'.repeat(NAME_MAX + 50)} `,+ writingStyle: ` ${'w'.repeat(WRITING_STYLE_MAX + 10)} `,+ bio: ' blurb ',+ physicalDescription: ' desc ',+ headshotStyle: ' studio ',+ headshotImageUrl: ' /img.png ',+ });+ expect(a.id).toBe('auth-1');+ expect(a.name.length).toBe(NAME_MAX);+ expect(a.writingStyle.length).toBe(WRITING_STYLE_MAX);+ expect(a.bio).toBe('blurb');+ expect(a.physicalDescription).toBe('desc');+ expect(a.headshotStyle).toBe('studio');+ expect(a.headshotImageUrl).toBe('/img.png');+ expect(a.deleted).toBe(false);+ expect(a.deletedAt).toBeNull();+ });++ it('clears deletedAt when not deleted', () => {+ const a = sanitizeAuthor({ id: 'auth-1', name: 'X', deleted: false, deletedAt: '2020-01-01' });+ expect(a.deletedAt).toBeNull();+ });+ });++ describe('buildAuthorRecord', () => {+ it('builds a fresh record with timestamps', () => {+ const now = '2026-06-14T00:00:00.000Z';+ const a = buildAuthorRecord({ name: 'Jane' }, { id: 'auth-9', now });+ expect(a.id).toBe('auth-9');+ expect(a.name).toBe('Jane');+ expect(a.createdAt).toBe(now);+ expect(a.updatedAt).toBe(now);+ expect(a.writingStyle).toBe('');+ });+ });++ describe('applyAuthorPatch', () => {+ const base = buildAuthorRecord({ name: 'Jane', bio: 'old bio' }, { id: 'auth-1', now: '2026-06-14T00:00:00.000Z' });++ it('overwrites present keys and preserves absent ones', () => {+ const next = applyAuthorPatch(base, { name: 'Janet' });+ expect(next.name).toBe('Janet');+ expect(next.bio).toBe('old bio');+ });++ it('applies an intentional clear (present empty string)', () => {+ const next = applyAuthorPatch(base, { bio: '' });+ expect(next.bio).toBe('');+ });++ it('bumps updatedAt', () => {+ const next = applyAuthorPatch(base, { name: 'Janet' });+ expect(next.updatedAt >= base.updatedAt).toBe(true);+ });+ });+});diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex f74a2087c6..6981759227 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -63,6 +63,10 @@ export const STYLE_PROMPT_OVERRIDE_MODE_DEFAULT = 'prepend';// style notes on series creation; editable in the bible.export const TITLE_LOGO_MAX = 2000;export const AUTHOR_MAX = 120;+// FK to an Author persona (auth-<uuid>). The `author` string above stays as a+// denormalized byline so a federated series renders the cover correctly even+// when the peer lacks the (local-only) author record. Empty/cleared → null.+export const AUTHOR_ID_MAX = 64;export const UNIVERSE_ID_MAX = 64;export const WRITERS_ROOM_WORK_ID_MAX = 64;export const TARGET_FORMATS = Object.freeze(['comic', 'tv', 'comic+tv']);@@ -137,6 +141,7 @@ const sanitizeSeries = (raw) => {styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),titleLogo: trimTo(raw.titleLogo, TITLE_LOGO_MAX),author: trimTo(raw.author, AUTHOR_MAX),+ authorId: trimTo(raw.authorId, AUTHOR_ID_MAX) || null,// Per-series override that prepends ahead of the linked universe's// stylePrompt during image-gen composition. Lets a single series in a// shared universe deviate slightly (e.g. a noir spin-off) without@@ -206,6 +211,7 @@ export async function createSeries(input = {}) {styleNotes: input.styleNotes || '',titleLogo: input.titleLogo || '',author: input.author || '',+ authorId: input.authorId || null,stylePromptOverride: input.stylePromptOverride || '',stylePromptOverrideMode: input.stylePromptOverrideMode,targetFormat: input.targetFormat || 'comic+tv',@@ -363,6 +369,7 @@ export async function updateSeries(id, patch = {}) {...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),...('titleLogo' in patch ? { titleLogo: patch.titleLogo } : {}),...('author' in patch ? { author: patch.author } : {}),+ ...('authorId' in patch ? { authorId: patch.authorId } : {}),...('stylePromptOverride' in patch ? { stylePromptOverride: patch.stylePromptOverride } : {}),...('stylePromptOverrideMode' in patch ? { stylePromptOverrideMode: patch.stylePromptOverrideMode } : {}),...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex d9f1596e86..bf0966bc0b 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -64,6 +64,25 @@ describe('pipeline series service', () => {expect(s.objects).toBeUndefined();});+ it('createSeries stores an author byline + authorId FK; defaults authorId to null', async () => {+ const s = await svc.createSeries({ name: 'Salt Run', author: 'Jane Doe', authorId: 'auth-1' });+ expect(s.author).toBe('Jane Doe');+ expect(s.authorId).toBe('auth-1');+ const noAuthor = await svc.createSeries({ name: 'No Byline' });+ expect(noAuthor.author).toBe('');+ expect(noAuthor.authorId).toBeNull();+ });++ it('updateSeries can re-link or clear the authorId FK', async () => {+ const s = await svc.createSeries({ name: 'Salt Run', author: 'Jane Doe', authorId: 'auth-1' });+ const relinked = await svc.updateSeries(s.id, { author: 'John Roe', authorId: 'auth-2' });+ expect(relinked.authorId).toBe('auth-2');+ expect(relinked.author).toBe('John Roe');+ const cleared = await svc.updateSeries(s.id, { author: '', authorId: null });+ expect(cleared.authorId).toBeNull();+ expect(cleared.author).toBe('');+ });+it('createSeries requires a non-empty name', async () => {await expect(svc.createSeries({})).rejects.toMatchObject({ code: svc.ERR_VALIDATION });await expect(svc.createSeries({ name: ' ' })).rejects.toMatchObject({ code: svc.ERR_VALIDATION });