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

import five server constant tables into the client instead of hand-copying them behind mirror tests

[._.]/ Adam Eivye558ec133082
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index 40f68460b7..10c6c205e0 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -9,16 +9,11 @@
import { describeRecurrence } from '../../utils/cronHelpers.js';
-// 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;
+// The brief field caps are the server's own (server/lib/creativeBriefLimits.js),
+// used here as the inputs' `maxLength`.
+export {
+ COMMISSION_BRIEF_TAG_MAX, COMMISSION_INTENT_MAX, COMMISSION_NAME_MAX, COMMISSION_STYLE_SPEC_MAX,
+} from '../../../../server/lib/creativeBriefLimits.js';
// Pause and Delete are real STOPS, not just "skip the next tick": the server also
// tears down the Creative Director projects the commission already spawned
@@ -95,9 +90,11 @@ const VIDEO_BACKEND_FIELD = {
// Per-ability generation field descriptors — the client mirror of the server's
// GENERATION_KEY_DEFS / ABILITY_GENERATION_SPEC (server/lib/creativeCommissionValidation.js).
-// The config form renders exactly these fields for the selected type. There is no
-// cross-package import, so this must be kept in sync with the server spec BY HAND
-// when a key/bound/default changes; commissionForm.test.js asserts only the
+// The config form renders exactly these fields for the selected type. The server
+// module pulls `zod`, so the browser cannot import the spec until it moves to a
+// pure leaf (as the brief caps did, creativeBriefLimits.js); until then keep this
+// in sync with the server spec BY HAND when a key/bound/default changes;
+// commissionForm.test.js asserts only the
// client-internal invariant (every field has a matching default), not server↔client
// parity.
export const GENERATION_FIELDS_BY_ABILITY = {
diff --git a/client/src/components/meatspace/post/constants.js b/client/src/components/meatspace/post/constants.js
index 5535013f89..5b9dae5fd8 100644
--- a/client/src/components/meatspace/post/constants.js
+++ b/client/src/components/meatspace/post/constants.js
@@ -102,67 +102,19 @@ export function countLlmCorrect(scoredResponses = []) {
// ---------------------------------------------------------------------------
// Practice topics (issue #3252)
// ---------------------------------------------------------------------------
-// MIRROR of server/lib/postTopics.js `POST_TOPICS` — the single source of truth
-// for "what am I actually studying?". Keep the two identical: id / label /
-// module / surface / drillTypes are asserted field-for-field by
-// server/lib/postTopics.mirror.test.js, which imports THIS file.
-//
-// Only the plain registry data lives here; the UI-only presentation (icon,
-// color, per-domain time budget) is layered on in TOPIC_UI below, so a topic
-// added server-side shows up here as soon as its UI row is filled in.
-export const POST_TOPICS = [
- {
- id: 'math',
- label: 'Mental Math',
- module: 'mental-math',
- surface: 'session',
- drillTypes: ['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation', 'applied-numeracy'],
- },
- {
- id: 'memory',
- label: 'Memory',
- module: 'memory',
- surface: 'session',
- drillTypes: ['memory-fill-blank', 'memory-sequence', 'memory-element-flash'],
- },
- {
- id: 'wordplay',
- label: 'Wordplay',
- module: 'llm-drills',
- surface: 'session',
- drillTypes: ['pun-wordplay', 'word-association', 'compound-chain', 'bridge-word', 'double-meaning', 'idiom-twist'],
- },
- {
- id: 'verbal',
- label: 'Verbal Agility',
- module: 'llm-drills',
- surface: 'session',
- drillTypes: ['story-recall', 'verbal-fluency', 'wit-comeback'],
- },
- {
- id: 'imagination',
- label: 'Imagination',
- module: 'llm-drills',
- surface: 'session',
- drillTypes: ['what-if', 'alternative-uses', 'story-prompt', 'invention-pitch', 'reframe'],
- },
- {
- id: 'cognitive',
- label: 'Cognitive',
- module: 'cognitive',
- surface: 'session',
- drillTypes: ['n-back', 'digit-span', 'stroop', 'schulte-table', 'mental-rotation', 'reaction-time', 'task-switching', 'go-no-go', 'flanker'],
- },
- {
- id: 'morse',
- label: 'Morse',
- module: null,
- surface: 'standalone',
- drillTypes: ['morse-copy', 'morse-head-copy', 'morse-send'],
- },
-];
-
-export const TOPIC_IDS = POST_TOPICS.map(t => t.id);
+// The practice-topic registry and its enablement predicates are the server's
+// own (server/lib/postTopics.js); only the UI-only presentation lives here, in
+// TOPIC_UI below, and `constants.test.js` checks it has a row for every topic.
+import {
+ POST_TOPICS,
+ TOPIC_IDS,
+ resolveTopicForDrillType,
+ isTopicEnabled,
+ isMemoryPracticeEnabled,
+ isMemoryItemEnabled,
+} from '../../../../../server/lib/postTopics.js';
+
+export { POST_TOPICS, TOPIC_IDS, resolveTopicForDrillType, isTopicEnabled, isMemoryPracticeEnabled, isMemoryItemEnabled };
// Per-topic presentation. `timeBudgetSec` is only meaningful for topics that
// compose into a session (it sizes the drill's slice of a 5-minute Quick run);
@@ -177,40 +129,6 @@ export const TOPIC_UI = {
morse: { icon: 'Radio', color: 'text-sky-400', bgColor: 'bg-sky-500/20' },
};
-/** The topic that owns a drill type, or `null` for an unmapped/legacy type. */
-export function resolveTopicForDrillType(type) {
- return POST_TOPICS.find(t => t.drillTypes.includes(type)) || null;
-}
-
-/**
- * Whether a topic participates in composition/recommendations under `config`.
- * MIRRORS the server's `isTopicEnabled` — absent entry = enabled, so a config
- * that predates the `topics` key behaves exactly as it did before.
- */
-export function isTopicEnabled(config, topicId) {
- if (!topicId) return true;
- return config?.topics?.[topicId]?.enabled !== false;
-}
-
-/**
- * MIRRORS the server's `isMemoryPracticeEnabled` — the topic entry plus the
- * module block, with no drill type consulted.
- */
-export function isMemoryPracticeEnabled(config) {
- return isTopicEnabled(config, 'memory') && config?.memory?.enabled !== false;
-}
-
-/**
- * MIRRORS the server's `isMemoryItemEnabled` — a per-item opt-out that keeps the
- * item's mastery/schedule history and its own practice page, and only removes it
- * from the automatic rotation.
- */
-export function isMemoryItemEnabled(config, itemId) {
- if (!isMemoryPracticeEnabled(config)) return false;
- if (!itemId) return true;
- return config?.memory?.items?.[itemId]?.enabled !== false;
-}
-
// Domain definitions for 5-minute balanced sessions — DERIVED from POST_TOPICS
// so the domain list has exactly one owner. A POST *domain* is a topic that
// reports a coarse module (i.e. can produce a scored POST task); Morse has a
diff --git a/client/src/components/meatspace/post/constants.test.js b/client/src/components/meatspace/post/constants.test.js
index 82cf7f3ca4..998e8aa50f 100644
--- a/client/src/components/meatspace/post/constants.test.js
+++ b/client/src/components/meatspace/post/constants.test.js
@@ -1,8 +1,8 @@
import { describe, it, expect } from 'vitest';
import {
computeDomainAverages, domainLabel, computeGoalProgress, hasGoals,
- POST_TOPICS, DOMAINS, DRILL_TO_DOMAIN, composedSessionDrillTypes,
- isTopicEnabled, isMemoryItemEnabled, resolveTopicForDrillType, appliedNumeracyAnswerCorrect,
+ POST_TOPICS, TOPIC_IDS, TOPIC_UI, DOMAINS, DRILL_TO_DOMAIN, composedSessionDrillTypes,
+ appliedNumeracyAnswerCorrect,
effectiveCognitiveDrillConfig,
} from './constants';
@@ -131,6 +131,16 @@ describe('computeGoalProgress (issue #2100)', () => {
});
});
+// TOPIC_UI is client-only (icons/colors have no server meaning), but a topic
+// added to the server registry with no UI row would render unstyled and, for a
+// domain, lose its per-domain time budget.
+describe('TOPIC_UI covers the server topic registry', () => {
+ it('declares an icon row for every topic', () => {
+ expect(Object.keys(TOPIC_UI).sort()).toEqual([...TOPIC_IDS].sort());
+ for (const id of TOPIC_IDS) expect(TOPIC_UI[id].icon, id).toBeTruthy();
+ });
+});
+
// Practice-topic registry (issue #3252). DOMAINS is now DERIVED from POST_TOPICS
// rather than hand-maintained, so these lock in that the derivation reproduces
// exactly what the launcher has always composed from.
@@ -235,35 +245,6 @@ describe('composedSessionDrillTypes (issue #3252)', () => {
});
});
-describe('isTopicEnabled / isMemoryItemEnabled client mirrors', () => {
- it('absent = enabled, so a legacy config runs everything', () => {
- expect(isTopicEnabled({}, 'wordplay')).toBe(true);
- expect(isMemoryItemEnabled({}, 'elements-song')).toBe(true);
- });
-
- it('only an explicit false disables', () => {
- expect(isTopicEnabled({ topics: { wordplay: { enabled: false } } }, 'wordplay')).toBe(false);
- expect(isMemoryItemEnabled({ memory: { items: { 'elements-song': { enabled: false } } } }, 'elements-song')).toBe(false);
- });
-
- it('a disabled memory topic disables every item under it', () => {
- expect(isMemoryItemEnabled({ topics: { memory: { enabled: false } } }, 'raven')).toBe(false);
- });
-});
-
-describe('resolveTopicForDrillType client mirror', () => {
- it('splits the llm-drills module into its three topics', () => {
- expect(resolveTopicForDrillType('bridge-word').id).toBe('wordplay');
- expect(resolveTopicForDrillType('story-recall').id).toBe('verbal');
- expect(resolveTopicForDrillType('reframe').id).toBe('imagination');
- });
-
- it('returns null for an unmapped type', () => {
- expect(resolveTopicForDrillType('nope')).toBeNull();
- });
-});
-
-
// Mirrors the server's progressive override in `resolveDrillConfig`
// (server/services/meatspacePost.js). Anything that DESCRIBES a cognitive drill
// to the user has to resolve through this, or it explains the stored knobs while
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index dacc49322f..fdefe1cde7 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -13,7 +13,8 @@ logic, the client imports the `server/lib` leaf — `export { a, b } from '../..
direction: nothing under `server/` may import from `client/`, because a client-only
dependency added to such a file breaks the server CI job. A server module the client
imports must reach no Node built-in and nothing outside `server/lib`; when the natural
-home does (`storyBible.js` pulls `crypto`), split the pure part into its own leaf.
+home does (`storyBible.js` pulls `crypto`), split the pure part into its own leaf — or,
+when the only impurity is an id, mint it through `uuid.js`, which reads the global WebCrypto.
`scripts/client-server-import-purity.test.js` and `scripts/server-imports-no-client.test.js`
enforce both halves.
@@ -53,7 +54,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `bibleLimits.js` | `BIBLE_LIMITS` re-exported from the pure leaf `server/lib/bibleLimits.js`, plus the client-only `capImageRefs` / `appendImageRefById` for the optimistic imageRefs-append paths. |
| `characterEvolution.js` | The five-stage character evolution lens as the editors consume it. Re-exports `EVOLUTION_STAGES` / `EVOLUTION_OUTCOMES` / `EVOLUTION_STAGE_LABELS` / `EVOLUTION_STAGE_TEXT_FIELDS` / `EVOLUTION_EVIDENCE_FIELDS` / `EVOLUTION_EVIDENCE_STATUSES` / `CHARACTER_EVOLUTION_LIMITS` / `evolutionEvidenceStatus` / `isDeclaredEvolution` from the pure leaf `server/lib/characterEvolution.js` (a guard in `server/lib/characterEvolution.test.js` fails if this file ever restates a vocabulary instead of re-exporting it), adds the editor descriptors `EVOLUTION_STAGE_EDITOR_FIELDS` / `EVOLUTION_OUTCOME_HINTS` (#6440), and the draft-mutation helpers `evolutionStage` / `patchEvolution` / `patchEvolutionStage` / `patchEvolutionEvidence` that keep an editor's draft collapsing to the same shape the server sanitizer produces — so a present-but-empty field is a real clear (#6441). |
| `characterFramework.js` | The narrative-character framework as the editors consume it. Re-exports `CHARACTER_ARC_TYPES` / `CHARACTER_FRAMEWORK_FIELDS` / `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_LIMITS` / `CHARACTER_PSYCHOLOGY_LIMITS` / `CHARACTER_SLIDER_AXES` / `PSYCHOLOGY_ASSESSMENTS` / `PSYCHOLOGY_DRIVE_AXES` / `RELATIONSHIP_LINK_TYPES` from the pure leaf `server/lib/characterFramework.js`, and adds the editor descriptors `CHARACTER_FRAMEWORK_EDITOR_FIELDS` (Ghost → Wound → Lie → Need → Want, with labels/placeholders/caps), `CHARACTER_MOTIVATIONS_FIELD`, `CHARACTER_SECRETS_FIELD`, `CHARACTER_PSYCHOLOGY_EDITOR_FIELDS` / `CHARACTER_PSYCHOLOGY_NOTE_FIELD` / `CHARACTER_PSYCHOLOGY_DRIVE_HINTS` (#6414), and `CHARACTER_SLIDER_MIN` / `CHARACTER_SLIDER_MAX`. Shared by the Universe cast editor and the Writers Room bible so the two never restate the same field copy (#6417). |
-| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — the finding kinds, review statuses and dimension ids mirrored from `server/lib/characterIntegrity.js` (guarded by `characterIntegrity.mirror.test.js`), plus `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy, `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `castIntegrityPassed`, `incompleteCoverage` and `humanizeIntegrityField` (a dotted field path rendered for a reader). |
+| `characterIntegrity.js` | Display half of the cast-integrity contract (#6415) — re-exports the finding kinds, review statuses, depths, dimensions and `castIntegrityPassed` from `server/lib/characterIntegrityVocabulary.js`, plus the client-only `FINDING_KIND_META` / `REVIEW_STATUS_META` / `DEPTH_META` badge copy and `DIMENSION_LABELS` (read off the server's dimension table), `findingIsRepairable` (which gates the Augment button off `contradictory` findings), `incompleteCoverage` and `humanizeIntegrityField` (a dotted field path rendered for a reader). `characterIntegrity.test.js` checks the tables cover every value the server can emit. |
| `catalogTypes.js` | The catalog ingredient type registry as the UI consumes it. `CATALOG_TYPES` is PROJECTED from `server/lib/catalogTypes.js` (label, badge color, primary-content key/label, snippet fallback chain, `editableListFields` and its `BIBLE_LIMITS` caps) and decorated with the client-only editor layout (`editorSections` / `editorFields`); `RELATION_KINDS`, `MEDIA_KINDS`, `canonicalTagKey`, `payloadSnippet`, `USER_TYPE_FIELD_KINDS` are re-exported outright. Also the badge/ref-role lookups and the user-defined-type normalization `useCatalogTypes` merges in. |
| `creativeDirectorPlan.js` | Pure presentation helpers for the CD studio Plan board (CDO Phase 4) — annotate `plan.steps[]` with tool cost-class/timing/approval flags, cost/status summaries, owning-surface deep links, status/cost badge tone maps. |
| `creativeDirectorPreview.js` | `selectProjectPreview(project)` → `{ kind: 'video'\|'image'\|'audio'\|'none', jobId?, src?, poster?, label, durationSec? }` — picks a CD project's representative produced asset (finalVideoId → last rendered scene → last done plan video/image step → `musicBed` audio → startingImageFile) for the list cards + Overview tab (#2702, audio #2772). Pure, computed off the already-returned project payload (no fetch). Plus `previewAspectClass(aspectRatio)` (literal Tailwind classes — a computed `aspect-[w/h]` never lands in the build), `startingImageSrc()` (client mirror of `localImageFilename`), and the `videoSrcForJob`/`videoPosterForJob`/`imageSrcForJob`/`musicBedSrc` path builders — the one client-side definition of the `<jobId>`-named asset convention, shared with `ScenePreview.jsx`. |
diff --git a/client/src/lib/characterIntegrity.js b/client/src/lib/characterIntegrity.js
index 1900e878fd..194cd451f7 100644
--- a/client/src/lib/characterIntegrity.js
+++ b/client/src/lib/characterIntegrity.js
@@ -1,41 +1,32 @@
/**
- * Client-side vocabulary for the shared cast-integrity contract (#6415).
- *
- * Mirrors the display-relevant half of `server/lib/characterIntegrity.js` —
- * the finding kinds, the review statuses, and the five semantic dimensions —
- * plus the labels/tones the report UI renders them with.
- *
- * MIRRORED, not imported: the server module pulls `storyBible.js` (crypto +
- * fileUtils) through `universeBibleCompleteness.js`, which has no place in the
- * browser bundle. `server/lib/characterIntegrity.mirror.test.js` fails when the
- * two lists drift, so this is a checked copy rather than a hopeful one.
+ * Client-side half of the shared cast-integrity contract (#6415): the badge
+ * copy, tones and hints the report renders the server's vocabulary with. The
+ * vocabulary itself — finding kinds, review statuses, depths, dimensions and
+ * `castIntegrityPassed` — is re-exported from the server's pure leaf, not
+ * copied; `characterIntegrity.test.js` checks every value has a row here.
*/
-/** @see INTEGRITY_FINDING_KINDS in server/lib/characterIntegrity.js */
-export const INTEGRITY_FINDING_KINDS = Object.freeze(['missing', 'underspecified', 'contradictory']);
+import {
+ AUGMENTABLE_FINDING_KINDS,
+ CHARACTER_REVIEW_STATUSES,
+ INCOMPLETE_REVIEW_STATUSES,
+ INTEGRITY_DEPTHS,
+ INTEGRITY_DIMENSIONS,
+ INTEGRITY_DIMENSION_IDS,
+ INTEGRITY_FINDING_KINDS,
+ castIntegrityPassed,
+} from '../../../server/lib/characterIntegrityVocabulary.js';
-/** @see AUGMENTABLE_FINDING_KINDS — `contradictory` needs the author, not a model. */
-export const AUGMENTABLE_FINDING_KINDS = Object.freeze(['missing', 'underspecified']);
-
-/** @see CHARACTER_REVIEW_STATUSES */
-export const CHARACTER_REVIEW_STATUSES = Object.freeze([
- 'passed', 'findings', 'not-reviewed', 'truncated', 'stale',
-]);
-
-/** @see INCOMPLETE_REVIEW_STATUSES — none of these license "clean". */
-export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'truncated', 'stale']);
-
-/** @see INTEGRITY_DEPTHS */
-export const INTEGRITY_DEPTHS = Object.freeze(['explained', 'light', 'full']);
-
-/** @see INTEGRITY_DIMENSION_IDS */
-export const INTEGRITY_DIMENSION_IDS = Object.freeze([
- 'control-predicts-behavior',
- 'origin-supports-control',
- 'drives-specific',
- 'relationships-pressure',
- 'challenge-testable',
-]);
+export {
+ AUGMENTABLE_FINDING_KINDS,
+ CHARACTER_REVIEW_STATUSES,
+ INCOMPLETE_REVIEW_STATUSES,
+ INTEGRITY_DEPTHS,
+ INTEGRITY_DIMENSIONS,
+ INTEGRITY_DIMENSION_IDS,
+ INTEGRITY_FINDING_KINDS,
+ castIntegrityPassed,
+};
/**
* How each finding kind reads and what the user can do about it. `tone` maps to
@@ -65,29 +56,15 @@ export const DEPTH_META = Object.freeze({
explained: Object.freeze({ label: 'Explained', hint: 'You ruled the interior unknown or not applicable and said why. That is a finished assessment.' }),
});
-export const DIMENSION_LABELS = Object.freeze({
- 'control-predicts-behavior': 'Belief predicts behavior',
- 'origin-supports-control': 'Origin supports the belief',
- 'drives-specific': 'Drives are specific',
- 'relationships-pressure': 'Relationships create pressure',
- 'challenge-testable': 'Strategy is testable',
-});
+/** Dimension id → label, read off the server's own dimension table. */
+export const DIMENSION_LABELS = Object.freeze(
+ Object.fromEntries(INTEGRITY_DIMENSIONS.map((d) => [d.id, d.label])),
+);
/** Whether a finding can be handed to the augment flow. */
export const findingIsRepairable = (finding) =>
FINDING_KIND_META[finding?.kind]?.repairable === true;
-/**
- * Whether a report may be described as a clean pass — mirrors
- * `castIntegrityPassed`. Any incomplete coverage row disqualifies it, so the UI
- * cannot render a green summary over a half-reviewed cast.
- */
-export const castIntegrityPassed = (report) => {
- const coverage = report?.coverage || [];
- if (coverage.length === 0) return false;
- return coverage.every((c) => c.status === 'passed' && c.semanticReviewed);
-};
-
/** Coverage rows that keep the report from being a clean pass, for the summary line. */
export const incompleteCoverage = (report) =>
(report?.coverage || []).filter((c) => INCOMPLETE_REVIEW_STATUSES.includes(c.status));
diff --git a/client/src/lib/characterIntegrity.test.js b/client/src/lib/characterIntegrity.test.js
new file mode 100644
index 0000000000..0879cf8c3d
--- /dev/null
+++ b/client/src/lib/characterIntegrity.test.js
@@ -0,0 +1,31 @@
+/**
+ * The presentation tables must cover the server's vocabulary exactly: a finding
+ * kind the server can emit but `FINDING_KIND_META` lacks renders as an
+ * unlabeled badge with no repair path, and a status `REVIEW_STATUS_META` lacks
+ * silently falls out of the coverage table. The vocabulary is re-exported from
+ * the server leaf, so only these client-owned tables can drift.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ AUGMENTABLE_FINDING_KINDS,
+ CHARACTER_REVIEW_STATUSES,
+ DEPTH_META,
+ FINDING_KIND_META,
+ INTEGRITY_DEPTHS,
+ INTEGRITY_FINDING_KINDS,
+ REVIEW_STATUS_META,
+ findingIsRepairable,
+} from './characterIntegrity.js';
+
+describe('cast-integrity presentation covers the server vocabulary', () => {
+ it('has badge copy for every finding kind, review status and depth', () => {
+ expect(Object.keys(FINDING_KIND_META).sort()).toEqual([...INTEGRITY_FINDING_KINDS].sort());
+ expect(Object.keys(REVIEW_STATUS_META).sort()).toEqual([...CHARACTER_REVIEW_STATUSES].sort());
+ expect(Object.keys(DEPTH_META).sort()).toEqual([...INTEGRITY_DEPTHS].sort());
+ });
+
+ it('offers the Augment button on exactly the machine-repairable kinds', () => {
+ const repairable = INTEGRITY_FINDING_KINDS.filter((kind) => findingIsRepairable({ kind }));
+ expect(repairable).toEqual([...AUGMENTABLE_FINDING_KINDS]);
+ });
+});
diff --git a/client/src/lib/creativeDirectorPlan.js b/client/src/lib/creativeDirectorPlan.js
index dd092cb4f0..525be21437 100644
--- a/client/src/lib/creativeDirectorPlan.js
+++ b/client/src/lib/creativeDirectorPlan.js
@@ -5,14 +5,9 @@
// 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 directive `goal` cap is the server's own (server/lib/creativeBriefLimits.js),
+// used as the composer's `maxLength`.
+export { CREATIVE_DIRECTOR_GOAL_MAX } from '../../../server/lib/creativeBriefLimits.js';
// 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
diff --git a/client/src/pages/PipelineSeries.evolutionLens.test.jsx b/client/src/pages/PipelineSeries.evolutionLens.test.jsx
index 4f0638a3bf..550758d36e 100644
--- a/client/src/pages/PipelineSeries.evolutionLens.test.jsx
+++ b/client/src/pages/PipelineSeries.evolutionLens.test.jsx
@@ -11,6 +11,9 @@ import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router';
import PipelineSeries from './PipelineSeries';
+import {
+ CHARACTER_ARC_LIMITS, TRANSITION_KINDS, TRANSITION_KIND_LABELS,
+} from '../../../server/lib/seriesCharacterArc.js';
const getPipelineSeries = vi.fn();
const listPipelineIssues = vi.fn();
@@ -89,6 +92,31 @@ describe('Pipeline series — character-arc evolution lens', () => {
listUniverses.mockResolvedValue([universe]);
});
+ it('caps every arc input at the server limits the PATCH route enforces', async () => {
+ getPipelineSeries.mockResolvedValue(seriesWith());
+ renderPage();
+ await screen.findByRole('heading', { name: 'Example Series' });
+
+ // Save re-sends the whole arc list, so an input that loses its cap lets one
+ // over-long field reject every subsequent series save with nothing visible.
+ const cappedAt = {
+ 'Character name': CHARACTER_ARC_LIMITS.CHARACTER_NAME_MAX,
+ Want: CHARACTER_ARC_LIMITS.WANT_MAX,
+ Need: CHARACTER_ARC_LIMITS.NEED_MAX,
+ 'Start state': CHARACTER_ARC_LIMITS.START_STATE_MAX,
+ 'End state': CHARACTER_ARC_LIMITS.END_STATE_MAX,
+ 'Transition label': CHARACTER_ARC_LIMITS.TRANSITION_LABEL_MAX,
+ };
+ for (const [name, max] of Object.entries(cappedAt)) {
+ expect(screen.getByRole('textbox', { name }), name).toHaveAttribute('maxlength', String(max));
+ }
+ expect(screen.getByRole('spinbutton', { name: 'At issue' }))
+ .toHaveAttribute('max', String(CHARACTER_ARC_LIMITS.ISSUE_MAX));
+ const kindPicker = screen.getByRole('combobox', { name: 'Transition kind' });
+ expect([...kindPicker.options].map((o) => [o.value, o.text]))
+ .toEqual(TRANSITION_KINDS.map((kind) => [kind, TRANSITION_KIND_LABELS[kind]]));
+ });
+
it('authors a sparse lens and declares a flat arc without raising a blocking state', async () => {
const user = userEvent.setup();
getPipelineSeries.mockResolvedValue(seriesWith());
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index c184310018..b58cfd6449 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -43,6 +43,7 @@ import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow';
import CharacterEvolutionLens from '../components/character/CharacterEvolutionLens';
import { EVOLUTION_STAGES, isDeclaredEvolution } from '../lib/characterEvolution.js';
+import { CHARACTER_ARC_LIMITS, TRANSITION_KINDS, TRANSITION_KIND_LABELS } from '../../../server/lib/seriesCharacterArc.js';
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
@@ -816,35 +817,6 @@ function VoiceCandidateCard({ candidate, filedAs, onFileExemplar, onFileAntiExem
);
}
-// Per-field caps for the character-arc editor — mirror CHARACTER_ARC_LIMITS in
-// server/lib/seriesCharacterArc.js, which the PATCH route enforces with Zod.
-//
-// These are not cosmetic. `updateSeries` replaces `characterArcs` wholesale, so
-// the Save button sends the entire arc list on every save; one over-long field
-// fails Zod and the server rejects the WHOLE series PATCH — name, logline,
-// premise, style guide and all — not just the offending arc. Without a
-// `maxLength` the field that bricks every subsequent save is invisible in the
-// UI, so cap at the input instead of discovering it in a rejected save.
-const ARC_LIMITS = {
- CHARACTER_NAME_MAX: 200,
- WANT_MAX: 1000,
- NEED_MAX: 1000,
- START_STATE_MAX: 1000,
- END_STATE_MAX: 1000,
- TRANSITION_LABEL_MAX: 200,
- ISSUE_MAX: 9999,
-};
-
-// The change-beat kinds the arc.transitions editorial check recognizes — mirror
-// TRANSITION_KINDS in server/lib/seriesCharacterArc.js.
-const TRANSITION_KIND_OPTIONS = [
- ['decision', 'Decision'],
- ['realization', 'Realization'],
- ['point-of-no-return', 'Point of no return'],
- ['relapse', 'Relapse'],
- ['sacrifice', 'Sacrifice'],
-];
-
// Fact-checking opt-in + author fact reference (#1588). When the series is flagged
// fact-critical AND a non-empty reference is supplied, the gated research.fact-accuracy
// editorial check reconciles the prose against these documented real-world facts.
@@ -896,6 +868,12 @@ function FactReferenceSection({ series, patchSeries }) {
// permissive — a freshly-added blank arc simply doesn't persist until named. The
// arc.transitions editorial check reconciles its detected change moments against
// what's authored here and flags characters with no transition scenes (flat arcs).
+//
+// Every input is capped at the server's CHARACTER_ARC_LIMITS, the table the PATCH
+// route enforces with Zod. Not cosmetic: Save re-sends the whole arc list, so one
+// over-long field rejects the ENTIRE series PATCH — name, logline, premise, style
+// guide and all — and without a `maxLength` the field that bricks every
+// subsequent save is invisible in the UI.
function CharacterArcsSection({ series, universes, patchSeries }) {
const arcs = Array.isArray(series.characterArcs) ? series.characterArcs : [];
// The linked universe's cast, for the read-only psychology baseline beside
@@ -955,7 +933,7 @@ function CharacterArcsSection({ series, universes, patchSeries }) {
value={arc.characterName || ''}
onChange={(e) => setArc(i, { characterName: e.target.value })}
placeholder="Character name"
- maxLength={ARC_LIMITS.CHARACTER_NAME_MAX}
+ maxLength={CHARACTER_ARC_LIMITS.CHARACTER_NAME_MAX}
className={`${inputCls} font-medium`}
/>
<button
@@ -968,10 +946,10 @@ function CharacterArcsSection({ series, universes, patchSeries }) {
</button>
</div>
<div className="grid grid-cols-2 gap-2">
- <input aria-label="Want" value={arc.want || ''} onChange={(e) => setArc(i, { want: e.target.value })} placeholder="Wants (external goal)" maxLength={ARC_LIMITS.WANT_MAX} className={inputCls} />
- <input aria-label="Need" value={arc.need || ''} onChange={(e) => setArc(i, { need: e.target.value })} placeholder="Needs (internal lesson)" maxLength={ARC_LIMITS.NEED_MAX} className={inputCls} />
- <input aria-label="Start state" value={arc.startState || ''} onChange={(e) => setArc(i, { startState: e.target.value })} placeholder="Starts as…" maxLength={ARC_LIMITS.START_STATE_MAX} className={inputCls} />
- <input aria-label="End state" value={arc.endState || ''} onChange={(e) => setArc(i, { endState: e.target.value })} placeholder="Ends as…" maxLength={ARC_LIMITS.END_STATE_MAX} className={inputCls} />
+ <input aria-label="Want" value={arc.want || ''} onChange={(e) => setArc(i, { want: e.target.value })} placeholder="Wants (external goal)" maxLength={CHARACTER_ARC_LIMITS.WANT_MAX} className={inputCls} />
+ <input aria-label="Need" value={arc.need || ''} onChange={(e) => setArc(i, { need: e.target.value })} placeholder="Needs (internal lesson)" maxLength={CHARACTER_ARC_LIMITS.NEED_MAX} className={inputCls} />
+ <input aria-label="Start state" value={arc.startState || ''} onChange={(e) => setArc(i, { startState: e.target.value })} placeholder="Starts as…" maxLength={CHARACTER_ARC_LIMITS.START_STATE_MAX} className={inputCls} />
+ <input aria-label="End state" value={arc.endState || ''} onChange={(e) => setArc(i, { endState: e.target.value })} placeholder="Ends as…" maxLength={CHARACTER_ARC_LIMITS.END_STATE_MAX} className={inputCls} />
</div>
<div className="mt-2">
@@ -994,21 +972,21 @@ function CharacterArcsSection({ series, universes, patchSeries }) {
onChange={(e) => setTransition(i, j, { kind: e.target.value })}
className="px-1.5 py-1 bg-port-bg border border-port-border rounded text-white text-xs shrink-0"
>
- {TRANSITION_KIND_OPTIONS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
+ {TRANSITION_KINDS.map((kind) => <option key={kind} value={kind}>{TRANSITION_KIND_LABELS[kind]}</option>)}
</select>
<input
aria-label="Transition label"
value={t.label || ''}
onChange={(e) => setTransition(i, j, { label: e.target.value })}
placeholder="What changes"
- maxLength={ARC_LIMITS.TRANSITION_LABEL_MAX}
+ maxLength={CHARACTER_ARC_LIMITS.TRANSITION_LABEL_MAX}
className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"
/>
<input
aria-label="At issue"
type="number"
min={0}
- max={ARC_LIMITS.ISSUE_MAX}
+ max={CHARACTER_ARC_LIMITS.ISSUE_MAX}
value={Number.isFinite(t.atIssue) ? t.atIssue : ''}
onChange={(e) => {
const n = parseInt(e.target.value, 10);
@@ -1019,7 +997,7 @@ function CharacterArcsSection({ series, universes, patchSeries }) {
// unclamped 99999 would sail through to the PATCH and
// fail the ISSUE_MAX Zod cap, taking the whole series
// save down with it.
- const clamped = Math.min(Math.max(n, 0), ARC_LIMITS.ISSUE_MAX);
+ const clamped = Math.min(Math.max(n, 0), CHARACTER_ARC_LIMITS.ISSUE_MAX);
setTransition(i, j, { atIssue: Number.isFinite(n) ? clamped : null });
}}
placeholder="#"
diff --git a/server/lib/README.md b/server/lib/README.md
index 4833daa8ea..c43c9142fa 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -77,8 +77,9 @@ 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 Code-Review settings slice, and the task-metadata sanitizer. The Review-Loop reviewer vocabulary lives in `reviewerConfig.js` (#5702) and is re-exported flat from here. |
-| `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`). |
+| `creativeBriefLimits.js` | `COMMISSION_NAME_MAX` / `COMMISSION_INTENT_MAX` / `COMMISSION_STYLE_SPEC_MAX` / `COMMISSION_BRIEF_TAG_MAX` and `CREATIVE_DIRECTOR_GOAL_MAX` — the creative brief caps the two Zod schemas above enforce and the browser forms use as a silent input `maxLength`. A pure leaf (the schemas pull `zod`) so `client/src/components/creative-commission/commissionForm.js` and `client/src/lib/creativeDirectorPlan.js` re-export one definition instead of copying the numbers. |
+| `creativeCommissionValidation.js` | Creative Commission (Autonomous Creation Engine) create/update + brief/schedule/generation schemas. The brief field caps it enforces come from `creativeBriefLimits.js`. |
+| `creativeDirectorValidation.js` | Creative Director project/treatment/scene + Create-Suite importer schemas. The directive `goal` cap it enforces comes from `creativeBriefLimits.js`. |
| `digitalTwinValidation.js` | Digital twin document/category schemas. |
| `eidoverseValidation.js` | Eidoverse world-projection schemas — the `EIDOVERSE_PROJECTION_SOURCE_KEYS` allowlist, the V1/V2 projection recipe union (includes/assets/terrain/scale/districts/environment, with the `..`-escape guard on every asset path), and the world augment/say/config-patch route bodies (incl. the 8KB augment-argument cap). Split out of `validation.js` (#5698), which re-exports it. |
| `fableLoomValidation.js` | FableLoom branching-narrative route schemas (loom/episode/node/transition CRUD, weave/branch/review, play turns). |
@@ -115,7 +116,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `characterEvolutionCoverage.js` | Branch coverage for the evolution lens (#6444): `analyzeCharacterEvolutionCoverage` walks every bounded playthrough and flags `EVOLUTION_UNEARNED_INHERITANCE` — a stage proved on one incoming branch of a reconvergence and not another, so a viewer inherits a change they never watched be earned — plus unproven declared endings, out-of-sequence stage anchors and dead evidence pointers (`EVOLUTION_COVERAGE_CODES`). Introduces `unreviewed` (`EVOLUTION_COVERAGE_STATUSES`): a bounded-out enumeration, a cycle or an unresolvable anchor is explicitly NOT `verified` and NOT a defect. Deterministic and provider-free; returns `null` when no lens is authored, so a loom that never opted in is byte-identical. |
| `characterEvolutionValidation.js` | Zod schemas for the evolution lens — `characterEvolutionSchema` (one lens), `characterEvolutionStageSchema`, `characterEvolutionEvidenceSchema` and `characterEvolutionListSchema` (the FableLoom plan's per-character list). Its own module rather than a `sharedSchemas.js` fragment so `validation.js` (which nearly every suite reaches) doesn't grow an eager edge for a shape only two hosts validate. |
| `characterFramework.js` | The narrative-character framework as one definition: `CHARACTER_ARC_TYPES`, `CHARACTER_FRAMEWORK_TEXT_FIELDS` / `CHARACTER_FRAMEWORK_FIELDS` (the Ghost→Wound→Lie→Need→Want chain plus motivations, arc type, secrets, relationship links, the psychology profile and the Three Sliders), `CHARACTER_FRAMEWORK_LIMITS`, the psychology/slider/link vocabularies re-exported by `storyBible.js` (`PSYCHOLOGY_DRIVE_AXES`, `PSYCHOLOGY_ASSESSMENTS`, `CHARACTER_PSYCHOLOGY_TEXT_FIELDS`, `CHARACTER_PSYCHOLOGY_LIMITS`, `CHARACTER_SLIDER_AXES`, `RELATIONSHIP_LINK_TYPES`), and `pickCharacterFramework` / `pickCastFramework` (framework-only projection for an author-side review prompt, empty entries dropped). A pure leaf over `bibleLimits.js` so the store editableFields, the Zod schemas, and the client editors share one list (#6417). |
-| `characterIntegrity.js` | The shared cast-integrity contract (#6415): `INTEGRITY_FINDING_KINDS` (`missing` / `underspecified` / `contradictory`), the five `INTEGRITY_DIMENSIONS`, `CHARACTER_REVIEW_STATUSES` (`passed` vs `not-reviewed` / `truncated` / `stale` — incomplete coverage can never read as clean), `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` / `staleReportCharacterIds` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
+| `characterIntegrityVocabulary.js` | The vocabulary the cast-integrity contract (#6415) reports in, as a pure leaf: `INTEGRITY_FINDING_KINDS` (`missing` / `underspecified` / `contradictory`) and the machine-repairable `AUGMENTABLE_FINDING_KINDS`, the five `INTEGRITY_DIMENSIONS` (+ `INTEGRITY_DIMENSION_IDS`), `CHARACTER_REVIEW_STATUSES` (`passed` vs `not-reviewed` / `truncated` / `stale`) and the `INCOMPLETE_REVIEW_STATUSES` that can never read as clean, `INTEGRITY_DEPTHS`, and `castIntegrityPassed(report)`. Split out of `characterIntegrity.js` (which reaches `crypto` through `storyBible.js`) so `client/src/lib/characterIntegrity.js` re-exports one definition for the report UI. |
+| `characterIntegrity.js` | The shared cast-integrity contract (#6415), stated in `characterIntegrityVocabulary.js`'s terms: `characterIntegrityDepth` (minor roles / flat arcs / an explained `unknown` psychology get lighter requirements), the no-provider `characterCompletenessFindings` / `buildCastIntegrityReport`, the validating `mergeSemanticFindings`, and `characterFingerprint` / `staleReportCharacterIds` (reports are derived, never persisted — the fingerprint is what makes a stale one detectable). |
| `castIntegrityPrompt.js` | The prompt-facing render of a `characterIntegrity.js` report (#6415): `renderCastIntegrity` (gap rows first, header always kept, so a budget-truncated block can never read as a clean cast) and `INTEGRITY_DEPTH_NOTES` (the `explained` / `light` / `full` rulings in the reviewer's own words). Shared by the Series foundation judge and the FableLoom whole-series editor so the two cannot drift on what a `light` character owes. |
| `bibleLimits.js` | `BIBLE_LIMITS` — the canon field length/count caps every story-bible sanitizer, Zod schema, and catalog payload upgrade measures against. A pure leaf split out of `storyBible.js` (which pulls `crypto` + `fileUtils`) so `catalogTypes.js` and the browser bundle can read the numbers alone. |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
@@ -130,7 +132,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `shotGrammar.js` | Pure shot-grammar vocabularies (`SHOT_TYPES`, `SCREEN_DIRECTIONS`) + normalizers (`normalizeShotType`, `normalizeScreenDirection`) for a storyboard shot's camera framing + on-screen direction. Shared by the scene extractor's sanitizer, the storyboards Zod schema, and the `visual.shot-continuity` editorial check (#1315). |
| `storyboardScenes.js` | Durable ids + id-first addressing for `stages.storyboards.scenes[]` (#3413). `ensureStoryboardIds(scenes)` stamps a deterministic `scene-NN` / `shot-NN` id on any entry lacking one — and re-stamps later copies of a DUPLICATE id (collision-escaped with a `-2` suffix, so peers and concurrent readers derive identical ids); `resolveStoryboardTarget(list, { id, index })` → `{ index, record, matchedBy, stale }` resolves a captured id against a fresh array, falling back to the index only when no id was captured, and reporting `stale: true` (409, never an index retarget) when a captured id is gone. |
| `seasonStructure.js` | Season/episode structure recommendation. |
-| `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check, `characterArcEvidenceRefs` (the transition-id set a lens anchor resolves against), and `renderCharacterEvolutionsForPrompt` — the cast-level render of `characterEvolution.js`'s five-stage lens the character-arc checks and the arc planner share. |
+| `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. `CHARACTER_ARC_LIMITS` / `TRANSITION_KINDS` + `TRANSITION_KIND_LABELS` / `CHARACTER_ARC_STATUSES` (a pure leaf — the arc editor in `PipelineSeries.jsx` imports the caps, kinds and labels, so no Node built-in here; ids come from `uuid.js`). Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check, `characterArcEvidenceRefs` (the transition-id set a lens anchor resolves against), and `renderCharacterEvolutionsForPrompt` — the cast-level render of `characterEvolution.js`'s five-stage lens the character-arc checks and the arc planner share. |
| `llmRoutePin.js` | The per-record LLM route pin `{ providerId, model, effort }` — `LLM_ROUTE_PIN_LIMITS` + `llmRoutePinSchema` (door check, `effort` as the shared `EFFORT_LEVELS` enum), `sanitizeLlmRoutePin(raw)` (trim/cap, `null` for an all-empty pin), and `resolveLlmRoutePin(pin, perCall)` → `{ providerId, model, effort, providerMatchesPin }`. Owns the never-cross-providers rule once, in its two shapes: `resolveLlmRoutePin` merges a record pin with an independent per-call pick per FIELD (guarded by a provider-id comparison), while `pickLlmRoutePinLayer(...layers)` + `llmRoutePinNamesProvider(layer)` take the most specific layer WHOLE for pins whose provider and model were chosen together in one control (falling through to the base layer). Consumed by `seriesLlmOverride.js`, FableLoom's play pin, and the Creative Director stage pins. |
| `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |
| `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |
@@ -463,7 +465,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `postProgression.js` | Generic mastery-gated progression ladder (extracted from `postMultiplicationLadder.js`) — `createProgression({ levels, describeLevel, speedTargetForLevel? })` resolves a user's current rung from exact-level sample, accuracy, completion, and optional speed evidence with an anti-demotion floor. Also defines meaningful cognitive-drill ladders (including task switching, Go/No-Go, and Flanker) and their level→generator-config mapping. |
| `spacedRepetition.js` | The shared SM-2-inspired review scheduler, extracted from `services/meatspacePostMemory.js` when SongBook practice became its second consumer (#4102). One four-field schedule shape (`{ ease, intervalDays, nextReview, lastReviewed }`, no `repetitions` counter — the 0 → 1 → 6 → `round(prev * ease)` ladder derives from the previous interval, so a schedule round-trips through import/export/federation on those four fields alone). `advanceSchedule(schedule, ratio, now)` is the core (ease clamped to `MIN_EASE`..`MAX_EASE`, interval capped at `MAX_INTERVAL_DAYS` so `new Date(now + interval*DAY)` can't overflow into an Invalid Date; quality < 3 zeroes the interval to resurface the record but still applies the ease penalty). `mergeScheduleAdvance(prev, advanced, now)` gates interval GROWTH to once per review day (a shrink always applies) for UIs that submit per chunk/section; `isSameReviewDay` is that gate's own predicate, reusable by callers gating their own once-a-day progression. `scheduleOrDefault(record, schedule?)` is the read-path fallback — a record with no schedule derives one anchored to its `updatedAt`/`createdAt` (stable and in the past → due now), so "due" can't flap between two reads a millisecond apart. `ratioToQuality` / `qualityToRatio` are exact inverses over the integers, so a self-graded 0..5 review lands on the quality the user picked. `isScheduleDue` treats an absent/unparseable `nextReview` as due — a record we can't schedule is one to surface, never one to hide forever. Pure. |
| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. |
-| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |
+| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. A pure leaf: the client's post `constants.js` re-exports it and layers the UI-only `TOPIC_UI` on top. |
| `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `shuffleForDay` supplies a stable pseudorandom daily mix; `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day so a tier never pins to one drill. Mirrored at `client/src/lib/postRotation.js`. |
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry), `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp), and `recordDayKey` / `withDerivedDayKeys` (re-derive a record's day key from its `startedAt`/`completedAt`/`timestamp` instant, so readers ignore a `date` frozen in a previously-configured timezone). |
| `activeDays.js` | Cross-domain "days active" set math (#4120) — `unionActiveDayKeys(sources, timezone)` unions several domains' stored date values into one sorted array of user-local `YYYY-MM-DD` keys (`.length` is the honest day count; summing per-domain counts would double-count any day logged in two domains), and `toUserDayKey(value, timezone)` is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps `userLocalToday()`) and the health logs (stamp the server-local `getDateString()`): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than `split('T')[0]`'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure. |
@@ -563,7 +565,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `untrustedContent.js` | Shared source policies, strict settings schema, data framing and API-only/local-private provider eligibility for untrusted GitHub and messaging content. |
| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |
| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594 / #5596): `USER_ACTION_TYPES` (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. |
-| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
+| `uuid.js` | `v4()` thin wrapper over the global `crypto.randomUUID()` — import-free, so a leaf the browser imports can mint ids through it without a Node built-in. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
| `eidoverseProxyRoutes.js` | Allowlist + path helpers for the same-origin Eidoverse reverse-proxy on `:5555` (`/eidoverse-host` prefix strip and root routes like `/ws` / `/version` while the host is active). Shared by `services/eidoverseProxy.js` so the main server and the optional `:5563` bridge stay in sync with eidoverse-worlds `server/routes.ts`. |
@@ -576,7 +578,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
|---|---|
| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. |
| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). `resetGitSandbox({ scratch, repo, initialHead })` / `resetGitWorktreeSandbox(repo, initialHead)` restore a sandbox in place (branches, worktrees, remote) so a `describe` can build one sandbox in `beforeAll` and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. |
-| `mirrorParity.js` | Source-comparison primitives for the remaining `*.mirror.test.js` parity tests — the copies that are NOT pure `server/lib` leaves (component constants, service tables), since a shared pure module is imported rather than mirrored: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |
+| `mirrorParity.js` | Source-extraction and comparison primitives for declaration-level contract tests: the vendored `aiToolkit/` copy of `TOOL_USE_RE` (`localModelHeuristics.mirror.test.js`), the client cadence table `autonomousJobIntervals.test.js` pins, and the bootstrap sequence's body assertions (`bootstrap*.test.js`). A pure module the browser needs is imported by the client rather than mirrored, so no client↔server copy test should need these: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |
| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |
| `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. |
| `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. |
diff --git a/server/lib/characterIntegrity.js b/server/lib/characterIntegrity.js
index c8c93b984f..84b100de23 100644
--- a/server/lib/characterIntegrity.js
+++ b/server/lib/characterIntegrity.js
@@ -19,6 +19,11 @@
* universe/series/work concepts — the callers own those, which is what lets
* Universe Bible, Series, FableLoom and Writers Room share one contract.
*
+ * The vocabulary itself — finding kinds, review statuses, depths, the five
+ * semantic dimensions and `castIntegrityPassed` — lives in
+ * `characterIntegrityVocabulary.js`, a browser-safe leaf the report UI imports
+ * directly; this module reaches Node built-ins through `storyBible.js`.
+ *
* Reports are DERIVED, never persisted, so `characterFingerprint` is what keeps
* a repair honest: a proposal carries the fingerprint of the character it was
* reviewed against, and applying it to a record that has since changed is
@@ -33,77 +38,11 @@ import {
characterPsychologyIsBlank,
} from './universeBibleCompleteness.js';
import { PSYCHOLOGY_DRIVE_AXES, isBlank } from './storyBible.js';
+import { INTEGRITY_DIMENSION_IDS, INTEGRITY_FINDING_KINDS } from './characterIntegrityVocabulary.js';
-/**
- * What KIND of gap a finding reports. The three are genuinely different repairs
- * and must not collapse into one "incomplete" bucket:
- * - `missing` — the field is blank. Fill-blanks can close it.
- * Deterministic; no model required.
- * - `underspecified` — populated, but too generic to predict behavior
- * ("wants to be happy"). Augmentation can close it.
- * - `contradictory` — populated and specific, but at odds with another
- * authored field. NOBODY can close it automatically; it needs the author,
- * because the report cannot know which of the two fields is the wrong one.
- */
-export const INTEGRITY_FINDING_KINDS = Object.freeze(['missing', 'underspecified', 'contradictory']);
const FINDING_KIND_SET = new Set(INTEGRITY_FINDING_KINDS);
-
-/** Only `missing` and `underspecified` are machine-repairable — see above. */
-export const AUGMENTABLE_FINDING_KINDS = Object.freeze(['missing', 'underspecified']);
-
-/**
- * The five questions the semantic review asks. Stated as checks on the
- * AUTHORED material, not as demands for a particular kind of character: each
- * one can be satisfied by a deliberately flat, opaque or minor character, and
- * "no finding" is the expected result for most of a cast.
- */
-export const INTEGRITY_DIMENSIONS = Object.freeze([
- Object.freeze({
- id: 'control-predicts-behavior',
- label: 'Belief predicts behavior',
- question: 'Does the stated control belief actually predict the behavior the profile describes?',
- }),
- Object.freeze({
- id: 'origin-supports-control',
- label: 'Origin supports the belief',
- question: 'Does the Ghost/Wound history make this belief a plausible thing for this character to have concluded?',
- }),
- Object.freeze({
- id: 'drives-specific',
- label: 'Drives are specific',
- question: 'Are the survival, connection and status desires/fears distinct and specific to this character, rather than one sentiment restated three times?',
- }),
- Object.freeze({
- id: 'relationships-pressure',
- label: 'Relationships create pressure',
- question: 'Do the authored relationships put meaningful pressure on the belief, rather than only describing who knows whom?',
- }),
- Object.freeze({
- id: 'challenge-testable',
- label: 'Strategy is testable',
- question: 'Can a plausible story challenge test this strategy — is there something that would actually cost this character to hold onto it?',
- }),
-]);
-export const INTEGRITY_DIMENSION_IDS = Object.freeze(INTEGRITY_DIMENSIONS.map((d) => d.id));
const DIMENSION_ID_SET = new Set(INTEGRITY_DIMENSION_IDS);
-/**
- * Per-character coverage. The whole point of the enum is that `passed` and
- * `not-reviewed` are NOT the same answer — a review that quietly skipped half
- * the cast and reported no findings would read as a clean bill of health.
- * - `passed` — reviewed, nothing found
- * - `findings` — reviewed, at least one finding
- * - `not-reviewed` — outside the requested scope, or the pass never reached it
- * - `truncated` — the review ran but its budget cut this character off
- * - `stale` — the character changed after the report was measured
- */
-export const CHARACTER_REVIEW_STATUSES = Object.freeze([
- 'passed', 'findings', 'not-reviewed', 'truncated', 'stale',
-]);
-
-/** Statuses that do NOT license "this cast is clean". */
-export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'truncated', 'stale']);
-
/**
* The framework fields the deterministic pass measures, in report order.
* Sourced from `characterFramework.js` plus the psychology profile so a field
@@ -117,23 +56,6 @@ export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'trunca
*/
export const INTEGRITY_FIELDS = Object.freeze([...CHARACTER_FRAMEWORK_TEXT_FIELDS, 'psychology']);
-/**
- * How much of the framework a character is expected to carry.
- *
- * The issue is explicit that minor roles, flat arcs, unknowns and deliberate
- * ambiguity get "lighter or explained requirements, not manufactured trauma or
- * mandatory redemption" — so the depth is COMPUTED from what the author already
- * declared rather than demanded uniformly:
- *
- * - `explained` — the author ruled the interior out (`psychology.assessment`
- * of `unknown` / `not-applicable`) AND said why. That is a finished
- * assessment; the pass asks for nothing further.
- * - `light` — a declared minor role, or a flat arc. Wants the conscious
- * pursuit (motivations/want) and nothing about origin damage.
- * - `full` — everything else.
- */
-export const INTEGRITY_DEPTHS = Object.freeze(['explained', 'light', 'full']);
-
/** Fields each depth actually asks for. `explained` asks for none. */
const DEPTH_FIELDS = Object.freeze({
explained: Object.freeze([]),
@@ -444,17 +366,6 @@ export function mergeSemanticFindings(report, {
};
}
-/**
- * Whether a report licenses "this cast has been reviewed and is clean".
- * False whenever ANY character is `not-reviewed` / `truncated` / `stale` —
- * incomplete coverage cannot pass.
- */
-export const castIntegrityPassed = (report) => {
- const coverage = report?.coverage || [];
- if (coverage.length === 0) return false;
- return coverage.every((c) => c.status === 'passed' && c.semanticReviewed);
-};
-
/**
* The field paths the augment flow may propose a value for: every integrity
* path that holds a plain STRING.
diff --git a/server/lib/characterIntegrity.mirror.test.js b/server/lib/characterIntegrity.mirror.test.js
deleted file mode 100644
index 9bbbd80a1d..0000000000
--- a/server/lib/characterIntegrity.mirror.test.js
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Parity guard: the client's integrity vocabulary must match the server's.
- *
- * `client/src/lib/characterIntegrity.js` cannot import the server module — it
- * reaches `storyBible.js` (crypto + fileUtils) through
- * `universeBibleCompleteness.js`, which has no place in the browser bundle — so
- * the two lists are mirrored by hand. A drift here is not cosmetic: the client
- * decides which findings offer an Augment button from its OWN kind list, so a
- * kind the server can emit but the client doesn't know renders as an unlabeled
- * badge with no repair path, and a status the client doesn't know silently
- * falls out of the "is this cast clean?" check.
- *
- * Reads the client file as TEXT rather than importing it: this suite runs in
- * the server (node) project, which has no React/JSX resolution.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { join, dirname } from 'path';
-import { fileURLToPath } from 'url';
-
-import {
- INTEGRITY_FINDING_KINDS,
- AUGMENTABLE_FINDING_KINDS,
- CHARACTER_REVIEW_STATUSES,
- INCOMPLETE_REVIEW_STATUSES,
- INTEGRITY_DEPTHS,
- INTEGRITY_DIMENSION_IDS,
-} from './characterIntegrity.js';
-
-const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
-const CLIENT_LIB = join(REPO_ROOT, 'client', 'src', 'lib', 'characterIntegrity.js');
-
-const source = readFileSync(CLIENT_LIB, 'utf8');
-
-/** Pull `export const NAME = Object.freeze([...])` string members out of the client source. */
-const mirroredList = (name) => {
- const match = source.match(new RegExp(`export const ${name} = Object\\.freeze\\(\\[([^\\]]*)\\]`));
- if (!match) throw new Error(`client characterIntegrity.js has no ${name} array`);
- return [...match[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
-};
-
-/** Pull the keys of `export const NAME = Object.freeze({ key: ... })`. */
-const mirroredKeys = (name) => {
- const start = source.indexOf(`export const ${name} = Object.freeze({`);
- if (start < 0) throw new Error(`client characterIntegrity.js has no ${name} object`);
- const body = source.slice(start, source.indexOf('\n});', start));
- return [...body.matchAll(/^ {2}'?([a-zA-Z][\w-]*)'?:/gm)].map((m) => m[1]);
-};
-
-describe('characterIntegrity client mirror', () => {
- it.each([
- ['INTEGRITY_FINDING_KINDS', INTEGRITY_FINDING_KINDS],
- ['AUGMENTABLE_FINDING_KINDS', AUGMENTABLE_FINDING_KINDS],
- ['CHARACTER_REVIEW_STATUSES', CHARACTER_REVIEW_STATUSES],
- ['INCOMPLETE_REVIEW_STATUSES', INCOMPLETE_REVIEW_STATUSES],
- ['INTEGRITY_DEPTHS', INTEGRITY_DEPTHS],
- ['INTEGRITY_DIMENSION_IDS', INTEGRITY_DIMENSION_IDS],
- ])('%s matches the server list exactly, in order', (name, expected) => {
- expect(mirroredList(name)).toEqual([...expected]);
- });
-
- it('has badge copy for every finding kind, review status and depth', () => {
- expect(mirroredKeys('FINDING_KIND_META').sort()).toEqual([...INTEGRITY_FINDING_KINDS].sort());
- expect(mirroredKeys('REVIEW_STATUS_META').sort()).toEqual([...CHARACTER_REVIEW_STATUSES].sort());
- expect(mirroredKeys('DEPTH_META').sort()).toEqual([...INTEGRITY_DEPTHS].sort());
- });
-
- it('labels every dimension the server can attribute a finding to', () => {
- expect(mirroredKeys('DIMENSION_LABELS').sort()).toEqual([...INTEGRITY_DIMENSION_IDS].sort());
- });
-
- it('marks exactly the augmentable kinds as repairable', () => {
- const repairable = [...INTEGRITY_FINDING_KINDS].filter((kind) => {
- const row = source.match(new RegExp(`\\b${kind}: Object\\.freeze\\(\\{[^}]*\\}\\)`));
- return row ? /repairable: true/.test(row[0]) : false;
- });
- expect(repairable).toEqual([...AUGMENTABLE_FINDING_KINDS]);
- });
-});
diff --git a/server/lib/characterIntegrity.test.js b/server/lib/characterIntegrity.test.js
index 5bd58f9942..6f5092c5ed 100644
--- a/server/lib/characterIntegrity.test.js
+++ b/server/lib/characterIntegrity.test.js
@@ -8,7 +8,6 @@ import { describe, it, expect } from 'vitest';
import {
buildCastIntegrityReport,
- castIntegrityPassed,
characterCompletenessFindings,
characterFingerprint,
characterIntegrityDepth,
@@ -17,6 +16,7 @@ import {
readIntegrityField,
withIntegrityField,
} from './characterIntegrity.js';
+import { castIntegrityPassed } from './characterIntegrityVocabulary.js';
/** A fully authored lead — nothing for the deterministic pass to report. */
const lead = () => ({
diff --git a/server/lib/characterIntegrityVocabulary.js b/server/lib/characterIntegrityVocabulary.js
new file mode 100644
index 0000000000..69adab9093
--- /dev/null
+++ b/server/lib/characterIntegrityVocabulary.js
@@ -0,0 +1,110 @@
+/**
+ * The cast-integrity vocabulary (#6415): the finding kinds, review statuses,
+ * depths and semantic dimensions a report is stated in, plus the one predicate
+ * that reads a whole report (`castIntegrityPassed`).
+ *
+ * A pure leaf on purpose. `characterIntegrity.js` (the passes and the merge)
+ * reaches `storyBible.js` (crypto + fileUtils) through
+ * `universeBibleCompleteness.js`, which has no place in the browser bundle —
+ * yet the report UI decides which findings offer an Augment button, which
+ * statuses keep a cast from reading as clean and how a dimension is labelled
+ * from these same lists. Keeping them here lets both runtimes import ONE
+ * definition (`client/src/lib/characterIntegrity.js` re-exports this module).
+ * Import no Node built-in here.
+ */
+
+/**
+ * What KIND of gap a finding reports. The three are genuinely different repairs
+ * and must not collapse into one "incomplete" bucket:
+ * - `missing` — the field is blank. Fill-blanks can close it.
+ * Deterministic; no model required.
+ * - `underspecified` — populated, but too generic to predict behavior
+ * ("wants to be happy"). Augmentation can close it.
+ * - `contradictory` — populated and specific, but at odds with another
+ * authored field. NOBODY can close it automatically; it needs the author,
+ * because the report cannot know which of the two fields is the wrong one.
+ */
+export const INTEGRITY_FINDING_KINDS = Object.freeze(['missing', 'underspecified', 'contradictory']);
+
+/** Only `missing` and `underspecified` are machine-repairable — see above. */
+export const AUGMENTABLE_FINDING_KINDS = Object.freeze(['missing', 'underspecified']);
+
+/**
+ * The five questions the semantic review asks. Stated as checks on the
+ * AUTHORED material, not as demands for a particular kind of character: each
+ * one can be satisfied by a deliberately flat, opaque or minor character, and
+ * "no finding" is the expected result for most of a cast.
+ */
+export const INTEGRITY_DIMENSIONS = Object.freeze([
+ Object.freeze({
+ id: 'control-predicts-behavior',
+ label: 'Belief predicts behavior',
+ question: 'Does the stated control belief actually predict the behavior the profile describes?',
+ }),
+ Object.freeze({
+ id: 'origin-supports-control',
+ label: 'Origin supports the belief',
+ question: 'Does the Ghost/Wound history make this belief a plausible thing for this character to have concluded?',
+ }),
+ Object.freeze({
+ id: 'drives-specific',
+ label: 'Drives are specific',
+ question: 'Are the survival, connection and status desires/fears distinct and specific to this character, rather than one sentiment restated three times?',
+ }),
+ Object.freeze({
+ id: 'relationships-pressure',
+ label: 'Relationships create pressure',
+ question: 'Do the authored relationships put meaningful pressure on the belief, rather than only describing who knows whom?',
+ }),
+ Object.freeze({
+ id: 'challenge-testable',
+ label: 'Strategy is testable',
+ question: 'Can a plausible story challenge test this strategy — is there something that would actually cost this character to hold onto it?',
+ }),
+]);
+export const INTEGRITY_DIMENSION_IDS = Object.freeze(INTEGRITY_DIMENSIONS.map((d) => d.id));
+
+/**
+ * Per-character coverage. The whole point of the enum is that `passed` and
+ * `not-reviewed` are NOT the same answer — a review that quietly skipped half
+ * the cast and reported no findings would read as a clean bill of health.
+ * - `passed` — reviewed, nothing found
+ * - `findings` — reviewed, at least one finding
+ * - `not-reviewed` — outside the requested scope, or the pass never reached it
+ * - `truncated` — the review ran but its budget cut this character off
+ * - `stale` — the character changed after the report was measured
+ */
+export const CHARACTER_REVIEW_STATUSES = Object.freeze([
+ 'passed', 'findings', 'not-reviewed', 'truncated', 'stale',
+]);
+
+/** Statuses that do NOT license "this cast is clean". */
+export const INCOMPLETE_REVIEW_STATUSES = Object.freeze(['not-reviewed', 'truncated', 'stale']);
+
+/**
+ * How much of the framework a character is expected to carry.
+ *
+ * The issue is explicit that minor roles, flat arcs, unknowns and deliberate
+ * ambiguity get "lighter or explained requirements, not manufactured trauma or
+ * mandatory redemption" — so the depth is COMPUTED from what the author already
+ * declared rather than demanded uniformly:
+ *
+ * - `explained` — the author ruled the interior out (`psychology.assessment`
+ * of `unknown` / `not-applicable`) AND said why. That is a finished
+ * assessment; the pass asks for nothing further.
+ * - `light` — a declared minor role, or a flat arc. Wants the conscious
+ * pursuit (motivations/want) and nothing about origin damage.
+ * - `full` — everything else.
+ */
+export const INTEGRITY_DEPTHS = Object.freeze(['explained', 'light', 'full']);
+
+/**
+ * Whether a report licenses "this cast has been reviewed and is clean".
+ * False whenever ANY character is `not-reviewed` / `truncated` / `stale` —
+ * incomplete coverage cannot pass.
+ */
+export const castIntegrityPassed = (report) => {
+ const coverage = report?.coverage || [];
+ if (coverage.length === 0) return false;
+ return coverage.every((c) => c.status === 'passed' && c.semanticReviewed);
+};
diff --git a/server/lib/creativeBriefLimits.js b/server/lib/creativeBriefLimits.js
new file mode 100644
index 0000000000..6ed5cdae3c
--- /dev/null
+++ b/server/lib/creativeBriefLimits.js
@@ -0,0 +1,34 @@
+/**
+ * The caps on creative brief text: the commission brief fields, and the
+ * Creative Director directive `goal` a commission's brief is composed into.
+ *
+ * A pure leaf on purpose. The Zod schemas that enforce these
+ * (`creativeCommissionValidation.js`, `creativeDirectorValidation.js`) pull
+ * `zod`, which the browser bundle is not handed — while the commission form and
+ * the directive composer use the same numbers as an input `maxLength`, a SILENT
+ * limit. A client cap below the schema's truncates a pasted brief at the
+ * textarea with no error to explain where the tail went; one above it turns the
+ * paste into a 400 at save time. Both sides import this one definition
+ * (`client/src/components/creative-commission/commissionForm.js`,
+ * `client/src/lib/creativeDirectorPlan.js`), so neither can drift. Import no
+ * Node built-in here.
+ */
+
+export const COMMISSION_NAME_MAX = 200;
+// 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;
+
+// Kept clear of the commission scheduler's MAX_DIRECTIVE_GOAL_LEN (derived from
+// the commission caps above plus the scheduler's own framing), 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 leaf can't import the service to derive it.
+export const CREATIVE_DIRECTOR_GOAL_MAX = 32000;
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index 1b0fc4f7fc..870d0d6d1b 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -2,6 +2,9 @@ import { z } from 'zod';
import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
import { RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
import { recurrenceRuleSchema } from './recurrenceValidation.js';
+import {
+ COMMISSION_BRIEF_TAG_MAX, COMMISSION_INTENT_MAX, COMMISSION_NAME_MAX, COMMISSION_STYLE_SPEC_MAX,
+} from './creativeBriefLimits.js';
// =============================================================================
// CREATIVE COMMISSION SCHEMAS (Autonomous Creation Engine — #2657, Phase 1)
@@ -76,8 +79,9 @@ export const COMMISSION_RENDER_MODEL_MAX = 64;
// defaults (`ABILITY_GENERATION_SPEC`), and the ability adapter's data-driven
// `sanitizeGeneration`. Keeping the bounds here (not re-typed in the schema AND
// the adapter AND the client) is what stops the four-way drift. The client
-// (commissionForm.js) mirrors these values in its own package — kept in sync by
-// hand; there is no cross-package import.
+// (commissionForm.js) still mirrors these values by hand: this module pulls
+// `zod`, so the browser can import them only once they move to a pure leaf,
+// the way the brief caps did (`creativeBriefLimits.js`).
// `type: 'id'` is a nullable free-string model id: absent/blank normalizes to
// `null` (= "the install's default model"), which is why its `default` is null
// rather than a string. Distinct from the `enum`/`int` numeric-or-member kinds so
@@ -149,17 +153,6 @@ function generationFieldSchema(def) {
return z.number().int().min(def.min).max(def.max).optional();
}
-export const COMMISSION_NAME_MAX = 200;
-// 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;
diff --git a/server/lib/creativeCommissionValidation.mirror.test.js b/server/lib/creativeCommissionValidation.mirror.test.js
deleted file mode 100644
index 1f7a3ae1ad..0000000000
--- a/server/lib/creativeCommissionValidation.mirror.test.js
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * 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.js
index f3527670d0..85bf17f9d9 100644
--- a/server/lib/creativeDirectorValidation.js
+++ b/server/lib/creativeDirectorValidation.js
@@ -4,6 +4,7 @@ import { ARC_SHAPE_IDS, ARC_ROLES } from './storyArc.js';
import { BIBLE_LIMITS } from './storyBible.js';
import { emptyToUndefined } from './zodCompat.js';
import { csvIdsParam } from './sharedSchemas.js';
+import { CREATIVE_DIRECTOR_GOAL_MAX } from './creativeBriefLimits.js';
// =============================================================================
// CREATIVE DIRECTOR + CREATE-SUITE IMPORTER SCHEMAS
@@ -51,12 +52,6 @@ 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
diff --git a/server/lib/creativeDirectorValidation.mirror.test.js b/server/lib/creativeDirectorValidation.mirror.test.js
deleted file mode 100644
index b1bea3d1f7..0000000000
--- a/server/lib/creativeDirectorValidation.mirror.test.js
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * 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/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 49b81f6b09..af1b29300d 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -239,7 +239,16 @@ describe('deferred imports stay deferred (#6156)', () => {
// loaded via the host mount at boot. Measured 95,246 on this branch (+46 over
// the prior ceiling) — ordinary growth for an intentional main-server edge,
// not an eager heavy subtree. Raise the ceiling to keep the ~1.5k allowance.
-const MAX_STATIC_INSTANTIATIONS = 95300;
+//
+// Replacing five client hand-copies of server constants (the component and page
+// mirrors the earlier sweeps left) with imports added two pure leaves the
+// browser bundle reads: `lib/characterIntegrityVocabulary.js`
+// (split out of `characterIntegrity.js`, which reaches `crypto`) and
+// `lib/creativeBriefLimits.js` (the caps both creative validation modules
+// enforce). Measured 95,414 (+168): each leaf is reached by every suite that
+// crosses its parent or the lib barrel, with nothing behind it to defer — the
+// tolerated leaf shape, not an eager edge. Restore the ~1.5k allowance.
+const MAX_STATIC_INSTANTIATIONS = 96900;
const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);
const serverTestFiles = (dir = SERVER_DIR, out = []) => {
diff --git a/server/lib/index.js b/server/lib/index.js
index 1bf29ac659..3e2932daff 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -33,6 +33,8 @@ export * as cosValidation from './cosValidation.js';
export * from './cosToolContracts.js';
export * as creativeCommissionValidation from './creativeCommissionValidation.js';
export * as creativeDirectorValidation from './creativeDirectorValidation.js';
+// The brief/goal caps both schemas above and the browser forms share, as a pure leaf.
+export * from './creativeBriefLimits.js';
export * as digitalTwinValidation from './digitalTwinValidation.js';
export * as eidoverseValidation from './eidoverseValidation.js';
export * as fableLoomValidation from './fableLoomValidation.js';
@@ -123,6 +125,8 @@ export * from './characterEvolutionCoverage.js';
// the namespaced storyBible below.
export * from './characterFramework.js';
export * from './characterIntegrity.js';
+// The cast-integrity vocabulary characterIntegrity.js reports in, as a pure leaf.
+export * from './characterIntegrityVocabulary.js';
export * from './castIntegrityPrompt.js';
// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for
// back-compat — namespace it so the canonical scenePrompt export wins flat.
diff --git a/server/lib/postTopics.js b/server/lib/postTopics.js
index abfd4c71c2..a35c6f65f1 100644
--- a/server/lib/postTopics.js
+++ b/server/lib/postTopics.js
@@ -21,10 +21,10 @@
* offered by the session picker (see the client's
* `POST_UNSUPPORTED_DRILL_TYPES`).
*
- * Mirrored to the client in `client/src/components/meatspace/post/constants.js`
- * (`POST_TOPICS`), where the UI-only fields — icon, color, time budget — are
- * layered on. `server/lib/postTopics.mirror.test.js` asserts the two lists match,
- * the same mirroring convention `canonPrompt.js` and `MEMORY_DRILL_TYPES` use.
+ * A pure leaf: `client/src/components/meatspace/post/constants.js` re-exports
+ * the registry and the enablement predicates, and layers the UI-only fields —
+ * icon, color, time budget — on top in its `TOPIC_UI`. Import no Node built-in
+ * here.
*
* Enablement convention — **absent = enabled**, matching the existing per-drill
* `drillTypes` convention: only an explicit `false` disables. That is what keeps
diff --git a/server/lib/postTopics.mirror.test.js b/server/lib/postTopics.mirror.test.js
deleted file mode 100644
index ae3c2f6887..0000000000
--- a/server/lib/postTopics.mirror.test.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Mirror parity test for server/lib/postTopics.js ↔ the client's POST topic
- * mirror in client/src/components/meatspace/post/constants.js (issue #3252).
- *
- * The registry is server-owned; the client mirrors the plain data so the
- * launcher, Practice Plan, and config UI can gate without a round-trip. If the
- * two drift, a topic the server filters on would be invisible to the UI (or
- * vice versa) — hence a hard parity assert rather than a convention.
- *
- * Mirrored: the POST_TOPICS literal and the two enablement predicates that the
- * client re-implements verbatim. NOT mirrored: `resolveTopicForDrillType`, which
- * the server backs with a prebuilt lookup map (built once at module load) while
- * the client does a linear find over a 7-entry list — same contract, different
- * implementation, so it's asserted behaviorally in postTopics.test.js instead.
- *
- * Comparison strips comments and normalizes whitespace (see lib/mirrorParity.js),
- * so JSDoc divergence is allowed and only code differences fail.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { resolve, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { compareDeclaration } from './mirrorParity.js';
-import { POST_TOPICS } from './postTopics.js';
-
-const __dirname = dirname(fileURLToPath(import.meta.url));
-
-const SERVER_PATH = resolve(__dirname, 'postTopics.js');
-const CLIENT_PATH = resolve(__dirname, '../../client/src/components/meatspace/post/constants.js');
-
-const MIRRORED_NAMES = ['POST_TOPICS', 'isTopicEnabled', 'isMemoryPracticeEnabled', 'isMemoryItemEnabled'];
-
-describe('postTopics server↔client mirror parity', () => {
- const serverSrc = readFileSync(SERVER_PATH, 'utf8');
- const clientSrc = readFileSync(CLIENT_PATH, 'utf8');
-
- it('both files are non-empty', () => {
- expect(serverSrc.length).toBeGreaterThan(100);
- expect(clientSrc.length).toBeGreaterThan(100);
- });
-
- for (const name of MIRRORED_NAMES) {
- it(`${name} is present and identical on both sides (code only)`, () => {
- const { serverDecl, clientDecl, serverNorm, clientNorm } =
- compareDeclaration(serverSrc, clientSrc, name);
-
- expect(serverDecl, `server/lib/postTopics.js is missing declaration: ${name}`).not.toBeNull();
- expect(clientDecl, `client post constants.js is missing declaration: ${name}`).not.toBeNull();
- expect(clientNorm, `"${name}" code diverged between server and client`).toBe(serverNorm);
- });
- }
-
- it('the client declares presentation for every topic', () => {
- // TOPIC_UI is client-only (icons/colors have no server meaning), but a
- // topic added server-side with no UI row would render unstyled and,
- // for a domain, lose its per-domain time budget.
- for (const topic of POST_TOPICS) {
- expect(clientSrc, `TOPIC_UI is missing a row for topic "${topic.id}"`)
- .toMatch(new RegExp(`^\\s*${topic.id}:\\s*\\{\\s*icon:`, 'm'));
- }
- });
-});
diff --git a/server/lib/seriesCharacterArc.js b/server/lib/seriesCharacterArc.js
index 98f566d44b..2fff0bbf56 100644
--- a/server/lib/seriesCharacterArc.js
+++ b/server/lib/seriesCharacterArc.js
@@ -30,10 +30,17 @@
*
* Used by `services/pipeline/series.js` (sanitize on load/save) and the
* `arc.transitions` editorial check in `lib/editorial/checkRegistry.js`.
+ *
+ * A pure leaf: the browser bundle imports `CHARACTER_ARC_LIMITS`,
+ * `TRANSITION_KINDS` and `TRANSITION_KIND_LABELS` from here (the arc editor in
+ * `PipelineSeries.jsx` caps its inputs at the numbers the PATCH route enforces),
+ * so this module must reach no Node built-in — ids come from `uuid.js`, which
+ * reads the global WebCrypto — and `scripts/client-server-import-purity.test.js`
+ * walks its import graph.
*/
-import { randomUUID } from 'crypto';
import { BIBLE_LIMITS } from './bibleLimits.js';
+import { v4 as randomUUID } from './uuid.js';
import {
characterIdentityKey,
isCanonCharacterId,
@@ -76,6 +83,17 @@ export const TRANSITION_KINDS = Object.freeze([
'sacrifice',
]);
+// How each kind reads in the arc editor's picker — beside the ids it labels, the
+// way `characterEvolution.js` keeps `EVOLUTION_STAGE_LABELS`; the test pins one
+// label per kind so a new kind cannot reach the picker unlabeled.
+export const TRANSITION_KIND_LABELS = Object.freeze({
+ decision: 'Decision',
+ realization: 'Realization',
+ 'point-of-no-return': 'Point of no return',
+ relapse: 'Relapse',
+ sacrifice: 'Sacrifice',
+});
+
const TRANSITION_ID_PREFIX = 'trn-';
// The canon id shapes, the issue clamp and the identity key are shared with the
diff --git a/server/lib/seriesCharacterArc.mirror.test.js b/server/lib/seriesCharacterArc.mirror.test.js
deleted file mode 100644
index dd8fbe2db4..0000000000
--- a/server/lib/seriesCharacterArc.mirror.test.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Parity guard: the character-arc editor's client-side input caps must match
- * the server's CHARACTER_ARC_LIMITS.
- *
- * `PipelineSeries.jsx` hard-codes an `ARC_LIMITS` object it feeds to the arc
- * inputs' `maxLength` / `max`. It can't import the server constant (browser
- * bundle), so the two are mirrored — and a mirror that drifts is worse than no
- * mirror here, because of how the write path fails: `updateSeries` replaces
- * `characterArcs` wholesale, so Save re-sends the entire arc list every time. A
- * single field over its Zod cap rejects the WHOLE series PATCH — name, logline,
- * premise, style guide and all — so a client cap that is larger than the
- * server's lets the user type a value that silently bricks every subsequent
- * save of the page.
- *
- * Reads the client file as TEXT rather than importing it: this suite runs in
- * the server (node) project, which has no React/lucide-react resolution.
- */
-
-import { describe, it, expect } from 'vitest';
-import { readFileSync } from 'fs';
-import { join, dirname } from 'path';
-import { fileURLToPath } from 'url';
-import { CHARACTER_ARC_LIMITS } from './seriesCharacterArc.js';
-
-const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
-const CLIENT_PAGE = join(REPO_ROOT, 'client', 'src', 'pages', 'PipelineSeries.jsx');
-
-// The keys the editor actually renders an input for. A server limit with no
-// input (e.g. TRANSITIONS_PER_ARC_MAX, enforced by the sanitizer dropping
-// extras) is deliberately absent from the client mirror.
-const MIRRORED_KEYS = [
- 'CHARACTER_NAME_MAX',
- 'WANT_MAX',
- 'NEED_MAX',
- 'START_STATE_MAX',
- 'END_STATE_MAX',
- 'TRANSITION_LABEL_MAX',
- 'ISSUE_MAX',
-];
-
-function clientArcLimits() {
- const src = readFileSync(CLIENT_PAGE, 'utf8');
- const block = src.match(/const ARC_LIMITS = \{([\s\S]*?)\};/);
- if (!block) return null;
- const out = {};
- for (const [, key, value] of block[1].matchAll(/(\w+):\s*(\d+)\s*,/g)) {
- out[key] = Number(value);
- }
- return out;
-}
-
-describe('PipelineSeries ARC_LIMITS ↔ server CHARACTER_ARC_LIMITS', () => {
- it('declares an ARC_LIMITS mirror in the client page', () => {
- expect(clientArcLimits()).not.toBeNull();
- });
-
- it('mirrors every cap the arc editor renders an input for', () => {
- const client = clientArcLimits();
- expect(Object.keys(client).sort()).toEqual([...MIRRORED_KEYS].sort());
- });
-
- it.each(MIRRORED_KEYS)('%s matches the server cap', (key) => {
- expect(clientArcLimits()[key]).toBe(CHARACTER_ARC_LIMITS[key]);
- });
-
- it('caps every arc input the editor renders', () => {
- const src = readFileSync(CLIENT_PAGE, 'utf8');
- // Each arc field's input must carry a maxLength (or max, for atIssue) drawn
- // from the mirror — not a bare uncapped input.
- for (const key of MIRRORED_KEYS) {
- expect(src).toContain(`ARC_LIMITS.${key}`);
- }
- });
-});
diff --git a/server/lib/seriesCharacterArc.test.js b/server/lib/seriesCharacterArc.test.js
index e663b1a9a1..de71ca8922 100644
--- a/server/lib/seriesCharacterArc.test.js
+++ b/server/lib/seriesCharacterArc.test.js
@@ -8,6 +8,7 @@ import {
renderCharacterEvolutionsForPrompt,
CHARACTER_ARC_LIMITS,
TRANSITION_KINDS,
+ TRANSITION_KIND_LABELS,
} from './seriesCharacterArc.js';
import { evolutionEvidenceStatus } from './characterEvolution.js';
@@ -40,9 +41,10 @@ describe('sanitizeTransition', () => {
expect(sanitizeTransition({ kind: 'decision', label: 'x', atIssue: 'foo' }).atIssue).toBeNull();
});
- it('exposes the full kind taxonomy', () => {
+ it('exposes the full kind taxonomy, each kind labelled for the editor picker', () => {
expect(TRANSITION_KINDS).toContain('point-of-no-return');
expect(TRANSITION_KINDS).toContain('sacrifice');
+ expect(Object.keys(TRANSITION_KIND_LABELS)).toEqual([...TRANSITION_KINDS]);
});
// The arc auto-resolve path writes through this sanitizer directly (the route
diff --git a/server/services/creativeCommissions/abilityAdapters.test.js b/server/services/creativeCommissions/abilityAdapters.test.js
index 613db66359..5cc5b40d53 100644
--- a/server/services/creativeCommissions/abilityAdapters.test.js
+++ b/server/services/creativeCommissions/abilityAdapters.test.js
@@ -2,10 +2,10 @@ 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';
+} from '../../lib/creativeBriefLimits.js';
import { MAX_DIRECTIVE_GOAL_LEN } from './directive.js';
import { buildVideoPromptGuidance, isMiniMaxVideoModel } from './videoPromptGuidance.js';
diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.js
index d73741610e..44d1813725 100644
--- a/server/services/creativeCommissions/directive.js
+++ b/server/services/creativeCommissions/directive.js
@@ -15,7 +15,7 @@
import {
COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,
-} from '../../lib/creativeCommissionValidation.js';
+} from '../../lib/creativeBriefLimits.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
diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.js
index a2f567aa1a..c35ef05739 100644
--- a/server/services/creativeCommissions/directive.test.js
+++ b/server/services/creativeCommissions/directive.test.js
@@ -3,7 +3,7 @@ import {
commissionToCron, commissionToRecurrence, renderFeedbackDigest, composeDirectiveGoal,
MAX_DIRECTIVE_GOAL_LEN, MAX_SYSTEM_PREFIX_LEN,
} from './directive.js';
-import { CREATIVE_DIRECTOR_GOAL_MAX } from '../../lib/creativeDirectorValidation.js';
+import { CREATIVE_DIRECTOR_GOAL_MAX } from '../../lib/creativeBriefLimits.js';
import {
renderMusicTasteRecipePrompt,
MUSIC_TASTE_RECIPE_MAX_CONTEXT, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION,
diff --git a/server/services/universeCastIntegrity.js b/server/services/universeCastIntegrity.js
index 4ccd7fd262..f31fe8dba5 100644
--- a/server/services/universeCastIntegrity.js
+++ b/server/services/universeCastIntegrity.js
@@ -40,11 +40,11 @@ import {
staleAugmentError,
} from './characterAugmentation.js';
import {
- INTEGRITY_DIMENSIONS,
buildCastIntegrityReport,
characterFingerprint,
mergeSemanticFindings,
} from '../lib/characterIntegrity.js';
+import { INTEGRITY_DIMENSIONS } from '../lib/characterIntegrityVocabulary.js';
const REVIEW_STAGE = 'universe-cast-integrity-review';
diff --git a/server/services/writersRoom/syncedReview.js b/server/services/writersRoom/syncedReview.js
index 9aff17dd5c..198497fc44 100644
--- a/server/services/writersRoom/syncedReview.js
+++ b/server/services/writersRoom/syncedReview.js
@@ -25,7 +25,8 @@
* exactly these cross-references.
*/
-import { buildCastIntegrityReport, castIntegrityPassed } from '../../lib/characterIntegrity.js';
+import { buildCastIntegrityReport } from '../../lib/characterIntegrity.js';
+import { castIntegrityPassed } from '../../lib/characterIntegrityVocabulary.js';
import { normalizeBibleName } from '../../lib/storyBible.js';
import { getWorkWithBody } from './local.js';
import { getAnalysis } from './evaluator.js';