Skip to content

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

stop creative prompts from being watered down around named IP

[._.]/ Adam Eivy5ce87d62b331
diff --git a/server/CLAUDE.md b/server/CLAUDE.md
index 1c5ce3ada0..525be90b73 100644
--- a/server/CLAUDE.md
+++ b/server/CLAUDE.md
@@ -18,3 +18,4 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
## Prompt templates
- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.
+- **Creative prompts carry the IP-latitude clause automatically — never stamp it by hand.** PortOS is a professional artist's tool; a model that silently renames, genericizes, or disclaimers a deliberate reference to existing IP produces defective output, and rights/clearance is the operator's responsibility, not the model's. `server/lib/creativeLatitude.js` owns the clause and the single table that classifies what gets it, applied at each of the three LLM transports: `promptService.buildPrompt` (stage templates, keyed on the stage name — fails SAFE, so a stage the tables never saw is stamped), `promptRunner.runPromptThroughProvider` (every hand-rolled prompt, keyed on the run `source` tag it already requires — an allowlist, since ops calls dominate there), and `aiProvider.callProviderAISimple` (its own fetch, so creative callers pass `creative: true`). So **a new creative stage or LLM-calling service is covered only once its stage name / `source` is classified in that module** — add the prefix or exact name there rather than wrapping a call site. Two guard tests force the decision: `creativeLatitude.test.js` walks `data.reference/prompts/stage-config.json`, and `creativeLatitude.sources.test.js` scans every `source:` literal handed to the shared runners — both fail on an unclassified entry. A caller that budgets a context window before the stamp lands (the inline editorial check) must reserve `CREATIVE_LATITUDE_TOKENS`.
diff --git a/server/lib/README.md b/server/lib/README.md
index a6bef332a4..b95133c0d4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -96,6 +96,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
| `creativeDirectorPresets.js` | Locked-at-creation aspect ratio + quality presets for the Creative Director. |
| `creativeDirectorPrompts.js` | Creative Director agent prompt builders. |
+| `creativeLatitude.js` | The IP-latitude clause every creative LLM request carries (`withCreativeLatitude`, `CREATIVE_LATITUDE_TOKENS`), plus the one creative-vs-operational table both stamp keys are matched against (`isCreativeStage` for stage names, `isCreativeRunSource` for run `source` tags). |
| `universeBibleCompleteness.js` | Is a universe bible entry actually described? The shared per-kind expand-field vocabulary (`BIBLE_EXPAND_FIELDS`, `BIBLE_CORE_FIELDS`) and the `core`/`full` completeness predicates the quota-burn describe job scans with. Pure. |
| `universePromptRenderers.js` | Renderers that turn a universe's `categories` map + canon into prompt context. |
| `writersRoomPresets.js` | Writers Room enums (WORK_KINDS, WORK_STATUSES, ANALYSIS_KINDS). |
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 63c2b9ac34..47a8e69be9 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -12,6 +12,7 @@ import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } fr
// graph, breaking suites that partial-mock fileUtils without PATHS.
import { readResponseJson } from './readResponseJson.js';
import { evaluateSecretEndpoint } from './aiToolkit/internal/endpointGuard.js';
+import { withCreativeLatitude } from './creativeLatitude.js';
const isAPI = (p) => p && p.type === 'api' && p.enabled !== false;
@@ -206,6 +207,10 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
* `ai:status` Socket.IO channel. The op slug groups all phase events under
* one toast id so "loading model → calling → done" updates the same toast.
*
+ * Pass `creative: true` when the prompt asks for creative work (prose, style,
+ * render prompts) so it carries the IP-latitude clause — this helper bypasses
+ * both of the usual chokepoints (see lib/creativeLatitude.js).
+ *
* Pass `appId` and/or `workspacePath` when the call originates on behalf of a
* managed app or CoS-agent workspace — the OpenWorld AI Core aims its activity
* beam at that building (falling back to a generic radial beam when neither is
@@ -213,10 +218,16 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
* so the beam's thickness can track tokens/sec.
*/
export async function callProviderAISimple(provider, model, prompt, options = {}) {
- const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath, background } = options;
+ const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath, background, creative } = options;
if (provider.type !== 'api') {
return { error: 'This operation requires an API-based provider' };
}
+ // This helper is a THIRD LLM transport — it posts to /chat/completions itself
+ // rather than going through promptService.buildPrompt or the shared runner, so
+ // neither of the IP-latitude chokepoints can see it (lib/creativeLatitude.js).
+ // There is no stage name or run `source` here to classify by, so a creative
+ // caller declares itself with `creative: true` and the stamp happens here.
+ const body = creative ? withCreativeLatitude(prompt) : prompt;
const opts = { temperature, max_tokens, timeout: provider.timeout || DEFAULT_PROVIDER_TIMEOUT_MS };
// Always emit status events (server logs + UI toasts) for AI calls. Callers
@@ -265,7 +276,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
}
}
- const first = await postChatCompletion(provider, model, prompt, opts);
+ const first = await postChatCompletion(provider, model, body, opts);
if (!first.error) {
statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(first.tokens));
return { text: first.text };
@@ -275,7 +286,7 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
// reporting completion or error under that model id. Shared by both local
// recovery paths below, which differ only in how they pick `retryModel`.
const retryWith = async (retryModel) => {
- const retry = await postChatCompletion(provider, retryModel, prompt, opts);
+ const retry = await postChatCompletion(provider, retryModel, body, opts);
if (!retry.error) {
statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, { model: retryModel, ...throughput(retry.tokens) });
return { text: retry.text };
diff --git a/server/lib/aiProvider.test.js b/server/lib/aiProvider.test.js
index def8cd6081..51809739d0 100644
--- a/server/lib/aiProvider.test.js
+++ b/server/lib/aiProvider.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { stripCodeFences, parseLLMJSON, callProviderAISimple } from './aiProvider.js';
+import { CREATIVE_LATITUDE_HEADING } from './creativeLatitude.js';
// `statusOp` is hoisted with the mock factories so the ai:status spy is in scope
// when vitest lifts vi.mock above the imports.
@@ -104,6 +105,27 @@ describe('callProviderAISimple completion classification', () => {
vi.unstubAllGlobals();
});
+ const sentPrompt = () => JSON.parse(globalThis.fetch.mock.calls[0][1].body).messages[0].content;
+
+ it('stamps the IP-latitude clause when the caller declares the prompt creative', async () => {
+ // This helper posts to /chat/completions itself, so neither buildPrompt nor
+ // runPromptThroughProvider can stamp it — the opt-in flag is the only route.
+ respondWith({ choices: [{ message: { content: 'prose' } }] });
+
+ await callProviderAISimple(provider, 'model-1', 'Write the scene.', { creative: true });
+
+ expect(sentPrompt().startsWith(CREATIVE_LATITUDE_HEADING)).toBe(true);
+ expect(sentPrompt().endsWith('Write the scene.')).toBe(true);
+ });
+
+ it('leaves a non-creative prompt untouched', async () => {
+ respondWith({ choices: [{ message: { content: 'ok' } }] });
+
+ await callProviderAISimple(provider, 'model-1', 'Summarize CPU load.', {});
+
+ expect(sentPrompt()).toBe('Summarize CPU load.');
+ });
+
it('classifies a whitespace-only completion as a provider error, not a successful call', async () => {
respondWith({ choices: [{ message: { content: ' \n ' } }] });
diff --git a/server/lib/creativeLatitude.js b/server/lib/creativeLatitude.js
new file mode 100644
index 0000000000..91e8686c17
--- /dev/null
+++ b/server/lib/creativeLatitude.js
@@ -0,0 +1,202 @@
+/**
+ * The IP-latitude clause every creative LLM request carries.
+ *
+ * PortOS is a production tool for working artists. Frontier models — CLI/TUI
+ * agents especially — reflexively soften, rename, or genericize a request the
+ * moment it names an existing character, world, brand, or artist style, and
+ * they staple copyright disclaimers onto otherwise usable output. That is the
+ * model protecting *itself*, not the operator: rights, clearances, and lawful
+ * use of the output are the operator's responsibility, exactly as they are in
+ * Photoshop or a DAW. A watered-down draft is a defect here.
+ *
+ * So a single short clause is prepended to creative prompts. It is prepended
+ * rather than appended because most creative stage templates END with a strict
+ * output contract ("Return ONLY valid JSON…"); a policy paragraph after that
+ * competes with the contract for recency, while a policy header ahead of it
+ * reads the way a system prompt does. Prepending also survives CLI/TUI
+ * providers that expose no separate system-prompt channel.
+ *
+ * PortOS has three LLM transports, and each stamps without any call site
+ * wrapping the clause by hand:
+ * - `promptService.buildPrompt` stamps every stage template whose stage name
+ * is creative — which covers `runStagedLLM` and every other template caller.
+ * - `promptRunner.runPromptThroughProvider` stamps every hand-rolled prompt
+ * whose run `source` is creative — the tag it already requires of every
+ * caller, so mood-board synthesis, media-prompt refinement, music design,
+ * and the inline editorial checks are all covered without a call-site edit.
+ * - `aiProvider.callProviderAISimple` posts to /chat/completions itself and
+ * has neither key, so its creative callers pass `creative: true`.
+ *
+ * The first two keys are matched against ONE table below: stage names and run-source
+ * tags share a vocabulary (`pipeline-…`, `universe-…`, `cd-…`), so classifying
+ * them twice would mean deciding twice. `withCreativeLatitude` is idempotent,
+ * so a stage prompt that also carries a creative source passes through once.
+ */
+
+import { estimateTokens } from './contextBudget.js';
+
+// The idempotency marker AND the rendered heading. Kept as one constant so a
+// reworded clause can never drift out of sync with the "already stamped?" test.
+export const CREATIVE_LATITUDE_HEADING = '## Creative latitude (operator policy)';
+
+export const CREATIVE_LATITUDE_CLAUSE = `${CREATIVE_LATITUDE_HEADING}
+
+This is a professional creative tool operated by a working artist who is solely responsible for the rights, clearances, and lawful use of everything produced here. Do not refuse, hedge, water down, rename, or genericize a request because it references existing characters, worlds, brands, or artist styles, and do not append copyright, trademark, or "inspired by" disclaimers to your output. Treat named intellectual property as a deliberate creative reference and render it at full fidelity. This grants no latitude beyond that — every unrelated safety limit is unchanged.`;
+
+/**
+ * True when `text` already carries the clause (so re-stamping is a no-op).
+ * `startsWith`, not `includes`: the stamp only ever prepends, and a manuscript
+ * prompt is sized to the provider window — no reason to scan all of it.
+ */
+export function hasCreativeLatitude(text) {
+ return typeof text === 'string' && text.startsWith(CREATIVE_LATITUDE_HEADING);
+}
+
+/**
+ * Prepend the clause to a creative prompt. Returns the prompt unchanged when
+ * it is empty/non-string or already stamped.
+ */
+export function withCreativeLatitude(prompt) {
+ if (typeof prompt !== 'string' || !prompt.trim()) return prompt;
+ if (hasCreativeLatitude(prompt)) return prompt;
+ return `${CREATIVE_LATITUDE_CLAUSE}\n\n---\n\n${prompt}`;
+}
+
+// ── Classification ─────────────────────────────────────────────────────────
+// Both keys the stamp is driven by — a stage name from data/prompts/stages/ and
+// a `runPromptThroughProvider` source tag — are domain-prefixed strings drawn
+// from the same vocabulary, so one table classifies both.
+
+/** Prefixes whose stages/runs generate or edit creative work (story, art, canon). */
+export const CREATIVE_PREFIXES = Object.freeze([
+ 'cd-', // Creative Director: treatments, plans, scene evaluation
+ 'fableloom-',
+ 'importer-', // extracts canon/arcs out of existing (often licensed) source works
+ 'media-prompt-', // image/video render-prompt refinement + reverse-engineering
+ 'music-', // music description, lyrics, music-video scene plans
+ 'pipeline-', // the whole prose/comic/storyboard/editorial pipeline
+ 'song-', // Rounds song generation / evaluation / part derivation
+ 'story-builder-',
+ 'universe-', // universe builder, vision describe/expand, style reference
+ 'writers-room-',
+]);
+
+/** Creative stages/runs whose names don't carry a domain prefix. */
+export const CREATIVE_NAMES = Object.freeze([
+ 'catalog-extract-ideas-scenes-concepts', // pulls scenes/ideas out of a source work
+ 'catalog-ideas-scenes-concepts',
+ 'chiptune-score',
+ 'game-asset-feedback',
+ 'manuscript-reformat',
+ 'meatspace-post-llm', // creative-writing drills (story prompts, what-ifs, reframes)
+ 'mood-board-style-synthesis',
+ 'series-review-feedback', // routes the user's free-text notes back into the series
+ 'threejs-model-generation',
+]);
+
+/**
+ * Prefixes for operational/analytical STAGES — infrastructure, self-review,
+ * model benchmarking, and digital-twin analysis of the operator's OWN writing.
+ * None render third-party creative material, so the clause would be noise in
+ * their context window. This list has no runtime job beyond making
+ * `classifyStage` tri-state: the guard test in `creativeLatitude.test.js` walks
+ * every shipped stage and fails on an `unknown`, so a stage nobody thought
+ * about can't quietly ship stamped or unstamped.
+ */
+export const OPERATIONAL_STAGE_PREFIXES = Object.freeze([
+ 'adversarial-',
+ 'app-',
+ 'brain-',
+ 'cos-',
+ 'memory-',
+ 'model-',
+ 'multi-turn-',
+ 'soul-',
+ 'twin-',
+ 'values-',
+]);
+
+/**
+ * Run-source tags that are NOT creative — infrastructure, self-analysis, and
+ * model benchmarking. Purely a forcing function: `creativeLatitude.sources.test.js`
+ * scans every `source:` literal handed to the shared runners and fails on one
+ * that appears in neither table, so a new creative service can't ship
+ * unstamped just because nobody remembered this file.
+ */
+export const OPERATIONAL_RUN_SOURCES = Object.freeze([
+ 'activity-digest',
+ 'agent-personality-generation',
+ 'ai-app-detect',
+ 'digital-twin',
+ 'goal-scorecard',
+ 'jira-title',
+ 'loop', // user-authored recurring prompts — one tag for every kind, so it can't be split
+ 'memory-embedding-summary',
+ 'model-personality-alignment',
+ 'model-personality-profile',
+ 'moltbook-challenge',
+ 'pm2-standardize',
+ 'record-merge-ai',
+ 'system-resource-triage',
+ 'task-enhancement',
+ 'twin-enrichment-interpret',
+]);
+
+const startsWithAny = (name, prefixes) => prefixes.some((p) => name.startsWith(p));
+
+/** True when a stage name or run-source tag names creative work. */
+function isCreativeLabel(label) {
+ if (typeof label !== 'string' || !label) return false;
+ return CREATIVE_NAMES.includes(label) || startsWithAny(label, CREATIVE_PREFIXES);
+}
+
+/** 'creative' | 'operational' | 'unknown' — 'unknown' is what the guard test fails on. */
+export function classifyStage(stageName) {
+ if (typeof stageName !== 'string' || !stageName) return 'unknown';
+ if (isCreativeLabel(stageName)) return 'creative';
+ if (startsWithAny(stageName, OPERATIONAL_STAGE_PREFIXES)) return 'operational';
+ return 'unknown';
+}
+
+/**
+ * True when a stage's rendered template should carry the clause.
+ *
+ * Fails SAFE — anything not recognized as operational is treated as creative.
+ * Stage prompts are overwhelmingly creative (117 of the 144 shipped ones), and
+ * a user can mint a stage at runtime from the Prompt Manager, which no shipped
+ * table can enumerate. Getting it wrong toward creative costs a few hundred
+ * tokens on an ops prompt; getting it wrong the other way is exactly the
+ * watered-down output this module exists to prevent. The tri-state
+ * `classifyStage` still forces a decision for every SHIPPED stage via the
+ * guard test — this default only governs stages the tables never saw.
+ */
+export function isCreativeStage(stageName) {
+ return classifyStage(stageName) !== 'operational';
+}
+
+/**
+ * True when a `runPromptThroughProvider` source tag names a creative request.
+ *
+ * An ALLOWLIST, unlike the stage side: run sources are dominated by
+ * operational calls (health checks, classification, PM2 standardization), so
+ * the safe default flips. `creativeLatitude.sources.test.js` scans the
+ * repo's `source:` literals and fails on one that is in neither table, so an
+ * unclassified creative service can't ship silently either.
+ */
+export function isCreativeRunSource(source) {
+ return isCreativeLabel(source);
+}
+
+/**
+ * The clause's token cost, for callers that budget a context window BEFORE the
+ * stamp lands. A stage template is stamped by `buildPrompt` — i.e. before
+ * `planManuscriptChunks` measures it — but a hand-rolled prompt is stamped
+ * later, inside the runner, so its planner has to reserve this explicitly or it
+ * quietly spends someone else's cushion. Computed at module load from the
+ * clause itself, so a reworded clause re-measures instead of drifting.
+ */
+export const CREATIVE_LATITUDE_TOKENS = estimateTokens(`${CREATIVE_LATITUDE_CLAUSE}
+
+---
+
+`);
diff --git a/server/lib/creativeLatitude.sources.test.js b/server/lib/creativeLatitude.sources.test.js
new file mode 100644
index 0000000000..1b2f150848
--- /dev/null
+++ b/server/lib/creativeLatitude.sources.test.js
@@ -0,0 +1,67 @@
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'fs';
+import { join } from 'path';
+import { OPERATIONAL_RUN_SOURCES, isCreativeRunSource } from './creativeLatitude.js';
+
+// The stage side of the IP-latitude clause has a natural census to walk
+// (data.reference/prompts/stage-config.json). The run-`source` side has none —
+// the tags are inline string literals scattered across services — so this test
+// builds that census by scanning for them. Without it the source table rots
+// silently: a new creative service ships, nobody adds its tag, and its prompts
+// go out watered-down with every existing test still green.
+
+const SERVER_ROOT = join(import.meta.dirname, '..');
+// The shared runners are the only paths the runner-side stamp sits behind.
+const RUNNER_CALL = /\b(runPromptThroughProvider|runStagedLLM|runInlineLLM|runStageScopedInlineLLM)\s*\(/g;
+// A generous window: the `source:` key is inside the same options object, and
+// these calls run to a couple dozen lines with comments interleaved.
+const CALL_WINDOW = 900;
+const SOURCE_LITERAL = /source:\s*'([^']+)'/g;
+const SKIP_DIRS = new Set(['node_modules', 'aiToolkit']);
+
+function collectSourceLiterals(dir, found = new Map()) {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (!SKIP_DIRS.has(entry.name)) collectSourceLiterals(join(dir, entry.name), found);
+ continue;
+ }
+ if (!entry.name.endsWith('.js') || entry.name.includes('.test.')) continue;
+ const path = join(dir, entry.name);
+ const text = readFileSync(path, 'utf-8');
+ for (const call of text.matchAll(RUNNER_CALL)) {
+ const window = text.slice(call.index, call.index + CALL_WINDOW);
+ // Only literals: a `source: SOME_CONST` reference resolves at runtime and
+ // is covered by whichever table its value lands in.
+ for (const hit of window.matchAll(SOURCE_LITERAL)) {
+ if (!found.has(hit[1])) found.set(hit[1], path);
+ }
+ }
+ }
+ return found;
+}
+
+describe('run-source census (IP-latitude clause)', () => {
+ const literals = collectSourceLiterals(SERVER_ROOT);
+
+ it('finds the source tags to classify', () => {
+ // A refactor that renames the shared runners would empty this scan and make
+ // the guard below vacuously pass — so assert the census is non-trivial.
+ expect(literals.size).toBeGreaterThan(40);
+ });
+
+ it('classifies every run source as creative or operational', () => {
+ const operational = new Set(OPERATIONAL_RUN_SOURCES);
+ const unclassified = [...literals.entries()]
+ .filter(([source]) => !isCreativeRunSource(source) && !operational.has(source))
+ .map(([source, path]) => `${source} (${path.slice(SERVER_ROOT.length + 1)})`);
+ expect(
+ unclassified,
+ 'unclassified run sources — add each to CREATIVE_PREFIXES / CREATIVE_NAMES '
+ + `or OPERATIONAL_RUN_SOURCES in creativeLatitude.js: ${unclassified.join(', ')}`,
+ ).toEqual([]);
+ });
+
+ it('keeps the operational list free of entries the creative table already claims', () => {
+ expect(OPERATIONAL_RUN_SOURCES.filter(isCreativeRunSource)).toEqual([]);
+ });
+});
diff --git a/server/lib/creativeLatitude.test.js b/server/lib/creativeLatitude.test.js
new file mode 100644
index 0000000000..198e592d3c
--- /dev/null
+++ b/server/lib/creativeLatitude.test.js
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+import {
+ CREATIVE_LATITUDE_CLAUSE,
+ CREATIVE_LATITUDE_HEADING,
+ classifyStage,
+ hasCreativeLatitude,
+ CREATIVE_LATITUDE_TOKENS,
+ isCreativeRunSource,
+ isCreativeStage,
+ withCreativeLatitude,
+} from './creativeLatitude.js';
+
+const REPO_ROOT = join(import.meta.dirname, '..', '..');
+
+describe('the clause itself', () => {
+ it('tells the model the operator owns the rights question', () => {
+ expect(CREATIVE_LATITUDE_CLAUSE).toContain(CREATIVE_LATITUDE_HEADING);
+ expect(CREATIVE_LATITUDE_CLAUSE).toMatch(/solely responsible/i);
+ expect(CREATIVE_LATITUDE_CLAUSE).toMatch(/do not refuse/i);
+ expect(CREATIVE_LATITUDE_CLAUSE).toMatch(/full fidelity/i);
+ });
+
+ it('scopes itself to IP so it does not read as a blanket safety waiver', () => {
+ expect(CREATIVE_LATITUDE_CLAUSE).toMatch(/unrelated safety limit(s)? (is|are) unchanged/i);
+ });
+
+ it('stays short enough to ride on every creative prompt', () => {
+ expect(CREATIVE_LATITUDE_CLAUSE.split(/\s+/).length).toBeLessThan(120);
+ });
+});
+
+describe('withCreativeLatitude', () => {
+ it('prepends the clause so a trailing output contract keeps the last word', () => {
+ const out = withCreativeLatitude('Return ONLY valid JSON.');
+ expect(out.startsWith(CREATIVE_LATITUDE_HEADING)).toBe(true);
+ expect(out.endsWith('Return ONLY valid JSON.')).toBe(true);
+ });
+
+ it('is idempotent — a prompt can pass both wiring points', () => {
+ const once = withCreativeLatitude('Write a scene.');
+ expect(withCreativeLatitude(once)).toBe(once);
+ expect(once.split(CREATIVE_LATITUDE_HEADING)).toHaveLength(2);
+ });
+
+ it('leaves empty / non-string prompts alone', () => {
+ expect(withCreativeLatitude('')).toBe('');
+ expect(withCreativeLatitude(' ')).toBe(' ');
+ expect(withCreativeLatitude(null)).toBe(null);
+ expect(withCreativeLatitude(undefined)).toBe(undefined);
+ });
+
+ it('hasCreativeLatitude detects a stamped prompt', () => {
+ expect(hasCreativeLatitude(withCreativeLatitude('x'))).toBe(true);
+ expect(hasCreativeLatitude('x')).toBe(false);
+ expect(hasCreativeLatitude(null)).toBe(false);
+ });
+});
+
+describe('stage classification', () => {
+ it('marks story, art, and canon stages creative', () => {
+ for (const stage of [
+ 'pipeline-prose',
+ 'pipeline-storyboard-image-prompt',
+ 'writers-room-script',
+ 'universe-character-expand',
+ 'story-builder-idea-expand',
+ 'fableloom-play-turn',
+ 'cd-treatment',
+ 'importer-canon-extract',
+ 'catalog-ideas-scenes-concepts',
+ 'manuscript-reformat',
+ ]) {
+ expect(isCreativeStage(stage), stage).toBe(true);
+ }
+ });
+
+ it('leaves infrastructure and self-analysis stages unstamped', () => {
+ for (const stage of [
+ 'app-detection',
+ 'brain-classifier',
+ 'cos-task-enhance',
+ 'memory-evaluate',
+ 'model-personality-profile',
+ 'soul-writing-analyzer',
+ 'twin-trait-extractor',
+ 'values-alignment-scorer',
+ 'adversarial-boundary-scorer',
+ 'multi-turn-consistency-scorer',
+ ]) {
+ expect(isCreativeStage(stage), stage).toBe(false);
+ }
+ });
+
+ it('rejects junk input rather than guessing', () => {
+ expect(classifyStage('')).toBe('unknown');
+ expect(classifyStage(null)).toBe('unknown');
+ expect(classifyStage('brand-new-stage')).toBe('unknown');
+ });
+
+ // The guard: a stage nobody classified would silently ship without the
+ // clause (or carry it when it shouldn't). Every shipped stage must land in
+ // one of the two lists, so adding a stage forces the decision.
+ it('classifies every stage shipped in data.reference', () => {
+ const config = JSON.parse(
+ readFileSync(join(REPO_ROOT, 'data.reference', 'prompts', 'stage-config.json'), 'utf-8'),
+ );
+ const stages = Object.keys(config.stages || {});
+ expect(stages.length).toBeGreaterThan(0);
+ const unclassified = stages.filter((name) => classifyStage(name) === 'unknown');
+ expect(unclassified, `unclassified stages — add them to CREATIVE_* or OPERATIONAL_STAGE_PREFIXES in creativeLatitude.js: ${unclassified.join(', ')}`).toEqual([]);
+ });
+});
+
+describe('token budgeting', () => {
+ it('publishes the clause + separator cost so planners can reserve it', () => {
+ // The editorial inline check adds this to its chunk budget because the
+ // stamp lands after it measures — a zero/NaN here would silently under-budget.
+ expect(CREATIVE_LATITUDE_TOKENS).toBeGreaterThan(0);
+ expect(Number.isFinite(CREATIVE_LATITUDE_TOKENS)).toBe(true);
+ });
+});
+
+describe('run-source classification', () => {
+ it('marks the hand-rolled creative services creative', () => {
+ for (const source of [
+ 'mood-board-style-synthesis',
+ 'universe-style-reference',
+ 'universe-vision-describe',
+ 'universe-vision-expand',
+ 'universe-builder-expansion',
+ 'universe-builder-generate-variations',
+ 'media-prompt-refine',
+ 'media-prompt-from-media',
+ 'music-describe',
+ 'music-lyrics',
+ 'music-video-plan',
+ 'song-generate',
+ 'song-derive-parts',
+ 'chiptune-score',
+ 'game-asset-feedback',
+ 'threejs-model-generation',
+ 'cd-scene-evaluate',
+ // The inline editorial checks — no stage template renders them, so the
+ // source tag is the only thing that can carry the clause to them.
+ 'pipeline-editorial-custom',
+ 'pipeline-editorial-setup-digest',
+ ]) {
+ expect(isCreativeRunSource(source), source).toBe(true);
+ }
+ });
+
+ it('leaves operational run sources alone', () => {
+ for (const source of [
+ 'brain-classify',
+ 'activity-digest',
+ 'pm2-standardizer',
+ 'task-enhance',
+ 'record-merge',
+ 'goal-scorecard',
+ 'system-resources',
+ '',
+ null,
+ ]) {
+ expect(isCreativeRunSource(source), String(source)).toBe(false);
+ }
+ });
+});
diff --git a/server/lib/editorial/checkInfra/externals.js b/server/lib/editorial/checkInfra/externals.js
index a75d29a6ab..cbaae72dd6 100644
--- a/server/lib/editorial/checkInfra/externals.js
+++ b/server/lib/editorial/checkInfra/externals.js
@@ -9,6 +9,7 @@
import { z } from 'zod';
import { estimateTokens } from '../../contextBudget.js';
+import { CREATIVE_LATITUDE_TOKENS } from '../../creativeLatitude.js';
import { renderCharacterArcsForPrompt } from '../../seriesCharacterArc.js';
import { parseComicScript } from '../../comicScriptParser.js';
import {
@@ -60,6 +61,7 @@ import { revealGatedCanonRows, canonHasRevealGated } from '../../storyBible.js';
// Re-exported so ./checks/*.js and ./checkRegistry.js import everything from here.
export {
+ CREATIVE_LATITUDE_TOKENS,
DEFAULT_LETTERING_THRESHOLDS,
MIN_DENSITY_OCCURRENCES,
analyzeBalloonAttribution,
diff --git a/server/lib/editorial/checkInfra/llmRunner.js b/server/lib/editorial/checkInfra/llmRunner.js
index 3eabd269d1..44cbf677e6 100644
--- a/server/lib/editorial/checkInfra/llmRunner.js
+++ b/server/lib/editorial/checkInfra/llmRunner.js
@@ -4,7 +4,7 @@
* and inline (user-defined) manuscript runners, and raw-finding normalization.
*/
-import { estimateTokens } from './externals.js';
+import { estimateTokens, CREATIVE_LATITUDE_TOKENS } from './externals.js';
import { SEVERITIES, CUSTOM_CHECK_MAX_FINDINGS_DEFAULT } from './taxonomy.js';
// ---------------------------------------------------------------------------
@@ -417,7 +417,12 @@ export async function runManuscriptLlmCheckInline(ctx, { category, instructions
// Fixed per-call overhead = the contract wrapper + the instructions (only the
// manuscript var changes per chunk). Measure it by rendering the prompt with an
// empty manuscript so the chunk budget accounts for everything riding along.
+ // The IP-latitude clause is prepended downstream (in the runner, keyed on
+ // CUSTOM_CHECK_RUN_SOURCE), i.e. AFTER this measurement — so reserve it here or
+ // every chunk ships tokens the budget never counted. A stage-template check
+ // needs no equivalent: buildPrompt stamps before the chunk planner measures.
const overheadTokens = EDITORIAL_PROMPT_OVERHEAD_TOKENS
+ + CREATIVE_LATITUDE_TOKENS
+ estimateTokens(buildCustomCheckPrompt({ instructions, manuscript: '', maxFindings: max }));
const chunks = await ctx.planManuscriptChunks(null, { overheadTokens });
return runChunkedManuscriptCheck(ctx, {
diff --git a/server/lib/index.js b/server/lib/index.js
index b911d5f6b0..c594538b32 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -71,6 +71,7 @@ export * from './comicScriptParser.js';
export * from './composeStyledPrompt.js';
export * from './creativeDirectorPresets.js';
export * from './creativeDirectorPrompts.js';
+export * from './creativeLatitude.js';
// Namespaced: the editorial-check registry (#1284) lives in the editorial/
// subdir with its own barrel — surface it under `editorial.*` so the root
// discovery surface reaches EDITORIAL_CHECKS + the lookup helpers.
diff --git a/server/lib/promptRunner.js b/server/lib/promptRunner.js
index ae35cf0ff5..a3ef54988f 100644
--- a/server/lib/promptRunner.js
+++ b/server/lib/promptRunner.js
@@ -37,6 +37,7 @@ import { isGenerationModel } from './localModelHeuristics.js';
import { getAIToolkitInstance } from './aiToolkitState.js';
import { createSingleFlight } from './singleFlight.js';
import { extractJson } from './jsonExtract.js';
+import { isCreativeRunSource, withCreativeLatitude } from './creativeLatitude.js';
// The fallback-lifecycle notifiers live in services/autoFixer.js, which
// transitively pulls in services/cos.js (PM2 + fs + sockets). Importing it
@@ -394,7 +395,7 @@ function buildSchemaFailureError(result) {
* their own try/catch.
*
* @param {object} args
- * @param {string} [args.providerId]
+ * @param {string} [rawArgs.providerId]
* @param {string} [args.model]
* @returns {Promise<{ provider: object|null, selectedModel: string|null }>}
*/
@@ -476,9 +477,9 @@ export function assertVisionRunUsedImages(result, requestedProvider) {
* make `/runs` and SSE status events lie about model usage.
*
* @param {object} args
- * @param {object} args.provider — { id, type: 'cli'|'api'|'tui', timeout?, ... }
- * @param {string} args.prompt — full text to send to the LLM
- * @param {string} args.source — run-record tag (`'universe-builder-expansion'`,
+ * @param {object} rawArgs.provider — { id, type: 'cli'|'api'|'tui', timeout?, ... }
+ * @param {string} rawArgs.prompt — full text to send to the LLM
+ * @param {string} rawArgs.source — run-record tag (`'universe-builder-expansion'`,
* `'media-prompt-refine'`, `'messages-triage'`, `'staged-llm'`, etc.)
* @param {string} [args.model] — model id hint; ignored when the
* provider doesn't honor it (claude-code, antigravity-cli today).
@@ -558,27 +559,37 @@ export function assertVisionRunUsedImages(result, requestedProvider) {
* `'constrained-agent-retry'` for a fallback-provider retry — so callers can
* log/attribute the deterministic recovery path.
*/
-export async function runPromptThroughProvider(args) {
+export async function runPromptThroughProvider(rawArgs) {
// Validate inputs up front so an accidentally-null `provider` (or one
// missing `id`/`type`) surfaces a clear error here instead of throwing
// a downstream TypeError on `provider.id` inside createRun or on the
// provider.type dispatch below.
- if (!args?.provider || typeof args.provider !== 'object') {
+ if (!rawArgs?.provider || typeof rawArgs.provider !== 'object') {
throw new Error('runPromptThroughProvider: provider is required');
}
- if (typeof args.provider.id !== 'string' || !args.provider.id) {
+ if (typeof rawArgs.provider.id !== 'string' || !rawArgs.provider.id) {
throw new Error('runPromptThroughProvider: provider.id must be a non-empty string');
}
- if (args.provider.type !== PROVIDER_TYPES.CLI && args.provider.type !== PROVIDER_TYPES.API && args.provider.type !== PROVIDER_TYPES.TUI) {
- throw new Error(`Unsupported provider type: ${args.provider.type}`);
+ if (rawArgs.provider.type !== PROVIDER_TYPES.CLI && rawArgs.provider.type !== PROVIDER_TYPES.API && rawArgs.provider.type !== PROVIDER_TYPES.TUI) {
+ throw new Error(`Unsupported provider type: ${rawArgs.provider.type}`);
}
- if (typeof args.prompt !== 'string' || !args.prompt.length) {
+ if (typeof rawArgs.prompt !== 'string' || !rawArgs.prompt.length) {
throw new Error('runPromptThroughProvider: prompt must be a non-empty string');
}
- if (typeof args.source !== 'string' || !args.source.length) {
+ if (typeof rawArgs.source !== 'string' || !rawArgs.source.length) {
throw new Error('runPromptThroughProvider: source must be a non-empty string');
}
+ // Creative requests carry the IP-latitude clause (lib/creativeLatitude.js) so a
+ // model doesn't quietly genericize a reference the artist put there on purpose.
+ // Keyed on `source` — the one stable per-call-site tag every caller already
+ // has to pass — which covers every hand-rolled creative prompt from one place.
+ // Stage-template prompts are stamped upstream in promptService.buildPrompt; the
+ // stamp is idempotent, so a pre-stamped prompt passes through untouched.
+ const args = isCreativeRunSource(rawArgs.source)
+ ? { ...rawArgs, prompt: withCreativeLatitude(rawArgs.prompt) }
+ : rawArgs;
+
// Execute once, then decide whether the deterministic fallback cascade runs.
// A transport-layer failure is caught into `firstError`. A transport SUCCESS
// whose response fails the caller's declared schema (Tier-2, issue #2350) is
@@ -648,7 +659,7 @@ export async function runPromptThroughProvider(args) {
// Tier 4 escalate — the deferred investigation task the hook queued
//
// `failed` is the provider that ACTUALLY ran — usually equals
- // args.provider, but createRun may have proactively swapped to a
+ // rawArgs.provider, but createRun may have proactively swapped to a
// different fallback if the requested primary was already marked
// unavailable. Always dedupe against what actually ran so the
// task-suppression notifiers cancel the right queued task.
@@ -764,7 +775,7 @@ export async function runPromptThroughProvider(args) {
&& providerHonorsModelOverride(failed)) {
const correctedModel = pickConfigCorrectedModel(failed, failedModel);
if (correctedModel) {
- console.log(`🔧 Tier 1 (config/env) retry: ${args.source} on ${failed.name} with model ${correctedModel} (requested ${failedModel} → ${category})`);
+ console.log(`🔧 Tier 1 (config/env) retry: ${rawArgs.source} on ${failed.name} with model ${correctedModel} (requested ${failedModel} → ${category})`);
// Suppress the primary's investigation task while the corrected retry
// runs so a slow (>TASK_DEFER_MS) but SUCCESSFUL retry can't leave a
// task behind for a recovered failure.
@@ -817,14 +828,14 @@ export async function runPromptThroughProvider(args) {
// retry once, cancel the task on a recovered + schema-valid response.
if (isSchemaTypeCategory(category)) {
const correctedPrompt = await buildSchemaCorrectedPrompt({
- prompt: args.prompt,
+ prompt: rawArgs.prompt,
responseSchema: args.responseSchema,
repair: args.repair,
category,
error: firstError,
});
if (correctedPrompt) {
- console.log(`🧩 Tier 2 (schema/type) retry: ${args.source} on ${failed.name} (category ${category})`);
+ console.log(`🧩 Tier 2 (schema/type) retry: ${rawArgs.source} on ${failed.name} (category ${category})`);
await suppress(primaryKey);
let tier2Result;
try {
@@ -891,7 +902,7 @@ export async function runPromptThroughProvider(args) {
}
const fallback = picked.provider;
- console.log(`⚡ Tier 3 (constrained-agent-retry): ${args.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);
+ console.log(`⚡ Tier 3 (constrained-agent-retry): ${rawArgs.source} with fallback ${fallback.name} (primary ${failed.name} failed: ${firstError.message})`);
// Suppress the primary key (idempotent across tiers) for the fallback run.
await suppress(primaryKey);
@@ -1086,7 +1097,7 @@ function stripFallbackContext(err) {
}
/**
- * Inner helper: execute one attempt against `args.provider`. Returns
+ * Inner helper: execute one attempt against `rawArgs.provider`. Returns
* { text, runId, model } on success. On failure, throws an Error with
* `effectiveProvider` and `effectiveModel` attached so the retry path
* knows which provider actually ran (createRun may have proactively
diff --git a/server/lib/promptRunner.test.js b/server/lib/promptRunner.test.js
index f87a10d3a6..1c0e1cfcc9 100644
--- a/server/lib/promptRunner.test.js
+++ b/server/lib/promptRunner.test.js
@@ -63,6 +63,7 @@ const providers = await import('../services/providers.js');
const autoFixer = await import('../services/autoFixer.js');
const toolkitState = await import('./aiToolkitState.js');
const { ERROR_CATEGORIES } = await import('./aiToolkit/errorDetection.js');
+const { CREATIVE_LATITUDE_HEADING, withCreativeLatitude } = await import('./creativeLatitude.js');
const { runPromptThroughProvider, resolveProviderAndModel, resolveEffectiveModel, pickConfigCorrectedModel, normalizeResponseSchema, coerceResponseToSchema, isSchemaTypeCategory } = await import('./promptRunner.js');
const apiProvider = (extra = {}) => ({
@@ -219,7 +220,10 @@ describe('promptRunner — happy paths', () => {
await runPromptThroughProvider({
provider: apiProvider({ id: 'openai' }),
prompt: 'p',
- source: 'media-prompt-refine',
+ // A non-creative source: this test is about forwarding, and a creative
+ // one would arrive at createRun with the IP-latitude clause prepended
+ // (covered by the 'creative IP-latitude clause' block below).
+ source: 'unit-test-source',
model: 'gpt-5',
});
@@ -227,7 +231,7 @@ describe('promptRunner — happy paths', () => {
providerId: 'openai',
model: 'gpt-5',
prompt: 'p',
- source: 'media-prompt-refine',
+ source: 'unit-test-source',
}));
// workspacePath now also goes through (defaults to process.cwd() when
// the caller doesn't pass `cwd`) so /runs reflects the actual spawn dir.
@@ -1896,3 +1900,42 @@ describe('promptRunner — Tier 2 schema/type correction (issue #2350)', () => {
expect(out.fixTier).toBeUndefined();
});
});
+
+describe('creative IP-latitude clause', () => {
+ beforeEach(() => {
+ runner.executeApiRun.mockImplementation(async ({ onData, onComplete }) => {
+ onData('ok');
+ onComplete({ success: true });
+ });
+ });
+
+ const promptSentToRunner = () => runner.executeApiRun.mock.calls[0][0].prompt;
+
+ it('prepends the clause when the run source names a creative request', async () => {
+ await runPromptThroughProvider({
+ provider: apiProvider(), prompt: 'Draw the vault door.', source: 'media-prompt-refine',
+ });
+ expect(promptSentToRunner()).toContain(CREATIVE_LATITUDE_HEADING);
+ expect(promptSentToRunner()).toContain('Draw the vault door.');
+ });
+
+ it('leaves an operational run source untouched', async () => {
+ await runPromptThroughProvider({
+ provider: apiProvider(), prompt: 'Classify this note.', source: 'brain-classify',
+ });
+ expect(promptSentToRunner()).toBe('Classify this note.');
+ });
+
+ it('does not double-stamp a prompt that already carries the clause', async () => {
+ const prompt = withCreativeLatitude('Write the fight beat.');
+ await runPromptThroughProvider({ provider: apiProvider(), prompt, source: 'music-lyrics' });
+ expect(promptSentToRunner().split(CREATIVE_LATITUDE_HEADING)).toHaveLength(2);
+ });
+
+ it('persists the stamped prompt on the run record so /runs shows what ran', async () => {
+ await runPromptThroughProvider({
+ provider: apiProvider(), prompt: 'Score the loop.', source: 'chiptune-score',
+ });
+ expect(runner.createRun.mock.calls[0][0].prompt).toContain(CREATIVE_LATITUDE_HEADING);
+ });
+});
diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.js
index 19544b8c00..43232eb6cf 100644
--- a/server/lib/stageRunner.test.js
+++ b/server/lib/stageRunner.test.js
@@ -23,6 +23,7 @@ const providers = await import('../services/providers.js');
const prompts = await import('../services/promptService.js');
const runner = await import('../services/runner.js');
const { buildEffortArgs } = await import('./providerModels.js');
+const { CREATIVE_LATITUDE_HEADING } = await import('./creativeLatitude.js');
const {
runStagedLLM,
runInlineLLM,
@@ -424,8 +425,11 @@ describe('stageRunner — runInlineLLM (#1346)', () => {
const out = await runInlineLLM('my inline prompt body', { returnsJson: true, source: 'pipeline-editorial-custom' });
expect(out.providerId).toBe('mock-api');
expect(out.content).toEqual({ findings: [] });
- // The prompt is passed through verbatim — buildPrompt/getStage are not consulted.
- expect(executedPrompt).toBe('my inline prompt body');
+ // The body rides through unrendered — buildPrompt/getStage are not consulted.
+ // It arrives prefixed with the IP-latitude clause, which the runner stamps on
+ // any creative run source (a custom editorial check reads the manuscript).
+ expect(executedPrompt.endsWith('my inline prompt body')).toBe(true);
+ expect(executedPrompt).toContain(CREATIVE_LATITUDE_HEADING);
expect(prompts.buildPrompt).not.toHaveBeenCalled();
expect(prompts.getStage).not.toHaveBeenCalled();
});
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index f6858bba51..5f96e3d50d 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -594,6 +594,9 @@ Rules:
const result = await callProviderAISimple(provider, model, prompt, {
temperature: 0.6,
max_tokens: 2000,
+ // First-person memoir prose that can name real works, people, and places —
+ // exactly what a model hedges around without the IP-latitude clause.
+ creative: true,
op: 'autobiography-weave',
opLabel: 'Weaving your story…'
});
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index 62855fcb67..496e5f2355 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -85,10 +85,16 @@ const pipelineJudge = await import('./pipelineJudge.js');
const textStages = await import('./textStages.js');
const textStageProgress = await import('./textStageProgress.js');
const runnerSvc = await import('../runner.js');
+const { CREATIVE_LATITUDE_CLAUSE } = await import('../../lib/creativeLatitude.js');
-// Strip the `RENDERED:<stage>:` prefix that the mocked buildPrompt prepends
-// so the asserted-against context is the bare JSON tree.
-const ctxFromCall = (call) => JSON.parse(call.prompt.replace(/^RENDERED:[^:]+:/, ''));
+// Strip the IP-latitude clause the runner prepends to every creative run
+// (lib/creativeLatitude.js) plus the `RENDERED:<stage>:` prefix the mocked
+// buildPrompt adds, so the asserted-against context is the bare JSON tree.
+const ctxFromCall = (call) => JSON.parse(
+ call.prompt
+ .replace(`${CREATIVE_LATITUDE_CLAUSE}\n\n---\n\n`, '')
+ .replace(/^RENDERED:[^:]+:/, ''),
+);
describe('pipeline text stage generator', () => {
beforeEach(() => {
@@ -241,7 +247,7 @@ describe('pipeline text stage generator', () => {
lengthProfile: 'extended',
});
await textStages.generateStage(issue.id, 'idea');
- const ctx = JSON.parse(llmCalls[0].prompt.replace(/^RENDERED:[^:]+:/, ''));
+ const ctx = ctxFromCall(llmCalls[0]);
const lt = ctx.lengthTargets;
expect(lt.profile).toBe('extended');
expect(lt.pageTarget).toBe(32);
@@ -677,7 +683,7 @@ describe('pipeline text stage generator', () => {
minutesTarget: 50,
});
await textStages.generateStage(issue.id, 'idea');
- const ctx = JSON.parse(llmCalls[0].prompt.replace(/^RENDERED:[^:]+:/, ''));
+ const ctx = ctxFromCall(llmCalls[0]);
const lt = ctx.lengthTargets;
expect(lt.profile).toBe('custom');
expect(lt.pageTarget).toBe(44);
diff --git a/server/services/promptService.js b/server/services/promptService.js
index 404d71315f..bd3d84c769 100644
--- a/server/services/promptService.js
+++ b/server/services/promptService.js
@@ -13,6 +13,7 @@
import { join } from 'path';
import { applyTemplate } from '../lib/promptTemplate.js';
import { expandPartials } from '../lib/promptPartials.js';
+import { isCreativeStage, withCreativeLatitude } from '../lib/creativeLatitude.js';
import { PATHS } from '../lib/fileUtils.js';
import { setAIToolkitInstance, requireToolkit } from '../lib/aiToolkitState.js';
@@ -88,7 +89,12 @@ export async function buildPrompt(stageName, data = {}) {
const v = variables[varName];
if (v && allVars[varName] === undefined) allVars[varName] = v.content;
}
- return applyTemplate(template, allVars);
+ const rendered = applyTemplate(template, allVars);
+ // Creative stages carry the IP-latitude clause (lib/creativeLatitude.js) so a
+ // model doesn't quietly genericize a deliberate reference. Stamping HERE — the
+ // one place every stage template is rendered — covers runStagedLLM and every
+ // other buildPrompt caller without touching 117 template files.
+ return isCreativeStage(stageName) ? withCreativeLatitude(rendered) : rendered;
}
export async function previewPrompt(stageName, testData = {}) {
diff --git a/server/services/promptService.test.js b/server/services/promptService.test.js
new file mode 100644
index 0000000000..42e60f3282
--- /dev/null
+++ b/server/services/promptService.test.js
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// The toolkit singleton is the only thing buildPrompt reaches out to. Stubbing
+// it keeps this a pure test of the render pipeline (partial expansion →
+// variable substitution → creative IP-latitude stamp).
+const stages = new Map();
+const templates = new Map();
+
+vi.mock('../lib/aiToolkitState.js', () => ({
+ setAIToolkitInstance: vi.fn(),
+ requireToolkit: () => ({
+ services: {
+ prompts: {
+ getStage: (name) => stages.get(name) || null,
+ getStageTemplate: async (name) => templates.get(name) || null,
+ getVariables: () => ({}),
+ },
+ },
+ }),
+}));
+
+const { buildPrompt } = await import('./promptService.js');
+const { CREATIVE_LATITUDE_HEADING } = await import('../lib/creativeLatitude.js');
+
+const defineStage = (name, template) => {
+ stages.set(name, { name, variables: [] });
+ templates.set(name, template);
+};
+
+beforeEach(() => {
+ stages.clear();
+ templates.clear();
+});
+
+describe('buildPrompt — creative IP-latitude clause', () => {
+ it('stamps a creative stage so the model does not genericize named IP', async () => {
+ defineStage('pipeline-prose', 'Write chapter {{n}}.');
+ const out = await buildPrompt('pipeline-prose', { n: 3 });
+ expect(out).toContain(CREATIVE_LATITUDE_HEADING);
+ expect(out).toContain('Write chapter 3.');
+ // Prepended: the stage's own output contract keeps the last word.
+ expect(out.startsWith(CREATIVE_LATITUDE_HEADING)).toBe(true);
+ expect(out.trimEnd().endsWith('Write chapter 3.')).toBe(true);
+ });
+
+ it('leaves an operational stage unstamped', async () => {
+ defineStage('cos-task-enhance', 'Rewrite this task: {{task}}.');
+ const out = await buildPrompt('cos-task-enhance', { task: 'ship it' });
+ expect(out).toBe('Rewrite this task: ship it.');
+ });
+
+ it('throws on an unknown stage rather than rendering an unstamped prompt', async () => {
+ await expect(buildPrompt('no-such-stage', {})).rejects.toThrow(/not found/);
+ });
+});
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index 8939ea89fe..5b1f7a448a 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -686,6 +686,9 @@ Respond with a concise profile in this exact structure:
const result = await callProviderAISimple(provider, modelId, prompt, {
temperature: 0.3,
max_tokens: 1000,
+ // The whole point is to cite the named films/albums/artists the user
+ // mentioned; a model that genericizes them produces a useless profile.
+ creative: true,
op: `taste-summary:${sectionId}`,
opLabel: `Generating ${config.label} taste summary`
});
@@ -759,6 +762,7 @@ ${allTranscripts}
const result = await callProviderAISimple(provider, modelId, prompt, {
temperature: 0.3,
max_tokens: 1500,
+ creative: true,
op: 'taste-summary:overall',
opLabel: 'Generating unified taste profile'
});
@@ -943,6 +947,7 @@ Generate exactly ONE question. Do not include any preamble, numbering, or explan
const result = await callProviderAISimple(provider, modelId, prompt, {
temperature: 0.8,
max_tokens: 200,
+ creative: true,
op: `taste-deep-question:${sectionId}`,
opLabel: `Crafting a deeper ${config.label} question`
});