Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([nounsstage-cheaper-seriesnamemap-fetch]): thin series-names endpoint for NounsStage chip lookup
[._.]/ Adam Eivy633df02ab563
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d92d806529..145be75d33 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,6 +42,7 @@## Refactors+- **NounsStage — drop heavy `canon-usage` fetch for a thin series-names lookup.** `NounsStage.jsx` was calling `GET /api/universe-builder/:id/canon-usage` purely to extract `seriesNameMap`, which forces the server to iterate every linked series × every issue × 3 prose matchers (O(series × issues × matchers)) just to label a CanonCard chip. New endpoint `GET /api/universe-builder/:id/series-names` returns `[{id,name}]` for linked series only — no issue scan, no matchers. Backed by `listLinkedSeriesNames` in `server/services/canonUsage.js`. `UniverseCanonSection` still uses the full `canon-usage` endpoint because it needs the per-entry usage counts. +3 vitest cases in `canonUsage.test.js`.- **`canonPrompt` shared helper (`server/lib/canonPrompt.js` + `client/src/lib/canonPrompt.js` mirror).** Single source of truth for per-kind canon descriptor field precedence. Exports `shortCanonDescriptorFragments` (UI-summary scope), `richCanonDescriptorFragments` (render-prompt scope), `descriptorForCanonEntry` (flattened short string), and `hasCanonDescriptorContent` (rich-field union for "has anything to render?" gates). Migrated four call sites: `synthesizeCanonPrompt` in `server/services/universeBuilder.js`, `KINDS[].descFor` in `client/src/components/universe/UniverseCanonSection.jsx`, `canonEntryHasContent` in `client/src/pages/UniverseBuilder.jsx`, and `settingFrags` in `server/lib/scenePrompt.js` + client mirror. Minor cosmetic uniformity: lowercase `palette:`/`era:`/`weather:`/`significance:` prefixes in canon render prompts are now capitalized to match the UI descriptor format — case-only change, no functional impact on diffusion models. 29 new tests in `server/lib/canonPrompt.test.js`.- **`TabPills` UI primitive (`client/src/components/ui/TabPills.jsx`).** Consolidates ten duplicated tab-nav patterns — two local `TabNav` components (UniverseBuilder, StoryboardPanel) plus eight inline tab-button blocks (Brain, Calendar, ChiefOfStaff, DigitalTwin, MediaGen, Messages, Settings, Wiki). Two variants (`underline` default, `pills`) with knobs for the call-site quirks (`runningKind` per-tab spinner, `stretch` flex-1 equal-width, `mobileDropdown` `<select>` fallback, `hideLabelOnMobile` icon-only at < sm, `controlsIdPrefix` for `aria-controls` wiring, `listRef`+`onScroll` for ChiefOfStaff's scroll-arrow overlay). Covered by 7 vitest cases. Minor intentional visual unification across the surface area: StoryboardPanel active tab text-port-accent (was text-white), ChiefOfStaff and Settings gained the standard `bg-port-accent/5` active wash + `hover:bg-port-card` inactive.- **`TabPills` — `trailing` slot for per-tab status indicators.** Added an optional `t.trailing` ReactNode rendered after the count in both `underline` and `pills` variants. Migrates `PipelineIssue.jsx`'s 11th inlined tab-row (the only remaining outlier — its per-tab status dot didn't fit the prior shape) onto the shared primitive, replacing 22 lines of bespoke `<button>` markup with the standard underline-variant render. Also brings the row's mobile touch targets (`min-h-[44px]`) and icon size (16 vs 14) in line with the rest of the app. +1 vitest case asserting DOM-order (`trailing` follows `count`).diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex 1c17f2a093..df044b70b6 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -22,7 +22,7 @@ import toast from '../../ui/Toast';import {getUniverse, updateUniverse,extractUniverseCanon, refineUniverseCharacter,- getUniverseCanonUsage,+ getUniverseSeriesNames,} from '../../../services/apiUniverseBuilder';import { getSettings, updateSettings, generateImage } from '../../../services/apiSystem';import { listImageModels } from '../../../services/apiImageVideo';@@ -154,15 +154,17 @@ export default function NounsStage({ issue, series }) {// Sibling-series name lookup for the canon-card "from <series>" chip.// The current series is in `series.name`; everything else (including the// entries that surface in the "Other series canon" details panel) needs the- // server-side aggregation. Failure is non-fatal — chips just fall back to- // the id-tooltip form.+ // server-side lookup. Failure is non-fatal — chips just fall back to the+ // id-tooltip form. Uses the thin /series-names endpoint to skip the per-+ // issue prose scan that /canon-usage also runs.const [seriesNameMap, setSeriesNameMap] = useState(null);useEffect(() => {if (!series?.universeId) { setSeriesNameMap(null); return; }let cancelled = false;- getUniverseCanonUsage(series.universeId).then((u) => {+ getUniverseSeriesNames(series.universeId).then((list) => {if (cancelled || !mountedRef.current) return;- setSeriesNameMap(u?.seriesNameMap || null);+ const map = Object.fromEntries((Array.isArray(list) ? list : []).map((s) => [s.id, s.name]));+ setSeriesNameMap(map);}).catch(() => { /* non-fatal */ });return () => { cancelled = true; };}, [series?.universeId, mountedRef]);diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.jsindex e095305935..e14f2e22a1 100644--- a/client/src/services/apiUniverseBuilder.js+++ b/client/src/services/apiUniverseBuilder.js@@ -186,6 +186,12 @@ export const differentiateUniverseCast = (universeId, { providerId, model } = {}export const getUniverseCanonUsage = (universeId) =>request(`/universe-builder/${encodeURIComponent(universeId)}/canon-usage`);+// Thin lookup: every series that links to this universe as `[{ id, name }]`.+// Use this when only the seriesId → seriesName mapping is needed — the full+// /canon-usage endpoint also runs prose-matching scans across every issue.+export const getUniverseSeriesNames = (universeId) =>+ request(`/universe-builder/${encodeURIComponent(universeId)}/series-names`);+// Toggle the `locked` flag on a single canon entry. Locked entries are// protected from AI rewrite paths (refine returns 409; differentiate skips// them at apply time; re-extract appends evidence only). `kind` must bediff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 9ea6954d7f..1283059264 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -19,7 +19,7 @@ import { validateRequest } from '../lib/validation.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';import { BIBLE_KINDS, BIBLE_LIMITS } from '../lib/storyBible.js';-import { getUniverseCanonUsage } from '../services/canonUsage.js';+import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';import { refineWorldPrompts } from '../services/universeBuilderRefine.js';import { promoteVariationToCanon, VALID_TARGET_KINDS } from '../services/universeBuilderPromote.js';@@ -613,6 +613,15 @@ router.get('/:id/canon-usage', asyncHandler(async (req, res) => {res.json(result);}));+// Thin lookup: linked-series id/name pairs for callers (e.g. NounsStage) that+// only need to label canon-card "from <series>" chips. Skips the O(series ×+// issues × matchers) prose scan that /canon-usage runs.+router.get('/:id/series-names', asyncHandler(async (req, res) => {+ const result = await listLinkedSeriesNames(req.params.id)+ .catch((err) => { throw mapServiceError(err); });+ res.json(result);+}));+// Lock toggle for canon entries. Locked entries are protected from AI rewrite// paths (refine, differentiate, re-extract field overwrites).const setLockSchema = z.object({diff --git a/server/services/canonUsage.js b/server/services/canonUsage.jsindex 84d2ab3742..5e044b2892 100644--- a/server/services/canonUsage.js+++ b/server/services/canonUsage.js@@ -35,6 +35,24 @@ function corpusForIssue(issue) {return parts.filter(Boolean).join('\n\n');}+/**+ * Thin variant of getUniverseCanonUsage that only returns the linked-series+ * id/name pairs — no per-issue prose scan, no canon matchers. Callers that+ * just need the seriesId → seriesName lookup (e.g. NounsStage's "from+ * <series>" canon-card chip) should prefer this; the full cross-reference+ * endpoint is O(series × issues × matchers).+ */+export async function listLinkedSeriesNames(universeId) {+ // Validate the universe exists so 404s line up with the heavier endpoint.+ await getUniverse(universeId).catch((err) => {+ throw new ServerError(err.message || 'Universe not found', { status: 404, code: 'UNIVERSE_NOT_FOUND' });+ });+ const allSeries = await listSeries();+ return allSeries+ .filter((s) => s.universeId === universeId)+ .map((s) => ({ id: s.id, name: s.name }));+}+/*** Return per-canon-entry usage across the universe's series.*diff --git a/server/services/canonUsage.test.js b/server/services/canonUsage.test.jsindex f59b7e1149..bc3f4acfa9 100644--- a/server/services/canonUsage.test.js+++ b/server/services/canonUsage.test.js@@ -23,7 +23,7 @@ vi.mock('./pipeline/issues.js', () => ({listIssues: vi.fn(async ({ seriesId }) => mockIssuesBySeries.get(seriesId) || []),}));-const { getUniverseCanonUsage } = await import('./canonUsage.js');+const { getUniverseCanonUsage, listLinkedSeriesNames } = await import('./canonUsage.js');beforeEach(() => {mockUniverses.clear();@@ -67,3 +67,36 @@ describe('canonUsage — seriesNameMap', () => {expect(usage.seriesCount).toBe(0);});});++describe('canonUsage — listLinkedSeriesNames', () => {+ it('returns only series linked to the requested universe as {id,name}', async () => {+ mockUniverses.set('uni-1', { id: 'uni-1', characters: [], settings: [], objects: [] });+ mockSeriesList.push(+ { id: 'ser-a', name: 'Alpha', universeId: 'uni-1' },+ { id: 'ser-b', name: 'Beta', universeId: 'uni-1' },+ // Different universe — must NOT appear in the result.+ { id: 'ser-c', name: 'Gamma', universeId: 'uni-other' },+ );+ // Seed issues to prove the thin variant skips the prose scan entirely —+ // if it accidentally routed through canon-usage these would show up in+ // the per-entry tally (which doesn't exist on this return shape).+ mockIssuesBySeries.set('ser-a', [{ id: 'iss-1', stages: { prose: { output: 'long prose' } } }]);++ const result = await listLinkedSeriesNames('uni-1');+ expect(result).toEqual([+ { id: 'ser-a', name: 'Alpha' },+ { id: 'ser-b', name: 'Beta' },+ ]);+ });++ it('returns an empty array when no series link to the universe', async () => {+ mockUniverses.set('uni-empty', { id: 'uni-empty', characters: [], settings: [], objects: [] });+ const result = await listLinkedSeriesNames('uni-empty');+ expect(result).toEqual([]);+ });++ it('throws 404 when the universe does not exist', async () => {+ await expect(listLinkedSeriesNames('missing'))+ .rejects.toMatchObject({ status: 404, code: 'UNIVERSE_NOT_FOUND' });+ });+});