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([extract-builduniversestylecontext-helper]): buildUniverseStyleContext helper — single source of truth for the shared "Universe context" prompt block
[._.]/ Adam Eivy2e9730844378
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex ac3945b311..684bb4d401 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -916,6 +916,61 @@ export function joinInfluenceList(structured = []) {return structured.filter((t) => typeof t === 'string' && t.trim()).join(', ');}+// Collapse newlines + control chars in user-supplied free text before+// embedding in a prompt. Defense-in-depth against a logline / styleNotes /+// variation label containing "\n# Output contract\n…" that could redirect the+// LLM's output structure. `trimTo` (the universe sanitizer) only trims+// leading/trailing whitespace, so embedded newlines flow through untouched+// without this pass.+export const stripPromptControlChars = (s) =>+ typeof s === 'string' ? s.replace(/[\r\n\t\f\v\u0085\u2028\u2029]+/g, ' ').trim() : '';++const identityText = (s) => s;++/**+ * Render the "established universe context" prompt section shared by the+ * Universe Builder LLM actions (auto-sort, promote-variation,+ * generate-category-variations). Returns the full block including leading+ * `\n# <header>\n` and trailing newline, ready to interpolate; returns `''`+ * when no fields populate so callers can drop the block entirely.+ *+ * Accepts a sanitized universe object or a shaped `{ logline, premise,+ * styleNotes }` literal (the expand-variations path passes the literal).+ *+ * @param {object} universe+ * @param {object} [options]+ * @param {boolean} [options.includePremise=false] — emit a `PREMISE:` line.+ * @param {boolean} [options.includeEmbrace=true] — emit an+ * `EMBRACE INFLUENCES:` line from `universe.influences.embrace`. Off for+ * callers that render their own influences section.+ * @param {boolean} [options.escape=false] — collapse newlines/control chars+ * in user-supplied text. Auto-sort opts in; promote/expand stayed off+ * historically and we preserve that to avoid behavior drift.+ * @param {string} [options.headerSuffix=''] — appended after `Universe+ * context — ` to bias the LLM.+ */+export function buildUniverseStyleContext(universe, options = {}) {+ if (!universe) return '';+ const {+ includePremise = false,+ includeEmbrace = true,+ escape = false,+ headerSuffix = '',+ } = options;+ const safeText = escape ? stripPromptControlChars : identityText;+ const lines = [];+ if (universe.logline) lines.push(`LOGLINE: ${safeText(universe.logline)}`);+ if (includePremise && universe.premise) lines.push(`PREMISE: ${safeText(universe.premise)}`);+ if (universe.styleNotes) lines.push(`STYLE NOTES: ${safeText(universe.styleNotes)}`);+ if (includeEmbrace) {+ const embraceTokens = joinInfluenceList(universe.influences?.embrace);+ if (embraceTokens) lines.push(`EMBRACE INFLUENCES: ${safeText(embraceTokens)}`);+ }+ if (lines.length === 0) return '';+ const header = headerSuffix ? `Universe context — ${headerSuffix}` : 'Universe context';+ return `\n# ${header}\n${lines.join('\n\n')}\n`;+}+// Order matches the Universe Builder tab order (Cast → Places → Objects) so// the compiled-prompts list is stable across renders.const CANON_TRUNKS = Object.freeze([diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex fb32a98989..143ecbe165 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -362,6 +362,80 @@ describe("universeBuilder service", () => {});});+ describe("buildUniverseStyleContext", () => {+ const universe = {+ logline: "A foundry city goes silent.",+ premise: "post-collapse industrial sprawl",+ styleNotes: "moebius linework, ash palette",+ influences: { embrace: ["moebius linework", "cel-shading"], avoid: ["blurry"] },+ };++ it("returns '' for null universe", () => {+ expect(svc.buildUniverseStyleContext(null)).toBe("");+ });++ it("returns '' when no fields populate", () => {+ expect(svc.buildUniverseStyleContext({})).toBe("");+ });++ it("default options match promote-prompt shape (logline + styleNotes + embrace)", () => {+ expect(svc.buildUniverseStyleContext(universe))+ .toBe("\n# Universe context\nLOGLINE: A foundry city goes silent.\n\nSTYLE NOTES: moebius linework, ash palette\n\nEMBRACE INFLUENCES: moebius linework, cel-shading\n");+ });++ it("headerSuffix appears after `Universe context — `", () => {+ const out = svc.buildUniverseStyleContext(+ { logline: "X" },+ { headerSuffix: "keep the new canon entry consistent with this established setting" },+ );+ expect(out).toBe("\n# Universe context — keep the new canon entry consistent with this established setting\nLOGLINE: X\n");+ });++ it("includePremise inserts PREMISE between LOGLINE and STYLE NOTES", () => {+ const out = svc.buildUniverseStyleContext(universe, { includePremise: true });+ expect(out.indexOf("LOGLINE:")).toBeLessThan(out.indexOf("PREMISE:"));+ expect(out.indexOf("PREMISE:")).toBeLessThan(out.indexOf("STYLE NOTES:"));+ expect(out).toContain("PREMISE: post-collapse industrial sprawl");+ });++ it("includeEmbrace:false suppresses the embrace line", () => {+ const out = svc.buildUniverseStyleContext(universe, { includeEmbrace: false });+ expect(out).not.toContain("EMBRACE INFLUENCES:");+ expect(out).toContain("LOGLINE:");+ expect(out).toContain("STYLE NOTES:");+ });++ it("escape:true collapses embedded newlines in styleNotes/logline", () => {+ const out = svc.buildUniverseStyleContext(+ { logline: "line1\nline2", styleNotes: "para1\n\npara2" },+ { escape: true },+ );+ expect(out).toContain("LOGLINE: line1 line2");+ expect(out).toContain("STYLE NOTES: para1 para2");+ });++ it("escape:false (default) preserves embedded newlines verbatim", () => {+ const out = svc.buildUniverseStyleContext({ logline: "line1\nline2" });+ expect(out).toContain("LOGLINE: line1\nline2");+ });++ it("returns '' when only premise is set but includePremise is false (the default)", () => {+ expect(svc.buildUniverseStyleContext({ premise: "p" })).toBe("");+ });++ it("expand-variations call shape (includePremise + includeEmbrace:false + headerSuffix) renders only logline/premise/styleNotes", () => {+ const out = svc.buildUniverseStyleContext(+ { logline: "L", premise: "P", styleNotes: "S", influences: { embrace: ["should-not-appear"] } },+ {+ includePremise: true,+ includeEmbrace: false,+ headerSuffix: "keep new variations consistent with this established setting",+ },+ );+ expect(out).toBe("\n# Universe context — keep new variations consistent with this established setting\nLOGLINE: L\n\nPREMISE: P\n\nSTYLE NOTES: S\n");+ });+ });+describe("compilePrompts", () => {it("returns one prompt per variation across selected categories with style prefix", async () => {const w = await seedWorld();diff --git a/server/services/universeBuilderAutoSort.js b/server/services/universeBuilderAutoSort.jsindex 85ffcc7ff2..44cb9518f1 100644--- a/server/services/universeBuilderAutoSort.js+++ b/server/services/universeBuilderAutoSort.js@@ -17,7 +17,8 @@ import {getUniverse,updateUniverse,normalizeCategoryKey,- joinInfluenceList,+ buildUniverseStyleContext,+ stripPromptControlChars,} from './universeBuilder.js';import { VALID_TARGET_KINDS } from './universeBuilderPromote.js';import { ServerError } from '../lib/errorHandler.js';@@ -30,34 +31,24 @@ const SORTABLE_KINDS = VALID_TARGET_KINDS;const VARIATION_SAMPLE_PER_BUCKET = 10;-// Collapse newlines + control chars in user-supplied free text before embedding-// in the prompt. Variation labels + logline + styleNotes are user-owned strings-// that pass sanitization but aren't newline-stripped — without this a label-// containing "\n# Output contract\n..." could redirect the LLM's structure.-// Downstream gates (per-entry kind filter, byKey lookup) keep the blast radius-// bounded even if injection lands, but stripping at the embed layer is the-// cheap defense.-const escapePromptText = (s) =>- typeof s === 'string' ? s.replace(/[\r\n\t\f\v\u0085\u2028\u2029]+/g, ' ').trim() : '';+// Variation labels are user-owned strings that pass sanitization but aren't+// newline-stripped — without `stripPromptControlChars` a label containing+// "\n# Output contract\n..." could redirect the LLM's structure. The+// universe-context block applies the same defense via+// `buildUniverseStyleContext({ escape: true })` below. Downstream gates+// (per-entry kind filter, byKey lookup) keep the blast radius bounded even+// if injection lands, but stripping at the embed layer is the cheap defense.const kindUnionForPrompt = SORTABLE_KINDS.map((k) => `"${k}"`).join(' | ');const kindListForPrompt = SORTABLE_KINDS.join(', ');const buildAutoSortPrompt = ({ buckets, universe }) => {- const embraceTokens = joinInfluenceList(universe.influences?.embrace);- const styleContext = [- universe.logline ? `LOGLINE: ${escapePromptText(universe.logline)}` : null,- universe.styleNotes ? `STYLE NOTES: ${escapePromptText(universe.styleNotes)}` : null,- embraceTokens ? `EMBRACE INFLUENCES: ${escapePromptText(embraceTokens)}` : null,- ].filter(Boolean).join('\n\n');- const styleSection = styleContext- ? `\n# Universe context\n${styleContext}\n`- : '';+ const styleSection = buildUniverseStyleContext(universe, { escape: true });const bucketBlock = buckets.map(({ key, variations }) => {const sample = variations.slice(0, VARIATION_SAMPLE_PER_BUCKET)- .map((v) => ` - ${escapePromptText(v.label)}`)+ .map((v) => ` - ${stripPromptControlChars(v.label)}`).join('\n');const body = sample || ' (no variations yet)';return `## ${key}\n${body}`;diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.jsindex dd93d0beb4..e51499cd1e 100644--- a/server/services/universeBuilderExpand.js+++ b/server/services/universeBuilderExpand.js@@ -22,6 +22,7 @@ import {LOGLINE_MAX,PREMISE_MAX,STYLE_NOTES_MAX,+ buildUniverseStyleContext,isInfluenceLockField,normalizeCategoryKey,sanitizeCategories,@@ -509,14 +510,17 @@ function buildCategoryGeneratePrompt({? `\n# Influences (embrace = style prompt, avoid = negative prompt)\nEmbrace: ${embrace.join(", ") || "(none)"}\nAvoid: ${avoid.join(", ") || "(none)"}\n`: "";- const stateLines = [- logline && `LOGLINE: ${logline}`,- premise && `PREMISE: ${premise}`,- styleNotes && `STYLE NOTES: ${styleNotes}`,- ].filter(Boolean);- const stateSection = stateLines.length- ? `\n# Universe context — keep new variations consistent with this established setting\n${stateLines.join('\n\n')}\n`- : "";+ // Influences ship in their own section above; the universe-context helper+ // skips EMBRACE INFLUENCES here so the variations prompt doesn't render+ // them twice with different framing.+ const stateSection = buildUniverseStyleContext(+ { logline, premise, styleNotes },+ {+ includePremise: true,+ includeEmbrace: false,+ headerSuffix: 'keep new variations consistent with this established setting',+ },+ );const existingSection = existingLabels.length? `\n# Existing "${category}" variations — DO NOT regenerate these labels or close paraphrases\n${existingLabels.map((l) => `- "${l}"`).join('\n')}\n`diff --git a/server/services/universeBuilderPromote.js b/server/services/universeBuilderPromote.jsindex 4b58073010..8f31cde146 100644--- a/server/services/universeBuilderPromote.js+++ b/server/services/universeBuilderPromote.js@@ -9,7 +9,7 @@ import {getUniverse,updateUniverse,normalizeCategoryKey,- joinInfluenceList,+ buildUniverseStyleContext,} from './universeBuilder.js';import {sanitizeBibleList,@@ -54,15 +54,9 @@ const buildPromotePrompt = ({category,universe,}) => {- const embraceTokens = joinInfluenceList(universe.influences?.embrace);- const styleContext = [- universe.logline ? `LOGLINE: ${universe.logline}` : null,- universe.styleNotes ? `STYLE NOTES: ${universe.styleNotes}` : null,- embraceTokens ? `EMBRACE INFLUENCES: ${embraceTokens}` : null,- ].filter(Boolean).join('\n\n');- const styleSection = styleContext- ? `\n# Universe context — keep the new canon entry consistent with this established setting\n${styleContext}\n`- : '';+ const styleSection = buildUniverseStyleContext(universe, {+ headerSuffix: 'keep the new canon entry consistent with this established setting',+ });// Per-kind output contract. The sanitizer drops unknown fields, so// listing the field whitelist here is the LLM's only contract.