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
let a commission brief carry a full prompting instruction set, not a one-line mood
[._.]/ Adam Eivy7c89c3f02bde
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsxindex 562f6060bf..3388cad84b 100644--- a/client/src/components/creative-commission/CommissionConfigForm.jsx+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx@@ -20,8 +20,15 @@ import {WEEKDAYS, inputCls, labelCls, describeSchedule,ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,backendFieldsForAbility, RENDER_BACKEND_AUTO,+ COMMISSION_NAME_MAX, COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,} from './commissionForm.js';+// Multi-line so the field reads as room for DIRECTION rather than a tagline.+const INTENT_PLACEHOLDER = `something surreal, dreamlike, unsettlingly beautiful++Describe the cause, not the effect: physics and emotion, not adjectives.+One causal beat per shot, in order. Diegetic audio only, no music.`;+export default function CommissionConfigForm({ form, patchForm, saving, onSave, onCancel, saveLabel = 'Save' }) {return (<div className="space-y-5">@@ -33,7 +40,7 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,id="commission-name"className={inputCls}value={form.name}- maxLength={200}+ maxLength={COMMISSION_NAME_MAX}onChange={(e) => patchForm(['name'], e.target.value)}placeholder="Nightly Surreal"/>@@ -80,12 +87,20 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,<label className={labelCls} htmlFor="commission-intent">Intent</label><textareaid="commission-intent"- className={`${inputCls} min-h-[70px]`}+ className={`${inputCls} min-h-[180px] leading-relaxed`}value={form.brief.intent}- maxLength={2000}+ maxLength={COMMISSION_INTENT_MAX}onChange={(e) => patchForm(['brief', 'intent'], e.target.value)}- placeholder="something surreal, dreamlike, unsettlingly beautiful"+ placeholder={INTENT_PLACEHOLDER}/>+ <div className="flex items-start justify-between gap-3 mt-1">+ <p className="text-xs text-gray-500">+ What to make, and the standing craft direction for how to make it.+ </p>+ <span className="text-xs text-gray-500 shrink-0 tabular-nums">+ {form.brief.intent.length}/{COMMISSION_INTENT_MAX}+ </span>+ </div></div><div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><div>@@ -94,7 +109,7 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,id="commission-genre"className={inputCls}value={form.brief.genre}- maxLength={120}+ maxLength={COMMISSION_BRIEF_TAG_MAX}onChange={(e) => patchForm(['brief', 'genre'], e.target.value)}placeholder="surrealism"/>@@ -105,7 +120,7 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,id="commission-style"className={inputCls}value={form.brief.styleSpec}- maxLength={5000}+ maxLength={COMMISSION_STYLE_SPEC_MAX}onChange={(e) => patchForm(['brief', 'styleSpec'], e.target.value)}placeholder="flat color, Magritte"/>diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.jsindex 426765ba24..ce5b3ddbdc 100644--- a/client/src/components/creative-commission/commissionForm.js+++ b/client/src/components/creative-commission/commissionForm.js@@ -7,6 +7,17 @@* Kept side-effect-free so both surfaces map record ↔ form identically.*/+// Client mirror of the server's brief field caps+// (server/lib/creativeCommissionValidation.js). The intent is roomy on purpose:+// it reaches the planning LLM verbatim, so it holds a whole instruction set —+// framework, rules, a sample prompt — not a one-line mood. Keep these in step+// with the server: a client cap BELOW the schema's truncates the user's brief at+// the textarea silently, with no error to explain where the tail went.+export const COMMISSION_NAME_MAX = 200;+export const COMMISSION_INTENT_MAX = 20000;+export const COMMISSION_STYLE_SPEC_MAX = 5000;+export const COMMISSION_BRIEF_TAG_MAX = 120;+export const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];export const inputCls = 'w-full bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-gray-100 focus:outline-none focus:border-port-accent';diff --git a/client/src/components/creative-director/DirectiveComposer.jsx b/client/src/components/creative-director/DirectiveComposer.jsxindex 7a0665eca2..bb73b04215 100644--- a/client/src/components/creative-director/DirectiveComposer.jsx+++ b/client/src/components/creative-director/DirectiveComposer.jsx@@ -1,4 +1,4 @@-import { DELIVERABLE_OPTIONS } from '../../lib/creativeDirectorPlan.js';+import { CREATIVE_DIRECTOR_GOAL_MAX, DELIVERABLE_OPTIONS } from '../../lib/creativeDirectorPlan.js';/*** Directive composer fields (CDO Phase 4, #2186) — the studio "brief" a directive@@ -58,7 +58,7 @@ export default function DirectiveComposer({onChange={(e) => patch({ goal: e.target.value })}placeholder="Produce a 6-issue noir comic in universe X, with covers, a polished manuscript, and a teaser trailer…"className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm h-28 font-mono disabled:opacity-50"- maxLength={5000}+ maxLength={CREATIVE_DIRECTOR_GOAL_MAX}/></div>diff --git a/client/src/lib/creativeDirectorPlan.js b/client/src/lib/creativeDirectorPlan.jsindex 50af124756..dd092cb4f0 100644--- a/client/src/lib/creativeDirectorPlan.js+++ b/client/src/lib/creativeDirectorPlan.js@@ -5,6 +5,15 @@// timing, and blocked-step triage. These helpers keep that presentation logic// pure + unit-tested so the component stays a thin renderer. No React, no I/O.+// Client mirror of the server's directive `goal` cap+// (server/lib/creativeDirectorValidation.js). It has to clear what the commission+// scheduler composes from a maxed-out brief, because the Plan tab loads a+// commission-spawned project's directive into the composer for editing — a+// `maxLength` below the schema's would silently drop the tail of that goal on+// save and re-plan against the mutilated brief. Parity is asserted in+// server/lib/creativeDirectorValidation.mirror.test.js.+export const CREATIVE_DIRECTOR_GOAL_MAX = 32000;+// The deliverable checklist offered by the directive composer. Free-form on the// wire (the planner reads the labels as intent); this is the curated menu the UI// surfaces. `id` is the token stored in `directive.deliverables[]`.diff --git a/server/lib/README.md b/server/lib/README.mdindex c6b0821d83..c465355474 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -41,8 +41,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). || `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). || `cosValidation.js` | Chief-of-Staff task/job/loop/learning schemas, the Review-Loop reviewer vocabulary + helpers (`normalizeReviewers`/`buildReviewWithArgs`), the Code-Review settings slice, and the task-metadata sanitizer. |-| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. |-| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. |+| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. Brief field caps are mirrored by the commission form in `client/src/components/creative-commission/commissionForm.js` (parity: `creativeCommissionValidation.mirror.test.js`). |+| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. `CREATIVE_DIRECTOR_GOAL_MAX` is mirrored in `client/src/lib/creativeDirectorPlan.js` (parity: `creativeDirectorValidation.mirror.test.js`). || `digitalTwinValidation.js` | Digital twin document/category schemas. || `genomeValidation.js` | Genome upload + search schemas. || `identityValidation.js` | Identity section + chronotype + scheduling schemas. |diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.jsindex a3a740bd56..c572a7d0bb 100644--- a/server/lib/creativeCommissionValidation.js+++ b/server/lib/creativeCommissionValidation.js@@ -149,7 +149,16 @@ function generationFieldSchema(def) {}export const COMMISSION_NAME_MAX = 200;-export const COMMISSION_INTENT_MAX = 2000;+// The intent goes to the PLANNING LLM verbatim (via the CD directive `goal`), so+// it is sized to hold a full instruction set — a prompting framework, causation+// and camera rules, an audio policy, and a worked sample prompt — not a line of+// mood. For scale: MiniMax H3's documented 7000-character ceiling applies to the+// RENDER prompt the director writes downstream, and a brief that TEACHES how to+// write that prompt needs several times its length. Raising this also means+// raising MAX_DIRECTIVE_GOAL_LEN (services/creativeCommissions/directive.js).+export const COMMISSION_INTENT_MAX = 20000;+export const COMMISSION_STYLE_SPEC_MAX = 5000;+export const COMMISSION_BRIEF_TAG_MAX = 120;export const COMMISSION_MUSIC_TASTE_ANCHOR_MAX = 5;export const COMMISSION_MUSIC_TASTE_PERCENT_MAX = 100;export const COMMISSION_MUSIC_TASTE_ENGINE_MAX = 64;@@ -189,9 +198,9 @@ export const creativeCommissionMusicTasteUpdateSchema = z.object({// CD project's styleSpec; `constraints` scopes the run to a universe/series.export const creativeCommissionBriefSchema = z.object({intent: z.string().trim().min(1).max(COMMISSION_INTENT_MAX),- genre: z.string().trim().max(120).nullable().optional(),- category: z.string().trim().max(120).nullable().optional(),- styleSpec: z.string().max(5000).default(''),+ genre: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),+ category: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),+ styleSpec: z.string().max(COMMISSION_STYLE_SPEC_MAX).default(''),constraints: z.object({universeId: z.string().max(120).nullable().optional(),seriesId: z.string().max(120).nullable().optional(),@@ -349,9 +358,9 @@ export const creativeCommissionCreateSchema = z.object({// omitted key stays omitted and the merge preserves the stored value.export const creativeCommissionBriefUpdateSchema = z.object({intent: z.string().trim().min(1).max(COMMISSION_INTENT_MAX).optional(),- genre: z.string().trim().max(120).nullable().optional(),- category: z.string().trim().max(120).nullable().optional(),- styleSpec: z.string().max(5000).optional(),+ genre: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),+ category: z.string().trim().max(COMMISSION_BRIEF_TAG_MAX).nullable().optional(),+ styleSpec: z.string().max(COMMISSION_STYLE_SPEC_MAX).optional(),constraints: z.object({universeId: z.string().max(120).nullable().optional(),seriesId: z.string().max(120).nullable().optional(),diff --git a/server/lib/creativeCommissionValidation.mirror.test.js b/server/lib/creativeCommissionValidation.mirror.test.jsnew file mode 100644index 0000000000..1f7a3ae1ad--- /dev/null+++ b/server/lib/creativeCommissionValidation.mirror.test.js@@ -0,0 +1,50 @@+/**+ * Mirror parity for the commission BRIEF field caps: server/lib/creativeCommissionValidation.js+ * ↔ client/src/components/creative-commission/commissionForm.js.+ *+ * The client uses these as the textarea/input `maxLength`, which is a SILENT+ * limit — the browser simply stops accepting characters, with no validation+ * error to explain why a pasted brief lost its tail. A client cap below the+ * server's therefore truncates the user's brief invisibly, and one above it+ * turns a paste into a 400 at save time. Both are drift the suite should catch,+ * so the caps are asserted identical rather than left to convention.+ *+ * Only the numbers are mirrored — the schemas themselves stay server-side.+ * Compared as source text rather than by importing both modules (the cheaper+ * `issueLength.mirror.test.js` shape) because the client side of this pair pulls+ * in client-only packages that do not resolve in the server test env.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';+import { compareDeclaration } from './mirrorParity.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++const SERVER_PATH = resolve(__dirname, 'creativeCommissionValidation.js');+const CLIENT_PATH = resolve(__dirname, '../../client/src/components/creative-commission/commissionForm.js');++const MIRRORED_NAMES = [+ 'COMMISSION_NAME_MAX',+ 'COMMISSION_INTENT_MAX',+ 'COMMISSION_STYLE_SPEC_MAX',+ 'COMMISSION_BRIEF_TAG_MAX',+];++describe('creative commission brief caps server↔client mirror parity', () => {+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');++ for (const name of MIRRORED_NAMES) {+ it(`${name} is declared identically on both sides`, () => {+ const { serverDecl, clientDecl, serverNorm, clientNorm } =+ compareDeclaration(serverSrc, clientSrc, name);++ expect(serverDecl, `server creativeCommissionValidation.js is missing: ${name}`).not.toBeNull();+ expect(clientDecl, `client commissionForm.js is missing: ${name}`).not.toBeNull();+ expect(clientNorm, `"${name}" diverged between server and client`).toBe(serverNorm);+ });+ }+});diff --git a/server/lib/creativeDirectorValidation.js b/server/lib/creativeDirectorValidation.jsindex 1d0764cda4..f3527670d0 100644--- a/server/lib/creativeDirectorValidation.js+++ b/server/lib/creativeDirectorValidation.js@@ -51,6 +51,12 @@ export const creativeDirectorCastMemberSchema = z.object({summary: z.string().max(500).optional(),});+// Kept clear of the commission scheduler's MAX_DIRECTIVE_GOAL_LEN, so a goal it+// composes from a maxed-out commission brief also validates on the HTTP path.+// That ordering is asserted in services/creativeCommissions/directive.test.js —+// this module can't import the service to derive it.+export const CREATIVE_DIRECTOR_GOAL_MAX = 32000;+// Production directive (CDO Phase 2, #2184) — the brief the planner agent turns// into a plan. `goal` is the free-text intent ("produce a 6-issue noir comic in// universe X with covers and a teaser trailer"); `deliverables` is the checklist@@ -59,7 +65,7 @@ export const creativeDirectorCastMemberSchema = z.object({// constraint values — the plan advance loop gates each tool call at dispatch, so// the directive is context for the planner, not an enforcement surface itself.export const creativeDirectorDirectiveSchema = z.object({- goal: z.string().min(1).max(5000),+ goal: z.string().min(1).max(CREATIVE_DIRECTOR_GOAL_MAX),deliverables: z.array(z.string().min(1).max(200)).max(20).default([]),constraints: z.object({universeId: z.string().max(120).nullable().optional(),diff --git a/server/lib/creativeDirectorValidation.mirror.test.js b/server/lib/creativeDirectorValidation.mirror.test.jsnew file mode 100644index 0000000000..b1bea3d1f7--- /dev/null+++ b/server/lib/creativeDirectorValidation.mirror.test.js@@ -0,0 +1,36 @@+/**+ * Mirror parity for the Creative Director directive `goal` cap:+ * server/lib/creativeDirectorValidation.js ↔ client/src/lib/creativeDirectorPlan.js.+ *+ * The client uses it as the composer textarea's `maxLength` — a SILENT limit. The+ * Plan tab loads a commission-spawned project's directive into that composer for+ * editing, so a client cap below the schema's would drop the tail of a long goal+ * on save with no error, and the project would re-plan against the mutilated+ * brief. Compared as source text rather than by importing both modules (the+ * cheaper `issueLength.mirror.test.js` shape) because the client side of this+ * pair pulls in client-only packages that do not resolve in the server test env.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';+import { compareDeclaration } from './mirrorParity.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++const SERVER_PATH = resolve(__dirname, 'creativeDirectorValidation.js');+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/creativeDirectorPlan.js');++describe('creative director goal cap server↔client mirror parity', () => {+ it('CREATIVE_DIRECTOR_GOAL_MAX is declared identically on both sides', () => {+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');+ const { serverDecl, clientDecl, serverNorm, clientNorm } =+ compareDeclaration(serverSrc, clientSrc, 'CREATIVE_DIRECTOR_GOAL_MAX');++ expect(serverDecl, 'server creativeDirectorValidation.js is missing the cap').not.toBeNull();+ expect(clientDecl, 'client creativeDirectorPlan.js is missing the cap').not.toBeNull();+ expect(clientNorm, 'CREATIVE_DIRECTOR_GOAL_MAX diverged between server and client').toBe(serverNorm);+ });+});diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.jsindex 1bd7b84ef4..bb016ad5e9 100644--- a/server/services/creativeCommissions/abilityAdapters.js+++ b/server/services/creativeCommissions/abilityAdapters.js@@ -232,10 +232,10 @@ const musicAdapter = {const lead = `Compose an original ~${secs}s music / audio piece. Use the music generation tools; do NOT plan a video or image render.`;const { lines, digest, constraints } = briefContext(commission, lead);const tastePrompt = renderMusicTasteRecipePrompt(tasteRecipe);- // Keep the bounded recipe + original-work constraint ahead of user-authored- // brief fields. composeDirectiveGoal truncates only the tail when the brief- // reaches its cap, so appending this would silently drop the authoritative- // taste prompt on long intents/styles before the audio job ever sees it.+ // Keep the bounded recipe + original-work constraint ahead of the optional+ // brief tags (genre / category / style). composeDirectiveGoal truncates only+ // the tail, so appending this would leave the authoritative taste prompt last+ // in line behind them if anything ever overran the goal budget.if (tastePrompt) lines.splice(1, 0, tastePrompt);return { goal: composeDirectiveGoal(lines, digest), deliverables: [`One ~${secs}s music track matching the brief`], constraints };},diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.jsindex d7fdd26c75..613db66359 100644--- a/server/services/creativeCommissions/abilityAdapters.test.js+++ b/server/services/creativeCommissions/abilityAdapters.test.js@@ -2,9 +2,15 @@ import { describe, it, expect } from 'vitest';import {ABILITY_ADAPTERS, getAbilityAdapter, buildCommissionDirective, buildRenderBackendPin,} from './abilityAdapters.js';-import { CREATIVE_COMMISSION_ABILITIES, ABILITY_GENERATION_SPEC } from '../../lib/creativeCommissionValidation.js';+import {+ CREATIVE_COMMISSION_ABILITIES, ABILITY_GENERATION_SPEC,+ COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,+} from '../../lib/creativeCommissionValidation.js';+import { MAX_DIRECTIVE_GOAL_LEN } from './directive.js';import { buildVideoPromptGuidance, isMiniMaxVideoModel } from './videoPromptGuidance.js';+const MAXED_INTENT = 'x'.repeat(COMMISSION_INTENT_MAX);+describe('ability adapter registry', () => {it('has an adapter for every supported ability (and no extras)', () => {expect(Object.keys(ABILITY_ADAPTERS).sort()).toEqual([...CREATIVE_COMMISSION_ABILITIES].sort());@@ -54,20 +60,20 @@ describe('buildCommissionDirective — video (unchanged brief/feedback fold)', (.toMatchObject({ targetAbility: 'video', generation: { quality: 'standard', videoMode: 'auto' } });});- it('clamps the goal under the CD 5000-char cap with a large feedback window + long notes', () => {+ it('clamps the goal under the directive cap with a large feedback window + long notes', () => {const feedback = Array.from({ length: 50 }, (_, i) => ({ rating: i % 2 === 0 ? 'up' : 'down', note: 'z'.repeat(1000) }));const directive = buildCommissionDirective({ targetAbility: 'video', brief: { intent: 'surreal' }, feedback, feedbackWindow: 50 });- expect(directive.goal.length).toBeLessThanOrEqual(4500);+ expect(directive.goal.length).toBeLessThanOrEqual(MAX_DIRECTIVE_GOAL_LEN);});it('keeps the feedback digest even when the brief text is very long', () => {const directive = buildCommissionDirective({targetAbility: 'video',- brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(3000) },+ brief: { intent: 'x'.repeat(COMMISSION_INTENT_MAX * 2), styleSpec: 'y'.repeat(COMMISSION_STYLE_SPEC_MAX * 2) },feedback: [{ rating: 'down', note: 'less horror' }],feedbackWindow: 5,});- expect(directive.goal.length).toBeLessThanOrEqual(4500);+ expect(directive.goal.length).toBeLessThanOrEqual(MAX_DIRECTIVE_GOAL_LEN);expect(directive.goal).toContain('Recent dislikes: less horror.');});@@ -93,13 +99,23 @@ describe('buildCommissionDirective — video (unchanged brief/feedback fold)', (expect(buildVideoPromptGuidance('ltx-2.5')).not.toContain('[Tracking shot]');});- it('keeps the MiniMax recipe when the brief nearly fills the directive budget', () => {+ // A brief filled to the SCHEMA caps is the largest one a route or PATCH can+ // store, so the system prefix AND the user's own words must both survive it:+ // the clamp drops the tail, and the guidance is prepended, so an under-sized+ // MAX_DIRECTIVE_GOAL_LEN would silently eat the brief instead of erroring.+ it('carries a brief filled to the schema caps AND the MiniMax recipe', () => {+ const intent = 'x'.repeat(COMMISSION_INTENT_MAX);+ const styleSpec = 'y'.repeat(COMMISSION_STYLE_SPEC_MAX);const directive = buildCommissionDirective({targetAbility: 'video',- brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(2000) },+ brief: { intent, styleSpec, genre: 'g'.repeat(COMMISSION_BRIEF_TAG_MAX), category: 'c'.repeat(COMMISSION_BRIEF_TAG_MAX) },+ feedback: Array.from({ length: 50 }, (_, i) => ({ rating: i % 2 === 0 ? 'up' : 'down', note: 'z'.repeat(1000) })),+ feedbackWindow: 50,generation: { videoModelId: 'minimax_h3_cuda' },});expect(directive.goal).toContain('MiniMax H3 prompt template');+ expect(directive.goal).toContain(intent);+ expect(directive.goal).toContain(styleSpec);});it('uses the install default model when choosing model-specific guidance', () => {@@ -184,7 +200,8 @@ describe('per-ability directives steer the planner to the right tools', () => {it('music: preserves taste anchors and original-work constraints under the goal cap', () => {const d = buildCommissionDirective({targetAbility: 'music',- brief: { intent: 'x'.repeat(2000), styleSpec: 'y'.repeat(5000) },+ // A brief filled to the schema caps — the largest a route or PATCH can store.+ brief: { intent: MAXED_INTENT, styleSpec: 'y'.repeat(COMMISSION_STYLE_SPEC_MAX) },generation: { lengthSeconds: 45 },}, {tasteRecipe: {@@ -194,7 +211,8 @@ describe('per-ability directives steer the planner to the right tools', () => {sourceVersion: 'music-taste-v1:example', sourceHash: 'example-hash',},});- expect(d.goal.length).toBeLessThanOrEqual(4500);+ expect(d.goal.length).toBeLessThanOrEqual(MAX_DIRECTIVE_GOAL_LEN);+ expect(d.goal).toContain(MAXED_INTENT);expect(d.goal).toContain('Example Artist');expect(d.goal).toContain('Create an original work');expect(d.goal).toContain('do not reproduce source tracks');diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.jsindex 218d64962b..3f74e44968 100644--- a/server/services/creativeCommissions/directive.js+++ b/server/services/creativeCommissions/directive.js@@ -4,29 +4,46 @@* These are side-effect-free helpers: `commissionToCron` turns a schedule* descriptor into a 5-field cron string; `renderFeedbackDigest` renders the taste* feedback into a steering digest; and `composeDirectiveGoal` folds a list of- * brief lines + that digest into a CD directive `goal` under the 5000-char cap.+ * brief lines + that digest into a CD directive `goal` under MAX_DIRECTIVE_GOAL_LEN.* The per-output-type directive assembly (which lines/deliverables each type* gets) lives in abilityAdapters.js (#2769), which imports these — this module- * stays a dependency-free leaf and never imports back. Kept pure so they're- * trivially unit-testable and importable anywhere without dragging the scheduler- * graph along. The authoritative cron-VALIDITY check (isValidCron) lives in the- * scheduler/service.+ * never imports back. Its only imports are the CAP CONSTANTS the goal budget is+ * derived from (see below); it pulls in no scheduler/store graph, so it stays+ * trivially unit-testable and importable anywhere. The authoritative+ * cron-VALIDITY check (isValidCron) lives in the scheduler/service.*/+import {+ COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,+} from '../../lib/creativeCommissionValidation.js';+// The CD directive `goal` this composes is fed straight into `createProject` by// the scheduler, which does NOT re-validate it against the route's-// `creativeDirectorDirectiveSchema` (that 5000-char cap only guards HTTP input).+// `creativeDirectorDirectiveSchema` (whose cap only guards HTTP input).// A commission with the max `feedbackWindow` (50) and long notes could otherwise// balloon the goal past what the planner should ever see. Clamp defensively: cap// each note's contribution to the digest, and hard-cap the final goal with// headroom under the CD schema limit.export const MAX_DIGEST_NOTE_LEN = 300;-export const MAX_DIRECTIVE_GOAL_LEN = 4500;// The digest is the whole point of the feedback loop, so it gets a reserved// slice of the goal budget the brief text can't eat into (see// buildCommissionDirective). Bounded on its own too, so 50 reactions can't blow// the reservation.export const MAX_DIGEST_LEN = 1500;+// Everything an adapter prepends that the user did not write: the lead sentence+// plus the longest system prefix (a model's prompt guidance, or a fully-populated+// music taste recipe). Not derived — those strings are prose, not capped fields —+// so directive.test.js measures the real ones against this allowance.+export const MAX_SYSTEM_PREFIX_LEN = 3000;+// DERIVED, not tuned: the sum of every bounded part one goal can hold. The clamp+// drops the TAIL and the adapters put system text FIRST, so a budget short of+// this sum eats the user's own words rather than erroring — which is why raising+// a brief cap has to move this number, and does so automatically here.+export const MAX_DIRECTIVE_GOAL_LEN = COMMISSION_INTENT_MAX+ + COMMISSION_STYLE_SPEC_MAX+ + (COMMISSION_BRIEF_TAG_MAX * 2) // genre + category+ + MAX_DIGEST_LEN+ + MAX_SYSTEM_PREFIX_LEN;const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);const clampNote = (note) => clamp(note, MAX_DIGEST_NOTE_LEN);@@ -109,7 +126,7 @@ export function renderFeedbackDigest(feedback, windowSize = 5) {/*** Compose a CD directive `goal` string from a list of brief lines and a feedback- * digest, under the CD's 5000-char cap. Ability-agnostic (#2769): each ability+ * digest, under MAX_DIRECTIVE_GOAL_LEN. Ability-agnostic (#2769): each ability* adapter builds its own type-specific `lines` (see abilityAdapters.js) and hands* them here so the char-budget / digest-reservation logic lives in exactly one* place.diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.jsindex 1743dea62e..d01ca4d1e8 100644--- a/server/services/creativeCommissions/directive.test.js+++ b/server/services/creativeCommissions/directive.test.js@@ -1,5 +1,48 @@import { describe, it, expect } from 'vitest';-import { commissionToCron, renderFeedbackDigest, composeDirectiveGoal } from './directive.js';+import {+ commissionToCron, renderFeedbackDigest, composeDirectiveGoal,+ MAX_DIRECTIVE_GOAL_LEN, MAX_SYSTEM_PREFIX_LEN,+} from './directive.js';+import { CREATIVE_DIRECTOR_GOAL_MAX } from '../../lib/creativeDirectorValidation.js';+import {+ renderMusicTasteRecipePrompt,+ MUSIC_TASTE_RECIPE_MAX_CONTEXT, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION,+} from './musicTasteRecipe.js';+import { COMMISSION_MUSIC_TASTE_ANCHOR_MAX } from '../../lib/creativeCommissionValidation.js';+import { buildVideoPromptGuidance } from './videoPromptGuidance.js';++// The goal budget is derived from the brief caps, but two of its terms are prose+// the derivation can only ALLOW FOR: the system prefix an adapter prepends, and+// the CD schema cap the composed goal has to pass on the HTTP path. Neither can+// be imported into directive.js (the first is prose, the second would invert the+// lib→service direction), so they are pinned here instead of left to a comment.+describe('directive goal budget invariants', () => {+ it('stays under the Creative Director schema cap for the goal', () => {+ expect(MAX_DIRECTIVE_GOAL_LEN).toBeLessThanOrEqual(CREATIVE_DIRECTOR_GOAL_MAX);+ });++ it('reserves enough prefix room for the longest system text an adapter prepends', () => {+ // The two candidates, each built at ITS OWN caps so growing one fails here+ // rather than silently eating the user's brief at compose time.+ const guidance = buildVideoPromptGuidance('minimax_h3_8bit');+ const tastePrompt = renderMusicTasteRecipePrompt({+ version: 1,+ sourceVersion: 'v'.repeat(MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION),+ sourceHash: 'h'.repeat(64),+ statedContext: 'x'.repeat(MUSIC_TASTE_RECIPE_MAX_CONTEXT),+ explorationPercent: 20,+ explorationDirection: 'balanced',+ anchors: Array.from({ length: COMMISSION_MUSIC_TASTE_ANCHOR_MAX }, (_, i) => ({+ kind: 'track', name: `n${i}${'a'.repeat(119)}`, artist: `r${i}${'b'.repeat(119)}`, count: 3, source: 'observed',+ })),+ });+ // + a lead sentence, the longest of which is the music-video one.+ const longestLead = 300;+ expect(Math.max(guidance.length, tastePrompt.length) + longestLead)+ .toBeLessThanOrEqual(MAX_SYSTEM_PREFIX_LEN);+ });+});+describe('commissionToCron', () => {it('composes a DAILY cron from HH:MM', () => {@@ -115,8 +158,8 @@ describe('composeDirectiveGoal', () => {it('reserves room for the digest and clamps the brief so the whole goal stays under the CD cap', () => {// A huge brief must not truncate away the digest (appended last, but reserved// for) — otherwise ratings stop steering the run.- const goal = composeDirectiveGoal(['x'.repeat(6000)], 'Recent dislikes: less horror.');- expect(goal.length).toBeLessThanOrEqual(4500);+ const goal = composeDirectiveGoal(['x'.repeat(MAX_DIRECTIVE_GOAL_LEN + 1500)], 'Recent dislikes: less horror.');+ expect(goal.length).toBeLessThanOrEqual(MAX_DIRECTIVE_GOAL_LEN);expect(goal).toContain('Recent dislikes: less horror.');});});diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.jsindex 02ebbee20d..4104d4e567 100644--- a/server/services/creativeCommissions/store.js+++ b/server/services/creativeCommissions/store.js@@ -86,6 +86,18 @@ export const commissionEvents = new EventEmitter();export const TYPE = 'creative-commissions';export const COMMISSIONS_SCHEMA_VERSION = 1;export const MAX_PERSISTED_RUNS = 50;+// A run's `promptUsed` is an EXCERPT of the directive goal, not a copy of it.+// Two things read it, and neither wants the whole brief: the run ledger keeps+// MAX_PERSISTED_RUNS of them in a record that is rewritten whole on every+// mutation and shipped entire by the list route, and+// `getCommissionMusicContextForProject` hands it to the audio enqueue as the+// authoritative music PROMPT. Since the goal now carries a full instruction set+// (COMMISSION_INTENT_MAX), an uncapped copy would put a planning brief into a+// render payload. 4000 keeps both at roughly their pre-instruction-set size.+export const MAX_RUN_PROMPT_LEN = 4000;+const clampRunPrompt = (value) => (typeof value === 'string' && value.length > MAX_RUN_PROMPT_LEN+ ? `${value.slice(0, MAX_RUN_PROMPT_LEN - 1)}…`+ : value);// Feedback is kept inline on the commission record (not a separate federated// store) — Phase 1's store shape reserved `feedback[]` precisely so Phase 2 adds// the rate surface without a schema change. Capped like runs so a long-lived@@ -153,6 +165,9 @@ function sanitizeMusicOutput(raw) {function sanitizeRunHistoryEntry(raw) {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return raw;const next = { ...raw };+ // Also on READ, so a ledger written before the cap (or by a peer) shrinks the+ // first time it is loaded instead of riding along forever.+ if (isStr(raw.promptUsed)) next.promptUsed = clampRunPrompt(raw.promptUsed);if ('tasteRecipe' in raw) {const tasteRecipe = sanitizeMusicTasteRecipe(raw.tasteRecipe);if (tasteRecipe) next.tasteRecipe = tasteRecipe;@@ -715,7 +730,7 @@ export async function recordCommissionRun(id, runEntry) {// scheduled, which is what they were.trigger: runEntry.trigger === 'manual' ? 'manual' : 'schedule',projectId: runEntry.projectId || null,- promptUsed: isStr(runEntry.promptUsed) ? runEntry.promptUsed : null,+ promptUsed: isStr(runEntry.promptUsed) ? clampRunPrompt(runEntry.promptUsed) : null,reason: isStr(runEntry.reason) ? runEntry.reason : null,error: isStr(runEntry.error) ? runEntry.error : null,...(tasteRecipe ? { tasteRecipe } : {}),diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.jsindex 58213eca9e..dc0983b2d3 100644--- a/server/services/creativeCommissions/store.test.js+++ b/server/services/creativeCommissions/store.test.js@@ -57,6 +57,7 @@ const {mergeCommissionsFromSync,pruneTombstonedCommissions,commissionStore,+ MAX_RUN_PROMPT_LEN,ERR_VALIDATION,ERR_NOT_FOUND,} = await import('./store.js');@@ -307,6 +308,18 @@ describe('recordCommissionRun', () => {expect(after.runs[0].id).toMatch(/^run-/);});+ // The directive goal now carries a full instruction set, but a run's copy of it+ // is an excerpt: it is retained MAX_PERSISTED_RUNS deep in a record rewritten+ // whole on every mutation, AND handed to the audio enqueue as the music prompt.+ it('stores the prompt as a bounded excerpt, not the whole directive goal', async () => {+ const created = await createCommission(validInput());+ const goal = 'p'.repeat(MAX_RUN_PROMPT_LEN * 3);+ await recordCommissionRun(created.id, { status: 'started', projectId: 'cd-1', promptUsed: goal });+ const after = await getCommission(created.id);+ expect(after.runs[0].promptUsed.length).toBeLessThanOrEqual(MAX_RUN_PROMPT_LEN);+ expect(after.runs[0].promptUsed.startsWith('ppp')).toBe(true);+ });+it('persists a manual trigger and defaults everything else to schedule', async () => {const created = await createCommission(validInput());await recordCommissionRun(created.id, { status: 'started', trigger: 'manual' });