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
add AI-generate button to invent a fresh series concept from a universe
[._.]/ Adam Eivy41df0550c37f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 38b92d3e89..6acb85a908 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **"Generate with AI" button on the New Series form invents a fresh story in the chosen universe.** Creating a series previously pulled the universe's own logline/premise into the form, which nudged every series toward being a retelling of the world rather than a distinct story within it. The new button (enabled once a universe is picked) asks the configured AI provider to invent a *different* series — a fresh **name, logline, premise, and recommended Vonnegut story shape** — using the universe premise, style notes, embrace/avoid influences, and canon (characters/places/objects) as seed material, and is explicitly told to diverge from the universe's existing series (their names + loglines are passed in so it doesn't duplicate a premise). The concept pre-fills the form for the user to edit before creating — nothing is persisted by the generate call itself; a malformed/unknown story shape is dropped rather than poisoning the form, and the one-line rationale surfaces in the success toast. Driven by a new `pipeline-series-generate` stage prompt. (`data.reference/prompts/stages/pipeline-series-generate.md`, `server/services/pipeline/seriesGenerate.js`, `server/routes/pipeline/series.js`, `client/src/services/apiPipeline.js`, `client/src/pages/Pipeline.jsx`)+- **The AI Providers page now shows runtime availability, not just the enable toggle.** An enabled provider can still be *benched* (runtime-unavailable) after a failure — a usage limit, auth error, or `model-not-found` — and silently skipped in favor of a fallback, which made "but it's enabled!" confusing. Each enabled-but-unavailable provider now shows an **UNAVAILABLE · {reason}** badge plus a detail panel with the underlying error message ("Why: …"), the auto-retry ETA, and a **Recover now** button (clears the bench so the next call retries it — though a persistent cause like an invalid model id will simply re-bench on the next failure). The availability map refreshes every 20s so a badge appears/clears on its own. Reads the existing `GET /api/providers/status` (`available`/`reason`/`message`/`timeUntilRecovery`) — `enabled` is the user toggle, this is the separate runtime-health state the fallback router acts on. (`client/src/pages/AIProviders.jsx`)- **Ship a "Claude Code TUI: Bedrock" provider option.** Installs that run Claude Code against Amazon Bedrock can now drive the interactive TUI on Bedrock without hand-editing `providers.json` — the seed (`data.reference/providers.json`, plus the toolkit fallback sample) now includes a `claude-code-tui-bedrock` provider alongside the existing `claude-code-tui` (Anthropic-native) and `claude-code-bedrock` (Bedrock CLI), completing the native/Bedrock × CLI/TUI matrix. Like the Bedrock CLI it ships **disabled with an empty `AWS_BEARER_TOKEN_BEDROCK`** (opt-in; no secret in git) and its `secretEnvVars` marks the token so the UI masks it and cross-install sync withholds it. Existing installs pick it up via `setup-data.js`'s `providers` merge on the next run, without touching their customized providers. (`data.reference/providers.json`, `server/lib/aiToolkit/defaults/providers.sample.json`)diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 501931fc22..7b219cca30 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -9,7 +9,7 @@import { useEffect, useMemo, useState } from 'react';import { Link, useNavigate } from 'react-router-dom';-import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput } from 'lucide-react';+import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2, FileInput, Sparkles } from 'lucide-react';import toast from '../components/ui/Toast';import ShareToButton from '../components/sharing/ShareToButton';import SyncToPeerButton from '../components/sharing/SyncToPeerButton';@@ -21,6 +21,7 @@ import {createPipelineSeries,deletePipelineSeries,generateSeriesTitleLogo,+ generateSeriesConcept,listUniverses,WORLD_LOGLINE_MAX,WORLD_PREMISE_MAX,@@ -50,6 +51,7 @@ export default function Pipeline() {const sync = useSyncIntegrity('series');const [creating, setCreating] = useState(false);+ const [generating, setGenerating] = useState(false);const [showForm, setShowForm] = useState(false);const [form, setForm] = useState(emptyForm);@@ -92,6 +94,38 @@ export default function Pipeline() {});};+ // Generate a fresh series concept from the selected universe and overwrite+ // the form's story fields (name / logline / premise / shape) so the user can+ // edit before creating. The user clicked "Generate" explicitly, so this+ // replaces whatever's there — but an empty field from the LLM keeps the prior+ // value as a fallback. styleNotes is left to the universe-pull (it's a+ // world-level aesthetic, not a per-series story choice).+ const handleGenerate = async () => {+ if (!form.universeId) {+ toast.error('Pick a universe first — the generator uses it as seed material');+ return;+ }+ setGenerating(true);+ const concept = await generateSeriesConcept(form.universeId).catch((err) => {+ toast.error(err.message || 'Failed to generate a series concept');+ return null;+ });+ setGenerating(false);+ if (!concept) return;+ setForm((f) => ({+ ...f,+ name: concept.name || f.name,+ logline: concept.logline || f.logline,+ premise: concept.premise || f.premise,+ shape: concept.shape || f.shape,+ }));+ toast.success(+ concept.rationale+ ? `Generated "${concept.name}" — ${concept.rationale}`+ : `Generated "${concept.name}"`,+ );+ };+const handleCreate = async (e) => {e?.preventDefault();const name = form.name.trim();@@ -254,6 +288,23 @@ export default function Pipeline() {</p></div></div>+ <div className="flex items-center gap-3 flex-wrap">+ <button+ type="button"+ onClick={handleGenerate}+ disabled={generating || !form.universeId}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg border border-port-accent/50 bg-port-accent/10 text-port-accent hover:bg-port-accent/20 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed"+ title={!form.universeId+ ? 'Pick a universe first — the generator uses it as seed material'+ : 'Invent a fresh series (name, logline, premise, story shape) from this universe'}+ >+ {generating ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} aria-hidden="true" />}+ {generating ? 'Generating…' : 'Generate with AI'}+ </button>+ <span className="text-[11px] text-gray-500">+ Invents a different story set in the chosen universe — name, logline, premise & story shape. Edit anything before creating.+ </span>+ </div><div className="grid grid-cols-1 sm:grid-cols-[1fr_240px] gap-3"><div><label htmlFor="series-logline" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">diff --git a/client/src/services/apiPipeline.js b/client/src/services/apiPipeline.jsindex 995c513df9..bbbd0acce6 100644--- a/client/src/services/apiPipeline.js+++ b/client/src/services/apiPipeline.js@@ -102,6 +102,16 @@ export const generateSeriesTitleLogo = (id, opts = {}, requestOptions = {}) =>...requestOptions,});+// Generate a fresh series concept (name / logline / premise / story shape) from+// a universe, used as seed material. Returns the concept WITHOUT persisting —+// the New Series form pre-fills it for the user to edit before creating.+export const generateSeriesConcept = (universeId, opts = {}, requestOptions = {}) =>+ request('/pipeline/series/generate-concept', {+ method: 'POST',+ body: JSON.stringify({ universeId, ...opts }),+ ...requestOptions,+ });+// Mirror server caps in `server/services/pipeline/series.js` — bump both sides.export const SERIES_TITLE_LOGO_MAX = 2000;export const SERIES_AUTHOR_MAX = 120;diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex acd703ae94..824843ec98 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -389,6 +389,13 @@"returnsJson": true,"variables": []},+ "pipeline-series-generate": {+ "name": "Pipeline — Generate Series Concept",+ "description": "Invent a new series within a universe — returns a {name, logline, premise, shape} JSON concept that tells a different story from existing series in the same universe, using the universe premise / style / influences / canon as seed material. Drives the 'Generate with AI' button on the New Series form; the concept pre-fills the form for the user to edit before creating.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-comic-panel-image-prompt": {"name": "Pipeline — Comic Panel Image Prompt","description": "Refine a single comic panel's description into a richer image-gen-ready prompt. Uses caption / dialogue / sfx context + neighboring-panel continuity to elaborate without re-imagining the scene.",diff --git a/data.reference/prompts/stages/pipeline-series-generate.md b/data.reference/prompts/stages/pipeline-series-generate.mdnew file mode 100644index 0000000000..0f350dcdc8--- /dev/null+++ b/data.reference/prompts/stages/pipeline-series-generate.md@@ -0,0 +1,56 @@+# Pipeline — Generate Series Concept++You are a showrunner / series developer. Invent **one new series** that lives inside the universe described below — a self-contained story with its own protagonist, conflict, and arc. The universe is the shared world (its tone, rules, places, and cast); the series is *one story told within it*, not a retelling of the world itself.++## Universe (seed material)++- **Name:** {{universe.name}}+- **Logline:** {{universe.logline}}+- **Premise:** {{universe.premise}}+- **Tone / style notes:** {{universe.styleNotes}}+- **Embrace influences:** {{universe.embrace}}+- **Avoid influences:** {{universe.avoid}}++### Canon you may draw on (reuse freely, or introduce new players that fit)++- **Characters:** {{characters}}+- **Places:** {{places}}+- **Objects:** {{objects}}++## Existing series in this universe++{{existingSeries}}++Your new series MUST tell a **different story** from the ones above — a different protagonist, a different central conflict, or a different corner of the world. Do not duplicate an existing premise or logline. It is fine to share canon (the same city, a recurring character), but the spine of the story must be new.++## Story shapes (choose the one that best fits the arc you're proposing)++{{shapes}}++## What to write++1. **name** — a distinctive series title (not the universe's name). Short, evocative, 1–5 words.+2. **logline** — one sentence: protagonist + their goal + the obstacle/stakes. Concrete, not abstract.+3. **premise** — 1–3 short paragraphs: the setting within the universe, the central conflict, the stakes, the tone. This is the elevator pitch a reader sees on the series page.+4. **shape** — the single best-fitting story-shape id from the list above (e.g. `man-in-hole`). Pick the one whose emotional curve matches the arc your premise implies.++## Rules++- Stay inside the universe's tone and rules — honor the embrace influences, steer clear of the avoid influences.+- Make it producible as a serialized comic / TV series (an ongoing arc, not a one-shot).+- Don't restate the universe premise back as the series premise — the series is one story, narrower and more specific than the world.+- `shape` must be exactly one of the ids listed above. If genuinely unsure, pick the closest fit rather than omitting it.++## Output++Return ONLY valid JSON in this exact shape:++```json+{+ "name": "<series title, 1–5 words>",+ "logline": "<one-sentence logline>",+ "premise": "<1–3 paragraph premise>",+ "shape": "<one story-shape id from the list>",+ "rationale": "<one short sentence on why this story + shape fits the universe — for the user, not stored>"+}+```diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex f2a239159c..b19bcbbacc 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -15,6 +15,7 @@ import { findDuplicateSeriesGroups, findSameNameSeries } from '../../services/duimport { mergeSeries } from '../../services/recordMerge.js';import { mergeFieldsWithAI } from '../../services/recordMergeAI.js';import { generateSeriesTitleLogo } from '../../services/pipeline/seriesTitleLogo.js';+import { generateSeriesConcept } from '../../services/pipeline/seriesGenerate.js';import {LENGTH_PROFILE_NAMES,CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,@@ -263,6 +264,22 @@ router.post('/series/merge/ai-resolve', asyncHandler(async (req, res) => {res.json(result);}));+// Generate a fresh series concept (name / logline / premise / story shape)+// from a universe, used as seed material. Returns the concept WITHOUT+// persisting it — the New Series form pre-fills these for the user to edit+// before creating. Static path: keep BEFORE `/series/:id`.+const seriesGenerateSchema = z.object({+ universeId: z.string().trim().min(1).max(seriesSvc.UNIVERSE_ID_MAX),+ providerId: z.string().trim().max(80).optional(),+ model: z.string().trim().max(200).optional(),+});+router.post('/series/generate-concept', asyncHandler(async (req, res) => {+ const body = validateRequest(seriesGenerateSchema, req.body ?? {});+ const result = await generateSeriesConcept(body.universeId, body)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+router.get('/series/:id', asyncHandler(async (req, res) => {const s = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });res.json(s);diff --git a/server/services/pipeline/seriesGenerate.js b/server/services/pipeline/seriesGenerate.jsnew file mode 100644index 0000000000..f2564fbffe--- /dev/null+++ b/server/services/pipeline/seriesGenerate.js@@ -0,0 +1,111 @@+/**+ * Pipeline — Series Concept Generator.+ *+ * Given a universe, asks the configured LLM to invent a NEW series that lives+ * in that world but tells a different story from any series already in it — a+ * fresh name, logline, premise, and a recommended Vonnegut story shape. The+ * universe (premise, style, influences, canon) is the seed; the universe's+ * existing series (names + loglines) are passed so the model deliberately+ * diverges from them.+ *+ * Unlike `generateSeriesTitleLogo` this does NOT persist anything — it returns+ * a concept that the New Series form pre-fills so the user can edit before+ * committing. Throws ServerError(502, PIPELINE_SERIES_CONCEPT_EMPTY) on+ * unusable output — matches the other refine helpers' error shape so the UI+ * surfaces a uniform "try again" toast.+ */++import { getUniverse, joinInfluenceList } from '../universeBuilder.js';+import { listSeries, NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';+import { ARC_SHAPES, ARC_SHAPE_IDS } from '../../lib/storyArc.js';+import { runPromptRefineRaw } from './refineHelpers.js';+import { ServerError } from '../../lib/errorHandler.js';++const CANON_LIST_MAX = 24; // cap per canon kind in the brief — keeps the prompt tight+const EXISTING_SERIES_MAX = 30;++// Render a universe canon list (characters / places / objects) as a compact+// "Name — role; Name — role" string the LLM can scan. Empty / nameless entries+// drop out; an empty (or all-nameless) list becomes an explicit "(none)" so the+// prompt never renders a dangling label.+function renderCanonList(entries) {+ const rendered = (Array.isArray(entries) ? entries : [])+ .slice(0, CANON_LIST_MAX)+ .map((e) => {+ const name = (e?.name || '').trim();+ if (!name) return null;+ const role = (e?.role || '').trim();+ return role ? `${name} — ${role}` : name;+ })+ .filter(Boolean)+ .join('; ');+ return rendered || '(none catalogued yet)';+}++const SHAPES_BLOCK = ARC_SHAPES+ .map((s) => `- \`${s.id}\` (${s.label}): ${s.description}`)+ .join('\n');++function buildContext(universe, existingSeries) {+ const existing = (existingSeries || [])+ .slice(0, EXISTING_SERIES_MAX)+ .map((s) => {+ const name = (s?.name || '').trim();+ if (!name) return null;+ const logline = (s?.logline || '').trim();+ return logline ? `- "${name}" — ${logline}` : `- "${name}"`;+ })+ .filter(Boolean);+ return {+ universe: {+ name: (universe.name || '').slice(0, 200),+ premise: (universe.premise || '').slice(0, 4000),+ logline: (universe.logline || '').slice(0, 500),+ styleNotes: (universe.styleNotes || '').slice(0, 4000),+ embrace: joinInfluenceList(universe.influences?.embrace) || '(none)',+ avoid: joinInfluenceList(universe.influences?.avoid) || '(none)',+ },+ characters: renderCanonList(universe.characters),+ places: renderCanonList(universe.places),+ objects: renderCanonList(universe.objects),+ shapes: SHAPES_BLOCK,+ existingSeries: existing.length+ ? existing.join('\n')+ : '(none yet — this is the first series in the universe)',+ };+}++export async function generateSeriesConcept(universeId, options = {}) {+ const universe = await getUniverse(universeId);+ const all = await listSeries().catch(() => []);+ const existingSeries = all.filter((s) => s.universeId === universeId);+ const emptyError = {+ code: 'PIPELINE_SERIES_CONCEPT_EMPTY',+ message: 'LLM returned an empty series concept — try again or pick a different provider.',+ };+ const { content, rationale, runId, providerId, model } = await runPromptRefineRaw({+ templateName: 'pipeline-series-generate',+ variables: buildContext(universe, existingSeries),+ options,+ source: 'pipeline-series-generate',+ logTag: `Series concept — universe=${universeId.slice(0, 8)}`,+ emptyError,+ // A concept with no name is unusable — the create form needs a title. The+ // other fields are clamped/defaulted below, so name is the only hard gate.+ validateContent: (c) => {+ const name = typeof c?.name === 'string' ? c.name.trim() : '';+ if (!name) {+ throw new ServerError('LLM returned a series concept with no name — try again.', {+ status: 502, code: emptyError.code,+ });+ }+ },+ });+ const name = content.name.trim().slice(0, NAME_MAX);+ const logline = typeof content.logline === 'string' ? content.logline.trim().slice(0, LOGLINE_MAX) : '';+ const premise = typeof content.premise === 'string' ? content.premise.trim().slice(0, PREMISE_MAX) : '';+ // Drop an unrecognized shape rather than poison the form — the create path+ // already treats `null` as "no shape picked."+ const shape = typeof content.shape === 'string' && ARC_SHAPE_IDS.includes(content.shape) ? content.shape : null;+ return { name, logline, premise, shape, rationale, runId, providerId, model };+}diff --git a/server/services/pipeline/seriesGenerate.test.js b/server/services/pipeline/seriesGenerate.test.jsnew file mode 100644index 0000000000..9aad8814f0--- /dev/null+++ b/server/services/pipeline/seriesGenerate.test.js@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mock the three dependencies generateSeriesConcept reaches out to: the universe+// store, the series list, and the LLM runner. We control `runPromptRefineRaw`'s+// returned `content` so we can assert the post-processing (clamps, shape+// validation, name gate) without a real DB or provider.+vi.mock('../universeBuilder.js', () => ({+ getUniverse: vi.fn(),+ joinInfluenceList: (a) => (Array.isArray(a) ? a.filter(Boolean).join(', ') : ''),+}));+vi.mock('./series.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, listSeries: vi.fn(async () => []) };+});+vi.mock('./refineHelpers.js', () => ({ runPromptRefineRaw: vi.fn() }));++import { generateSeriesConcept } from './seriesGenerate.js';+import { getUniverse } from '../universeBuilder.js';+import { listSeries } from './series.js';+import { runPromptRefineRaw } from './refineHelpers.js';+import { NAME_MAX, LOGLINE_MAX, PREMISE_MAX } from './series.js';++const baseUniverse = {+ id: 'uni-1',+ name: 'Saltworks',+ premise: 'A foundry world.',+ logline: 'Metal and salt.',+ styleNotes: 'gritty',+ influences: { embrace: ['noir'], avoid: ['camp'] },+ characters: [{ name: 'Ash', role: 'survivor' }],+ places: [{ name: 'The Foundry' }],+ objects: [],+};++function mockLLM(content, meta = {}) {+ runPromptRefineRaw.mockResolvedValue({+ content,+ rationale: meta.rationale || 'fits the world',+ runId: 'run-1',+ providerId: 'p1',+ model: 'm1',+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ getUniverse.mockResolvedValue(baseUniverse);+ listSeries.mockResolvedValue([]);+});++describe('generateSeriesConcept', () => {+ it('returns a clean concept with a valid shape', async () => {+ mockLLM({ name: 'Salt Run', logline: 'A child survives.', premise: 'p', shape: 'man-in-hole' });+ const out = await generateSeriesConcept('uni-1');+ expect(out).toMatchObject({+ name: 'Salt Run',+ logline: 'A child survives.',+ premise: 'p',+ shape: 'man-in-hole',+ rationale: 'fits the world',+ providerId: 'p1',+ model: 'm1',+ });+ });++ it('drops an unrecognized story shape to null', async () => {+ mockLLM({ name: 'X', logline: 'l', premise: 'p', shape: 'not-a-real-shape' });+ const out = await generateSeriesConcept('uni-1');+ expect(out.shape).toBeNull();+ });++ it('clamps overlong fields to their series caps', async () => {+ mockLLM({+ name: 'N'.repeat(NAME_MAX + 50),+ logline: 'L'.repeat(LOGLINE_MAX + 50),+ premise: 'P'.repeat(PREMISE_MAX + 50),+ shape: 'tragedy',+ });+ const out = await generateSeriesConcept('uni-1');+ expect(out.name).toHaveLength(NAME_MAX);+ expect(out.logline).toHaveLength(LOGLINE_MAX);+ expect(out.premise).toHaveLength(PREMISE_MAX);+ });++ it('coerces non-string logline/premise to empty strings', async () => {+ mockLLM({ name: 'OK', logline: 42, premise: { a: 1 }, shape: null });+ const out = await generateSeriesConcept('uni-1');+ expect(out.logline).toBe('');+ expect(out.premise).toBe('');+ expect(out.shape).toBeNull();+ });++ it('throws PIPELINE_SERIES_CONCEPT_EMPTY when the name is missing', async () => {+ // The empty-name gate runs inside the validateContent hook we pass to+ // runPromptRefineRaw — invoke it the way the real runner would.+ runPromptRefineRaw.mockImplementation(async ({ validateContent }) => {+ validateContent({ logline: 'l', premise: 'p' });+ return { content: { logline: 'l', premise: 'p' }, rationale: '', runId: 'r', providerId: 'p', model: 'm' };+ });+ await expect(generateSeriesConcept('uni-1')).rejects.toMatchObject({+ code: 'PIPELINE_SERIES_CONCEPT_EMPTY',+ });+ });++ it('passes the universe and existing-series context into the prompt', async () => {+ listSeries.mockResolvedValue([+ { id: 'ser-a', universeId: 'uni-1', name: 'First Tale', logline: 'an old story' },+ { id: 'ser-b', universeId: 'uni-other', name: 'Elsewhere', logline: 'different world' },+ ]);+ mockLLM({ name: 'Fresh', logline: 'l', premise: 'p', shape: 'icarus' });+ await generateSeriesConcept('uni-1');+ const call = runPromptRefineRaw.mock.calls[0][0];+ expect(call.templateName).toBe('pipeline-series-generate');+ expect(call.variables.universe.name).toBe('Saltworks');+ expect(call.variables.characters).toContain('Ash — survivor');+ // Only the same-universe series is listed; the other-universe one is excluded.+ expect(call.variables.existingSeries).toContain('First Tale');+ expect(call.variables.existingSeries).not.toContain('Elsewhere');+ });+});