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

give the string predicates one owner in textUtils and delete the 73 private copies (#6837)

[._.]/ Adam Eivyf297d0195196
diff --git a/client/src/components/songs/RoundReadView.jsx b/client/src/components/songs/RoundReadView.jsx
index 495c88dd8b..72330f0a4f 100644
--- a/client/src/components/songs/RoundReadView.jsx
+++ b/client/src/components/songs/RoundReadView.jsx
@@ -8,6 +8,7 @@ import RoundStack from './RoundStack';
import SongRecordings from './SongRecordings';
import SongTraining from './SongTraining';
import { rhythmShapeLabel } from '../../lib/songCraft';
+import { isNonBlankStr } from '../../lib/textUtils';
// --- Read-only performance view -------------------------------------------
// Renders the song for reading / playing / recording: lyrics shown in full
@@ -18,7 +19,6 @@ export default function RoundReadView({ song, setField, onRefreshTemplate, refre
const sections = song.sections || [];
const layers = song.layers || [];
const references = song.references || [];
- const hasText = (v) => typeof v === 'string' && v.trim().length > 0;
const feel = song.rhythmShapeId ? rhythmShapeLabel(song.rhythmShapeId) : '';
// Only actually swap to the stacked view when there are partners to stack —
// otherwise `?stack=1` with no partners would hide the single-song view and
@@ -38,8 +38,8 @@ export default function RoundReadView({ song, setField, onRefreshTemplate, refre
{song.builtIn && <RoundBuiltInBanner onRefresh={onRefreshTemplate} refreshing={refreshing} />}
{/* Compact meta line — no form fields, just the at-a-glance facts. */}
<div className="flex flex-wrap items-center gap-2">
- {hasText(song.artist) && metaBadge('Artist', song.artist)}
- {hasText(song.key) && metaBadge('Key', song.key)}
+ {isNonBlankStr(song.artist) && metaBadge('Artist', song.artist)}
+ {isNonBlankStr(song.key) && metaBadge('Key', song.key)}
{song.tempo != null && metaBadge('Tempo', `${song.tempo} BPM`)}
{feel && metaBadge('Feel', feel)}
<Pill tone={song.learned ? 'success' : 'muted'} icon={song.learned ? CheckCircle2 : Circle}>
@@ -116,7 +116,7 @@ export default function RoundReadView({ song, setField, onRefreshTemplate, refre
{sections.map((s) => (
<div key={s.id} className="bg-port-card border border-port-border rounded-lg p-4">
<h3 className="text-xs font-semibold uppercase tracking-wide text-port-accent mb-2">{s.label || 'Section'}</h3>
- {hasText(s.lyrics)
+ {isNonBlankStr(s.lyrics)
? <p className="text-sm text-gray-100 whitespace-pre-wrap leading-relaxed">{s.lyrics}</p>
: <p className="text-xs text-gray-600 italic">No lyrics</p>}
</div>
@@ -127,7 +127,7 @@ export default function RoundReadView({ song, setField, onRefreshTemplate, refre
{/* Side rail — notation, layers, and notes. */}
<aside className="space-y-6">
- {hasText(song.notation) && (
+ {isNonBlankStr(song.notation) && (
<section>
<h2 className="text-sm font-semibold text-white mb-2">Notation / chords</h2>
<p className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-100 whitespace-pre-wrap leading-relaxed font-mono">{song.notation}</p>
@@ -144,16 +144,16 @@ export default function RoundReadView({ song, setField, onRefreshTemplate, refre
<li key={l.id} className="bg-port-card border border-port-border rounded-lg p-3">
<div className="flex items-baseline justify-between gap-2">
<span className="text-sm text-white">{l.label || 'Layer'}</span>
- {hasText(l.part) && <span className="text-xs text-gray-500">{l.part}</span>}
+ {isNonBlankStr(l.part) && <span className="text-xs text-gray-500">{l.part}</span>}
</div>
- {hasText(l.notes) && <p className="mt-1 text-xs text-gray-400 whitespace-pre-wrap leading-relaxed">{l.notes}</p>}
+ {isNonBlankStr(l.notes) && <p className="mt-1 text-xs text-gray-400 whitespace-pre-wrap leading-relaxed">{l.notes}</p>}
</li>
))}
</ul>
</section>
)}
- {hasText(song.notes) && (
+ {isNonBlankStr(song.notes) && (
<section>
<h2 className="text-sm font-semibold text-white mb-2">Arrangement & notes</h2>
<p className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-200 whitespace-pre-wrap leading-relaxed">{song.notes}</p>
diff --git a/client/src/components/songs/RoundStack.jsx b/client/src/components/songs/RoundStack.jsx
index a81f84cde6..a145b7bfc0 100644
--- a/client/src/components/songs/RoundStack.jsx
+++ b/client/src/components/songs/RoundStack.jsx
@@ -21,8 +21,7 @@ import { scoreHasMusic } from '../../lib/scoreNotation';
import { createLayeredPlayer } from '../../lib/songPlayback';
import { getUploadUrl } from '../../services/api';
import { rhythmShapeLabel } from '../../lib/songCraft';
-
-const hasText = (v) => typeof v === 'string' && v.trim().length > 0;
+import { isNonBlankStr } from '../../lib/textUtils';
export default function RoundStack({ songs = [] }) {
const [playing, setPlaying] = useState(false);
@@ -133,7 +132,7 @@ export default function RoundStack({ songs = [] }) {
)}
</h3>
<span className="text-xs text-gray-500">
- {[hasText(s.key) && s.key, feel].filter(Boolean).join(' · ')}
+ {[isNonBlankStr(s.key) && s.key, feel].filter(Boolean).join(' · ')}
</span>
</div>
@@ -148,7 +147,7 @@ export default function RoundStack({ songs = [] }) {
{sections.map((sec) => (
<div key={sec.id}>
<h4 className="text-xs font-semibold uppercase tracking-wide text-port-accent mb-1">{sec.label || 'Section'}</h4>
- {hasText(sec.lyrics)
+ {isNonBlankStr(sec.lyrics)
? <p className="text-sm text-gray-100 whitespace-pre-wrap leading-relaxed">{sec.lyrics}</p>
: <p className="text-xs text-gray-600 italic">No lyrics</p>}
</div>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 5a3958b882..e69e96f470 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -232,7 +232,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. |
| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
-| `textUtils.js` | `escapeRegExp(value)` and `countWords(text)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. |
+| `textUtils.js` | `escapeRegExp(value)`, `countWords(text)`, `isStr(v)` and `isNonBlankStr(v)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. |
| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |
| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |
diff --git a/client/src/lib/fableLoomReadiness.js b/client/src/lib/fableLoomReadiness.js
index 5ba63f67e0..19f04aca87 100644
--- a/client/src/lib/fableLoomReadiness.js
+++ b/client/src/lib/fableLoomReadiness.js
@@ -7,8 +7,8 @@
* The server remains authoritative for expansion and batch preflight.
*/
+import { isNonBlankStr } from './textUtils';
const asArray = (value) => (Array.isArray(value) ? value : []);
-const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
const reachableNodes = (episode) => {
const nodes = asArray(episode?.nodes);
@@ -38,12 +38,12 @@ const playableChallenge = (item) => item?.kind === 'challenge'
const nodeHasMotionDelivery = (node) => {
const assets = node?.playbackAssets || {};
- const hasEntry = hasText(node?.videoHistoryId) || hasText(assets.entryVideoHistoryId);
+ const hasEntry = isNonBlankStr(node?.videoHistoryId) || isNonBlankStr(assets.entryVideoHistoryId);
if (!hasEntry) return false;
if (node?.playbackMode !== 'decision' || node?.isEnding) return true;
const exits = assets.exitByTransition || {};
return asArray(assets.holdLoopVideoHistoryIds).length > 0
- && asArray(node.transitions).every((transition) => hasText(exits[transition.id]));
+ && asArray(node.transitions).every((transition) => isNonBlankStr(exits[transition.id]));
};
const deliveryHandoffsReady = (loom) => {
@@ -55,11 +55,11 @@ const deliveryHandoffsReady = (loom) => {
[`${item?.fromEpisodeId}::${item?.toEpisodeId}`, item]
)));
const missing = episodes.slice(0, -1).some((episode, index) => (
- !hasText(messages.get(`${episode.id}::${episodes[index + 1]?.id}`)?.transcript)
+ !isNonBlankStr(messages.get(`${episode.id}::${episodes[index + 1]?.id}`)?.transcript)
));
if (missing) return false;
}
- return options.nextSeasonTeaser !== true || hasText(plan.nextSeasonTeaser?.transcript);
+ return options.nextSeasonTeaser !== true || isNonBlankStr(plan.nextSeasonTeaser?.transcript);
};
export function fableLoomEpisodeOrderReadiness(loom, episode) {
@@ -69,7 +69,7 @@ export function fableLoomEpisodeOrderReadiness(loom, episode) {
return { ready: false, reason: 'The selected episode is not present in the ordered loom.' };
}
for (const [index, priorEpisode] of episodes.slice(0, currentIndex).entries()) {
- const missing = reachableNodes(priorEpisode).filter((node) => !hasText(node.image));
+ const missing = reachableNodes(priorEpisode).filter((node) => !isNonBlankStr(node.image));
if (missing.length) {
const priorNumber = priorEpisode.number || index + 1;
const currentNumber = episode.number || currentIndex + 1;
@@ -110,7 +110,7 @@ export function fableLoomStoryReadiness(loom) {
const from = episodes[index];
const to = episodes[index + 1];
const voicemail = voicemails.get(`${from.id}::${to.id}`);
- if (!hasText(voicemail?.transcript)) {
+ if (!isNonBlankStr(voicemail?.transcript)) {
return {
ready: false,
reason: `Author the overnight voicemail from Episode ${from.number || index + 1} to Episode ${to.number || index + 2} before generating media.`,
@@ -120,7 +120,7 @@ export function fableLoomStoryReadiness(loom) {
}
if (deliveryOptions.nextSeasonTeaser === true
- && !hasText(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
+ && !isNonBlankStr(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
return { ready: false, reason: 'Author the finale next-season teaser before generating media.' };
}
@@ -161,9 +161,9 @@ export function fableLoomProductionWorkflow(loom, episode, {
const structureReady = teleplaysReady && episodes.length > 0
&& structurePassedCount === episodes.length;
const planReady = challenges.length > 0 && plotPoints.every((item) => (
- hasText(item?.title) && hasText(item?.description) && hasText(item?.episodeId)
+ isNonBlankStr(item?.title) && isNonBlankStr(item?.description) && isNonBlankStr(item?.episodeId)
));
- const imagesReady = reachable.length > 0 && reachable.every((node) => hasText(node?.image));
+ const imagesReady = reachable.length > 0 && reachable.every((node) => isNonBlankStr(node?.image));
const motionReady = reachable.length > 0 && reachable.every(nodeHasMotionDelivery)
&& structural?.productionReadiness?.ready !== false;
const handoffsReady = deliveryHandoffsReady(loom);
@@ -173,19 +173,19 @@ export function fableLoomProductionWorkflow(loom, episode, {
const continuityReviewedCount = continuityResults.filter(Boolean).length;
const continuityPassedCount = continuityResults.filter((result) => result?.passed === true).length;
const continuityReady = episodes.length > 0 && continuityPassedCount === episodes.length;
- const editorialIsCurrent = hasText(loom?.productionStatus?.editorialApprovedAt)
+ const editorialIsCurrent = isNonBlankStr(loom?.productionStatus?.editorialApprovedAt)
|| editorialRun?.status === 'completed';
- const deliveryApproved = hasText(loom?.productionStatus?.deliveryApprovedAt);
+ const deliveryApproved = isNonBlankStr(loom?.productionStatus?.deliveryApprovedAt);
const stages = [
{
id: 'foundation', label: 'Story foundation', action: 'settings',
- complete: hasText(loom?.name) && (hasText(loom?.premise) || hasText(loom?.logline)),
+ complete: isNonBlankStr(loom?.name) && (isNonBlankStr(loom?.premise) || isNonBlankStr(loom?.logline)),
detail: 'Lock the format, premise, protagonist, and audience participation mode.',
},
{
id: 'series-arc', label: 'Series arc', action: 'series-arc',
- complete: hasText(loom?.seriesPlan?.storyArc),
+ complete: isNonBlankStr(loom?.seriesPlan?.storyArc),
detail: 'Define the beginning-to-end dramatic movement before expanding episodes.',
},
{
@@ -236,7 +236,7 @@ export function fableLoomProductionWorkflow(loom, episode, {
{
id: 'storyboards', label: 'Storyboard images', action: 'render',
complete: imagesReady,
- detail: `${reachable.filter((node) => hasText(node?.image)).length}/${reachable.length} reachable scenes have storyboard images.`,
+ detail: `${reachable.filter((node) => isNonBlankStr(node?.image)).length}/${reachable.length} reachable scenes have storyboard images.`,
},
{
id: 'motion', label: 'Motion & live voice assets', action: 'render',
diff --git a/client/src/lib/textUtils.js b/client/src/lib/textUtils.js
index 48ab9b7e3e..5ac74e62cb 100644
--- a/client/src/lib/textUtils.js
+++ b/client/src/lib/textUtils.js
@@ -1,12 +1,14 @@
/**
* Pure prose helpers, from the module that owns them on both sides.
*
- * `escapeRegExp` and `countWords` are named re-exports of
- * `server/lib/textUtils.js` — imported rather than copied so the two runtimes
- * cannot drift: the word count the Writers Room and autobiography editors show
- * beside a draft is the same `\S+` rule the server stores for it. Named rather
+ * `escapeRegExp`, `countWords`, `isStr` and `isNonBlankStr` are named
+ * re-exports of `server/lib/textUtils.js` — imported rather than copied so the
+ * two runtimes cannot drift: the word count the Writers Room and autobiography
+ * editors show beside a draft is the same `\S+` rule the server stores for it,
+ * and the "has text" check the Songs views and FableLoom readiness use is the
+ * same non-blank predicate the server's sanitizers apply (#6837). Named rather
* than `export *` so this file stays the list of what the browser bundle has a
* caller for; the file itself stays so every `lib/textUtils` import path in the
* client is unchanged.
*/
-export { countWords, escapeRegExp } from '../../../server/lib/textUtils.js';
+export { countWords, escapeRegExp, isStr, isNonBlankStr } from '../../../server/lib/textUtils.js';
diff --git a/client/src/lib/universeBuilderCounts.js b/client/src/lib/universeBuilderCounts.js
index 8eca30ecd9..3e3f7f6817 100644
--- a/client/src/lib/universeBuilderCounts.js
+++ b/client/src/lib/universeBuilderCounts.js
@@ -1,5 +1,6 @@
import { hasCanonDescriptorContent } from './canonPrompt.js';
import { getCategoryKeys } from './universeBuilderShared.js';
+import { isNonBlankStr } from './textUtils';
// Pure prompt-count helpers for the Universe Builder (#2374). They mirror the
// server's compile/skip rules so inline "Render N images" buttons can advertise
@@ -14,19 +15,17 @@ export function totalVariationCount(world) {
);
}
-const hasNonBlankString = (v) => typeof v === 'string' && v.trim().length > 0;
-
// Mirror the server's synthesizeCanonPrompt skip rule: entries with no
// identity-anchor (name / slugline / prompt) AND no descriptive content for the
// kind compile to an empty seed and get skipped at render time.
export const canonEntryHasContent = (e, kind) => {
if (!e) return false;
- if (hasNonBlankString(e.prompt)) return true;
+ if (isNonBlankStr(e.prompt)) return true;
// Identifier anchors per kind — places allow slugline-only entries (bible
// sanitizer); characters/objects ignore stray slugline. Mirrors server
// synthesizeCanonPrompt's identifier-seed rule.
- if (hasNonBlankString(e.name)) return true;
- if (kind === 'places' && hasNonBlankString(e.slugline)) return true;
+ if (isNonBlankStr(e.name)) return true;
+ if (kind === 'places' && isNonBlankStr(e.slugline)) return true;
return hasCanonDescriptorContent(kind, e);
};
diff --git a/server/lib/README.md b/server/lib/README.md
index e41527f4e4..b2bd6158a1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -480,7 +480,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
-| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels); `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
+| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels); `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). |
| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
| `pipelineStages.js` | Canonical pipeline data-stage groups, visible tab order, UI/voice labels, spoken aliases, and derived voice-intent regex. |
| `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. |
diff --git a/server/lib/browserConfig.js b/server/lib/browserConfig.js
index 749bedd060..dd8da283c4 100644
--- a/server/lib/browserConfig.js
+++ b/server/lib/browserConfig.js
@@ -1,9 +1,7 @@
-export function isNonEmptyString(value) {
- return typeof value === 'string' && value.trim().length > 0;
-}
+import { isNonBlankStr } from './textUtils.js';
export function deriveMacAppBundleFromChromePath(chromePath) {
- if (!isNonEmptyString(chromePath)) return null;
+ if (!isNonBlankStr(chromePath)) return null;
const normalized = chromePath.trim().replaceAll('\\', '/');
const appMarker = '.app/';
const appIndex = normalized.toLowerCase().indexOf(appMarker);
@@ -12,12 +10,12 @@ export function deriveMacAppBundleFromChromePath(chromePath) {
}
export function hasConfiguredBrowser(config) {
- return isNonEmptyString(config?.chromePath) || isNonEmptyString(config?.macAppBundle);
+ return isNonBlankStr(config?.chromePath) || isNonBlankStr(config?.macAppBundle);
}
export function normalizeBrowserConfig(config) {
const next = { ...(config || {}) };
- if (!isNonEmptyString(next.macAppBundle)) {
+ if (!isNonBlankStr(next.macAppBundle)) {
const derived = deriveMacAppBundleFromChromePath(next.chromePath);
if (derived) next.macAppBundle = derived;
}
@@ -25,12 +23,12 @@ export function normalizeBrowserConfig(config) {
}
export function isMacAppBundlePath(value) {
- if (!isNonEmptyString(value)) return false;
+ if (!isNonBlankStr(value)) return false;
return /(^|[/\\])[^/\\]+\.app[/\\]?$/i.test(value.trim());
}
export function validateChromePath(value) {
- if (!isNonEmptyString(value)) return null;
+ if (!isNonBlankStr(value)) return null;
const trimmed = value.trim();
if (/[\\/]$/.test(trimmed)) return 'chromePath must point to an executable file, not a directory';
if (isMacAppBundlePath(trimmed)) {
@@ -43,7 +41,7 @@ export function validateChromePath(value) {
}
export function validateMacAppBundle(value) {
- if (!isNonEmptyString(value)) return null;
+ if (!isNonBlankStr(value)) return null;
if (!isMacAppBundlePath(value)) return 'macAppBundle must point to a macOS .app bundle';
return null;
}
diff --git a/server/lib/characterEvolution.js b/server/lib/characterEvolution.js
index cbcecf492a..33db838a7f 100644
--- a/server/lib/characterEvolution.js
+++ b/server/lib/characterEvolution.js
@@ -39,7 +39,7 @@
*/
import { BIBLE_LIMITS } from './bibleLimits.js';
-import { trimTo, trimToClause } from './textUtils.js';
+import { trimTo, trimToClause, isStr } from './textUtils.js';
// Storr's sequence as #6418 restates it, in order: the control strategy is
// visibly failing; an event forces exploration of another way; the character
@@ -127,8 +127,6 @@ const EPISODE_ID_RE = /^ep-[a-zA-Z0-9-]+$/;
// the Writers Room host pairs it with `anchorQuote` below.
const SEGMENT_ID_RE = /^seg-\d+$/;
-const isStr = (v) => typeof v === 'string';
-
/** True for a canon cast pointer (`chr-<uuid>`). */
export const isCanonCharacterId = (raw) => isStr(raw) && CHARACTER_ID_RE.test(raw);
diff --git a/server/lib/characterEvolutionCoverage.js b/server/lib/characterEvolutionCoverage.js
index 674c0b0ca3..d95d0af292 100644
--- a/server/lib/characterEvolutionCoverage.js
+++ b/server/lib/characterEvolutionCoverage.js
@@ -46,9 +46,9 @@
import { EVOLUTION_STAGES, EVOLUTION_STAGE_LABELS, isDeclaredEvolution } from './characterEvolution.js';
import { computeTopologicalNodeOrder } from './fableLoomProduction.js';
import { enumerateEpisodePlaythroughs } from './fableLoomPlaytest.js';
+import { isNonBlankStr } from './textUtils.js';
const asArray = (value) => (Array.isArray(value) ? value : []);
-const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
/**
* Per-lens and whole-report coverage. Mirrors `CHARACTER_REVIEW_STATUSES` in
@@ -107,7 +107,7 @@ export const EVOLUTION_COVERAGE_FINDINGS_MAX = 40;
const STAGE_INDEX = new Map(EVOLUTION_STAGES.map((stageId, index) => [stageId, index]));
const stageLabel = (stageId) => EVOLUTION_STAGE_LABELS[stageId] || stageId;
-const nodeLabel = (node, nodeId) => (hasText(node?.title) ? node.title : nodeId);
+const nodeLabel = (node, nodeId) => (isNonBlankStr(node?.title) ? node.title : nodeId);
/**
* The scenes each episode can anchor evidence to, and the nodes that are
@@ -119,10 +119,10 @@ const nodeLabel = (node, nodeId) => (hasText(node?.title) ? node.title : nodeId)
* resolves, and only a pointer at something genuinely deleted reads stale.
*/
const buildSceneIndex = (loom) => new Map(asArray(loom?.episodes).map((episode) => {
- const nodeIds = new Set(asArray(episode?.nodes).map((node) => node?.id).filter(hasText));
+ const nodeIds = new Set(asArray(episode?.nodes).map((node) => node?.id).filter(isNonBlankStr));
const sceneKeys = new Set(nodeIds);
for (const scene of asArray(episode?.storyOutline?.scenes)) {
- if (hasText(scene?.key)) sceneKeys.add(scene.key);
+ if (isNonBlankStr(scene?.key)) sceneKeys.add(scene.key);
}
return [episode.id, { episode, nodeIds, sceneKeys }];
}));
@@ -137,8 +137,8 @@ const buildSceneIndex = (loom) => new Map(asArray(loom?.episodes).map((episode)
* is the direction the "never silently verified" rule allows.
*/
const resolveStageAnchor = (evidence, sceneIndex) => {
- const episodeId = hasText(evidence?.episodeId) ? evidence.episodeId : '';
- const sceneKey = hasText(evidence?.sceneKey) ? evidence.sceneKey : '';
+ const episodeId = isNonBlankStr(evidence?.episodeId) ? evidence.episodeId : '';
+ const sceneKey = isNonBlankStr(evidence?.sceneKey) ? evidence.sceneKey : '';
if (!episodeId && !sceneKey) return { resolution: 'unanchored', episodeId: null, nodeId: null };
if (episodeId && !sceneIndex.has(episodeId)) {
return {
diff --git a/server/lib/characterIntegrity.js b/server/lib/characterIntegrity.js
index 84b100de23..499dc07275 100644
--- a/server/lib/characterIntegrity.js
+++ b/server/lib/characterIntegrity.js
@@ -37,8 +37,9 @@ import {
bibleFieldIsBlank,
characterPsychologyIsBlank,
} from './universeBibleCompleteness.js';
-import { PSYCHOLOGY_DRIVE_AXES, isBlank } from './storyBible.js';
+import { PSYCHOLOGY_DRIVE_AXES } from './storyBible.js';
import { INTEGRITY_DIMENSION_IDS, INTEGRITY_FINDING_KINDS } from './characterIntegrityVocabulary.js';
+import { isEmptyScalar } from './objects.js';
const FINDING_KIND_SET = new Set(INTEGRITY_FINDING_KINDS);
const DIMENSION_ID_SET = new Set(INTEGRITY_DIMENSION_IDS);
@@ -87,7 +88,7 @@ export function characterIntegrityDepth(entry) {
if (!entry || typeof entry !== 'object') return 'light';
const assessment = entry.psychology?.assessment;
if ((assessment === 'unknown' || assessment === 'not-applicable')
- && !isBlank(entry.psychology?.assessmentNote)) {
+ && !isEmptyScalar(entry.psychology?.assessmentNote)) {
return 'explained';
}
if (roleIsMinor(entry.role) || entry.arcType === 'flat') return 'light';
@@ -155,7 +156,7 @@ export function characterCompletenessFindings(entry) {
}));
continue;
}
- if (isBlank(entry.psychology.theoryOfControl)) {
+ if (isEmptyScalar(entry.psychology.theoryOfControl)) {
findings.push(makeFinding({
...base,
field: 'psychology.theoryOfControl',
@@ -164,7 +165,7 @@ export function characterCompletenessFindings(entry) {
}
for (const axis of PSYCHOLOGY_DRIVE_AXES) {
for (const leaf of ['desire', 'fear']) {
- if (!isBlank(entry.psychology.drives?.[axis]?.[leaf])) continue;
+ if (!isEmptyScalar(entry.psychology.drives?.[axis]?.[leaf])) continue;
findings.push(makeFinding({
...base,
field: `psychology.drives.${axis}.${leaf}`,
diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.js
index 7691bacd40..9fba9f0315 100644
--- a/server/lib/comicScriptParser.js
+++ b/server/lib/comicScriptParser.js
@@ -15,8 +15,8 @@
* null) so downstream template renderers don't need null-guards.
* Unexpected text between panels is ignored.
*/
-import { trimTo } from './storyBible.js';
import { normalizeSlugline } from './scenePrompt.js';
+import { trimTo } from './textUtils.js';
const PAGE_RE = /^##\s+Page\s+([\dIVX]+)\b/i;
// Capture everything after the page number on a `## Page N …` header so the
diff --git a/server/lib/editorial/panelDisagreement.js b/server/lib/editorial/panelDisagreement.js
index d7687562c3..63952492e7 100644
--- a/server/lib/editorial/panelDisagreement.js
+++ b/server/lib/editorial/panelDisagreement.js
@@ -17,6 +17,7 @@
// The four personas, in render order. `id` is the stable machine key (also the
// stage-prompt suffix `pipeline-panel-<id>.md`); `label` is the human name.
+import { trimTo } from '../textUtils.js';
export const PANEL_PERSONAS = Object.freeze([
{ id: 'editor', label: 'The Editor', blurb: 'Senior editor — prose texture, subtext, over-explaining.' },
{ id: 'genre-reader', label: 'The Genre Reader', blurb: 'Reads 50 novels a year — pacing and page-turn pull.' },
@@ -64,8 +65,6 @@ const VERDICT_MAX = 600;
const MAX_ISSUES_PER_ANSWER = 12;
const PROBLEM_MAX = 1900;
-const cleanStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
// Accept an array of issue numbers the persona cited; keep valid positive
// integers, dedupe, cap. Optionally intersect with the known series issue
// numbers so a hallucinated citation never reaches the findings store.
@@ -99,9 +98,9 @@ export function sanitizePersonaResponse(personaId, raw, { validIssueNumbers = nu
for (const qid of PANEL_QUESTION_IDS) {
const a = src[qid];
if (a && typeof a === 'object' && !Array.isArray(a)) {
- answers[qid] = { text: cleanStr(a.text ?? a.answer, ANSWER_TEXT_MAX), issues: cleanIssueNumbers(a.issues ?? a.issueNumbers, validSet) };
+ answers[qid] = { text: trimTo(a.text ?? a.answer, ANSWER_TEXT_MAX), issues: cleanIssueNumbers(a.issues ?? a.issueNumbers, validSet) };
} else if (typeof a === 'string') {
- answers[qid] = { text: cleanStr(a, ANSWER_TEXT_MAX), issues: [] };
+ answers[qid] = { text: trimTo(a, ANSWER_TEXT_MAX), issues: [] };
} else {
answers[qid] = { text: '', issues: [] };
}
@@ -109,7 +108,7 @@ export function sanitizePersonaResponse(personaId, raw, { validIssueNumbers = nu
return {
persona: personaId,
answers,
- verdict: cleanStr(raw?.verdict ?? raw?.summary, VERDICT_MAX),
+ verdict: trimTo(raw?.verdict ?? raw?.summary, VERDICT_MAX),
};
}
diff --git a/server/lib/fableLoomContinuity.js b/server/lib/fableLoomContinuity.js
index 5c8a8205cd..fd10ba64ef 100644
--- a/server/lib/fableLoomContinuity.js
+++ b/server/lib/fableLoomContinuity.js
@@ -18,6 +18,7 @@ import {
validateAudioOccupancy,
} from './fableLoomPlayback.js';
import { characterIdentityPackReadiness } from './storyBible.js';
+import { isNonBlankStr } from './textUtils.js';
export const CONTINUITY_CATEGORIES = Object.freeze(['visual', 'voice', 'playback', 'graph']);
@@ -50,8 +51,6 @@ export const CONTINUITY_CODES = Object.freeze({
PRONUNCIATION_REVISION_DRIFT: 'PRONUNCIATION_REVISION_DRIFT',
});
-const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
-
/**
* Run comprehensive episodic continuity review.
* Pure deterministic rule evaluation — NO unsolicited AI calls.
@@ -122,10 +121,10 @@ export function analyzeEpisodeContinuity({
}
}
- const canonicalProtagonistId = isStr(loom?.protagonistCharacterId)
+ const canonicalProtagonistId = isNonBlankStr(loom?.protagonistCharacterId)
? loom.protagonistCharacterId
: null;
- const canonicalWardrobeId = isStr(loom?.protagonistWardrobeId)
+ const canonicalWardrobeId = isNonBlankStr(loom?.protagonistWardrobeId)
? loom.protagonistWardrobeId
: null;
const canonicalProtagonist = canonicalProtagonistId && Array.isArray(universe?.characters)
@@ -214,7 +213,7 @@ export function analyzeEpisodeContinuity({
const visualCanon = node.visualCanon || {};
const interaction = node.interactionWindow || {};
const assets = node.playbackAssets || {};
- const interactionProtagonistId = isStr(interaction.protagonistCharacterId)
+ const interactionProtagonistId = isNonBlankStr(interaction.protagonistCharacterId)
? interaction.protagonistCharacterId
: null;
const sceneProtagonistIds = new Set(
diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.js
index 6f7b549d33..552e96fbed 100644
--- a/server/lib/fableLoomGraph.js
+++ b/server/lib/fableLoomGraph.js
@@ -13,8 +13,8 @@
* blocks on.
*/
+import { isNonBlankStr } from './textUtils.js';
const asArray = (v) => (Array.isArray(v) ? v : []);
-const isStr = (v) => typeof v === 'string' && v.length > 0;
export const GRAPH_ISSUE_CODES = Object.freeze({
MISSING_START: 'MISSING_START',
@@ -85,7 +85,7 @@ export function analyzeEpisodeGraph(episode, {
if (!nodes.length) {
push(GRAPH_ISSUE_CODES.NO_NODES, 'error', 'The episode has no scenes yet.');
}
- if (!isStr(episode?.startNodeId)) {
+ if (!isNonBlankStr(episode?.startNodeId)) {
if (nodes.length) push(GRAPH_ISSUE_CODES.MISSING_START, 'error', 'No opening scene is set.');
} else if (nodes.length && !byId.has(episode.startNodeId)) {
push(GRAPH_ISSUE_CODES.START_NOT_FOUND, 'error', 'The opening scene points at a scene that no longer exists.');
@@ -205,7 +205,7 @@ export function describeGraphForPrompt(episode, {
for (const node of nodes) {
const flags = [
node.id === episode?.startNodeId ? 'START' : null,
- node?.isEnding ? `ENDING${isStr(node?.endingLabel) ? `: ${node.endingLabel}` : ''}` : null,
+ node?.isEnding ? `ENDING${isNonBlankStr(node?.endingLabel) ? `: ${node.endingLabel}` : ''}` : null,
node?.isEnding ? null : (node?.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION LOOP'),
participationMode === 'helper'
? (node?.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED')
@@ -216,12 +216,12 @@ export function describeGraphForPrompt(episode, {
lines.push(`[${node.id}] ${node.title || 'Untitled scene'}${flags.length ? ` (${flags.join(') (')})` : ''}`);
const prose = typeof node.prose === 'string' ? node.prose.trim() : '';
if (prose) lines.push(prose.length > proseLimit ? `${prose.slice(0, proseLimit)}…` : prose);
- if (isStr(node.videoPrompt)) {
+ if (isNonBlankStr(node.videoPrompt)) {
lines.push(`Video: ${node.videoPrompt.length > proseLimit ? `${node.videoPrompt.slice(0, proseLimit)}…` : node.videoPrompt}`);
}
- if (isStr(node.cameraMovement)) lines.push(`Camera movement: ${node.cameraMovement}`);
+ if (isNonBlankStr(node.cameraMovement)) lines.push(`Camera movement: ${node.cameraMovement}`);
for (const tr of asArray(node.transitions)) {
- const triggers = asArray(tr?.triggers).filter(isStr);
+ const triggers = asArray(tr?.triggers).filter(isNonBlankStr);
lines.push(`-> [${tr?.targetNodeId}] intent "${tr?.intent || ''}"${triggers.length ? ` (triggers: ${triggers.join('; ')})` : ''}`);
}
lines.push('');
diff --git a/server/lib/fableLoomOutline.js b/server/lib/fableLoomOutline.js
index 5418fef268..52f36fd420 100644
--- a/server/lib/fableLoomOutline.js
+++ b/server/lib/fableLoomOutline.js
@@ -10,11 +10,10 @@
import { LOOM_LIMITS } from './fableLoomLimits.js';
import { FABLELOOM_PROTAGONIST_PRESENCE } from './fableLoomPlayback.js';
-import { trimTo } from './textUtils.js';
+import { trimTo, isNonBlankStr } from './textUtils.js';
const asArray = (value) => (Array.isArray(value) ? value : []);
const isObject = (value) => value && typeof value === 'object';
-const isText = (value) => typeof value === 'string' && value.trim().length > 0;
export const OUTLINE_ISSUE_CODES = Object.freeze({
NO_SCENES: 'NO_SCENES',
@@ -80,7 +79,7 @@ export const fableLoomEpisodeChallenges = (loom, episodeId) => asArray(loom?.ser
.filter((item) => item?.episodeId === episodeId && fableLoomPlotPointKind(item) === 'challenge');
const uniqueKey = (candidate, index, seen) => {
- const base = isText(candidate)
+ const base = isNonBlankStr(candidate)
? candidate.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
: `s${index + 1}`;
let key = base || `s${index + 1}`;
@@ -104,7 +103,7 @@ const sanitizeValidation = (raw) => {
code: trimTo(issue.code, 80),
severity: issue.severity === 'warning' ? 'warning' : 'error',
message: trimTo(issue.message, LOOM_LIMITS.OUTLINE_ISSUE_MESSAGE_MAX),
- ...(isText(issue.sceneKey) ? { sceneKey: issue.sceneKey.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) } : {}),
+ ...(isNonBlankStr(issue.sceneKey) ? { sceneKey: issue.sceneKey.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) } : {}),
...(Number.isInteger(issue.transitionIndex) && issue.transitionIndex >= 0
? { transitionIndex: issue.transitionIndex }
: {}),
@@ -113,7 +112,7 @@ const sanitizeValidation = (raw) => {
return {
status,
issues,
- ...(isText(raw.validatedAt) ? { validatedAt: raw.validatedAt.slice(0, 80) } : {}),
+ ...(isNonBlankStr(raw.validatedAt) ? { validatedAt: raw.validatedAt.slice(0, 80) } : {}),
};
};
@@ -129,12 +128,12 @@ export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' }
const keyByRawKey = new Map();
const scenes = rawScenes.map((scene, index) => {
const key = uniqueKey(scene?.key, index, seen);
- if (isText(scene?.key) && !keyByRawKey.has(scene.key.trim())) keyByRawKey.set(scene.key.trim(), key);
+ if (isNonBlankStr(scene?.key) && !keyByRawKey.has(scene.key.trim())) keyByRawKey.set(scene.key.trim(), key);
const transitions = asArray(scene?.transitions)
.slice(0, LOOM_LIMITS.OUTLINE_TRANSITIONS_MAX)
.filter(isObject)
.map((transition) => ({
- targetKey: isText(transition.targetKey)
+ targetKey: isNonBlankStr(transition.targetKey)
? transition.targetKey.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
: '',
intent: trimTo(transition.intent, LOOM_LIMITS.INTENT_MAX),
@@ -143,7 +142,7 @@ export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' }
key,
title: trimTo(scene?.title, LOOM_LIMITS.NODE_TITLE_MAX),
summary: trimTo(scene?.summary, LOOM_LIMITS.OUTLINE_SUMMARY_MAX),
- plotPointId: isText(scene?.plotPointId)
+ plotPointId: isNonBlankStr(scene?.plotPointId)
? scene.plotPointId.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
: null,
challengePhase: challengePhaseSet.has(scene?.challengePhase) ? scene.challengePhase : null,
@@ -161,7 +160,7 @@ export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' }
transitions,
};
});
- const rawStart = isText(raw.startKey) ? raw.startKey.trim() : '';
+ const rawStart = isNonBlankStr(raw.startKey) ? raw.startKey.trim() : '';
const startKey = keyByRawKey.get(rawStart) || rawStart.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) || scenes[0]?.key || null;
return {
version: 1,
@@ -188,7 +187,7 @@ export function analyzeStoryOutline(outline, {
push(OUTLINE_ISSUE_CODES.NO_SCENES, 'error', 'The story outline has no scene beats yet.');
}
const startKey = outline?.startKey;
- if (!isText(startKey)) {
+ if (!isNonBlankStr(startKey)) {
if (scenes.length) push(OUTLINE_ISSUE_CODES.MISSING_START, 'error', 'The story outline has no opening beat.');
} else if (scenes.length && !byKey.has(startKey)) {
push(OUTLINE_ISSUE_CODES.START_NOT_FOUND, 'error', 'The opening beat points at a key that does not exist.');
@@ -257,7 +256,7 @@ export function analyzeStoryOutline(outline, {
if (episodeId && assignedPlot?.episodeId && assignedPlot.episodeId !== episodeId) {
push(OUTLINE_ISSUE_CODES.WRONG_EPISODE_PLOT_POINT, 'error', `"${label}" uses a plot point assigned to another episode. Keep that payoff in its assigned episode.`, { sceneKey: scene.key });
}
- if (!isText(scene.summary)) {
+ if (!isNonBlankStr(scene.summary)) {
push(OUTLINE_ISSUE_CODES.EMPTY_SUMMARY, 'error', `"${label}" has no scene log-line.`, { sceneKey: scene.key });
}
if (!reachable.has(scene.key)) {
@@ -298,7 +297,7 @@ export function analyzeStoryOutline(outline, {
const seenIntents = new Set();
transitions.forEach((transition, transitionIndex) => {
- const intent = isText(transition.intent) ? transition.intent.trim().toLowerCase() : '';
+ const intent = isNonBlankStr(transition.intent) ? transition.intent.trim().toLowerCase() : '';
if (!intent) {
push(
OUTLINE_ISSUE_CODES.EMPTY_INTENT,
@@ -573,7 +572,7 @@ export function analyzeSeriesStoryOutlines(loom, { replacingEpisodeId = null } =
`The handoff from Episode ${fromEpisode.number} to Episode ${toEpisode.number} needs an overnight voicemail.`,
{ episodeId: fromEpisode.id },
);
- } else if (!isText(voicemail.transcript)) {
+ } else if (!isNonBlankStr(voicemail.transcript)) {
push(
OUTLINE_ISSUE_CODES.EMPTY_OVERNIGHT_VOICEMAIL,
'error',
@@ -583,7 +582,7 @@ export function analyzeSeriesStoryOutlines(loom, { replacingEpisodeId = null } =
}
});
}
- if (delivery.nextSeasonTeaser === true && !isText(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
+ if (delivery.nextSeasonTeaser === true && !isNonBlankStr(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
push(
OUTLINE_ISSUE_CODES.MISSING_NEXT_SEASON_TEASER,
'error',
diff --git a/server/lib/fableLoomPlayback.js b/server/lib/fableLoomPlayback.js
index b78cc34068..c9983f47ec 100644
--- a/server/lib/fableLoomPlayback.js
+++ b/server/lib/fableLoomPlayback.js
@@ -8,6 +8,7 @@
*/
import { LOOM_LIMITS } from './fableLoomLimits.js';
+import { isNonBlankStr, trimTo } from './textUtils.js';
export const FABLELOOM_PLAYBACK_MODES = Object.freeze(['cut', 'decision']);
export const FABLELOOM_PLAYBACK_MODE_DEFAULT = 'decision';
@@ -54,8 +55,6 @@ export const asFableLoomPlaybackMode = (value) => (
export const isSafeVideoHistoryId = (value) =>
typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value);
-const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
-const trimTo = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
const SAFE_PRODUCTION_PARAMETER_KEYS = new Set([
'width', 'height', 'numFrames', 'fps', 'steps', 'guidance', 'guidanceScale',
@@ -73,10 +72,10 @@ export function sanitizeAudioInterval(raw) {
return {
startMs,
endMs,
- ...(isStr(raw.characterId) ? { characterId: trimTo(raw.characterId, 80) } : {}),
- ...(isStr(raw.speaker) ? { speaker: trimTo(raw.speaker, 100) } : {}),
+ ...(isNonBlankStr(raw.characterId) ? { characterId: trimTo(raw.characterId, 80) } : {}),
+ ...(isNonBlankStr(raw.speaker) ? { speaker: trimTo(raw.speaker, 100) } : {}),
...(raw.blocking === true ? { blocking: true } : {}),
- ...(isStr(raw.name) ? { name: trimTo(raw.name, 100) } : {}),
+ ...(isNonBlankStr(raw.name) ? { name: trimTo(raw.name, 100) } : {}),
};
}
@@ -153,7 +152,7 @@ export const sanitizeAudioOccupancy = validateAudioOccupancy;
export function sanitizeVisualConditioning(raw) {
if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
const list = (value, max) => (Array.isArray(value) ? value.slice(0, max) : []);
- const nullableRef = (value) => (isStr(value) ? trimTo(value, LOOM_LIMITS.REF_ID_MAX) : null);
+ const nullableRef = (value) => (isNonBlankStr(value) ? trimTo(value, LOOM_LIMITS.REF_ID_MAX) : null);
const capability = raw.capability && typeof raw.capability === 'object' ? raw.capability : {};
const bindings = raw.bindings && typeof raw.bindings === 'object' ? raw.bindings : {};
const protagonistBinding = bindings.protagonist && typeof bindings.protagonist === 'object'
@@ -171,7 +170,7 @@ export function sanitizeVisualConditioning(raw) {
if (!SAFE_PRODUCTION_PARAMETER_KEYS.has(key)) return [];
if (typeof value === 'number' && Number.isFinite(value)) return [[key.slice(0, 40), value]];
if (typeof value === 'boolean') return [[key.slice(0, 40), value]];
- if (isStr(value)) return [[key.slice(0, 40), trimTo(value, 200)]];
+ if (isNonBlankStr(value)) return [[key.slice(0, 40), trimTo(value, 200)]];
return [];
}))
: {};
@@ -246,7 +245,7 @@ export function sanitizeVisualConditioning(raw) {
.filter((value) => Number.isFinite(value))
.map((value) => Math.max(0, Math.min(1, value)))
.slice(0, LOOM_LIMITS.VISUAL_PROVENANCE_ASSETS_MAX),
- ...(isStr(raw.assetId) ? { assetId: nullableRef(raw.assetId) } : {}),
+ ...(isNonBlankStr(raw.assetId) ? { assetId: nullableRef(raw.assetId) } : {}),
...(raw.render && typeof raw.render === 'object' ? {
render: {
provider: trimTo(raw.render.provider, 40),
@@ -255,7 +254,7 @@ export function sanitizeVisualConditioning(raw) {
parameters: productionParameters,
},
} : {}),
- compiledAt: isStr(raw.compiledAt) ? raw.compiledAt : null,
+ compiledAt: isNonBlankStr(raw.compiledAt) ? raw.compiledAt : null,
};
}
@@ -343,17 +342,17 @@ export function sanitizeProvenance(raw) {
if (!raw || typeof raw !== 'object') return null;
return {
version: Number.isFinite(raw.version) ? Math.max(1, Math.round(raw.version)) : 1,
- loomId: isStr(raw.loomId) ? trimTo(raw.loomId, 80) : null,
- episodeId: isStr(raw.episodeId) ? trimTo(raw.episodeId, 80) : null,
- nodeId: isStr(raw.nodeId) ? trimTo(raw.nodeId, 80) : null,
- universeId: isStr(raw.universeId) ? trimTo(raw.universeId, 80) : null,
+ loomId: isNonBlankStr(raw.loomId) ? trimTo(raw.loomId, 80) : null,
+ episodeId: isNonBlankStr(raw.episodeId) ? trimTo(raw.episodeId, 80) : null,
+ nodeId: isNonBlankStr(raw.nodeId) ? trimTo(raw.nodeId, 80) : null,
+ universeId: isNonBlankStr(raw.universeId) ? trimTo(raw.universeId, 80) : null,
characters: (Array.isArray(raw.characters) ? raw.characters : [])
- .filter((c) => c && typeof c === 'object' && isStr(c.characterId))
+ .filter((c) => c && typeof c === 'object' && isNonBlankStr(c.characterId))
.slice(0, LOOM_LIMITS.PROVENANCE_CHARACTERS_MAX || 12)
.map((c) => ({
characterId: trimTo(c.characterId, 80),
- wardrobeId: isStr(c.wardrobeId) ? trimTo(c.wardrobeId, 80) : null,
- identityAssets: Array.isArray(c.identityAssets) ? c.identityAssets.filter(isStr).slice(0, 5) : [],
+ wardrobeId: isNonBlankStr(c.wardrobeId) ? trimTo(c.wardrobeId, 80) : null,
+ identityAssets: Array.isArray(c.identityAssets) ? c.identityAssets.filter(isNonBlankStr).slice(0, 5) : [],
lora: c.lora && typeof c.lora === 'object' ? {
filename: trimTo(c.lora.filename, 200),
sha256: trimTo(c.lora.sha256, 128),
@@ -372,8 +371,8 @@ export function sanitizeProvenance(raw) {
visualConditioningVersion: Number.isFinite(raw.visualConditioningVersion) ? raw.visualConditioningVersion : 1,
promptCompilerVersion: Number.isFinite(raw.promptCompilerVersion) ? raw.promptCompilerVersion : 1,
audioMixVersion: Number.isFinite(raw.audioMixVersion) ? raw.audioMixVersion : 1,
- omitted: Array.isArray(raw.omitted) ? raw.omitted.filter(isStr).slice(0, 20) : [],
- warnings: Array.isArray(raw.warnings) ? raw.warnings.filter(isStr).slice(0, 20) : [],
+ omitted: Array.isArray(raw.omitted) ? raw.omitted.filter(isNonBlankStr).slice(0, 20) : [],
+ warnings: Array.isArray(raw.warnings) ? raw.warnings.filter(isNonBlankStr).slice(0, 20) : [],
};
}
@@ -394,7 +393,7 @@ export function sanitizePlaybackAssets(raw) {
const exitByTransition = {};
if (raw.exitByTransition && typeof raw.exitByTransition === 'object') {
for (const [trId, vid] of Object.entries(raw.exitByTransition)) {
- if (isStr(trId) && isSafeVideoHistoryId(vid)) {
+ if (isNonBlankStr(trId) && isSafeVideoHistoryId(vid)) {
exitByTransition[trId.slice(0, 80)] = vid;
}
}
@@ -403,7 +402,7 @@ export function sanitizePlaybackAssets(raw) {
const audioOccupancy = {};
if (raw.audioOccupancy && typeof raw.audioOccupancy === 'object') {
for (const [assetId, occ] of Object.entries(raw.audioOccupancy)) {
- if (isStr(assetId) && occ && typeof occ === 'object') {
+ if (isNonBlankStr(assetId) && occ && typeof occ === 'object') {
audioOccupancy[assetId.slice(0, 200)] = validateAudioOccupancy(occ);
}
}
@@ -446,7 +445,7 @@ export function sanitizeInteractionWindow(raw) {
if (!raw || typeof raw !== 'object') return null;
const enabled = raw.enabled === true;
- const protagonistCharacterId = isStr(raw.protagonistCharacterId)
+ const protagonistCharacterId = isNonBlankStr(raw.protagonistCharacterId)
? trimTo(raw.protagonistCharacterId, LOOM_LIMITS.REF_ID_MAX || 64)
: null;
diff --git a/server/lib/fableLoomPlaytest.js b/server/lib/fableLoomPlaytest.js
index 4102170c82..13d23f0de9 100644
--- a/server/lib/fableLoomPlaytest.js
+++ b/server/lib/fableLoomPlaytest.js
@@ -8,9 +8,9 @@
*/
import { analyzeEpisodeGraph } from './fableLoomGraph.js';
+import { isNonBlankStr } from './textUtils.js';
const asArray = (value) => (Array.isArray(value) ? value : []);
-const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
export const FABLELOOM_PLAYTEST_LIMITS = Object.freeze({
DEFAULT_MAX_PATHS: 96,
@@ -41,7 +41,7 @@ const boundedInteger = (value, fallback, max) => (
);
const transitionKey = (nodeId, transition, index) => (
- hasText(transition?.id) ? transition.id : `${nodeId}:transition-${index + 1}`
+ isNonBlankStr(transition?.id) ? transition.id : `${nodeId}:transition-${index + 1}`
);
const transitionCoverageKey = (nodeId, transitionId, index) => (
@@ -206,7 +206,7 @@ export function enumerateEpisodePlaythroughs(episode, options = {}) {
}
};
- if (hasText(episode?.startNodeId) && byId.has(episode.startNodeId)) {
+ if (isNonBlankStr(episode?.startNodeId) && byId.has(episode.startNodeId)) {
walk({
nodeId: episode.startNodeId,
nodeIds: [],
@@ -233,7 +233,7 @@ export function enumerateEpisodePlaythroughs(episode, options = {}) {
const issues = [];
const push = (code, severity, message, extra = {}) => issues.push({ code, severity, message, ...extra });
- if (!hasText(episode?.startNodeId) || !byId.has(episode.startNodeId)) {
+ if (!isNonBlankStr(episode?.startNodeId) || !byId.has(episode.startNodeId)) {
push(PLAYTEST_ISSUE_CODES.NO_START, 'error', 'Playthrough testing cannot start because the opening scene is missing.');
}
for (const path of paths) {
diff --git a/server/lib/fableLoomProduction.js b/server/lib/fableLoomProduction.js
index 55944253b5..57eca66d41 100644
--- a/server/lib/fableLoomProduction.js
+++ b/server/lib/fableLoomProduction.js
@@ -11,6 +11,7 @@ import { computeGraphLayers } from './fableLoomGraph.js';
import { EFFORT_LEVELS } from './providerModels.js';
import { validateAudioOccupancy } from './fableLoomPlayback.js';
import { QUEUEABLE_IMAGE_MODES, VIDEO_GEN_MODES } from './generationModes.js';
+import { isNonBlankStr } from './textUtils.js';
export const FABLELOOM_PRODUCTION_MODES = Object.freeze(['current_canon', 'exact_inputs']);
export const FABLELOOM_PRODUCTION_MODE_DEFAULT = 'current_canon';
@@ -103,7 +104,6 @@ export const FABLELOOM_ASSET_TYPES = Object.freeze([
'dialogue',
]);
-const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
const isLockedCanon = (node) => Boolean(node?.visualCanon && node.visualCanon.mode !== 'draft');
const EXACT_RENDER_KEYS = Object.freeze({
@@ -121,9 +121,9 @@ const EXACT_RENDER_KEYS = Object.freeze({
});
const validRenderParameter = (key, value) => {
- if (['aspectRatio', 'mode', 'videoMode', 'tiling'].includes(key)) return isStr(value);
+ if (['aspectRatio', 'mode', 'videoMode', 'tiling'].includes(key)) return isNonBlankStr(value);
if (key === 'disableAudio') return typeof value === 'boolean';
- if (key === 'quantize') return isStr(value) || Number.isFinite(value);
+ if (key === 'quantize') return isNonBlankStr(value) || Number.isFinite(value);
if (!Number.isFinite(value)) return false;
if (['seed', 'guidance', 'guidanceScale'].includes(key)) return value >= 0;
return value > 0;
@@ -263,7 +263,7 @@ export function inspectEpisodeProductionOrder(loom, episode) {
continue;
}
for (const node of orderedNodes) {
- if (isStr(node.image)) continue;
+ if (isNonBlankStr(node.image)) continue;
const missing = {
episodeId: priorEpisode.id,
episodeNumber: priorEpisode.number || index + 1,
@@ -347,7 +347,7 @@ export function verifyExactInputProvenance(recordedProvenance, {
if (recordedProvenance.version !== 1) {
errors.push(`Recorded visual conditioning manifest version "${recordedProvenance.version ?? 'unknown'}" is unsupported.`);
}
- if (!isStr(recordedProvenance.compilerVersion)) {
+ if (!isNonBlankStr(recordedProvenance.compilerVersion)) {
errors.push('Recorded visual conditioning has no compiler revision.');
}
if (recordedProvenance.status !== 'locked') {
@@ -358,9 +358,9 @@ export function verifyExactInputProvenance(recordedProvenance, {
if (!capability || typeof capability !== 'object') {
errors.push('Recorded visual conditioning has no provider capability manifest.');
} else {
- if (!isStr(capability.backend)) errors.push('Recorded visual conditioning has no backend.');
- if (!isStr(capability.modelId)) errors.push('Recorded visual conditioning has no model revision or model id.');
- if (capability.backend === 'local' && !isStr(capability.modelRevision)) {
+ if (!isNonBlankStr(capability.backend)) errors.push('Recorded visual conditioning has no backend.');
+ if (!isNonBlankStr(capability.modelId)) errors.push('Recorded visual conditioning has no model revision or model id.');
+ if (capability.backend === 'local' && !isNonBlankStr(capability.modelRevision)) {
errors.push(`Recorded local ${capability.kind || 'media'} model "${capability.modelId || 'unknown'}" has no immutable model revision to verify exact inputs.`);
}
// Local model registries can only verify local manifests. Cloud model ids
@@ -370,12 +370,12 @@ export function verifyExactInputProvenance(recordedProvenance, {
const availableModels = capability.backend === 'local'
? (capability.kind === 'video' ? availableVideoModels : availableImageModels)
: null;
- if (Array.isArray(availableModels) && isStr(capability.modelId)) {
+ if (Array.isArray(availableModels) && isNonBlankStr(capability.modelId)) {
const matchingModel = availableModels.find((model) => model?.id === capability.modelId);
if (!matchingModel) {
errors.push(`Recorded ${capability.kind || 'media'} model "${capability.modelId}" is not available locally.`);
- } else if (isStr(capability.modelRevision)
- && (!isStr(matchingModel.revision) || matchingModel.revision !== capability.modelRevision)) {
+ } else if (isNonBlankStr(capability.modelRevision)
+ && (!isNonBlankStr(matchingModel.revision) || matchingModel.revision !== capability.modelRevision)) {
errors.push(`Recorded ${capability.kind || 'media'} model "${capability.modelId}" revision mismatch (recorded ${capability.modelRevision}, current local ${matchingModel.revision || 'unknown'}).`);
}
}
@@ -395,14 +395,14 @@ export function verifyExactInputProvenance(recordedProvenance, {
const canonChar = universe.characters.find((character) => character.id === charId);
if (!canonChar) {
errors.push(`Character "${charId || 'unknown'}" in recorded visual bindings no longer exists in Universe.`);
- } else if (isStr(appearance.wardrobeId)
+ } else if (isNonBlankStr(appearance.wardrobeId)
&& (!Array.isArray(canonChar.wardrobes)
|| !canonChar.wardrobes.some((wardrobe) => wardrobe.id === appearance.wardrobeId))) {
errors.push(`Wardrobe "${appearance.wardrobeId}" in recorded visual bindings is not present on character "${charId}".`);
}
}
}
- if (universe && isStr(bindings.placeId)
+ if (universe && isNonBlankStr(bindings.placeId)
&& Array.isArray(universe.places)
&& !universe.places.some((place) => place.id === bindings.placeId)) {
errors.push(`Place "${bindings.placeId}" in recorded visual bindings no longer exists in Universe.`);
@@ -420,7 +420,7 @@ export function verifyExactInputProvenance(recordedProvenance, {
errors.push('Recorded visual conditioning has no asset manifest.');
} else {
for (const asset of recordedProvenance.assets) {
- if (!isStr(asset?.filename)) {
+ if (!isNonBlankStr(asset?.filename)) {
errors.push(`Recorded visual conditioning asset "${asset?.role || 'unknown'}" has no filename.`);
} else if (typeof resolveAsset === 'function' && !resolveAsset(asset.filename)) {
errors.push(`Recorded visual conditioning asset "${asset.filename}" is unavailable locally.`);
@@ -432,18 +432,18 @@ export function verifyExactInputProvenance(recordedProvenance, {
errors.push('Recorded visual conditioning has no adapter manifest.');
} else {
for (const adapter of recordedProvenance.adapters) {
- if (!isStr(adapter?.filename)) {
+ if (!isNonBlankStr(adapter?.filename)) {
errors.push('Recorded visual conditioning contains an adapter with no filename.');
continue;
}
- if (!isStr(adapter.sha256)) {
+ if (!isNonBlankStr(adapter.sha256)) {
errors.push(`Recorded character adapter "${adapter.filename}" has no checksum to verify exact inputs.`);
continue;
}
const matchedLora = installedLoras.find((lora) => lora?.filename === adapter.filename);
if (!matchedLora) {
errors.push(`Recorded character adapter "${adapter.filename}" is not installed locally.`);
- } else if (!isStr(matchedLora.sha256)) {
+ } else if (!isNonBlankStr(matchedLora.sha256)) {
errors.push(`Installed character adapter "${adapter.filename}" has no checksum to verify exact inputs.`);
} else if (matchedLora.sha256 !== adapter.sha256) {
errors.push(`Recorded character adapter "${adapter.filename}" checksum mismatch (expected ${adapter.sha256}, found ${matchedLora.sha256}).`);
@@ -477,16 +477,16 @@ export function verifyExactInputProvenance(recordedProvenance, {
// Check LoRA matching
if (char.lora) {
const recordedFilename = char.lora.filename;
- if (!isStr(recordedFilename)) {
+ if (!isNonBlankStr(recordedFilename)) {
errors.push(`Recorded character LoRA binding for "${charId}" has no filename.`);
} else {
const recordedSha = char.lora.sha256;
const matchedLora = installedLoras.find((l) => l.filename === recordedFilename);
if (!matchedLora) {
errors.push(`Recorded character LoRA "${recordedFilename}" is not installed locally.`);
- } else if (!isStr(recordedSha)) {
+ } else if (!isNonBlankStr(recordedSha)) {
errors.push(`Recorded character LoRA "${recordedFilename}" has no checksum to verify.`);
- } else if (!isStr(matchedLora.sha256)) {
+ } else if (!isNonBlankStr(matchedLora.sha256)) {
errors.push(`Installed character LoRA "${recordedFilename}" has no checksum to verify exact inputs.`);
} else if (matchedLora.sha256 !== recordedSha) {
errors.push(`Recorded character LoRA "${recordedFilename}" checksum mismatch (expected ${recordedSha}, found ${matchedLora.sha256}).`);
@@ -500,7 +500,7 @@ export function verifyExactInputProvenance(recordedProvenance, {
const recordedVersion = char.voice.profileVersion;
const recordedEngine = char.voice.engine;
const recordedModelRev = char.voice.modelRevision;
- if (!isStr(recordedProfileId)) {
+ if (!isNonBlankStr(recordedProfileId)) {
errors.push(`Recorded voice binding for character "${charId}" has no profile id.`);
continue;
}
@@ -521,10 +521,10 @@ export function verifyExactInputProvenance(recordedProvenance, {
if (!Number.isFinite(recordedVersion) || matchedProfile.version !== recordedVersion) {
errors.push(`Recorded voice profile "${recordedProfileId}" version mismatch (recorded v${recordedVersion ?? 'unknown'}, current local v${matchedProfile.version ?? 'unknown'}).`);
}
- if (!isStr(recordedEngine) || !isStr(matchedProfile.engine) || matchedProfile.engine !== recordedEngine) {
+ if (!isNonBlankStr(recordedEngine) || !isNonBlankStr(matchedProfile.engine) || matchedProfile.engine !== recordedEngine) {
errors.push(`Recorded voice profile "${recordedProfileId}" engine mismatch (recorded ${recordedEngine || 'unknown'}, current local ${matchedProfile.engine || 'unknown'}).`);
}
- if (!isStr(recordedModelRev) || !isStr(matchedProfile.modelRevision) || matchedProfile.modelRevision !== recordedModelRev) {
+ if (!isNonBlankStr(recordedModelRev) || !isNonBlankStr(matchedProfile.modelRevision) || matchedProfile.modelRevision !== recordedModelRev) {
errors.push(`Recorded voice profile "${recordedProfileId}" model revision mismatch (recorded ${recordedModelRev || 'unknown'}, current local ${matchedProfile.modelRevision || 'unknown'}).`);
}
}
@@ -584,7 +584,7 @@ export function buildEpisodeProductionPlan({
const lockedCanon = isLockedCanon(node);
const universeCharacters = Array.isArray(universe?.characters) ? universe.characters : [];
const characterById = new Map(universeCharacters.map((character) => [character.id, character]));
- const canonicalProtagonistId = isStr(loom?.protagonistCharacterId)
+ const canonicalProtagonistId = isNonBlankStr(loom?.protagonistCharacterId)
? loom.protagonistCharacterId
: null;
const canonicalProtagonist = canonicalProtagonistId
@@ -625,7 +625,7 @@ export function buildEpisodeProductionPlan({
}
let temporalSourceNodeId = null;
- const explicitTemporalSource = isStr(visualCanon?.continuitySourceNodeId)
+ const explicitTemporalSource = isNonBlankStr(visualCanon?.continuitySourceNodeId)
? visualCanon.continuitySourceNodeId
: null;
@@ -662,8 +662,8 @@ export function buildEpisodeProductionPlan({
}
const assets = node.playbackAssets || null;
- const existingStill = isStr(node.image) ? node.image : null;
- const existingEntryVideo = isStr(assets?.entryVideoHistoryId) ? assets.entryVideoHistoryId : (isStr(node.videoHistoryId) ? node.videoHistoryId : null);
+ const existingStill = isNonBlankStr(node.image) ? node.image : null;
+ const existingEntryVideo = isNonBlankStr(assets?.entryVideoHistoryId) ? assets.entryVideoHistoryId : (isNonBlankStr(node.videoHistoryId) ? node.videoHistoryId : null);
// Exact input provenance verification if requested
if (effectiveMode === 'exact_inputs') {
diff --git a/server/lib/fleetQuotas.js b/server/lib/fleetQuotas.js
index 4f17babb11..50a743a993 100644
--- a/server/lib/fleetQuotas.js
+++ b/server/lib/fleetQuotas.js
@@ -25,6 +25,7 @@
*/
import { parseTsMs } from './lwwTimestamp.js';
+import { isNonBlankStr } from './textUtils.js';
// Structural bounds on ONE peer-supplied quota payload. Same reasoning as the
// usage digest's caps in services/peerUsage.js: the wire shape is fixed and
@@ -36,8 +37,7 @@ const MAX_NOTES_PER_ACTIVITY = 8;
// How many instance names a note spells out before collapsing the tail.
const NOTE_NAME_LIMIT = 3;
-const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
-const str = (v, max) => (isNonEmptyStr(v) ? v.slice(0, max) : null);
+const str = (v, max) => (isNonBlankStr(v) ? v.slice(0, max) : null);
const int = (v) => (typeof v === 'number' && Number.isFinite(v) ? Math.round(v) : null);
const pct = (v) => {
const n = int(v);
diff --git a/server/lib/hostShutdown.js b/server/lib/hostShutdown.js
index 193db5086b..44349df46c 100644
--- a/server/lib/hostShutdown.js
+++ b/server/lib/hostShutdown.js
@@ -31,6 +31,7 @@
import { join } from 'path';
import { rm } from 'fs/promises';
import { PATHS, atomicWrite, readJSONFile } from './fileUtils.js';
+import { isNonBlankStr } from './textUtils.js';
/** Completion reason recorded for a run the host restart tore down. */
export const HOST_SHUTDOWN_REASON = 'host-shutdown';
@@ -45,8 +46,6 @@ export const HOST_SHUTDOWN_REASON = 'host-shutdown';
*/
export const hostShutdownMarkerPath = () => join(PATHS.cos, 'host-shutdown.json');
-const isNonEmptyString = (value) => typeof value === 'string' && !!value;
-
// Process-local. Never persisted — a fresh process is by definition not the one
// that was shutting down, so this always starts false.
let shuttingDown = false;
@@ -104,7 +103,7 @@ export async function writeHostShutdownMarker({ agentIds = [], signal = null } =
// orphans — the exact penalty this marker exists to prevent. Consuming the
// marker is the sweep's job, so anything still here has not been recovered yet.
const prior = await readHostShutdownMarker();
- const ids = [...new Set([...(prior?.agentIds || []), ...agentIds.filter(isNonEmptyString)])];
+ const ids = [...new Set([...(prior?.agentIds || []), ...agentIds.filter(isNonBlankStr)])];
// Nothing was running — don't leave a marker the next boot has to reason
// about (and don't overwrite a prior one; a marker with no agents is noise).
if (ids.length === 0) return false;
@@ -129,7 +128,7 @@ export async function writeHostShutdownMarker({ agentIds = [], signal = null } =
export async function readHostShutdownMarker() {
const raw = await readJSONFile(hostShutdownMarkerPath(), null, { logError: false, allowArray: false });
if (!raw || typeof raw !== 'object') return null;
- return { ...raw, agentIds: Array.isArray(raw.agentIds) ? raw.agentIds.filter(isNonEmptyString) : [] };
+ return { ...raw, agentIds: Array.isArray(raw.agentIds) ? raw.agentIds.filter(isNonBlankStr) : [] };
}
/**
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index 89ac567b87..8df75d67b4 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -88,6 +88,16 @@ const NARROWED = [
'needs getInstanceId, which instanceIdentity.js declares'],
['routes/systemHealth.js', 'services/instances.js',
'needs getInstanceId, which instanceIdentity.js declares'],
+ // #6837: the string predicates / bounders live in textUtils.js; these pure
+ // leaves used to reach the whole story bible (crypto + fileUtils) for isStr.
+ ['lib/storyArc.js', 'lib/storyBible.js',
+ 'needs isStr / trimTo / trimToClause, which textUtils.js declares'],
+ ['lib/styleGuide.js', 'lib/storyBible.js',
+ 'needs isStr / trimTo, which textUtils.js declares'],
+ ['lib/sharingOrigin.js', 'lib/storyBible.js',
+ 'needs isStr / trimTo, which textUtils.js declares'],
+ ['lib/renderSlot.js', 'lib/storyBible.js',
+ 'needs isStr / trimTo, which textUtils.js declares'],
];
describe('narrowed imports stay narrow (#6009)', () => {
@@ -112,6 +122,7 @@ describe('narrowed imports stay narrow (#6009)', () => {
expect(reaches('lib/slashdoInvocation.js', 'lib/providerVendors.js')).toBe(true);
expect(reaches('services/voice/tools/pipeline.js', 'lib/pipelineStages.js')).toBe(true);
expect(reaches('services/instances.js', 'services/instanceIdentity.js')).toBe(true);
+ expect(reaches('lib/storyBible.js', 'lib/textUtils.js')).toBe(true);
});
// And a control on the other side: the barrels themselves still reach what
diff --git a/server/lib/localImageFilename.js b/server/lib/localImageFilename.js
index c9851b5c3e..94d287aa73 100644
--- a/server/lib/localImageFilename.js
+++ b/server/lib/localImageFilename.js
@@ -18,8 +18,6 @@
// basename. Path-traversal scrubbing happens downstream in
// `sanitizeAssetFilename`; here we only decide IS-this-a-local-image + basename.
-const isStr = (v) => typeof v === 'string';
-
/**
* Strip any querystring/hash a stored reference might carry, then reduce it to
* the basename — the bare unit the peer-sync asset pipeline hashes + transfers.
@@ -31,6 +29,7 @@ const isStr = (v) => typeof v === 'string';
* @param {unknown} pathOrName - a path segment or bare filename (no mount prefix)
* @returns {string|null} the basename, or null when it collapses to empty
*/
+import { isStr } from './textUtils.js';
export function assetBasename(pathOrName) {
if (!isStr(pathOrName)) return null;
const base = pathOrName.split(/[?#]/)[0].split('/').pop();
diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.js
index fc36a86098..83514e08e6 100644
--- a/server/lib/mediaModels.js
+++ b/server/lib/mediaModels.js
@@ -89,6 +89,7 @@ import {
isHardwareCompatible,
withHardwareCompatibility,
} from './systemCapabilities.js';
+import { isNonBlankStr } from './textUtils.js';
// fileUtils.ensureDir is async/Promise-returning; this module needs a
// synchronous version because `loadMediaModels()` is called at import-time
// from videoGen/imageGen modules, which can't await before exporting.
@@ -1977,7 +1978,7 @@ const MFLUX_LEGACY_REPOS = {
export const repoForModel = (model) => {
if (!model || typeof model !== 'object') return null;
- if (isNonEmptyString(model.repo)) return model.repo;
+ if (isNonBlankStr(model.repo)) return model.repo;
if (MFLUX_LEGACY_REPOS[model.id]) return MFLUX_LEGACY_REPOS[model.id];
return null;
};
@@ -1993,7 +1994,7 @@ export const requiredReposForModel = (model) => {
const main = repoForModel(model);
if (!main) return null;
const aux = [];
- if (isNonEmptyString(model?.textEncoderRepo)) aux.push(model.textEncoderRepo);
+ if (isNonBlankStr(model?.textEncoderRepo)) aux.push(model.textEncoderRepo);
return [main, ...aux];
};
@@ -2025,7 +2026,6 @@ export const isHfRepoId = (value) => {
// install) when it exists; otherwise returns the HF repo id which mlx_video
// will resolve via the HF cache (downloading on first run).
const FALLBACK_TEXT_ENCODER_REPO = 'mlx-community/gemma-3-12b-it-4bit';
-const isNonEmptyString = (v) => typeof v === 'string' && v.length > 0;
export const getTextEncoderRepo = () => {
const reg = loadMediaModels();
@@ -2034,7 +2034,7 @@ export const getTextEncoderRepo = () => {
if (!entry) {
console.log(`⚠️ Unknown selectedTextEncoder "${id}"; falling back to first entry`);
const firstRepo = reg.textEncoders?.[0]?.repo;
- return isNonEmptyString(firstRepo) ? firstRepo : FALLBACK_TEXT_ENCODER_REPO;
+ return isNonBlankStr(firstRepo) ? firstRepo : FALLBACK_TEXT_ENCODER_REPO;
}
if (entry.localPath) {
const expanded = expandHome(entry.localPath);
@@ -2043,7 +2043,7 @@ export const getTextEncoderRepo = () => {
// Spawn args must be non-empty strings — a malformed registry entry
// (missing/empty `repo`) would otherwise reach mlx_video as undefined and
// surface as a confusing TypeError or downstream CLI error.
- if (!isNonEmptyString(entry.repo)) {
+ if (!isNonBlankStr(entry.repo)) {
console.log(`⚠️ Text encoder "${id}" has no repo; falling back to "${FALLBACK_TEXT_ENCODER_REPO}"`);
return FALLBACK_TEXT_ENCODER_REPO;
}
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index facf2ed6bc..0747ae07d9 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -17,6 +17,7 @@ import {
normalizePersistentMindThinkingRequests,
normalizePersistentMindThinkingSelection,
} from './persistentMindThinkingPresets.js';
+import { trimTo } from './textUtils.js';
export const PERSISTENT_MIND_SCHEMA_VERSION = 8;
@@ -70,12 +71,8 @@ const asIso = (value) => {
return new Date(value).toISOString();
};
-const asBoundedString = (value, max) => (
- typeof value === 'string' ? value.trim().slice(0, max) : ''
-);
-
-const asId = (value) => asBoundedString(value, 200);
-const asMindId = (value) => asBoundedString(value, 128);
+const asId = (value) => trimTo(value, 200);
+const asMindId = (value) => trimTo(value, 128);
const asCount = (value) => (
Number.isSafeInteger(value) && value >= 0 ? value : 0
@@ -198,7 +195,7 @@ export function persistentMindMessageFingerprint(value) {
const selection = normalizePersistentMindThinkingSelection(value?.thinkingPreset);
return createHash('sha256')
.update(JSON.stringify({
- text: asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS),
+ text: trimTo(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS),
images,
...(thinkingPresetId ? { thinkingPresetId } : {}),
...(thinkingPresetId && selection ? {
@@ -236,7 +233,7 @@ export function publicPersistentMindAttachment(value) {
const sanitizeMessage = (value) => {
const id = asId(value?.id);
- const text = asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);
+ const text = trimTo(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);
const images = [];
const seenImageIds = new Set();
for (const candidate of Array.isArray(value?.images) ? value.images : []) {
@@ -273,14 +270,14 @@ const sanitizeCallRecord = (value) => {
if (!at) return null;
return {
at,
- reason: asBoundedString(value?.reason, PERSISTENT_MIND_LIMITS.MAX_CALL_REASON_CHARS),
- source: asBoundedString(value?.source, PERSISTENT_MIND_LIMITS.MAX_CALL_SOURCE_CHARS) || 'mind',
+ reason: trimTo(value?.reason, PERSISTENT_MIND_LIMITS.MAX_CALL_REASON_CHARS),
+ source: trimTo(value?.source, PERSISTENT_MIND_LIMITS.MAX_CALL_SOURCE_CHARS) || 'mind',
};
};
const sanitizeSelfWake = (value) => {
const id = asId(value?.id);
- const reason = asBoundedString(value?.reason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS);
+ const reason = trimTo(value?.reason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS);
const sourceTurnId = asId(value?.sourceTurnId);
if (!id || !reason || !sourceTurnId) return null;
return {
@@ -315,8 +312,8 @@ const sanitizeActiveTurn = (value) => {
startedAt: asIso(value?.startedAt) || new Date(0).toISOString(),
heartbeatAt: asIso(value?.heartbeatAt) || asIso(value?.startedAt) || new Date(0).toISOString(),
providerId: asId(value?.providerId) || null,
- model: asBoundedString(value?.model, 500) || null,
- effort: asBoundedString(value?.effort, 100) || null,
+ model: trimTo(value?.model, 500) || null,
+ effort: trimTo(value?.effort, 100) || null,
};
};
@@ -436,7 +433,7 @@ export function normalizePersistentMindState(raw) {
enabled,
started,
status,
- pauseReason: asBoundedString(source.pauseReason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,
+ pauseReason: trimTo(source.pauseReason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,
queuedMessages,
pendingAttachments,
selfWake,
@@ -449,7 +446,7 @@ export function normalizePersistentMindState(raw) {
lastCompletedAt: asIso(source.lastCompletedAt),
nextEligibleWakeAt: asIso(source.nextEligibleWakeAt),
failureCount: asCount(source.failureCount),
- lastError: asBoundedString(source.lastError, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,
+ lastError: trimTo(source.lastError, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,
};
}
diff --git a/server/lib/persistentMindProfile.js b/server/lib/persistentMindProfile.js
index 1ea9b7d68a..cea8f5aac2 100644
--- a/server/lib/persistentMindProfile.js
+++ b/server/lib/persistentMindProfile.js
@@ -8,6 +8,7 @@
import { z } from 'zod';
import { EFFORT_LEVELS } from './providerModels.js';
+import { trimTo } from './textUtils.js';
export const PERSISTENT_MIND_PROFILE_SCHEMA_VERSION = 1;
@@ -50,8 +51,6 @@ export function createDefaultPersistentMindProfile() {
};
}
-const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
-
const wakeIntervalMinutes = (value) => (
Number.isInteger(value)
&& value >= PERSISTENT_MIND_PROFILE_LIMITS.WAKE_INTERVAL_MINUTES_MIN
@@ -64,12 +63,12 @@ const wakeIntervalMinutes = (value) => (
export function normalizePersistentMindProfile(raw) {
const defaults = createDefaultPersistentMindProfile();
const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
- const effort = text(source.effort, 20);
+ const effort = trimTo(source.effort, 20);
return {
...defaults,
enabled: source.enabled === true,
- providerId: text(source.providerId, PERSISTENT_MIND_PROFILE_LIMITS.PROVIDER_ID_MAX),
- model: text(source.model, PERSISTENT_MIND_PROFILE_LIMITS.MODEL_MAX),
+ providerId: trimTo(source.providerId, PERSISTENT_MIND_PROFILE_LIMITS.PROVIDER_ID_MAX),
+ model: trimTo(source.model, PERSISTENT_MIND_PROFILE_LIMITS.MODEL_MAX),
effort: EFFORT_LEVELS.includes(effort) ? effort : '',
thinkingInterface: source.thinkingInterface === PERSISTENT_MIND_THINKING_INTERFACE
? source.thinkingInterface
diff --git a/server/lib/persistentMindThinkingPresets.js b/server/lib/persistentMindThinkingPresets.js
index de306fc1a9..269c49b061 100644
--- a/server/lib/persistentMindThinkingPresets.js
+++ b/server/lib/persistentMindThinkingPresets.js
@@ -15,6 +15,7 @@
import { z } from 'zod';
import { EFFORT_LEVELS } from './providerModels.js';
+import { trimTo } from './textUtils.js';
export const PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION = 1;
@@ -71,8 +72,6 @@ export function createDefaultPersistentMindThinkingPresets() {
};
}
-const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
-
/**
* Coerce a preset reference to the exact stored id, or null.
*
@@ -80,7 +79,7 @@ const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0,
* same rule the preset list itself enforces, rather than re-deriving it.
*/
export function asPersistentMindThinkingPresetId(value) {
- const id = text(value, PERSISTENT_MIND_THINKING_PRESET_LIMITS.ID_MAX);
+ const id = trimTo(value, PERSISTENT_MIND_THINKING_PRESET_LIMITS.ID_MAX);
return ID_PATTERN.test(id) ? id : null;
}
@@ -92,13 +91,13 @@ const sanitizePreset = (value) => {
const parsed = storedThinkingPresetSchema.safeParse({
...value,
id: asPersistentMindThinkingPresetId(value?.id),
- label: text(value?.label, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX),
+ label: trimTo(value?.label, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX),
});
if (!parsed.success) return null;
const { id, providerId, model, effort = '', label } = parsed.data;
return {
id,
- label: label || text(`${providerId} / ${model}`, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX),
+ label: label || trimTo(`${providerId} / ${model}`, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX),
providerId,
model,
effort,
@@ -136,7 +135,6 @@ export function findPersistentMindThinkingPreset(raw, presetId) {
return normalizePersistentMindThinkingPresets(raw).presets.find((preset) => preset.id === id) || null;
}
-
export const persistentMindThinkingRequestSchema = z.object({
presetId: persistentMindThinkingPresetSchema.shape.id,
reason: z.string().trim().min(1).max(200),
diff --git a/server/lib/proseExportSettings.js b/server/lib/proseExportSettings.js
index 3bec20dace..b3d4c3883c 100644
--- a/server/lib/proseExportSettings.js
+++ b/server/lib/proseExportSettings.js
@@ -14,6 +14,7 @@
// Trade-paperback trim sizes, in PDF points (1pt = 1/72"). The keys are stable
// wire values; the labels are UI-only (kept on the client). us-trade (6"×9") is
// the default fiction trade size.
+import { trimTo } from './textUtils.js';
export const TRIM_SIZES = Object.freeze({
'us-trade': { width: 432, height: 648 }, // 6" × 9"
'digest': { width: 396, height: 612 }, // 5.5" × 8.5"
@@ -34,8 +35,6 @@ const AUTHOR_MAX = 120;
const COPYRIGHT_MAX = 500;
const DEDICATION_MAX = 2000;
-const trimTo = (val, max) => (typeof val === 'string' ? val.trim().slice(0, max) : '');
-
/**
* Sanitize the optional `series.exportSettings` field. Returns `null` when the
* settings carry no non-default content (so a series that only accepted the
diff --git a/server/lib/providerConnections.js b/server/lib/providerConnections.js
index 97fdb2fdfe..607aaf9cd9 100644
--- a/server/lib/providerConnections.js
+++ b/server/lib/providerConnections.js
@@ -7,6 +7,7 @@ import {
isOpencodeCommand,
parseOpencodeConfigContent,
} from './providerModels.js';
+import { isNonBlankStr } from './textUtils.js';
/**
* The CONNECTION half of the provider-connection graph proposed in
@@ -88,8 +89,6 @@ const DYNAMIC_REFERENCE_RE = /\$[({]?[A-Za-z_]/;
/** Flags that point a harness at an external config file we cannot read here. */
const EXTERNAL_CONFIG_FLAGS = new Set(['--config', '--config-file', '--configuration']);
-const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !== '';
-
/**
* The base URL an OpenCode record declares for `namespace` inside its inline
* config, plus every OTHER namespace it declares. A config naming a namespace
@@ -98,13 +97,13 @@ const isNonEmptyString = (value) => typeof value === 'string' && value.trim() !=
*/
function opencodeDeclaredEndpoints(provider, namespace) {
const raw = provider?.envVars?.OPENCODE_CONFIG_CONTENT;
- if (!isNonEmptyString(raw)) return { baseUrl: null, foreign: [], unparsable: false, declared: false };
+ if (!isNonBlankStr(raw)) return { baseUrl: null, foreign: [], unparsable: false, declared: false };
const parsed = parseOpencodeConfigContent(raw);
if (!parsed) return { baseUrl: null, foreign: [], unparsable: true, declared: true };
const declaredProviders = parsed.provider && typeof parsed.provider === 'object' ? parsed.provider : {};
const baseUrl = declaredProviders?.[namespace]?.options?.baseURL;
return {
- baseUrl: isNonEmptyString(baseUrl) ? baseUrl : null,
+ baseUrl: isNonBlankStr(baseUrl) ? baseUrl : null,
foreign: Object.keys(declaredProviders).filter((key) => key !== namespace),
unparsable: false,
declared: true,
@@ -171,13 +170,13 @@ export function providerConnectionProfile(provider) {
// is null/empty — so the split below stays lossless either way.
if (Object.hasOwn(record, 'endpoint')) ownedFields.endpoint = record.endpoint;
for (const [name, envProtocol] of Object.entries(TRANSPORT_ENV_VARS)) {
- if (!isNonEmptyString(envVars[name])) continue;
+ if (!isNonBlankStr(envVars[name])) continue;
ownedEnvVars[name] = envVars[name];
protocol = envProtocol;
baseUrl = envVars[name];
break;
}
- if (!baseUrl && isNonEmptyString(record.endpoint)) baseUrl = record.endpoint;
+ if (!baseUrl && isNonBlankStr(record.endpoint)) baseUrl = record.endpoint;
}
if (baseUrl) transports[protocol] = { baseUrl };
@@ -192,12 +191,12 @@ export function providerConnectionProfile(provider) {
const credentials = {};
if (Object.hasOwn(record, 'apiKey')) {
ownedFields.apiKey = record.apiKey;
- if (isNonEmptyString(record.apiKey)) credentials.apiKey = record.apiKey;
+ if (isNonBlankStr(record.apiKey)) credentials.apiKey = record.apiKey;
}
for (const name of CONNECTION_CREDENTIAL_ENV_VARS) {
if (!Object.hasOwn(envVars, name)) continue;
ownedEnvVars[name] = envVars[name];
- if (isNonEmptyString(envVars[name])) credentials[name] = envVars[name];
+ if (isNonBlankStr(envVars[name])) credentials[name] = envVars[name];
}
if (Object.values(credentials).includes(REDACTED_CREDENTIAL)) {
addReason('redacted-credential', 'profile built from a sanitized record');
@@ -211,7 +210,7 @@ export function providerConnectionProfile(provider) {
if (dynamic.length > 0) addReason('dynamic-config', dynamic.map(([name]) => name).join(','));
const externalConfig = [
- ...Object.keys(envVars).filter((name) => /_CONFIG(_FILE)?$/.test(name) && isNonEmptyString(envVars[name])),
+ ...Object.keys(envVars).filter((name) => /_CONFIG(_FILE)?$/.test(name) && isNonBlankStr(envVars[name])),
...(Array.isArray(record.args) ? record.args.filter((arg) => EXTERNAL_CONFIG_FLAGS.has(arg)) : []),
];
if (externalConfig.length > 0) addReason('external-harness-config', externalConfig.join(','));
diff --git a/server/lib/providerModelAliases.js b/server/lib/providerModelAliases.js
index 7abb0499ca..2918304025 100644
--- a/server/lib/providerModelAliases.js
+++ b/server/lib/providerModelAliases.js
@@ -1,4 +1,5 @@
import { routeSettingsRevision } from './providerRouteSettings.js';
+import { isNonBlankStr } from './textUtils.js';
/**
* Hand-authored model aliases for one provider route (#6369).
@@ -34,8 +35,6 @@ import { routeSettingsRevision } from './providerRouteSettings.js';
/** Bounds shared by the row sanitizer and the request schema. */
export const MODEL_ALIAS_LIMITS = Object.freeze({ maxEntries: 200, maxLength: 512 });
-const isUsable = (value) => typeof value === 'string' && value.trim() !== '';
-
/**
* A stored alias map with unusable entries dropped.
*
@@ -46,7 +45,7 @@ const isUsable = (value) => typeof value === 'string' && value.trim() !== '';
*/
export const sanitizeModelAliases = (aliases) => Object.fromEntries(
Object.entries(aliases && typeof aliases === 'object' ? aliases : {})
- .filter(([canonical, executable]) => isUsable(canonical) && isUsable(executable))
+ .filter(([canonical, executable]) => isNonBlankStr(canonical) && isNonBlankStr(executable))
.map(([canonical, executable]) => [canonical.trim(), executable.trim()]),
);
@@ -107,7 +106,7 @@ export function applyModelAliasPatch(current, patch) {
* @returns {string[]} canonical names, in the order the overrides were stored
*/
export function staleModelAliases(overrides, storedModels) {
- const stored = Array.isArray(storedModels) ? storedModels.filter(isUsable) : [];
+ const stored = Array.isArray(storedModels) ? storedModels.filter(isNonBlankStr) : [];
if (stored.length === 0) return [];
return Object.entries(sanitizeModelAliases(overrides))
.filter(([, executable]) => !stored.includes(executable))
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index 9ac0e9b54d..f6185107fc 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -30,6 +30,7 @@ import {
normalizeQuotaBurnTaskRef,
} from './quotaBurnTaskRef.js';
import { BIBLE_DESCRIBE_DEPTHS, BIBLE_DESCRIBE_SCOPES } from './universeBibleCompleteness.js';
+import { trimTo } from './textUtils.js';
/** Provider quota families a burn plan may target. Mirrors `providerUsage.js`'s card ids. */
export const QUOTA_BURN_FAMILIES = Object.freeze(['claude', 'codex', 'agy', 'grok']);
@@ -230,11 +231,8 @@ const clampDispatchCap = (value) => {
return num < 0 ? QUOTA_BURN_UNLIMITED_DISPATCHES : clampInt(BOUNDS.maxDispatchesPerWindow, num);
};
-const trimString = (value, max) =>
- (typeof value === 'string' ? value.trim().slice(0, max) : '');
-
const nullableString = (value, max) => {
- const trimmed = trimString(value, max);
+ const trimmed = trimTo(value, max);
return trimmed || null;
};
@@ -303,9 +301,9 @@ export function normalizeQuotaBurnJob(raw, index = 0) {
};
return {
- id: trimString(raw.id, BOUNDS.idLength.max) || `job-${index + 1}`,
+ id: trimTo(raw.id, BOUNDS.idLength.max) || `job-${index + 1}`,
enabled: raw.enabled !== false,
- label: trimString(raw.label, BOUNDS.labelLength.max),
+ label: trimTo(raw.label, BOUNDS.labelLength.max),
taskRef,
// Only a legacy step keeps a `jobType`; a reference step reports null so no
// reader can mistake a stale field for the step's identity.
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.js
index 2446e0b12d..4fef30c684 100644
--- a/server/lib/quotaBurnOrigin.js
+++ b/server/lib/quotaBurnOrigin.js
@@ -27,6 +27,7 @@
*/
import { isPlainObject, POLLUTING_KEYS } from './objects.js';
+import { trimTo } from './textUtils.js';
/**
* The `origin` a quota-burn on-demand request carries. Declared here rather
@@ -152,8 +153,7 @@ export function burnPlanOwnsTask(taskMetadata) {
}
export const burnPlanOwnsAgent = (agent) => Boolean(agent?.metadata?.taskQuotaBurnFamily) && !agent.metadata.taskQuotaBurnMaintenanceRunId;
-const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
-const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
+const nullable = (value, max = MAX_FIELD) => trimTo(value, max) || null;
const scalarParams = (raw) => {
if (!isPlainObject(raw)) return {};
@@ -197,8 +197,8 @@ const scalarParams = (raw) => {
*/
export function normalizeQuotaBurnProvenance(raw) {
if (!isPlainObject(raw)) return null;
- const family = trimmed(raw.family);
- const stepId = trimmed(raw.stepId);
+ const family = trimTo(raw.family, MAX_FIELD);
+ const stepId = trimTo(raw.stepId, MAX_FIELD);
if (!family || !stepId) return null;
const limitingResetAt = Number(raw.limitingResetAt);
const overrides = isPlainObject(raw.overrides) ? raw.overrides : {};
@@ -245,7 +245,7 @@ export function onDemandRequestMetadata(request) {
const burn = request?.origin === QUOTA_BURN_REQUEST_ORIGIN
? normalizeQuotaBurnProvenance(request.burn)
: null;
- const requestId = trimmed(request?.id, 128);
+ const requestId = trimTo(request?.id, 128);
return {
onDemand: true,
onDemandOrigin: nullable(request?.origin),
diff --git a/server/lib/quotaBurnTaskRef.js b/server/lib/quotaBurnTaskRef.js
index 27541b60e5..3177926bff 100644
--- a/server/lib/quotaBurnTaskRef.js
+++ b/server/lib/quotaBurnTaskRef.js
@@ -35,6 +35,7 @@
import { isPlainObject, POLLUTING_KEYS } from './objects.js';
import { requiresInstallWideTarget, requiresManagedAppTarget } from './taskTargetScope.js';
+import { trimTo } from './textUtils.js';
/** The two things a burn step may point at. */
export const QUOTA_BURN_TASK_REF_KIND = Object.freeze({
@@ -78,8 +79,7 @@ export const QUOTA_BURN_UNAVAILABLE = Object.freeze({
const MAX_REF_FIELD = 64;
-const trimmed = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
-const nullable = (value, max) => trimmed(value, max) || null;
+const nullable = (value, max) => trimTo(value, max) || null;
/**
* Normalize a stored/submitted task reference. Returns `null` when the payload
@@ -94,12 +94,12 @@ const nullable = (value, max) => trimmed(value, max) || null;
export function normalizeQuotaBurnTaskRef(raw) {
if (!isPlainObject(raw)) return null;
if (raw.kind === QUOTA_BURN_TASK_REF_KIND.BUILTIN) {
- const taskType = trimmed(raw.taskType, MAX_REF_FIELD);
+ const taskType = trimTo(raw.taskType, MAX_REF_FIELD);
if (!taskType) return null;
return { kind: QUOTA_BURN_TASK_REF_KIND.BUILTIN, taskType, appId: nullable(raw.appId, MAX_REF_FIELD) };
}
if (raw.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM) {
- const jobId = trimmed(raw.jobId, MAX_REF_FIELD);
+ const jobId = trimTo(raw.jobId, MAX_REF_FIELD);
if (!jobId) return null;
return { kind: QUOTA_BURN_TASK_REF_KIND.CUSTOM, jobId };
}
diff --git a/server/lib/renderSlot.js b/server/lib/renderSlot.js
index 2912ec60d0..d9a4b4c1a0 100644
--- a/server/lib/renderSlot.js
+++ b/server/lib/renderSlot.js
@@ -16,8 +16,7 @@
* storyArc.js (season cover, backCover slots) without circular imports.
*/
-import { isStr, trimTo } from './storyBible.js';
-
+import { isStr, trimTo } from './textUtils.js';
export const COVER_SCRIPT_MAX = 8000;
export const COVER_PROMPT_MAX = 16_000;
export const RENDER_FILENAME_MAX = 500;
diff --git a/server/lib/roundsValidation.js b/server/lib/roundsValidation.js
index 9e0f8d89f2..198838f7a6 100644
--- a/server/lib/roundsValidation.js
+++ b/server/lib/roundsValidation.js
@@ -16,6 +16,7 @@
*/
import { randomUUID } from 'crypto';
+import { trimTo } from './textUtils.js';
// --- Shape bounds (shared with routes/rounds.js#roundInputSchema) -------------
export const TITLE_MAX_LENGTH = 200;
@@ -59,10 +60,6 @@ export const PROGRESS_SCOPES_MAX = 80; // distinct training scopes tracked
// poison the persisted array).
export const RECORDING_GRADES = ['in-tune', 'close', 'off', 'missed', 'pending'];
-// Trim a string field, returning '' for non-strings. Mirrors the
-// absent-vs-empty rule in AGENTS.md: callers decide whether '' clears.
-const trimField = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
// Clamp an integer tempo into the supported band; null when unparseable so a
// song without a tempo stays distinct from one pinned to a bound.
const sanitizeTempo = (v) => {
@@ -74,11 +71,11 @@ const sanitizeTempo = (v) => {
// id when blank so a section card is never headerless. Drops shapeless entries.
const sanitizeSection = (s) => {
if (!s || typeof s !== 'object') return null;
- const label = trimField(s.label, LABEL_MAX_LENGTH);
- const lyrics = trimField(s.lyrics, FIELD_MAX_LENGTH);
+ const label = trimTo(s.label, LABEL_MAX_LENGTH);
+ const lyrics = trimTo(s.lyrics, FIELD_MAX_LENGTH);
if (!label && !lyrics) return null;
return {
- id: trimField(s.id, ID_MAX_LENGTH) || `sec-${randomUUID().slice(0, 8)}`,
+ id: trimTo(s.id, ID_MAX_LENGTH) || `sec-${randomUUID().slice(0, 8)}`,
label: label || 'Section',
lyrics,
};
@@ -88,12 +85,12 @@ const sanitizeSection = (s) => {
// references a songCraft VOICE_LAYERS entry when known but is free-text-safe.
const sanitizeLayer = (l) => {
if (!l || typeof l !== 'object') return null;
- const label = trimField(l.label, LABEL_MAX_LENGTH);
- const part = trimField(l.part, PART_MAX_LENGTH);
- const notes = trimField(l.notes, FIELD_MAX_LENGTH);
+ const label = trimTo(l.label, LABEL_MAX_LENGTH);
+ const part = trimTo(l.part, PART_MAX_LENGTH);
+ const notes = trimTo(l.notes, FIELD_MAX_LENGTH);
if (!label && !part && !notes) return null;
return {
- id: trimField(l.id, ID_MAX_LENGTH) || `layer-${randomUUID().slice(0, 8)}`,
+ id: trimTo(l.id, ID_MAX_LENGTH) || `layer-${randomUUID().slice(0, 8)}`,
label: label || 'Layer',
part,
notes,
@@ -132,7 +129,7 @@ const sanitizeAccuracy = (a) => {
if (!a || typeof a !== 'object') return null;
const counts = a.counts && typeof a.counts === 'object' ? a.counts : {};
const perNote = (Array.isArray(a.perNote) ? a.perNote : [])
- .map((g) => trimField(g, LABEL_MAX_LENGTH))
+ .map((g) => trimTo(g, LABEL_MAX_LENGTH))
.filter((g) => RECORDING_GRADES.includes(g))
.slice(0, PER_NOTE_GRADES_MAX);
const clampPercent = finiteOrNull(a.percentInTune);
@@ -180,7 +177,7 @@ const sanitizeProgress = (p) => {
let scopeCount = 0;
for (const [scope, attempts] of Object.entries(rawHistory)) {
if (scopeCount >= PROGRESS_SCOPES_MAX) break;
- const key = trimField(scope, ID_MAX_LENGTH);
+ const key = trimTo(scope, ID_MAX_LENGTH);
// Skip empty keys and the prototype-pollution-prone keys — a section id is
// always `sec-N` (or the `__whole__` sentinel), never one of these, so a
// hand-edited `__proto__`/`constructor` scope is a malformed file, not data.
@@ -207,16 +204,16 @@ const sanitizeProgress = (p) => {
// when there's analysis to keep, so a pre-feature record reads back unchanged.
const sanitizeRecording = (r) => {
if (!r || typeof r !== 'object') return null;
- const filename = trimField(r.filename, URL_MAX_LENGTH);
+ const filename = trimTo(r.filename, URL_MAX_LENGTH);
if (!filename) return null;
const durationMs = typeof r.durationMs === 'number' && Number.isFinite(r.durationMs)
? Math.max(0, Math.round(r.durationMs)) : 0;
const peak = typeof r.peak === 'number' && Number.isFinite(r.peak)
? Math.max(0, Math.min(1, r.peak)) : 0;
const rec = {
- id: trimField(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,
- layerId: trimField(r.layerId, ID_MAX_LENGTH),
- label: trimField(r.label, LABEL_MAX_LENGTH),
+ id: trimTo(r.id, ID_MAX_LENGTH) || `rec-${randomUUID().slice(0, 8)}`,
+ layerId: trimTo(r.layerId, ID_MAX_LENGTH),
+ label: trimTo(r.label, LABEL_MAX_LENGTH),
filename,
durationMs,
peak,
@@ -257,7 +254,7 @@ const sanitizeRefSegment = (s) => {
const endMs = Math.max(0, Math.round(endRaw));
if (endMs <= startMs) return null;
const seg = {
- layerId: trimField(s.layerId, ID_MAX_LENGTH),
+ layerId: trimTo(s.layerId, ID_MAX_LENGTH),
startMs,
endMs,
};
@@ -287,18 +284,18 @@ const sanitizeRefSegment = (s) => {
// no migration).
const sanitizeReference = (r) => {
if (!r || typeof r !== 'object') return null;
- const url = trimField(r.url, URL_MAX_LENGTH);
+ const url = trimTo(r.url, URL_MAX_LENGTH);
// Require an http(s) scheme — defense-in-depth so a hand-edited file or a
// non-PortOS writer can't persist a javascript:/data: URL that a renderer
// might trust (mirrors the client's isHttpUrl guard).
if (!/^https?:\/\//i.test(url)) return null;
const ref = {
- id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,
+ id: trimTo(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,
url,
- label: trimField(r.label, LABEL_MAX_LENGTH),
- note: trimField(r.note, FIELD_MAX_LENGTH),
+ label: trimTo(r.label, LABEL_MAX_LENGTH),
+ note: trimTo(r.note, FIELD_MAX_LENGTH),
};
- const audioFilename = trimField(r.audioFilename, URL_MAX_LENGTH);
+ const audioFilename = trimTo(r.audioFilename, URL_MAX_LENGTH);
if (audioFilename) {
ref.audioFilename = audioFilename;
// Segments are time ranges INTO the attached audio — meaningless without
@@ -311,7 +308,7 @@ const sanitizeReference = (r) => {
// pointer) — same structural invariant as segments: derived from this
// audio, so removing the audio drops it and a stale transcription can't
// resurrect against a later, different recording.
- const midiFilename = trimField(r.midiFilename, URL_MAX_LENGTH);
+ const midiFilename = trimTo(r.midiFilename, URL_MAX_LENGTH);
if (midiFilename) ref.midiFilename = midiFilename;
}
return ref;
@@ -326,12 +323,12 @@ const sanitizeReference = (r) => {
// never headerless.
const sanitizeScorePart = (p) => {
if (!p || typeof p !== 'object') return null;
- const score = trimField(p.score, SCORE_MAX_LENGTH);
+ const score = trimTo(p.score, SCORE_MAX_LENGTH);
if (!score) return null;
- const label = trimField(p.label, LABEL_MAX_LENGTH);
- const role = trimField(p.role, ID_MAX_LENGTH);
+ const label = trimTo(p.label, LABEL_MAX_LENGTH);
+ const role = trimTo(p.role, ID_MAX_LENGTH);
return {
- id: trimField(p.id, ID_MAX_LENGTH) || `part-${randomUUID().slice(0, 8)}`,
+ id: trimTo(p.id, ID_MAX_LENGTH) || `part-${randomUUID().slice(0, 8)}`,
label: label || 'Part',
role,
score,
@@ -352,7 +349,7 @@ const sanitizeList = (arr, fn, max) =>
const sanitizePartnerIds = (arr, selfId) => {
const seen = new Set();
return (Array.isArray(arr) ? arr : [])
- .map((v) => trimField(v, ID_MAX_LENGTH))
+ .map((v) => trimTo(v, ID_MAX_LENGTH))
.filter((id) => id && id !== selfId && !seen.has(id) && seen.add(id))
.slice(0, PARTNERS_MAX);
};
@@ -368,26 +365,26 @@ const NO_BUILTIN_IDS = new Set();
// so the flag can't be lost on edit or spoofed on a hand-edited custom song.
export const sanitizeRound = (raw, builtinIds = NO_BUILTIN_IDS) => {
if (!raw || typeof raw !== 'object') return null;
- const id = trimField(raw.id, ID_MAX_LENGTH);
+ const id = trimTo(raw.id, ID_MAX_LENGTH);
if (!id) return null;
const song = {
id,
- title: trimField(raw.title, TITLE_MAX_LENGTH) || 'Untitled round',
- artist: trimField(raw.artist, ARTIST_MAX_LENGTH),
- key: trimField(raw.key, KEY_MAX_LENGTH),
+ title: trimTo(raw.title, TITLE_MAX_LENGTH) || 'Untitled round',
+ artist: trimTo(raw.artist, ARTIST_MAX_LENGTH),
+ key: trimTo(raw.key, KEY_MAX_LENGTH),
tempo: sanitizeTempo(raw.tempo),
- rhythmShapeId: trimField(raw.rhythmShapeId, ID_MAX_LENGTH),
- notation: trimField(raw.notation, FIELD_MAX_LENGTH),
+ rhythmShapeId: trimTo(raw.rhythmShapeId, ID_MAX_LENGTH),
+ notation: trimTo(raw.notation, FIELD_MAX_LENGTH),
// Sheet-music notation in the PortOS lead-sheet DSL (client/src/lib/
// scoreNotation.js). A bounded free-text string — the client parses + renders
// it; the server only length-caps it, so a newer/older DSL revision can't 400.
- score: trimField(raw.score, SCORE_MAX_LENGTH),
+ score: trimTo(raw.score, SCORE_MAX_LENGTH),
// Harmony variations of the base `score` (bass, mid/high harmonies …), each
// its own lead-sheet DSL. Absent ⇒ [] — purely additive, so an older peer or
// a pre-feature record reads back as a song with no parts (no migration of
// the on-disk shape needed; the field simply appears when the user adds one).
scoreParts: sanitizeList(raw.scoreParts, sanitizeScorePart, SCORE_PARTS_MAX),
- notes: trimField(raw.notes, FIELD_MAX_LENGTH),
+ notes: trimTo(raw.notes, FIELD_MAX_LENGTH),
learned: raw.learned === true,
sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),
layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),
diff --git a/server/lib/sharingOrigin.js b/server/lib/sharingOrigin.js
index 0eb6333260..ca5610f38e 100644
--- a/server/lib/sharingOrigin.js
+++ b/server/lib/sharingOrigin.js
@@ -11,8 +11,7 @@
* full history.
*/
-import { isStr, trimTo } from './storyBible.js';
-
+import { isStr, trimTo } from './textUtils.js';
export const ORIGIN_BUCKET_ID_MAX = 64;
export const ORIGIN_BUCKET_NAME_MAX = 120;
export const ORIGIN_SOURCE_MAX = 120;
diff --git a/server/lib/storyArc.js b/server/lib/storyArc.js
index a801a497f6..a183df8267 100644
--- a/server/lib/storyArc.js
+++ b/server/lib/storyArc.js
@@ -17,9 +17,9 @@
*/
import { randomUUID } from 'crypto';
-import { isStr, trimTo, trimToClause } from './storyBible.js';
import { sanitizeCoverLike } from './renderSlot.js';
import { ARC_LIMITS } from './storyArcLimits.js';
+import { isStr, trimTo, trimToClause } from './textUtils.js';
export { ARC_LIMITS } from './storyArcLimits.js';
export const ARC_STATUSES = Object.freeze(['draft', 'verified']);
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 157515ac39..bd545b0790 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -12,9 +12,9 @@
import { randomUUID } from 'crypto';
import { normalizeSlugline } from './scenePrompt.js';
import { PATHS, resolveImageRef } from './fileUtils.js';
-import { isPlainObject } from './objects.js';
+import { isPlainObject, isEmptyScalar } from './objects.js';
import { shortCanonPrimaryField } from './canonPrompt.js';
-import { trimTo, trimToClause } from './textUtils.js';
+import { isStr, trimTo, trimToClause } from './textUtils.js';
import { BIBLE_LIMITS } from './bibleLimits.js';
import {
CHARACTER_ARC_TYPES,
@@ -28,12 +28,6 @@ import { sanitizeCharacterEvolution } from './characterEvolution.js';
// Re-export so callers (writers-room domain files) can import a single
// canonical normalizer when they need to match places by slugline.
export { normalizeSlugline };
-// `trimTo` and the boundary-aware `trimToClause` both live in the
-// dependency-free `textUtils.js` so the pure story-model leaves the browser
-// bundle shares (`characterFramework.js`, `characterEvolution.js`) can cap
-// prose without importing this module's `crypto` / `fileUtils`. Re-exported
-// here because every existing sanitizer reaches for them through storyBible.
-export { trimTo, trimToClause };
// The canon field caps live in a pure leaf (`bibleLimits.js`) so the browser
// bundle and `catalogTypes.js` can read them without this module's `crypto` /
@@ -202,11 +196,6 @@ const DEFAULT_ID_PREFIX = Object.freeze({
object: 'obj-',
});
-// Shared string predicate retained here for the story-bible domain. `trimTo`
-// and `trimToClause` now live in dependency-free textUtils and are re-exported
-// above so existing story-bible consumers keep the same public contract.
-export const isStr = (v) => typeof v === 'string';
-
// Walk a raw array through a per-item sanitizer, dropping rejected entries
// (falsy return from `sanitizer`) and capping the output at `cap`. Three
// near-identical loops elsewhere in this file (cleanStringArray, the wardrobe
@@ -227,13 +216,6 @@ const sanitizeListWith = (raw, sanitizer, cap) => {
const cleanStringArray = (raw, itemMax, listMax) =>
sanitizeListWith(raw, (v) => trimTo(v, itemMax), listMax);
-export const isBlank = (v) => {
- if (v == null) return true;
- if (Array.isArray(v)) return v.length === 0;
- if (isStr(v)) return v.trim() === '';
- return false;
-};
-
export const normalizeBibleName = (name) => String(name || '').trim().toLowerCase();
/**
@@ -1528,7 +1510,7 @@ export function mergeExtractedBible(existing, incoming, kind, {
continue;
}
for (const field of cfg.userEditable) {
- if (isBlank(found[field]) && !isBlank(sane[field])) {
+ if (isEmptyScalar(found[field]) && !isEmptyScalar(sane[field])) {
found[field] = sane[field];
}
}
@@ -1537,7 +1519,7 @@ export function mergeExtractedBible(existing, incoming, kind, {
// resolves to this canonical record instead of inserting a duplicate.
let reindex = false;
for (const { field } of cfg.keyFields) {
- if (isBlank(found[field]) && !isBlank(sane[field])) {
+ if (isEmptyScalar(found[field]) && !isEmptyScalar(sane[field])) {
found[field] = sane[field];
reindex = true;
}
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index 068e37d897..831d2cded5 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -22,7 +22,6 @@ const {
sanitizeObject,
sanitizeBibleList,
mergeExtractedBible,
- isBlank,
normalizeBibleName,
normalizeSlugline,
findBibleEntryByName,
@@ -1375,14 +1374,6 @@ describe('storyBible — mergeExtractedBible (objects)', () => {
});
describe('storyBible — helpers', () => {
- it('isBlank covers null, empty array, whitespace string', () => {
- expect(isBlank(null)).toBe(true);
- expect(isBlank(' ')).toBe(true);
- expect(isBlank([])).toBe(true);
- expect(isBlank('x')).toBe(false);
- expect(isBlank(['x'])).toBe(false);
- });
-
it('normalizeBibleName lowercases + trims', () => {
expect(normalizeBibleName(' Aria Reyes ')).toBe('aria reyes');
expect(normalizeBibleName(null)).toBe('');
diff --git a/server/lib/storyboardScenes.js b/server/lib/storyboardScenes.js
index 24beff74b2..17b13e9fcd 100644
--- a/server/lib/storyboardScenes.js
+++ b/server/lib/storyboardScenes.js
@@ -35,10 +35,9 @@
* mis-target this module exists to prevent.
*/
+import { isNonBlankStr } from './textUtils.js';
const ID_MAX = 80;
-const isNonEmptyStr = (v) => typeof v === 'string' && v.trim().length > 0;
-
export const sceneIdForIndex = (index) => `scene-${String(index + 1).padStart(2, '0')}`;
export const shotIdForIndex = (index) => `shot-${String(index + 1).padStart(2, '0')}`;
@@ -66,13 +65,13 @@ const stampIds = (list, idFor) => {
// a duplicate is about to be replaced, so it must not reserve its own id.
const taken = new Set();
for (const rec of list) {
- if (rec && typeof rec === 'object' && isNonEmptyStr(rec.id)) taken.add(rec.id);
+ if (rec && typeof rec === 'object' && isNonBlankStr(rec.id)) taken.add(rec.id);
}
const seen = new Set();
let changed = false;
const out = list.map((rec, i) => {
if (!rec || typeof rec !== 'object' || Array.isArray(rec)) return rec;
- if (isNonEmptyStr(rec.id) && !seen.has(rec.id)) {
+ if (isNonBlankStr(rec.id) && !seen.has(rec.id)) {
seen.add(rec.id);
return rec;
}
@@ -129,7 +128,7 @@ export function resolveStoryboardTarget(list, { id = null, index = null } = {})
// "index 0" (AGENTS.md sentinel discipline), so coerce only real numerics.
const idx = index === null || index === undefined || index === '' ? NaN : Number(index);
const hasIndex = Number.isInteger(idx) && idx >= 0;
- if (isNonEmptyStr(id)) {
+ if (isNonBlankStr(id)) {
if (hasIndex && arr[idx] && arr[idx].id === id) {
return { index: idx, record: arr[idx], matchedBy: 'id', stale: false };
}
diff --git a/server/lib/styleGuide.js b/server/lib/styleGuide.js
index e9f8b726a3..97caf0452b 100644
--- a/server/lib/styleGuide.js
+++ b/server/lib/styleGuide.js
@@ -20,8 +20,7 @@
* all-empty guide collapses to `null` ("no style guide yet").
*/
-import { isStr, trimTo } from './storyBible.js';
-
+import { isStr, trimTo } from './textUtils.js';
export const STYLE_GUIDE_LIMITS = Object.freeze({
TONE_MAX: 60,
TONES_MAX: 20,
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 3d23629b7c..d6b93658f4 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -3,21 +3,17 @@ import {
IDENTITY_ASSET_ROLES,
VOICE_CANON_SOURCE_POLICIES,
} from './storyBible.js';
+import { isNonBlankStr, trimTo } from './textUtils.js';
-const isNonEmptyStr = (v) => typeof v === 'string' && v.trim().length > 0;
const IDENTITY_ASSET_ROLE_SET = new Set(IDENTITY_ASSET_ROLES);
const VOICE_CANON_SOURCE_POLICY_SET = new Set(VOICE_CANON_SOURCE_POLICIES);
-const boundedWireString = (value, max) => (
- typeof value === 'string' ? value.trim().slice(0, max) : ''
-);
-
const portableStringArray = (value, itemMax, listMax) => {
if (!Array.isArray(value)) return [];
const seen = new Set();
const result = [];
for (const item of value) {
- const text = boundedWireString(item, itemMax);
+ const text = trimTo(item, itemMax);
if (!text || seen.has(text)) continue;
seen.add(text);
result.push(text);
@@ -40,7 +36,7 @@ const portableStringArray = (value, itemMax, listMax) => {
*/
export function sanitizeSoftDeleteFields(raw) {
const deleted = raw?.deleted === true;
- const deletedAt = deleted && isNonEmptyStr(raw?.deletedAt) ? raw.deletedAt : null;
+ const deletedAt = deleted && isNonBlankStr(raw?.deletedAt) ? raw.deletedAt : null;
return { deleted, deletedAt };
}
@@ -77,8 +73,8 @@ function stripUniverseCharacterLocalProductionFields(record) {
version: Number.isInteger(voiceCanon.version) && voiceCanon.version > 0
? Math.min(voiceCanon.version, BIBLE_LIMITS.VOICE_CANON_VERSION_MAX)
: 1,
- description: boundedWireString(voiceCanon.description, BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX),
- defaultDelivery: boundedWireString(voiceCanon.defaultDelivery, BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX),
+ description: trimTo(voiceCanon.description, BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX),
+ defaultDelivery: trimTo(voiceCanon.defaultDelivery, BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX),
emotionalRange: portableStringArray(
voiceCanon.emotionalRange,
BIBLE_LIMITS.VOICE_CANON_RANGE_ITEM_MAX,
@@ -92,8 +88,8 @@ function stripUniverseCharacterLocalProductionFields(record) {
pronunciations: (Array.isArray(voiceCanon.pronunciations) ? voiceCanon.pronunciations : [])
.flatMap((item) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) return [];
- const term = boundedWireString(item.term, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX);
- const pronunciation = boundedWireString(
+ const term = trimTo(item.term, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX);
+ const pronunciation = trimTo(
item.pronunciation,
BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_VALUE_MAX,
);
@@ -182,7 +178,7 @@ export function sanitizeRecordForWire(kind, record) {
// the snapshot checksum reflects content the receiver can never apply —
// permanent mismatch + churn until both sides clean up the corrupt entries.
if (!record || typeof record !== 'object' || Array.isArray(record)) return null;
- if (!isNonEmptyStr(record.id)) return null;
+ if (!isNonBlankStr(record.id)) return null;
// Ephemeral records are local-only — scratch universes/series/issues the
// user (or a test fixture) explicitly marks "don't sync to peers." Filter
// here so BOTH transports (60s snapshot + per-record push) skip them
@@ -243,7 +239,7 @@ export function sanitizeRecordForWire(kind, record) {
...(record.updatedAt ? { updatedAt: record.updatedAt } : {}),
};
if (kind === 'universe' || kind === 'series') {
- minimized.name = isNonEmptyStr(record.name) ? record.name : '_';
+ minimized.name = isNonBlankStr(record.name) ? record.name : '_';
} else if (kind === 'issue') {
// seriesId is REQUIRED by sanitizeIssue on the receiver. Without
// a placeholder, an ephemeral issue tombstone whose on-disk
@@ -251,8 +247,8 @@ export function sanitizeRecordForWire(kind, record) {
// partial-delete race) would be silently dropped on receive and
// the tombstone would never land — peer keeps the live issue
// copy forever.
- minimized.seriesId = isNonEmptyStr(record.seriesId) ? record.seriesId : '_';
- minimized.title = isNonEmptyStr(record.title) ? record.title : '_';
+ minimized.seriesId = isNonBlankStr(record.seriesId) ? record.seriesId : '_';
+ minimized.title = isNonBlankStr(record.title) ? record.title : '_';
}
return { ...minimized, ...sanitizeSoftDeleteFields(record) };
}
diff --git a/server/lib/textUtils.js b/server/lib/textUtils.js
index b939d700e7..72cbd3304d 100644
--- a/server/lib/textUtils.js
+++ b/server/lib/textUtils.js
@@ -7,6 +7,32 @@
// server-side home. `client/src/lib/textUtils.js` re-exports `escapeRegExp` from
// here, so keep this module pure: no Node built-in, nothing outside `server/lib`.
+/**
+ * The one string-type predicate under `server/` (and, via the client mirror, the
+ * browser bundle). Every sanitizer used to carry its own copy — 16 of them under
+ * this exact body, the rest under `isString` / `hasText` / `isNonEmptyStr`
+ * with drifting semantics — because the only exported one lived in
+ * `storyBible.js` behind `crypto` / `fileUtils`. The "no private string
+ * predicate or bounder" guard in `textUtils.test.js` fails the suite when a
+ * copy reappears (#6837).
+ *
+ * @param {unknown} v
+ * @returns {v is string}
+ */
+export const isStr = (v) => typeof v === 'string';
+
+/**
+ * `isStr` plus "has visible content": a string whose `trim()` is non-empty.
+ * This is the predicate for ids, keys, hosts, model names, and prose fields
+ * where a whitespace-only value is already invalid, so it also replaces the
+ * looser `v.length > 0` / `!!v` copies (which accepted `' '`). It does not
+ * trim the value it accepts; callers that store the string still `trim()`.
+ *
+ * @param {unknown} v
+ * @returns {v is string}
+ */
+export const isNonBlankStr = (v) => typeof v === 'string' && v.trim().length > 0;
+
/**
* Count whitespace-separated words in a string.
*
diff --git a/server/lib/textUtils.test.js b/server/lib/textUtils.test.js
index 296980f3ef..e9c4e00cea 100644
--- a/server/lib/textUtils.test.js
+++ b/server/lib/textUtils.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { clampToCharLimit, countWords, escapeRegExp, trimTo, trimToClause } from './textUtils.js';
+import { clampToCharLimit, countWords, escapeRegExp, isNonBlankStr, isStr, trimTo, trimToClause } from './textUtils.js';
import { collectClientSources, collectServerSources, readClientSource, readServerSource } from './testHelper.js';
describe('countWords', () => {
@@ -37,6 +37,26 @@ describe('trimTo', () => {
});
});
+describe('isStr / isNonBlankStr', () => {
+ it('isStr is the bare type check — an empty string is a string', () => {
+ expect(isStr('')).toBe(true);
+ expect(isStr(' ')).toBe(true);
+ expect(isStr(new String('boxed'))).toBe(false);
+ expect(isStr(null)).toBe(false);
+ expect(isStr(42)).toBe(false);
+ });
+
+ it('isNonBlankStr rejects blank and non-string values without trimming what it accepts', () => {
+ expect(isNonBlankStr('x')).toBe(true);
+ expect(isNonBlankStr(' padded ')).toBe(true);
+ expect(isNonBlankStr('')).toBe(false);
+ expect(isNonBlankStr(' ')).toBe(false);
+ expect(isNonBlankStr('\n\t')).toBe(false);
+ expect(isNonBlankStr(null)).toBe(false);
+ expect(isNonBlankStr(0)).toBe(false);
+ });
+});
+
describe('clampToCharLimit', () => {
it('passes text through when there is no cap or it already fits', () => {
expect(clampToCharLimit('a neon alley', 800)).toEqual({ text: 'a neon alley', truncated: false });
@@ -240,6 +260,95 @@ describe('no private countWords', () => {
});
});
+// String predicates and `trimTo`-shaped bounders had the same history as the
+// RegExp escape above. The only exported predicate lived in `storyBible.js`
+// behind `crypto` / `fileUtils`, so 73 sanitizers grew a private copy: 17
+// spelling the bare type check, 28 a non-empty / non-blank variant — under
+// `isStr`, `hasText`, `isText`, `isUsable`, `isNonEmptyStr`, …, with half of
+// FableLoom's `isStr` accepting `''` and the other half rejecting it — and 26
+// re-rolling `trimTo` as `clampStr` / `trimString` / `str` / `text` / `trim`.
+// #6837 moved every one onto `isStr` / `isNonBlankStr` / `trimTo` here; this
+// guard is what keeps them here.
+//
+// It keys on the declared BODY, never the identifier, and every idiom is
+// anchored on the statement's terminating `;` (or a function's closing brace).
+// That anchoring is what leaves a DOMAIN predicate alone: one whose first line
+// merely ends in `typeof x === 'string'` and continues with `&& RE.test(x)`,
+// or one that adds any clause at all, never matches — only the pure generic
+// bodies do. A one-line alias (`const hasText = isNonBlankStr;`) has no
+// `typeof` and passes; a normalizer without `.slice(` is not a bounder.
+const GENERIC_STRING_TAIL = String.raw`(?:\s*&&\s*(?:!!\2|\2(?:\.trim\(\))?\.length\s*>\s*0|\2\.trim\(\)\s*!==\s*''))?`;
+const STRING_HELPER_IDIOMS = [
+ // const isX = (v) => typeof v === 'string'[ && <generic non-empty / non-blank tail>];
+ new RegExp(String.raw`^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*\(?\s*(\w+)\s*\)?\s*=>\s*typeof\s+\2\s*===\s*'string'${GENERIC_STRING_TAIL}\s*;[ \t]*$`, 'gm'),
+ // function isX(v) { return typeof v === 'string'[ && <tail>]; }
+ new RegExp(String.raw`^[ \t]*(?:export\s+)?function\s+(\w+)\s*\(\s*(\w+)\s*\)\s*\{\s*return\s+typeof\s+\2\s*===\s*'string'${GENERIC_STRING_TAIL}\s*;?\s*\}`, 'gm'),
+ // const trimX = (v, max[ = DEFAULT]) => [(]typeof v === 'string' ? v.trim().slice(0, max) : ''[)]; (isStr(v) ? … as well)
+ new RegExp(String.raw`^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*\(\s*(\w+)\s*,\s*(\w+)(?:\s*=\s*[^,)]+)?\s*\)\s*=>\s*\(?\s*(?:typeof\s+\2\s*===\s*'string'|isStr\(\s*\2\s*\))\s*\?\s*\2\.trim\(\)\.slice\(\s*0\s*,\s*\3\s*\)\s*:\s*''\s*\)?\s*;[ \t]*$`, 'gm'),
+];
+
+// Total declarations across all three idioms (a file carrying a predicate AND a
+// bounder counts both) — unlike `idiomCount` above, which takes the max of
+// alternative spellings of ONE idiom and drops the `m` flag these rely on.
+const stringHelperDeclarationCount = (source) => STRING_HELPER_IDIOMS
+ .reduce((sum, idiom) => sum + (source.match(new RegExp(idiom.source, idiom.flags))?.length ?? 0), 0);
+
+describe('no private string predicate or bounder', () => {
+ it('leaves lib/textUtils.js as the only string predicate or bounder under server/', () => {
+ const offenders = collectServerSources()
+ .filter((rel) => rel !== 'lib/textUtils.js')
+ .filter((rel) => stringHelperDeclarationCount(readServerSource(rel)) > 0);
+ expect(
+ offenders,
+ `these re-declare a string predicate or a trimTo-shaped bounder — import isStr / isNonBlankStr / trimTo from lib/textUtils.js instead: ${offenders.join(', ')}`
+ ).toEqual([]);
+ });
+
+ // The client mirror re-exports the predicates, so nothing over there needs one.
+ it('leaves no string predicate or bounder anywhere under client/src/', () => {
+ const offenders = collectClientSources()
+ .filter((rel) => stringHelperDeclarationCount(readClientSource(rel)) > 0);
+ expect(
+ offenders,
+ `these re-declare a string predicate or a trimTo-shaped bounder — import isStr / isNonBlankStr / trimTo from lib/textUtils instead: ${offenders.join(', ')}`
+ ).toEqual([]);
+ });
+
+ it('detects a re-rolled copy under any of its spellings, and not a domain predicate', () => {
+ // Positive control on the owner: isStr, isNonBlankStr, and the two-line trimTo.
+ expect(stringHelperDeclarationCount(readServerSource('lib/textUtils.js'))).toBe(3);
+ expect(collectClientSources().length).toBeGreaterThan(100);
+
+ const fires = [
+ "const isStr = (v) => typeof v === 'string';",
+ "export const isString = value => typeof value === 'string';",
+ "const isNonEmptyString = (value) => typeof value === 'string' && !!value;",
+ "const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;",
+ " const hasText = (value) => typeof value === 'string' && value.trim().length > 0;",
+ "const filled = (v) => typeof v === 'string' && v.trim() !== '';",
+ "export function isNonEmptyString(value) {\n return typeof value === 'string' && value.trim().length > 0;\n}",
+ "const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');",
+ "const trimString = (value, max = MAX_PROMPT_LEN) =>\n typeof value === 'string' ? value.trim().slice(0, max) : '';",
+ "const asBoundedString = (value, max) => (\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n);",
+ "const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');",
+ ];
+ for (const copy of fires) expect(stringHelperDeclarationCount(copy), copy).toBe(1);
+
+ const passes = [
+ "const isHexHash = (v) => typeof v === 'string' && HEX_64.test(v);",
+ "const isInstanceId = (id) => typeof id === 'string' && id.length > 0 && id.length <= MAX_ID_LEN;",
+ "const validLibraryPath = (path) => typeof path === 'string'\n && path.startsWith('/') && !path.includes('..');",
+ "const hasPrompt = (prompt) => typeof prompt === 'string' && prompt.trim() !== '' && prompt !== '(no prompt)';",
+ "const normalizeText = (text) => typeof text === 'string' ? text.trim() : '';",
+ "const normalizeTitle = (title) => typeof title === 'string' ? title.trim().slice(0, MAX_TITLE_LENGTH) : '';",
+ "const text = (value, max = 6000) => typeof value === 'string'\n ? value.length > max ? `${value.slice(0, max)}\\n[truncated]` : value : '';",
+ 'const hasText = isNonBlankStr;',
+ "const label = typeof name === 'string' ? name.trim().slice(0, 80) : '';",
+ ];
+ for (const source of passes) expect(stringHelperDeclarationCount(source), source).toBe(0);
+ });
+});
+
describe('trimToClause (boundary-aware prose cap)', () => {
it('returns text untouched when it fits', () => {
expect(trimToClause('A short logline.', 500)).toBe('A short logline.');
diff --git a/server/lib/universeBibleCompleteness.js b/server/lib/universeBibleCompleteness.js
index ba28a3b997..ec70f3ec8c 100644
--- a/server/lib/universeBibleCompleteness.js
+++ b/server/lib/universeBibleCompleteness.js
@@ -24,7 +24,8 @@
* scan, so the two are deliberately one list rather than two that agree today.
*/
-import { BIBLE_KEYS, isBlank, PSYCHOLOGY_DRIVE_AXES } from './storyBible.js';
+import { BIBLE_KEYS, PSYCHOLOGY_DRIVE_AXES } from './storyBible.js';
+import { isEmptyScalar } from './objects.js';
/** Depth vocabulary. `core` = renderable at all; `full` = the whole sheet. */
export const BIBLE_DESCRIBE_DEPTHS = Object.freeze(['core', 'full']);
@@ -122,7 +123,7 @@ const requiredFields = (kind, depth) => {
* Whether ONE field on an entry is still unfilled — the single blank predicate
* the completeness scan AND the expand merges both call, so the code that
* decides an entry needs work can't disagree with the code that does it.
- * `isBlank` (storyBible) carries the base string/array rule; the two exceptions
+ * `isEmptyScalar` (objects.js) carries the base string/array rule; the two exceptions
* below are what this wrapper adds.
*/
export function bibleFieldIsBlank(entry, field) {
@@ -130,7 +131,7 @@ export function bibleFieldIsBlank(entry, field) {
// 019 rewrites the legacy `description` alias forward but the read-side fallback
// stays, so a pre-migration entry must not read as blank here — it would be
// re-described on top of text it already has.
- if (field === 'physicalDescription') return isBlank(entry?.physicalDescription) && isBlank(entry?.description);
+ if (field === 'physicalDescription') return isEmptyScalar(entry?.physicalDescription) && isEmptyScalar(entry?.description);
// `sliders` is an always-present object whose axes are individually null until
// rated, so plain presence would report it filled the moment the sanitizer
// materialized it.
@@ -138,7 +139,7 @@ export function bibleFieldIsBlank(entry, field) {
// `psychology` is absent entirely until authored, and materializes all three
// drive slots the moment any leaf is filled — so it needs its own rule too.
if (field === 'psychology') return characterPsychologyIsBlank(entry?.psychology);
- return isBlank(entry?.[field]);
+ return isEmptyScalar(entry?.[field]);
}
/**
@@ -154,11 +155,11 @@ export function bibleFieldIsBlank(entry, field) {
export function characterPsychologyIsBlank(psychology) {
if (!psychology || typeof psychology !== 'object' || Array.isArray(psychology)) return true;
if (psychology.assessment === 'unknown' || psychology.assessment === 'not-applicable') {
- return isBlank(psychology.assessmentNote);
+ return isEmptyScalar(psychology.assessmentNote);
}
- if (isBlank(psychology.theoryOfControl)) return true;
- return PSYCHOLOGY_DRIVE_AXES.some((axis) => isBlank(psychology.drives?.[axis]?.desire)
- || isBlank(psychology.drives?.[axis]?.fear));
+ if (isEmptyScalar(psychology.theoryOfControl)) return true;
+ return PSYCHOLOGY_DRIVE_AXES.some((axis) => isEmptyScalar(psychology.drives?.[axis]?.desire)
+ || isEmptyScalar(psychology.drives?.[axis]?.fear));
}
/** Normalize an untrusted depth param to a known depth, defaulting to `full`. */
diff --git a/server/routes/peerSync.js b/server/routes/peerSync.js
index 23051ed0af..2187d9897e 100644
--- a/server/routes/peerSync.js
+++ b/server/routes/peerSync.js
@@ -15,7 +15,7 @@ import { isPlainObject } from '../lib/objects.js';
* (Express returns arrays for repeated keys; the guard prevents those from
* leaking into the filter).
* - DELETE /:id is forwarded straight to the service layer, which validates
- * it via the same `isNonEmptyStr` check used by every other id-keyed
+ * it via the same `isNonBlankStr` check used by every other id-keyed
* call (returns ERR_NOT_FOUND for missing, ERR_VALIDATION for malformed).
*
* Service errors carry an `ERR_*` code that maps to the HTTP status here;
diff --git a/server/services/albums/logic.js b/server/services/albums/logic.js
index 9ecd0fc33e..aa38293fdc 100644
--- a/server/services/albums/logic.js
+++ b/server/services/albums/logic.js
@@ -25,6 +25,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { localImageFilename } from '../../lib/localImageFilename.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export const ALBUM_ID_RE = /^album-[A-Za-z0-9-]{1,64}$/;
@@ -41,9 +42,6 @@ export const TRACK_ID_MAX = 80;
export const RELEASE_YEAR_MIN = 1850;
export const RELEASE_YEAR_MAX = 2200;
-const isStr = (v) => typeof v === 'string';
-const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
-
// Clamp an integer release year into the supported band; null when unparseable
// so an album without a year stays distinct from one pinned to a bound.
function sanitizeReleaseYear(v) {
diff --git a/server/services/artists/logic.js b/server/services/artists/logic.js
index d1c1eaa3cc..f8b1eb37dd 100644
--- a/server/services/artists/logic.js
+++ b/server/services/artists/logic.js
@@ -26,6 +26,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { localImageFilename } from '../../lib/localImageFilename.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export const ARTIST_ID_RE = /^artist-[A-Za-z0-9-]{1,64}$/;
@@ -37,9 +38,6 @@ export const PHYSICAL_DESCRIPTION_MAX = 2000;
export const PORTRAIT_STYLE_MAX = 2000;
export const PORTRAIT_IMAGE_URL_MAX = 1000;
-const isStr = (v) => typeof v === 'string';
-const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
-
/**
* Normalize a raw artist record into the canonical stored shape. Returns null
* for a non-object or a record without a usable id/name (mirrors the other
diff --git a/server/services/audioModels.js b/server/services/audioModels.js
index 0b6a5f755b..f858e61c96 100644
--- a/server/services/audioModels.js
+++ b/server/services/audioModels.js
@@ -25,26 +25,26 @@ import { join } from 'path';
import { readJSONFile, atomicWrite, ensureDir } from '../lib/fileUtils.js';
import { PATHS } from '../lib/fileUtils.js';
import { getEngine, ENGINES } from './pipeline/musicGen.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
const REGISTRY_FILE = join(PATHS.data, 'audio-models.json');
-const isStr = (v) => typeof v === 'string' && v.trim().length > 0;
// HF repo ids look like `org/name` (optionally with extra path segments). Keep
// the guard permissive but reject path-traversal / whitespace / control chars.
const REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._\/-]+$/;
export function isValidRepoId(repo) {
- return isStr(repo) && REPO_RE.test(repo.trim()) && !repo.includes('..');
+ return isNonBlankStr(repo) && REPO_RE.test(repo.trim()) && !repo.includes('..');
}
// One sanitized user-model entry, or null to drop. `id` defaults to the repo id
// (what the sidecar's --model wants); `name` defaults to the repo's basename.
function sanitizeUserModel(raw) {
if (!raw || typeof raw !== 'object') return null;
- const repo = isStr(raw.repo) ? raw.repo.trim() : '';
+ const repo = isNonBlankStr(raw.repo) ? raw.repo.trim() : '';
if (!isValidRepoId(repo)) return null;
- const id = isStr(raw.id) ? raw.id.trim() : repo;
- const name = isStr(raw.name) ? raw.name.trim().slice(0, 200) : repo.split('/').pop();
+ const id = isNonBlankStr(raw.id) ? raw.id.trim() : repo;
+ const name = isNonBlankStr(raw.name) ? raw.name.trim().slice(0, 200) : repo.split('/').pop();
return { id, repo, name };
}
diff --git a/server/services/authors/logic.js b/server/services/authors/logic.js
index 7301d22221..0a5ed1970b 100644
--- a/server/services/authors/logic.js
+++ b/server/services/authors/logic.js
@@ -26,6 +26,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { localImageFilename } from '../../lib/localImageFilename.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export const AUTHOR_ID_RE = /^auth-[A-Za-z0-9-]{1,64}$/;
@@ -36,9 +37,6 @@ export const PHYSICAL_DESCRIPTION_MAX = 2000;
export const HEADSHOT_STYLE_MAX = 2000;
export const HEADSHOT_IMAGE_URL_MAX = 1000;
-const isStr = (v) => typeof v === 'string';
-const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
-
/**
* Normalize a raw author record into the canonical stored shape. Returns null
* for a non-object or a record without a usable id/name (mirrors the other
diff --git a/server/services/brainParity.js b/server/services/brainParity.js
index ed472bc2e5..1376cc1279 100644
--- a/server/services/brainParity.js
+++ b/server/services/brainParity.js
@@ -44,6 +44,7 @@ import { peerFetch } from '../lib/peerHttpClient.js';
import * as brainStorage from './brainStorage.js';
import * as brainReconcile from './brainReconcile.js';
import { getPeers } from './instances.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
const { BRAIN_ENTITY_TYPES } = brainStorage;
@@ -61,8 +62,6 @@ const STORED_RECORDS_PER_TYPE = 25;
// pulls a peer's ENTIRE brain, which is legitimately slow on a large install.
const PEER_FETCH_TIMEOUT_MS = 30000;
-const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
-
/**
* Build this instance's brain manifest: `{ types: { [type]: [row] } }` where a
* row is `{ id, updatedAt, deleted }`. Tombstones are included (deleted:true) so
@@ -107,7 +106,7 @@ function normalizeRemoteManifest(body) {
const rows = types[type];
if (!Array.isArray(rows)) continue;
out[type] = rows
- .filter((r) => r && typeof r === 'object' && !Array.isArray(r) && isNonEmptyStr(r.id))
+ .filter((r) => r && typeof r === 'object' && !Array.isArray(r) && isNonBlankStr(r.id))
.map((r) => ({ id: r.id, updatedAt: r.updatedAt ?? null, deleted: r.deleted === true }));
}
return out;
@@ -243,7 +242,7 @@ async function compareChecksums(peer) {
brainReconcile.getBrainChecksum().catch(() => null),
fetchPeerJson(peer, '/api/brain/reconcile/checksum'),
]);
- const peerChecksum = isNonEmptyStr(remote.body?.checksum) ? remote.body.checksum : null;
+ const peerChecksum = isNonBlankStr(remote.body?.checksum) ? remote.body.checksum : null;
return {
local: local ?? null,
peer: peerChecksum,
@@ -339,11 +338,11 @@ export async function runBrainParityCheck({ peerId } = {}) {
// where silent divergence accumulates — filtering it out would hide the case
// the audit exists to find. An un-probed peer (no instanceId) is skipped
// because there is no stable key to file its report under.
- const targets = isNonEmptyStr(peerId)
+ const targets = isNonBlankStr(peerId)
? peers.filter((p) => p.id === peerId)
- : peers.filter((p) => p.syncEnabled !== false && isNonEmptyStr(p.instanceId));
+ : peers.filter((p) => p.syncEnabled !== false && isNonBlankStr(p.instanceId));
- if (isNonEmptyStr(peerId) && targets.length === 0) {
+ if (isNonBlankStr(peerId) && targets.length === 0) {
return { reports: [{ peerId, available: false, reason: 'peer-not-found', checkedAt: new Date().toISOString() }] };
}
diff --git a/server/services/creativeCommissions/abilityAdapters.js b/server/services/creativeCommissions/abilityAdapters.js
index 1a1aeb3b83..4fabf016a6 100644
--- a/server/services/creativeCommissions/abilityAdapters.js
+++ b/server/services/creativeCommissions/abilityAdapters.js
@@ -38,8 +38,7 @@ import {
import { resolvedDefault } from '../../lib/creativeCommissionSpec.js';
import { VIDEO_GEN_MODE } from '../videoGen/modes.js';
import { buildVideoPromptGuidance } from './videoPromptGuidance.js';
-
-const isStr = (v) => typeof v === 'string';
+import { isStr } from '../../lib/textUtils.js';
// The optional per-type engine/model override, universal across abilities. A free
// string, so it's handled separately from the typed/bounded spec keys.
diff --git a/server/services/creativeCommissions/feedbackLogic.js b/server/services/creativeCommissions/feedbackLogic.js
index 5e29750e4a..63f37348c4 100644
--- a/server/services/creativeCommissions/feedbackLogic.js
+++ b/server/services/creativeCommissions/feedbackLogic.js
@@ -28,8 +28,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
-
-const isStr = (v) => typeof v === 'string';
+import { isStr } from '../../lib/textUtils.js';
// The peer-sync record kind. Exported so the feedback store / peerSync.js
// reference one source of truth instead of bare strings.
diff --git a/server/services/creativeCommissions/feedbackStore.js b/server/services/creativeCommissions/feedbackStore.js
index b990282fea..77912cdd2a 100644
--- a/server/services/creativeCommissions/feedbackStore.js
+++ b/server/services/creativeCommissions/feedbackStore.js
@@ -45,6 +45,7 @@ import {
mergeCommissionFeedbackRecord,
toInlineFeedback,
} from './feedbackLogic.js';
+import { isStr } from '../../lib/textUtils.js';
export const TYPE = 'commission-feedback';
export const FEEDBACK_SCHEMA_VERSION = 1;
@@ -56,7 +57,6 @@ export const FEEDBACK_SCHEMA_VERSION = 1;
// `feedbackWindow` reactions anyway, so aging out the oldest is invisible).
export const MAX_LIVE_FEEDBACK_PER_COMMISSION = 100;
-const isStr = (v) => typeof v === 'string';
const notDeleted = (r) => r && r.deleted !== true;
// --- File backend (dev/test escape hatch): wraps collectionStore ---
diff --git a/server/services/creativeCommissions/musicTasteRecipe.js b/server/services/creativeCommissions/musicTasteRecipe.js
index 4029e51653..1eee3138cc 100644
--- a/server/services/creativeCommissions/musicTasteRecipe.js
+++ b/server/services/creativeCommissions/musicTasteRecipe.js
@@ -14,6 +14,7 @@ import {
COMMISSION_MUSIC_TASTE_PERCENT_MAX,
CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS,
} from '../../lib/creativeCommissionValidation.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export const MUSIC_TASTE_RECIPE_VERSION = 1;
export const MUSIC_TASTE_RECIPE_MAX_CONTEXT = 500;
@@ -27,16 +28,14 @@ export const MUSIC_TASTE_FEEDBACK_TAGS = Object.freeze([
]);
const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);
-const isString = (value) => typeof value === 'string';
const clampInt = (value, min, max, fallback) => Number.isInteger(value)
? Math.min(max, Math.max(min, value)) : fallback;
-const clampText = (value, max) => isString(value) ? value.trim().slice(0, max) : '';
export function normalizeMusicTasteConfig(raw) {
if (!isObject(raw) || raw.source !== 'digital-twin') return null;
const window = CREATIVE_COMMISSION_MUSIC_TASTE_WINDOWS.includes(raw.window) ? raw.window : 'month';
const pickId = (value) => {
- if (!isString(value) || !value.trim()) return null;
+ if (!isStr(value) || !value.trim()) return null;
return value.trim().slice(0, 64);
};
return {
@@ -59,7 +58,7 @@ function hashNumber(value) {
}
function anchorKey(anchor) {
- const artist = isString(anchor?.artist) && anchor.artist ? `:${anchor.artist}` : '';
+ const artist = isStr(anchor?.artist) && anchor.artist ? `:${anchor.artist}` : '';
return `${anchor?.kind || ''}:${anchor?.name || ''}${artist}`.toLowerCase();
}
@@ -75,9 +74,9 @@ function normalizeCandidates(observedWindow) {
const candidates = [];
const seen = new Set();
const add = (kind, raw) => {
- if (!isObject(raw) || !isString(raw.name) || !raw.name.trim()) return;
+ if (!isObject(raw) || !isStr(raw.name) || !raw.name.trim()) return;
const name = raw.name.trim().slice(0, 120);
- const artist = kind === 'track' && isString(raw.artist) && raw.artist.trim()
+ const artist = kind === 'track' && isStr(raw.artist) && raw.artist.trim()
? raw.artist.trim().slice(0, 120) : null;
const key = `${kind}:${name.toLowerCase()}:${artist?.toLowerCase() || ''}`;
if (seen.has(key)) return;
@@ -203,10 +202,10 @@ export function sanitizeMusicTasteRecipe(raw) {
if (!isObject(raw) || raw.version !== MUSIC_TASTE_RECIPE_VERSION || raw.source !== 'digital-twin') return null;
const anchors = Array.isArray(raw.anchors)
? raw.anchors.slice(0, COMMISSION_MUSIC_TASTE_ANCHOR_MAX).map((anchor) => {
- if (!isObject(anchor) || !['artist', 'track'].includes(anchor.kind) || !isString(anchor.name)) return null;
+ if (!isObject(anchor) || !['artist', 'track'].includes(anchor.kind) || !isStr(anchor.name)) return null;
const name = anchor.name.trim().slice(0, 120);
if (!name) return null;
- const artist = anchor.kind === 'track' && isString(anchor.artist) && anchor.artist.trim()
+ const artist = anchor.kind === 'track' && isStr(anchor.artist) && anchor.artist.trim()
? anchor.artist.trim().slice(0, 120) : null;
return {
kind: anchor.kind,
@@ -228,9 +227,9 @@ export function sanitizeMusicTasteRecipe(raw) {
explorationDirection: ['more-familiar', 'more-experimental', 'balanced'].includes(raw.explorationDirection)
? raw.explorationDirection : 'balanced',
anchors,
- statedContext: clampText(raw.statedContext, MUSIC_TASTE_RECIPE_MAX_CONTEXT) || null,
- sourceVersion: clampText(raw.sourceVersion, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION) || 'unknown',
- sourceHash: isString(raw.sourceHash) ? raw.sourceHash.trim().slice(0, 64) : 'unknown',
+ statedContext: trimTo(raw.statedContext, MUSIC_TASTE_RECIPE_MAX_CONTEXT) || null,
+ sourceVersion: trimTo(raw.sourceVersion, MUSIC_TASTE_RECIPE_MAX_SOURCE_VERSION) || 'unknown',
+ sourceHash: isStr(raw.sourceHash) ? raw.sourceHash.trim().slice(0, 64) : 'unknown',
};
}
@@ -243,7 +242,7 @@ export function buildMusicTasteRecipe({ commissionId, config: rawConfig, stated,
const config = normalizeMusicTasteConfig(rawConfig);
if (!config) return { status: 'unavailable', reason: 'taste-source-unavailable' };
const observedWindow = observed?.windows?.[config.window] || null;
- const statedContext = clampText(stated?.summary, MUSIC_TASTE_RECIPE_MAX_CONTEXT);
+ const statedContext = trimTo(stated?.summary, MUSIC_TASTE_RECIPE_MAX_CONTEXT);
const candidates = normalizeCandidates(observedWindow);
// A free-text stated summary is useful prompt context, but it is not a
// deterministic artist/track anchor. Taste mode therefore requires at least
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index e4bba25b1c..4573246ea5 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -80,6 +80,7 @@ import {
backfillInlineFeedback,
tombstoneFeedbackForCommission,
} from './feedbackStore.js';
+import { isStr } from '../../lib/textUtils.js';
// Emits `commission:changed` on any create/update/delete (not on run-record
// appends, which don't affect scheduling). The scheduler subscribes to re-sync.
@@ -134,8 +135,6 @@ export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
export const makeErr = (message, code) => Object.assign(new Error(message), { code });
-const isStr = (v) => typeof v === 'string';
-
/**
* Normalize a single feedback reaction (#2657, Phase 2). A reaction MUST carry a
* meaningful rating — 'up'/'down' or a non-zero number (numeric ratings are
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index 5109bdc3a8..b197cd655f 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -24,14 +24,13 @@ import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { pickLlmRoutePinLayer } from '../../lib/llmRoutePin.js';
import { localImageFilename } from '../../lib/localImageFilename.js';
import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
+import { isStr } from '../../lib/textUtils.js';
// Preserve the existing validation export for callers on the project-store surface.
export { validateVideoShot } from '../../lib/creativeDirectorVideoCompiler.js';
export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
-const isStr = (v) => typeof v === 'string';
-
// Per-project AI model override (per-project CD provider/model pins). Stored on
// the project record as `modelOverrides.{treatment,plan,evaluation}` — each an
// optional `{ providerId, model, effort }`. Only stages that name a `providerId` are
@@ -387,7 +386,6 @@ export function applyProjectPatch(project, patch) {
return next;
}
-
function retireVideoPlan(plan) {
return { history: [...(plan.history || []), { steps: structuredClone(plan.steps), updatedAt: plan.updatedAt }] };
}
diff --git a/server/services/fableLoom/editorial.js b/server/services/fableLoom/editorial.js
index d21e77a9eb..3205f6b195 100644
--- a/server/services/fableLoom/editorial.js
+++ b/server/services/fableLoom/editorial.js
@@ -32,7 +32,6 @@ import {
isFableLoomPlaybackMode,
FABLELOOM_PROTAGONIST_PRESENCE,
} from '../../lib/fableLoomPlayback.js';
-import { trimTo } from '../../lib/storyBible.js';
import { renderStoryCanonDigest } from '../../lib/universePromptRenderers.js';
import { normalizeFableLoomCameraMovement } from '../../lib/fableLoomCameraMovements.js';
import { startAIOp } from '../aiStatusEvents.js';
@@ -45,6 +44,7 @@ import {
mutateLoom,
sanitizeLoom,
} from './records.js';
+import { trimTo, isNonBlankStr } from '../../lib/textUtils.js';
const REVIEW_SEVERITIES = new Set(['high', 'medium', 'low']);
const REVIEW_CATEGORIES = new Set([
@@ -75,7 +75,6 @@ const INSTRUCTION_PLACEHOLDER_VALUES = new Set([
]);
const asArray = (value) => (Array.isArray(value) ? value : []);
-const hasText = (value) => typeof value === 'string' && value.trim().length > 0;
const hasOwn = (value, key) => Object.hasOwn(value, key);
const clampScore = (value) => (Number.isFinite(value)
? Math.max(0, Math.min(10, Math.round(value * 10) / 10))
@@ -346,13 +345,13 @@ const resolveEditorialPromptBudgetChars = async (stage, route, source) => {
*/
const loomCastCharacterIds = (loom) => {
const ids = new Set();
- if (hasText(loom?.protagonistCharacterId)) ids.add(loom.protagonistCharacterId);
+ if (isNonBlankStr(loom?.protagonistCharacterId)) ids.add(loom.protagonistCharacterId);
for (const episode of asArray(loom?.episodes)) {
for (const node of asArray(episode.nodes)) {
for (const appearance of asArray(node.visualCanon?.characterAppearances)) {
- if (hasText(appearance?.characterId)) ids.add(appearance.characterId);
+ if (isNonBlankStr(appearance?.characterId)) ids.add(appearance.characterId);
}
- if (hasText(node.interactionWindow?.protagonistCharacterId)) {
+ if (isNonBlankStr(node.interactionWindow?.protagonistCharacterId)) {
ids.add(node.interactionWindow.protagonistCharacterId);
}
}
@@ -586,7 +585,7 @@ const sanitizeEvaluation = (content, loom) => {
new Set(episode.nodes.map((node) => node.id)),
]));
const findings = asArray(content?.findings)
- .filter((finding) => finding && typeof finding === 'object' && hasText(finding.problem))
+ .filter((finding) => finding && typeof finding === 'object' && isNonBlankStr(finding.problem))
.slice(0, 40)
.map((finding) => {
const episodeId = episodeIds.has(finding.episodeId) ? finding.episodeId : null;
@@ -768,7 +767,7 @@ const applyScenePatch = (episode, scene, rawScene) => {
}
const returnedTransitionIds = new Set();
for (const rawTransition of asArray(rawScene.transitions)) {
- if (!isPlainObject(rawTransition) || !hasText(rawTransition.id)) {
+ if (!isPlainObject(rawTransition) || !isNonBlankStr(rawTransition.id)) {
throw aiShapeError(`The model returned a transition without an existing id for scene ${scene.id}`);
}
const transition = transitionsById.get(rawTransition?.id);
@@ -803,7 +802,7 @@ const applyContinuitySourcePatch = (scene, sourceId, predecessorsByNodeId) => {
const validPredecessors = new Set(
asArray(predecessorsByNodeId.get(scene.id)).map((item) => item.nodeId),
);
- if (sourceId !== null && (!hasText(sourceId) || !validPredecessors.has(sourceId))) {
+ if (sourceId !== null && (!isNonBlankStr(sourceId) || !validPredecessors.has(sourceId))) {
throw aiShapeError(`The model selected an invalid continuity predecessor for scene ${scene.id}`);
}
scene.visualCanon = {
@@ -915,7 +914,7 @@ export function applyFableLoomEditorialPatch(
const episodesById = new Map(candidate.episodes.map((episode) => [episode.id, episode]));
const returnedEpisodeIds = new Set();
for (const rawEpisode of asArray(content.episodes)) {
- if (!isPlainObject(rawEpisode) || !hasText(rawEpisode.id)) {
+ if (!isPlainObject(rawEpisode) || !isNonBlankStr(rawEpisode.id)) {
throw aiShapeError('The model returned an episode patch without an existing id');
}
const episode = episodesById.get(rawEpisode?.id);
@@ -946,7 +945,7 @@ export function applyFableLoomEditorialPatch(
}
const returnedSceneIds = new Set();
for (const rawScene of asArray(rawEpisode.scenes)) {
- if (!isPlainObject(rawScene) || !hasText(rawScene.id)) {
+ if (!isPlainObject(rawScene) || !isNonBlankStr(rawScene.id)) {
throw aiShapeError(`The model returned a scene patch without an existing id for episode ${episode.id}`);
}
const scene = scenesById.get(rawScene?.id);
@@ -1150,7 +1149,7 @@ const sanitizePlaythroughReview = (content, loom, deterministic) => {
new Set(episode.paths.map((path) => path.id)),
]));
const findings = asArray(content?.findings)
- .filter((finding) => finding && typeof finding === 'object' && hasText(finding.problem))
+ .filter((finding) => finding && typeof finding === 'object' && isNonBlankStr(finding.problem))
.slice(0, 60)
.map((finding) => {
const episode = episodeById.get(finding.episodeId);
@@ -1172,7 +1171,7 @@ const sanitizePlaythroughReview = (content, loom, deterministic) => {
};
});
const qualityScore = clampScore(content?.qualityScore);
- if (qualityScore === null || !hasText(content?.summary)) {
+ if (qualityScore === null || !isNonBlankStr(content?.summary)) {
throw aiShapeError('The model returned no usable playthrough quality verdict');
}
return {
diff --git a/server/services/fableLoom/editorialAutopilot.js b/server/services/fableLoom/editorialAutopilot.js
index b8349b868b..7d53930c39 100644
--- a/server/services/fableLoom/editorialAutopilot.js
+++ b/server/services/fableLoom/editorialAutopilot.js
@@ -11,7 +11,6 @@
import { randomUUID } from 'node:crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { LOOM_LIMITS } from '../../lib/fableLoomLimits.js';
-import { trimTo } from '../../lib/storyBible.js';
import { getLoom, mutateLoom } from './records.js';
import {
evaluateAndRemediateFableLoom,
@@ -21,6 +20,7 @@ import {
runFableLoomEditorialSelfImprove,
shouldDiagnoseFableLoomEditorial,
} from './editorialSelfImprove.js';
+import { trimTo } from '../../lib/textUtils.js';
export const FABLELOOM_EDITORIAL_AUTOPILOT_LIMITS = Object.freeze({
DEFAULT_ROUNDS: 3,
diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.js
index e2ea3a8d5c..701fb83566 100644
--- a/server/services/fableLoom/records.js
+++ b/server/services/fableLoom/records.js
@@ -14,7 +14,6 @@
import { sanitizeShot } from '../../lib/fableLoomShots.js';
import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeLlmRoutePin } from '../../lib/llmRoutePin.js';
import { sanitizeCharacterEvolutionList } from '../../lib/characterEvolution.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
@@ -71,6 +70,7 @@ import {
mergeFableLoomRenderSettings,
sanitizeFableLoomRenderSettings,
} from '../../lib/fableLoomProduction.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export { LOOM_LIMITS };
diff --git a/server/services/fableLoom/weave.js b/server/services/fableLoom/weave.js
index a07e55db3f..17f8788fb7 100644
--- a/server/services/fableLoom/weave.js
+++ b/server/services/fableLoom/weave.js
@@ -16,7 +16,6 @@ import { randomUUID } from 'crypto';
import { ServerError } from '../../lib/errorHandler.js';
import { startAIOp } from '../aiStatusEvents.js';
import { runStagedLLM } from '../stageRunner.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { resolveLlmRoutePin } from '../../lib/llmRoutePin.js';
import { renderStoryCanonDigest } from '../../lib/universePromptRenderers.js';
import { renderCharacterEvolutionListForPrompt } from '../../lib/characterEvolution.js';
@@ -48,6 +47,7 @@ import {
import { getUniverse } from '../universeBuilder.js';
import { LOOM_LIMITS, fableLoomEvolutionEvidenceRefs, findEpisode, findNode, getLoom, mutateLoom } from './records.js';
import { asLoomFormat, loomFormatLabel, narrationFormatContract, sceneFormatContract } from './formats.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
const TRANSCRIPT_TURNS_MAX = 12;
const AUDIENCE_GRAPH_ERROR_CODES = new Set([
diff --git a/server/services/importer.js b/server/services/importer.js
index c0344d26ec..480dbc5231 100644
--- a/server/services/importer.js
+++ b/server/services/importer.js
@@ -39,6 +39,7 @@ import { IMPORTER_CONTENT_TYPES, IMPORTER_PROSE_EXCERPT_MAX } from '../lib/valid
// same value the mechanical comic split validates against.
export { IMPORTER_PROSE_EXCERPT_MAX };
import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
+import { isStr } from '../lib/textUtils.js';
// Surfaced to the route layer so the importer's policy errors become 400s
// with stable codes.
@@ -182,7 +183,6 @@ export async function reformatSeededExcerpts(issues, { contentType = null } = {}
}
const normName = (s) => String(s || '').trim().toLowerCase();
-const isStr = (v) => typeof v === 'string';
// Required + oversized-ceiling guard for the source corpus. Shared by
// analyze / classify / retry-issues so the check and its (verbatim) error
diff --git a/server/services/issueWatcher.js b/server/services/issueWatcher.js
index 06d537353d..36c04c9ce2 100644
--- a/server/services/issueWatcher.js
+++ b/server/services/issueWatcher.js
@@ -31,6 +31,7 @@ import { mergePR, resolveForgeForRepo } from './git.js';
import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';
import { normalizeEligibilityFacts } from './modelAbuseGuard.js';
import { issuePrerequisiteWaived, linkedIssueIntentFingerprint } from '../lib/modelAbuseGuard.js';
+import { trimTo } from '../lib/textUtils.js';
const IN_PROGRESS_LABEL_SPEC = dispatchLabelSpec(IN_PROGRESS_LABEL);
@@ -58,7 +59,6 @@ const FAILED_CHECKS = new Set(['ACTION_REQUIRED', 'CANCELLED', 'ERROR', 'FAILURE
let stateWriteTail = Promise.resolve();
-const text = (value, max = 8_000) => typeof value === 'string' ? value.trim().slice(0, max) : '';
const fullText = (value) => typeof value === 'string' ? value : '';
const sameLogin = (a, b) => Boolean(a && b) && String(a).toLowerCase() === String(b).toLowerCase();
// GitHub reports issue state as `open`/`closed`; normalize once so every caller
@@ -142,7 +142,7 @@ async function resolveContext(app) {
/** True only for an affirmative, explicit request to take ownership. */
export function isIssueClaimRequest(body) {
- const value = text(body, 4_000).replace(/```[\s\S]*?```/g, '').split('\n').filter((line) => !line.trimStart().startsWith('>')).join('\n');
+ const value = trimTo(body, 4_000).replace(/```[\s\S]*?```/g, '').split('\n').filter((line) => !line.trimStart().startsWith('>')).join('\n');
if (!value || /\b(?:cannot|can't|can not|won't|will not|not able to)\b/i.test(value)) return false;
return [
/\b(?:i\s+can|i'll|i\s+will)\s+(?:take|handle|work\s+on)\s+(?:this|it|the\s+issue)\b/i,
@@ -188,7 +188,7 @@ export function classifyChecks(statusCheckRollup) {
function normalizeFinding(finding, anchors) {
if (!finding || typeof finding !== 'object') return null;
- const path = text(finding.path, 500);
+ const path = trimTo(finding.path, 500);
const side = String(finding.side || '').toUpperCase();
const line = Number(finding.line);
// A finding without an explicit boolean is blocking. The watcher must not
@@ -211,7 +211,7 @@ function normalizeReviewDecision(value) {
if (!verdict || !ciPolicy || typeof value.rebaseRequired !== 'boolean') return null;
return {
number: value.number,
- headSha: text(value.headSha, 80),
+ headSha: trimTo(value.headSha, 80),
verdict,
ciPolicy,
rebaseRequired: value.rebaseRequired,
@@ -1173,7 +1173,7 @@ async function runScheduledIssueIntake({ app, interval } = {}) {
async function postIssueReply(ctx, decision) {
return runGh([
- 'issue', 'comment', String(decision.issueNumber), '--repo', ctx.repoSpec, '--body', text(decision.body, 5_000),
+ 'issue', 'comment', String(decision.issueNumber), '--repo', ctx.repoSpec, '--body', trimTo(decision.body, 5_000),
], ctx).then(() => true).catch((err) => {
console.error(`❌ issue-watcher: issue reply failed for #${decision.issueNumber}: ${err.message}`);
return false;
@@ -1204,7 +1204,7 @@ async function readCurrentIssueComment(ctx, item) {
}
async function submitReview(ctx, number, { body, event, comments = [] }) {
- const input = JSON.stringify({ body: text(body, MAX_REVIEW_BODY_CHARS), event, comments });
+ const input = JSON.stringify({ body: trimTo(body, MAX_REVIEW_BODY_CHARS), event, comments });
return runGh([...apiArgs(ctx, `repos/${ctx.repoFullName}/pulls/${number}/reviews`, { method: 'POST' }), '--input', '-'], ctx, input)
.then(() => true)
.catch((err) => {
@@ -1214,7 +1214,7 @@ async function submitReview(ctx, number, { body, event, comments = [] }) {
}
async function postReviewFallback(ctx, number, body) {
- return runGh(['pr', 'comment', String(number), '--repo', ctx.repoSpec, '--body', text(body, MAX_REVIEW_BODY_CHARS)], ctx)
+ return runGh(['pr', 'comment', String(number), '--repo', ctx.repoSpec, '--body', trimTo(body, MAX_REVIEW_BODY_CHARS)], ctx)
.then(() => true)
.catch((err) => {
console.error(`❌ issue-watcher: review comment failed for PR #${number}: ${err.message}`);
@@ -1291,7 +1291,7 @@ export async function processTaskOutput({ appId, success, payload, task, require
const current = await readCurrentIssueComment(ctx, item);
if (!current || !item.contentFingerprint || abuseFingerprint('issue-comment', current, issueAbuseInput(current)) !== item.contentFingerprint) continue;
if (decision.action === 'reply') {
- const posted = text(decision.body, 5_000) && await postIssueReply(ctx, { ...current, body: decision.body });
+ const posted = trimTo(decision.body, 5_000) && await postIssueReply(ctx, { ...current, body: decision.body });
if (!posted) continue;
replies += 1;
}
diff --git a/server/services/mediaPromptFromMedia.js b/server/services/mediaPromptFromMedia.js
index c67b7da7ef..771c44b9d4 100644
--- a/server/services/mediaPromptFromMedia.js
+++ b/server/services/mediaPromptFromMedia.js
@@ -18,7 +18,7 @@ import { extname, join } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { clampToCharLimit } from '../lib/textUtils.js';
+import { clampToCharLimit, trimTo } from '../lib/textUtils.js';
import { extractJson } from '../lib/jsonExtract.js';
import { PATHS, resolveGalleryImage } from '../lib/fileUtils.js';
import { extractEvaluationFrames, safeUnder } from '../lib/ffmpeg.js';
@@ -43,9 +43,6 @@ const VIDEO_ID_RE = /^(?:[a-f0-9-]{36}|upload-[a-f0-9]{8})$/i;
const IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp)$/i;
const VIDEO_EXT_RE = /\.(mp4|webm|mov|m4v|mkv)$/i;
-const trimString = (value, max = MAX_PROMPT_LEN) =>
- typeof value === 'string' ? value.trim().slice(0, max) : '';
-
const isPlaceholderPrompt = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);
export const PROMPT_FROM_MEDIA_TARGETS = Object.freeze(['image', 'video']);
@@ -127,15 +124,15 @@ export function parsePromptFromMediaJson(raw, targets) {
if (!v || typeof v !== 'object') return false;
if (wantImage && (typeof v.imagePrompt !== 'string' || isPlaceholderPrompt(v.imagePrompt))) return false;
if (wantVideo && (typeof v.videoPrompt !== 'string' || isPlaceholderPrompt(v.videoPrompt))) return false;
- return (wantImage ? trimString(v.imagePrompt) : true) && (wantVideo ? trimString(v.videoPrompt) : true);
+ return (wantImage ? trimTo(v.imagePrompt, MAX_PROMPT_LEN) : true) && (wantVideo ? trimTo(v.videoPrompt, MAX_PROMPT_LEN) : true);
},
});
if (!value) {
throw new Error(lastError?.message || 'Invalid JSON in AI response');
}
- const imagePrompt = wantImage ? trimString(value.imagePrompt) : '';
- const videoPrompt = wantVideo ? trimString(value.videoPrompt) : '';
+ const imagePrompt = wantImage ? trimTo(value.imagePrompt, MAX_PROMPT_LEN) : '';
+ const videoPrompt = wantVideo ? trimTo(value.videoPrompt, MAX_PROMPT_LEN) : '';
if (wantImage && (isPlaceholderPrompt(value.imagePrompt) || !imagePrompt)) {
throw new Error('LLM returned an empty image prompt');
}
@@ -146,13 +143,13 @@ export function parsePromptFromMediaJson(raw, targets) {
return {
...(wantImage ? {
imagePrompt,
- imageNegativePrompt: trimString(value.imageNegativePrompt),
+ imageNegativePrompt: trimTo(value.imageNegativePrompt, MAX_PROMPT_LEN),
} : {}),
...(wantVideo ? {
videoPrompt,
- videoNegativePrompt: trimString(value.videoNegativePrompt),
+ videoNegativePrompt: trimTo(value.videoNegativePrompt, MAX_PROMPT_LEN),
} : {}),
- rationale: trimString(value.rationale, MAX_REASON_LEN),
+ rationale: trimTo(value.rationale, MAX_REASON_LEN),
};
}
diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.js
index 1db89f9c73..45285fd124 100644
--- a/server/services/mediaPromptRefiner.js
+++ b/server/services/mediaPromptRefiner.js
@@ -1,6 +1,6 @@
import { ServerError } from '../lib/errorHandler.js';
import { extractNonPlaceholderJson } from '../lib/jsonExtract.js';
-import { clampToCharLimit } from '../lib/textUtils.js';
+import { clampToCharLimit, trimTo } from '../lib/textUtils.js';
import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';
import { getProviderById } from './providers.js';
@@ -8,12 +8,9 @@ const MAX_PROMPT_LEN = 8000;
const MAX_REASON_LEN = 1200;
const MAX_CHANGES = 8;
-const trimString = (value, max = MAX_PROMPT_LEN) =>
- typeof value === 'string' ? value.trim().slice(0, max) : '';
-
const cleanChanges = (changes) => (
Array.isArray(changes)
- ? changes.map((c) => trimString(c, 240)).filter(Boolean).slice(0, MAX_CHANGES)
+ ? changes.map((c) => trimTo(c, 240)).filter(Boolean).slice(0, MAX_CHANGES)
: []
);
@@ -152,9 +149,9 @@ export async function refineMediaPrompt({
const llmPrompt = buildMediaPromptRefinePrompt({
kind,
- prompt: trimString(prompt),
- negativePrompt: trimString(negativePrompt),
- feedback: trimString(feedback, 3000),
+ prompt: trimTo(prompt, MAX_PROMPT_LEN),
+ negativePrompt: trimTo(negativePrompt, MAX_PROMPT_LEN),
+ feedback: trimTo(feedback, 3000),
renderConfig,
maxPromptLength,
});
@@ -177,7 +174,7 @@ export async function refineMediaPrompt({
throw new ServerError(e.message, { status: 502, code: 'PROMPT_REFINE_BAD_JSON' });
}
- const refinedPrompt = trimString(parsed.prompt);
+ const refinedPrompt = trimTo(parsed.prompt, MAX_PROMPT_LEN);
if (!refinedPrompt) {
throw new ServerError('LLM returned an empty prompt', { status: 502, code: 'PROMPT_REFINE_EMPTY_PROMPT' });
}
@@ -194,8 +191,8 @@ export async function refineMediaPrompt({
return {
prompt: boundedPrompt,
- negativePrompt: trimString(parsed.negativePrompt),
- rationale: trimString(parsed.rationale, MAX_REASON_LEN),
+ negativePrompt: trimTo(parsed.negativePrompt, MAX_PROMPT_LEN),
+ rationale: trimTo(parsed.rationale, MAX_REASON_LEN),
changes: cleanChanges(parsed.changes),
providerId: provider.id,
model: selectedModel,
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
index 5116880810..d21395b29e 100644
--- a/server/services/moodBoard/logic.js
+++ b/server/services/moodBoard/logic.js
@@ -17,8 +17,7 @@ import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { localImageFilename, assetBasename } from '../../lib/localImageFilename.js';
import { isVideoItemMediaKey } from '../../lib/moodBoardValidation.js';
-
-const isStr = (v) => typeof v === 'string';
+import { isStr } from '../../lib/textUtils.js';
// Bound the inline items[] so a single board row's JSONB can't grow without
// limit (a board is loaded/serialized whole on every read/write). Far above any
diff --git a/server/services/moodBoardStyleSynthesis.js b/server/services/moodBoardStyleSynthesis.js
index f9d558a3c7..508fa09241 100644
--- a/server/services/moodBoardStyleSynthesis.js
+++ b/server/services/moodBoardStyleSynthesis.js
@@ -13,13 +13,13 @@
import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';
import { ServerError } from '../lib/errorHandler.js';
import { assertProvider, runPromptThroughProvider } from './promptRunner.js';
-import { trimTo } from '../lib/storyBible.js';
import {
sanitizeInfluences,
sanitizeLocked,
STYLE_NOTES_MAX,
} from './universeBuilder.js';
import { buildStyleReferenceDiff } from './universeStyleReference.js';
+import { trimTo } from '../lib/textUtils.js';
// Context bounds: a board caps at 500 items, but the synthesis context must
// stay well inside a chat-completion window. Items are taken in board order
diff --git a/server/services/musicDesigner.js b/server/services/musicDesigner.js
index 1caeaea667..1df0531ddf 100644
--- a/server/services/musicDesigner.js
+++ b/server/services/musicDesigner.js
@@ -24,6 +24,7 @@
import { ServerError } from '../lib/errorHandler.js';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
+import { trimTo } from '../lib/textUtils.js';
// Caps mirror the Generate form's own field limits so a designer round-trip
// can't produce text the generate route would then reject.
@@ -65,12 +66,10 @@ const DESCRIBE_OUTPUT_CONTRACT = [
'No preamble, bullet list, song title, quoted lyrics, reasoning trace, or markdown fence.',
].join('\n');
-const clean = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
-
// A blank/whitespace override means "use the shipped default" — the UI clears
// the field to reset, and an empty instruction block would otherwise leave the
// provider with nothing but the raw concept text.
-const pickTemplate = (template, fallback) => clean(template, MAX_TEMPLATE) || fallback;
+const pickTemplate = (template, fallback) => trimTo(template, MAX_TEMPLATE) || fallback;
// The output instruction lives OUTSIDE the overridable template on purpose: a
// user editing the meta-prompt is tuning the creative brief, not the wire
@@ -80,8 +79,8 @@ const section = (label, body) => (body ? `\n\n${label}:\n${body}` : '');
export function buildDescribePrompt({ concept, guidance, template } = {}) {
return [
pickTemplate(template, DEFAULT_DESCRIBE_TEMPLATE),
- section('MUSICAL REFERENCE / VIBE', clean(concept, MAX_CONCEPT) || '(none given)'),
- section('ADDITIONAL GUIDANCE FROM THE USER', clean(guidance, MAX_GUIDANCE)),
+ section('MUSICAL REFERENCE / VIBE', trimTo(concept, MAX_CONCEPT) || '(none given)'),
+ section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),
`\n\n${DESCRIBE_OUTPUT_CONTRACT}`,
].join('');
}
@@ -89,8 +88,8 @@ export function buildDescribePrompt({ concept, guidance, template } = {}) {
export function buildLyricsPrompt({ description, guidance, template } = {}) {
return [
pickTemplate(template, DEFAULT_LYRICS_TEMPLATE),
- section('MUSICAL DESCRIPTION', clean(description, MAX_DESCRIPTION) || '(none given)'),
- section('ADDITIONAL GUIDANCE FROM THE USER', clean(guidance, MAX_GUIDANCE)),
+ section('MUSICAL DESCRIPTION', trimTo(description, MAX_DESCRIPTION) || '(none given)'),
+ section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE)),
'\n\nReturn ONLY the lyrics with their section tags. No preamble, no commentary, no markdown fence.',
].join('');
}
@@ -124,7 +123,7 @@ export async function describeMusic({ concept, guidance, template, providerId, m
provider, model: selectedModel, effort, prompt, source: 'music-describe',
});
- const description = clean(unfence(text), MAX_DESCRIPTION);
+ const description = trimTo(unfence(text), MAX_DESCRIPTION);
if (!description) {
throw new ServerError('The AI returned an empty description. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });
}
@@ -153,7 +152,7 @@ export async function writeLyrics({ description, guidance, template, providerId,
provider, model: selectedModel, effort, prompt, source: 'music-lyrics',
});
- const lyrics = clean(unfence(text), MAX_LYRICS);
+ const lyrics = trimTo(unfence(text), MAX_LYRICS);
if (!lyrics) {
throw new ServerError('The AI returned empty lyrics. Try rerunning or picking a stronger model.', { status: 502, code: 'LLM_EMPTY' });
}
diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.js
index cd0a1c64b2..22dbc5cb99 100644
--- a/server/services/musicVideo/projectsLogic.js
+++ b/server/services/musicVideo/projectsLogic.js
@@ -27,14 +27,13 @@ import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { stripMusicVideoLocalRenderPins } from '../../lib/syncWire.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
import { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
+import { isStr } from '../../lib/textUtils.js';
export { sanitizeProjectForSync } from '../../lib/projectStoreKit.js';
// Re-exported for the PG backend's typed mirror columns (mirrors the CD store).
export { mirrorTimestamp } from '../../lib/pgTimestamp.js';
-const isStr = (v) => typeof v === 'string';
-
const STATUS_COLUMN_MAX = 32;
/** Safe value for the `status` mirror column — bounded, never null. */
diff --git a/server/services/peerUsage.js b/server/services/peerUsage.js
index bfd0d0c731..456f3abcaa 100644
--- a/server/services/peerUsage.js
+++ b/server/services/peerUsage.js
@@ -36,6 +36,7 @@ import { roundCents } from '../lib/subscriptionSavings.js';
import { sanitizeQuotaCards } from '../lib/fleetQuotas.js';
import { buildUsageDigest, buildUsageReport, getUsage, USAGE_FILE } from './usage.js';
import { readLocalQuotaCards, PROVIDER_QUOTAS_FILE } from './providerQuotaShare.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
const PEER_USAGE_FILE = join(PATHS.data, 'peer-usage.json');
@@ -60,9 +61,8 @@ const MAX_MODELS_PER_PROVIDER = 400;
const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
const MONTH_KEY_RE = /^\d{4}-\d{2}$/;
-const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
-const str = (v, max) => (isNonEmptyStr(v) ? v.slice(0, max) : null);
+const str = (v, max) => (isNonBlankStr(v) ? v.slice(0, max) : null);
const COUNT_FIELDS = ['sessions', 'messages', 'tokens', 'tokensIn', 'tokensOut', 'cacheReadTokens', 'cacheWriteTokens'];
@@ -89,7 +89,7 @@ function sanitizeProviderBucket(raw) {
if (isPlainObject(raw?.byModel)) {
out.byModel = {};
for (const [model, mRaw] of Object.entries(raw.byModel).slice(0, MAX_MODELS_PER_PROVIDER)) {
- if (!isNonEmptyStr(model)) continue;
+ if (!isNonBlankStr(model)) continue;
out.byModel[model.slice(0, 200)] = sanitizeModelBucket(mRaw);
}
}
@@ -101,7 +101,7 @@ function sanitizeActivityBucket(raw) {
if (isPlainObject(raw?.byProvider)) {
out.byProvider = {};
for (const [pid, pRaw] of Object.entries(raw.byProvider).slice(0, MAX_PROVIDERS_PER_BUCKET)) {
- if (!isNonEmptyStr(pid)) continue;
+ if (!isNonBlankStr(pid)) continue;
out.byProvider[pid.slice(0, 200)] = sanitizeProviderBucket(pRaw);
}
}
@@ -151,10 +151,10 @@ const withLock = createMutex();
async function readSelfIdentity() {
const { getSelf, UNKNOWN_INSTANCE_ID } = await import('./instanceIdentity.js');
const self = await getSelf().catch(() => null);
- const instanceId = isNonEmptyStr(self?.instanceId) && self.instanceId !== UNKNOWN_INSTANCE_ID
+ const instanceId = isNonBlankStr(self?.instanceId) && self.instanceId !== UNKNOWN_INSTANCE_ID
? self.instanceId
: null;
- return { instanceId, name: isNonEmptyStr(self?.name) ? self.name : null };
+ return { instanceId, name: isNonBlankStr(self?.name) ? self.name : null };
}
async function readStore() {
@@ -177,11 +177,11 @@ function sanitizeEntry(entry, expectedId) {
// A digest may omit its own id (the key is authoritative), but it may never
// claim a DIFFERENT one — that would let a peer smuggle a digest in under our
// id, or overwrite a third instance's slot.
- if (isNonEmptyStr(entry.instanceId) && entry.instanceId !== expectedId) return null;
+ if (isNonBlankStr(entry.instanceId) && entry.instanceId !== expectedId) return null;
if (parseTsMs(entry.capturedAt) === null) return null;
return {
instanceId: expectedId,
- name: isNonEmptyStr(entry.name) ? entry.name.slice(0, 120) : expectedId,
+ name: isNonBlankStr(entry.name) ? entry.name.slice(0, 120) : expectedId,
capturedAt: entry.capturedAt,
usage: sanitizeDigest(entry.usage),
// Optional: a peer running an older build publishes no quota readings, and
@@ -228,7 +228,7 @@ async function buildSelfEntry() {
async function entriesWithSelf() {
const [store, self] = await Promise.all([readStore(), buildSelfEntry()]);
const peers = Object.values(store.instances).filter((e) => isPlainObject(e) && isPlainObject(e.usage));
- const publishable = self && isNonEmptyStr(self.capturedAt) ? self : null;
+ const publishable = self && isNonBlankStr(self.capturedAt) ? self : null;
return {
self: publishable,
peers: peers.filter((e) => e.instanceId !== self?.instanceId),
@@ -319,7 +319,7 @@ export async function applyUsageRemote(remoteData) {
let changed = 0;
for (const [key, rawEntry] of Object.entries(incoming)) {
- if (!isNonEmptyStr(key) || key === selfId) continue;
+ if (!isNonBlankStr(key) || key === selfId) continue;
const entry = sanitizeEntry(rawEntry, key);
if (!entry) continue;
// A digest CAPTURED after the deletion is a machine that came back, and
@@ -486,7 +486,7 @@ export async function getFleetQuotaEntries({ excludeInstanceIds = [] } = {}) {
* captured AFTER the tombstone still wins, so re-adding the machine later works.
*/
export async function forgetInstanceUsage(instanceId) {
- if (!isNonEmptyStr(instanceId)) return { removed: false };
+ if (!isNonBlankStr(instanceId)) return { removed: false };
return withLock(async () => {
const store = await readStore();
store.tombstones = recordTombstone(store.tombstones, instanceId, { keyField: 'instanceId' });
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 716b29e316..0e2fc130a5 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -10,7 +10,6 @@
import { MANUSCRIPT_TYPES } from '../series.js';
import { listIssues, STAGE_INPUT_MAX } from '../issues.js';
import { ARC_LIMITS, ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';
-import { trimToClause } from '../../../lib/storyBible.js';
import { composeStyleNotes } from '../../../lib/styleGuide.js';
import {
CHARACTER_ARC_LIMITS,
@@ -22,6 +21,7 @@ import { computeIssueTargets, DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } fro
import { getUniverse } from '../../universeBuilder.js';
import { getSeriesPlanningCanon, scopeCanonForSeries } from '../seriesCanon.js';
import { CHARACTER_NARRATIVE_ARC_MAX, renderCanonForPrompt, renderCategoriesForPrompt, renderCharacterNarrativeContext, renderCompositesForPrompt, renderEntitiesSummary } from '../../../lib/universePromptRenderers.js';
+import { trimToClause } from '../../../lib/textUtils.js';
export const ERR_VALIDATION = 'PIPELINE_ARC_VALIDATION';
diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.js
index adff5ebb53..fd14fd1245 100644
--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js
+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js
@@ -13,7 +13,7 @@ import { resolveSeriesLlmOverride } from '../../../lib/seriesLlmOverride.js';
import { getSeriesPlanningCanon } from '../seriesCanon.js';
import { ARC_ROLES, ERR_VALIDATION, SEASON_LENGTH_PRESETS, SHAPE_GUIDANCE_NONE, appendCharacterFirstArcGuidance, appendTickingClock, lengthProfileForArcRole, makeErr, renderPriorSeason, resolveWorldContext } from './context.js';
import { ARC_LIMITS } from '../../../lib/storyArc.js';
-import { trimToClause } from '../../../lib/storyBible.js';
+import { trimToClause } from '../../../lib/textUtils.js';
/**
* Build the context for one season's episode breakdown. `priorSeasonsContext`
diff --git a/server/services/pipeline/audioCues.js b/server/services/pipeline/audioCues.js
index 64a1389fab..8840216cd8 100644
--- a/server/services/pipeline/audioCues.js
+++ b/server/services/pipeline/audioCues.js
@@ -29,12 +29,12 @@
import { runStagedLLM } from '../stageRunner.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { trimTo } from '../../lib/storyBible.js';
import {
AUDIO_CUES_MAX,
AUDIO_CUE_LABEL_MAX,
AUDIO_CUE_PROMPT_MAX,
} from './issues.js';
+import { trimTo } from '../../lib/textUtils.js';
export const ERR_NO_SOURCE = 'PIPELINE_AUDIO_CUES_NO_SOURCE';
export const ERR_EMPTY_RESULT = 'PIPELINE_AUDIO_CUES_EMPTY';
diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.js
index 26c679f992..593a2152d2 100644
--- a/server/services/pipeline/continuityBible.js
+++ b/server/services/pipeline/continuityBible.js
@@ -33,6 +33,7 @@ import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextB
import { seriesStore, getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
+import { trimTo } from '../../lib/textUtils.js';
const STAGE = 'pipeline-continuity-bible';
@@ -72,7 +73,6 @@ const ANCHOR_MAX = 240;
const LEDGER_OUTPUT_RESERVE_TOKENS = 6_000;
const nowIso = () => new Date().toISOString();
-const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
// Content hash — pins an input so a later edit flips the ledger to `stale`.
const contentHash = (text) => createHash('sha256').update(text || '').digest('hex');
@@ -105,8 +105,8 @@ const factKey = (f) => `${f.category}::${(f.subject || '').toLowerCase().trim()}
export function seedFactsFromCanon(canon) {
const out = [];
const push = (kind, entry, description) => {
- const subject = clampStr(entry?.name, SUBJECT_MAX);
- const statement = clampStr(description, STATEMENT_MAX);
+ const subject = trimTo(entry?.name, SUBJECT_MAX);
+ const statement = trimTo(description, STATEMENT_MAX);
if (!subject || !statement) return;
out.push({
category: CANON_KIND_CATEGORY[kind],
@@ -136,8 +136,8 @@ export function seedFactsFromCanon(canon) {
function sanitizeProseFact(raw) {
if (!raw || typeof raw !== 'object') return null;
const category = typeof raw.category === 'string' && CATEGORY_IDS.has(raw.category) ? raw.category : null;
- const subject = clampStr(raw.subject, SUBJECT_MAX);
- const statement = clampStr(raw.statement, STATEMENT_MAX);
+ const subject = trimTo(raw.subject, SUBJECT_MAX);
+ const statement = trimTo(raw.statement, STATEMENT_MAX);
if (!category || !subject || !statement) return null;
return {
category,
@@ -148,7 +148,7 @@ function sanitizeProseFact(raw) {
canonKind: null,
canonEntryId: null,
issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,
- anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX) || null,
+ anchorQuote: trimTo(raw.anchorQuote, ANCHOR_MAX) || null,
};
}
diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.js
index 363ba03a27..38288636f7 100644
--- a/server/services/pipeline/editorialAnalysis.js
+++ b/server/services/pipeline/editorialAnalysis.js
@@ -23,6 +23,7 @@ import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextB
import { getIssue, listIssues } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
+import { trimTo } from '../../lib/textUtils.js';
const STAGE = 'pipeline-editorial-analysis';
const ARC_DIRECTIONS = Object.freeze(['rising', 'falling', 'flat', 'complex']);
@@ -85,37 +86,35 @@ const clampNum = (v, min, max, fallback = 0) => {
return Math.max(min, Math.min(max, Math.round(n)));
};
-const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
function sanitizeSection(raw) {
if (!raw || typeof raw !== 'object') return null;
return {
- label: str(raw.label, LABEL_MAX) || 'Section',
- excerpt: str(raw.excerpt, EXCERPT_MAX),
- primaryEmotion: str(raw.primaryEmotion, EMOTION_MAX),
+ label: trimTo(raw.label, LABEL_MAX) || 'Section',
+ excerpt: trimTo(raw.excerpt, EXCERPT_MAX),
+ primaryEmotion: trimTo(raw.primaryEmotion, EMOTION_MAX),
emotions: Array.isArray(raw.emotions)
- ? raw.emotions.map((e) => str(e, EMOTION_MAX)).filter(Boolean).slice(0, 5)
+ ? raw.emotions.map((e) => trimTo(e, EMOTION_MAX)).filter(Boolean).slice(0, 5)
: [],
tension: clampNum(raw.tension, 0, 100),
valence: clampNum(raw.valence, -100, 100),
- note: str(raw.note, NOTE_MAX),
+ note: trimTo(raw.note, NOTE_MAX),
};
}
function sanitizeCharacter(raw) {
if (!raw || typeof raw !== 'object') return null;
- const name = str(raw.name, LABEL_MAX);
+ const name = trimTo(raw.name, LABEL_MAX);
if (!name) return null;
return {
name,
- role: str(raw.role, EMOTION_MAX),
+ role: trimTo(raw.role, EMOTION_MAX),
isProtagonist: raw.isProtagonist === true ? true : raw.isProtagonist === false ? false : null,
arcDirection: ARC_DIRECTIONS.includes(raw.arcDirection) ? raw.arcDirection : 'flat',
- arcSummary: str(raw.arcSummary, NOTE_MAX),
+ arcSummary: trimTo(raw.arcSummary, NOTE_MAX),
beats: Array.isArray(raw.beats)
? raw.beats
.map((b) => (b && typeof b === 'object'
- ? { sectionIndex: clampNum(b.sectionIndex, 0, MAX_SECTIONS), state: str(b.state, LABEL_MAX) }
+ ? { sectionIndex: clampNum(b.sectionIndex, 0, MAX_SECTIONS), state: trimTo(b.state, LABEL_MAX) }
: null))
.filter((b) => b && b.state)
.slice(0, MAX_BEATS)
@@ -138,10 +137,10 @@ function sanitizeAnalysis(parsed) {
characterProgress: clampNum(rollupRaw.characterProgress, 0, 100),
readerValence: clampNum(rollupRaw.readerValence, -100, 100),
readerIntensity: clampNum(rollupRaw.readerIntensity, 0, 100),
- primaryEmotion: str(rollupRaw.primaryEmotion, EMOTION_MAX),
+ primaryEmotion: trimTo(rollupRaw.primaryEmotion, EMOTION_MAX),
peakTension: clampNum(rollupRaw.peakTension, 0, 100),
cliffhanger: rollupRaw.cliffhanger === true,
- oneLine: str(rollupRaw.oneLine, NOTE_MAX),
+ oneLine: trimTo(rollupRaw.oneLine, NOTE_MAX),
},
};
}
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 680987c2fc..dfd7d5b859 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -77,6 +77,7 @@ import {
repairableSeriesFoundationCharacters,
seriesFoundationCharacters,
} from './foundationJudgeContext.js';
+import { trimTo, isNonBlankStr } from '../../lib/textUtils.js';
// Compatibility surface: callers keep importing these projection helpers from
// foundationJudge.js while their implementation lives with the context builder.
@@ -253,14 +254,12 @@ export function foundationFixTarget(dimensions, threshold = DEFAULT_FOUNDATION_T
// ---------- sanitize LLM output ----------
-const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
function sanitizeDimension(raw) {
const d = raw && typeof raw === 'object' ? raw : {};
return {
score: clampScore(d.score),
- gap: str(d.gap, GAP_MAX),
- fix: str(d.fix, FIX_MAX),
+ gap: trimTo(d.gap, GAP_MAX),
+ fix: trimTo(d.fix, FIX_MAX),
};
}
@@ -301,7 +300,7 @@ export function sanitizeFoundationJudge(parsed) {
return {
dimensions,
weightedScore: computeWeightedScore(dimensions),
- oneLineVerdict: str(p.oneLineVerdict, SUMMARY_MAX),
+ oneLineVerdict: trimTo(p.oneLineVerdict, SUMMARY_MAX),
};
}
@@ -1206,10 +1205,9 @@ async function refineWorld(universeId, { providerId, model, effort, onRunCreated
// clear. Writing it would erase the existing unlocked value (sanitize turns a
// non-string into ''). Skip locked fields AND absent/blank ones; preserve the
// current value in both cases (the AGENTS.md absent-vs-empty rule).
- const filled = (v) => typeof v === 'string' && v.trim() !== '';
- if (locked.logline !== true && filled(expanded.logline)) patch.logline = expanded.logline;
- if (locked.premise !== true && filled(expanded.premise)) patch.premise = expanded.premise;
- if (locked.styleNotes !== true && filled(expanded.styleNotes)) patch.styleNotes = expanded.styleNotes;
+ if (locked.logline !== true && isNonBlankStr(expanded.logline)) patch.logline = expanded.logline;
+ if (locked.premise !== true && isNonBlankStr(expanded.premise)) patch.premise = expanded.premise;
+ if (locked.styleNotes !== true && isNonBlankStr(expanded.styleNotes)) patch.styleNotes = expanded.styleNotes;
// `influences` is an { embrace, avoid } object and updateUniverse replaces it
// WHOLESALE — but the lockable keys are the two SUBLISTS
// (`influencesEmbrace`/`influencesAvoid`, see universeBuilder LOCKABLE_FIELDS),
diff --git a/server/services/pipeline/issueCrud.js b/server/services/pipeline/issueCrud.js
index 24fbd7ee5d..6227cf41a5 100644
--- a/server/services/pipeline/issueCrud.js
+++ b/server/services/pipeline/issueCrud.js
@@ -11,7 +11,6 @@
import { randomUUID } from 'crypto';
import { pickRenderedFilename } from '../../lib/renderSlot.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
import * as seriesSvc from './series.js';
@@ -22,6 +21,7 @@ import {
ERR_NOT_FOUND, ERR_VALIDATION, ERR_DUPLICATE, ERR_SEASON_LOCKED,
TITLE_MAX, SERIES_ID_MAX, ISSUES_PER_RESPONSE_MAX,
} from './issuesShared.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export async function listIssues({
seriesId = null,
diff --git a/server/services/pipeline/issueStages.js b/server/services/pipeline/issueStages.js
index 8eb8a62f87..57d5c4a8da 100644
--- a/server/services/pipeline/issueStages.js
+++ b/server/services/pipeline/issueStages.js
@@ -9,7 +9,6 @@
*/
import { isPlainObject } from '../../lib/objects.js';
-import { isStr } from '../../lib/storyBible.js';
import { pickRenderedFilename } from '../../lib/renderSlot.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
import { getIssue } from './issueCrud.js';
@@ -20,6 +19,7 @@ import {
ERR_NOT_FOUND, ERR_VALIDATION,
STAGE_IDS, TEXT_STAGE_IDS, VISUAL_STAGE_IDS, AUDIO_STAGE_IDS,
} from './issuesShared.js';
+import { isStr } from '../../lib/textUtils.js';
/**
* Partial update to a single stage on an issue. Use this from generators so
diff --git a/server/services/pipeline/issueSync.js b/server/services/pipeline/issueSync.js
index bd349ff003..20abe92c19 100644
--- a/server/services/pipeline/issueSync.js
+++ b/server/services/pipeline/issueSync.js
@@ -7,7 +7,6 @@
* (`store().queueTypeIndexWrite`) for one consistent merge/prune snapshot.
*/
-import { isStr } from '../../lib/storyBible.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
import * as seriesSvc from './series.js';
import {
@@ -15,6 +14,7 @@ import {
flushBaseHashes, deleteSyncBaseHash, withBaseHashFlushBatch,
} from '../../lib/conflictJournal.js';
import { store, readState, saveIssuesNow, renumberInline, sanitizeIssue } from './issuesShared.js';
+import { isStr } from '../../lib/textUtils.js';
/**
* Sync-orchestrator entry point. Merges a remote peer's issues array into
diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.js
index 6fdaba2a1e..447049593d 100644
--- a/server/services/pipeline/issuesShared.js
+++ b/server/services/pipeline/issuesShared.js
@@ -29,7 +29,6 @@ import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { ServerError } from '../../lib/errorHandler.js';
import { ARC_ROLES } from '../../lib/storyArc.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeCoverLike } from '../../lib/renderSlot.js';
import { ensureStoryboardIds } from '../../lib/storyboardScenes.js';
import { applyVolumeOrderedNumbers } from '../../lib/pipelineIssueOrder.js';
@@ -46,6 +45,7 @@ import {
TEXT_STAGE_IDS,
VISUAL_STAGE_IDS,
} from '../../lib/pipelineStages.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
// Backward-compatible data-stage export. Voice navigation now uses the visible
// tab order from pipelineStages.js, but existing service consumers may still
diff --git a/server/services/pipeline/manuscriptComments.js b/server/services/pipeline/manuscriptComments.js
index 6e6faa9d0e..e15380e937 100644
--- a/server/services/pipeline/manuscriptComments.js
+++ b/server/services/pipeline/manuscriptComments.js
@@ -30,6 +30,7 @@ import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { seriesStore, listSeries } from './series.js';
import { REPLACEMENT_STRATEGIES, replacementStrategyForCategory } from './arcPlanner.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
+import { trimTo } from '../../lib/textUtils.js';
// Storage-layout version for the review document. Bump + migrate if the
// comment shape changes in a way older peers can't read.
@@ -57,8 +58,6 @@ export const queueReviewWrite = createKeyedFileWriteQueue();
const emptyReview = () => ({ schemaVersion: SCHEMA_VERSION, comments: [] });
-const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
function sanitizeFix(raw) {
if (!raw || typeof raw !== 'object') return null;
const find = typeof raw.find === 'string' ? raw.find : '';
@@ -74,10 +73,10 @@ function sanitizeFix(raw) {
issueNumber: Number.isInteger(e.issueNumber) ? e.issueNumber : null,
issueId: typeof e.issueId === 'string' ? e.issueId : null,
stageId: typeof e.stageId === 'string' ? e.stageId : null,
- title: clampStr(e.title, 200),
+ title: trimTo(e.title, 200),
find: editFind,
replace: editReplace,
- note: clampStr(e.note, 1000),
+ note: trimTo(e.note, 1000),
};
if (e.fuzzy === true) out.fuzzy = true;
return out;
@@ -125,9 +124,9 @@ function sanitizeAcceptedSnapshot(raw) {
// or older-peer file round-trips without dropping fields.
export function sanitizeComment(raw) {
if (!raw || typeof raw !== 'object') return null;
- const problem = clampStr(raw.problem, 2000);
+ const problem = trimTo(raw.problem, 2000);
if (!problem) return null;
- const category = clampStr(raw.category, 40) || 'other';
+ const category = trimTo(raw.category, 40) || 'other';
const severity = ['high', 'medium', 'low'].includes(raw.severity) ? raw.severity : 'medium';
const status = STATUS_SET.has(raw.status) ? raw.status : 'open';
return {
@@ -152,10 +151,10 @@ export function sanitizeComment(raw) {
// value never reaches here; the clamp is a belt-and-suspenders bound for
// hand-edited / older-peer files. Optional + additive → the synced review doc
// stays backward-compatible (no schema bump needed).
- subtype: clampStr(raw.subtype, 40) || null,
- location: clampStr(raw.location, 200),
+ subtype: trimTo(raw.subtype, 40) || null,
+ location: trimTo(raw.location, 200),
problem,
- suggestion: clampStr(raw.suggestion, 8000),
+ suggestion: trimTo(raw.suggestion, 8000),
// How `suggestion` should be read: 'full-page' = it's a complete replacement
// document (comic-structure panel rewrite); 'delta' = it's advice. Trust a
// valid stored value, else derive from category so legacy comments (written
@@ -163,7 +162,7 @@ export function sanitizeComment(raw) {
replacementStrategy: REPLACEMENT_STRATEGIES.has(raw.replacementStrategy)
? raw.replacementStrategy
: replacementStrategyForCategory(category),
- anchorQuote: clampStr(raw.anchorQuote, 400),
+ anchorQuote: trimTo(raw.anchorQuote, 400),
// Which editorial check produced this finding (#1284). `null` for findings
// from the manuscript-completeness pass (and older peers / legacy records)
// — those predate the registry, so they group as a single un-checked set.
diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.js
index 0feb39657c..89ecadf279 100644
--- a/server/services/pipeline/perspectiveRewrite.js
+++ b/server/services/pipeline/perspectiveRewrite.js
@@ -31,6 +31,7 @@ import { getIssue } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
import { pickAnalyzableContent } from './editorialAnalysis.js';
+import { trimTo } from '../../lib/textUtils.js';
const REWRITE_STAGE = 'pipeline-pov-rewrite';
const ANALYSIS_STAGE = 'pipeline-pov-analysis';
@@ -58,7 +59,6 @@ const REWRITE_OUTPUT_RESERVE_TOKENS = 6_000;
const ANALYSIS_OUTPUT_RESERVE_TOKENS = 3_000;
const nowIso = () => new Date().toISOString();
-const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
const clampNum = (v, min, max, fallback = 0) => {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
@@ -91,17 +91,17 @@ const queueWrite = createKeyedFileWriteQueue();
// POV in everything we know about them.
function shapeCastEntry(char) {
if (!char || typeof char !== 'object') return null;
- const name = str(char.name, 120);
+ const name = trimTo(char.name, 120);
if (!name) return null;
const descriptorParts = [
flattenCanonDescriptorFragments(richCanonDescriptorFragments('character', char)),
- char.personality ? `Personality: ${str(char.personality, 600)}` : '',
- char.background ? `Background: ${str(char.background, 600)}` : '',
+ char.personality ? `Personality: ${trimTo(char.personality, 600)}` : '',
+ char.background ? `Background: ${trimTo(char.background, 600)}` : '',
].filter(Boolean);
return {
- id: str(char.id, 120) || name,
+ id: trimTo(char.id, 120) || name,
name,
- role: str(char.role, 80),
+ role: trimTo(char.role, 80),
descriptor: descriptorParts.join('. '),
};
}
@@ -133,7 +133,7 @@ async function resolveCast(series, issueNumber, keepFullPov = null) {
function sanitizeStringList(raw) {
if (!Array.isArray(raw)) return [];
- return raw.map((v) => str(v, ITEM_MAX)).filter(Boolean).slice(0, MAX_LIST_ITEMS);
+ return raw.map((v) => trimTo(v, ITEM_MAX)).filter(Boolean).slice(0, MAX_LIST_ITEMS);
}
function sanitizeFoldBack(raw) {
@@ -141,9 +141,9 @@ function sanitizeFoldBack(raw) {
return raw
.map((f) => {
if (!f || typeof f !== 'object') return null;
- const suggestion = str(f.suggestion, ITEM_MAX);
+ const suggestion = trimTo(f.suggestion, ITEM_MAX);
if (!suggestion) return null;
- return { suggestion, rationale: str(f.rationale, RATIONALE_MAX) };
+ return { suggestion, rationale: trimTo(f.rationale, RATIONALE_MAX) };
})
.filter(Boolean)
.slice(0, MAX_LIST_ITEMS);
@@ -158,11 +158,11 @@ export function sanitizeAnalysis(parsed) {
arcStrength: {
score: clampNum(arc.score, 0, 100),
strongerThanOriginal: arc.strongerThanOriginal === true,
- rationale: str(arc.rationale, RATIONALE_MAX),
+ rationale: trimTo(arc.rationale, RATIONALE_MAX),
},
foldBackSuggestions: sanitizeFoldBack(p.foldBackSuggestions),
- povJustification: str(p.povJustification, RATIONALE_MAX),
- oneLine: str(p.oneLine, ONE_LINE_MAX),
+ povJustification: trimTo(p.povJustification, RATIONALE_MAX),
+ oneLine: trimTo(p.oneLine, ONE_LINE_MAX),
};
}
@@ -286,7 +286,7 @@ export async function generatePerspectiveRewrite(issueId, { povCharacterId, sour
modelOverride: model,
source: 'pipeline-pov-rewrite',
});
- const rewriteText = str(rewriteResult.content, REWRITE_MAX_CHARS);
+ const rewriteText = trimTo(rewriteResult.content, REWRITE_MAX_CHARS);
if (!rewriteText) return { status: 'empty-rewrite', issueId, seriesId: issue.seriesId };
// 2. Analyze original vs rewrite (structured JSON). Budget against the
diff --git a/server/services/pipeline/pipelineJudge.js b/server/services/pipeline/pipelineJudge.js
index a915bc50a4..e487e1e626 100644
--- a/server/services/pipeline/pipelineJudge.js
+++ b/server/services/pipeline/pipelineJudge.js
@@ -42,6 +42,7 @@ import { pickAnalyzableContent } from './editorialAnalysis.js';
import { getIssue, listIssues } from './issues.js';
import { getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
+import { trimTo } from '../../lib/textUtils.js';
const STAGE = 'pipeline-judge-issue';
@@ -130,18 +131,16 @@ export function computeQualityScore(judgeOverall, slopPenalty) {
// ---------- sanitize LLM output ----------
-const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
const strList = (v, max, cap) => (Array.isArray(v)
- ? v.map((s) => str(s, max)).filter(Boolean).slice(0, cap)
+ ? v.map((s) => trimTo(s, max)).filter(Boolean).slice(0, cap)
: []);
function sanitizeDimension(raw) {
const d = raw && typeof raw === 'object' ? raw : {};
return {
score: clampScore(d.score),
- weakestMoment: str(d.weakestMoment, MOMENT_MAX),
- fix: str(d.fix, FIX_MAX),
+ weakestMoment: trimTo(d.weakestMoment, MOMENT_MAX),
+ fix: trimTo(d.fix, FIX_MAX),
};
}
@@ -166,7 +165,7 @@ export function sanitizeJudge(parsed) {
weakestSentences: strList(p.weakestSentences, SENTENCE_MAX, MAX_SENTENCES),
sceneVsSummaryRatio: Number.isFinite(ratio) ? Math.max(0, Math.min(1, Math.round(ratio * 100) / 100)) : null,
topRevisions: strList(p.topRevisions, REVISION_MAX, MAX_REVISIONS),
- oneLineVerdict: str(p.oneLineVerdict, VERDICT_MAX),
+ oneLineVerdict: trimTo(p.oneLineVerdict, VERDICT_MAX),
};
}
diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.js
index 47c025bd61..0e25f3141b 100644
--- a/server/services/pipeline/reverseOutline.js
+++ b/server/services/pipeline/reverseOutline.js
@@ -31,6 +31,7 @@ import { seriesStore, getSeries } from './series.js';
import { getSeriesCanon } from './seriesCanon.js';
import { collectManuscriptSections, sectionsCorpus } from './arcPlanner.js';
import { emitRecordUpdated } from '../sharing/recordEvents.js';
+import { trimTo } from '../../lib/textUtils.js';
const STAGE = 'pipeline-reverse-outline';
@@ -84,7 +85,6 @@ const PLOTLINE_COLORS = Object.freeze([
const UNASSIGNED_PLOTLINE = Object.freeze({ id: '_unassigned', label: 'Unassigned', kind: 'other', color: '#6b7280' });
const nowIso = () => new Date().toISOString();
-const clampStr = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
const colorForIndex = (i) => PLOTLINE_COLORS[i % PLOTLINE_COLORS.length];
// Content hash — pins the analyzed manuscript so a later edit flips the outline
@@ -111,8 +111,8 @@ function sanitizePlotlines(rawList) {
for (const raw of Array.isArray(rawList) ? rawList : []) {
if (out.length >= MAX_PLOTLINES) break;
if (!raw || typeof raw !== 'object') continue;
- const id = clampStr(raw.id, PLOTLINE_ID_MAX);
- const label = clampStr(raw.label, LABEL_MAX);
+ const id = trimTo(raw.id, PLOTLINE_ID_MAX);
+ const label = trimTo(raw.label, LABEL_MAX);
if (!id || !label || seen.has(id)) continue;
seen.add(id);
out.push({
@@ -139,13 +139,13 @@ function sanitizeComponents(raw) {
// synthetic '_unassigned' plotline so the grid never references a missing row).
function sanitizeScene(raw, idx, { byNumber, plotlineIds }) {
if (!raw || typeof raw !== 'object') return null;
- const summary = clampStr(raw.summary, SUMMARY_MAX);
- const heading = clampStr(raw.heading, LABEL_MAX);
+ const summary = trimTo(raw.summary, SUMMARY_MAX);
+ const heading = trimTo(raw.heading, LABEL_MAX);
if (!summary && !heading) return null;
const issueNumber = Number.isInteger(raw.issueNumber) ? raw.issueNumber : null;
const section = issueNumber != null ? byNumber.get(issueNumber) : null;
- const primary = clampStr(raw.plotlineId, PLOTLINE_ID_MAX);
- const secondary = clampStr(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);
+ const primary = trimTo(raw.plotlineId, PLOTLINE_ID_MAX);
+ const secondary = trimTo(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);
return {
id: `scene-${String(idx + 1).padStart(3, '0')}`,
sequence: idx,
@@ -154,14 +154,14 @@ function sanitizeScene(raw, idx, { byNumber, plotlineIds }) {
issueTitle: section ? section.title : '',
heading: heading || summary.slice(0, LABEL_MAX),
summary,
- anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX),
- povCharacter: clampStr(raw.povCharacter, NAME_MAX) || null,
+ anchorQuote: trimTo(raw.anchorQuote, ANCHOR_MAX),
+ povCharacter: trimTo(raw.povCharacter, NAME_MAX) || null,
plotlineId: plotlineIds.has(primary) ? primary : UNASSIGNED_PLOTLINE.id,
secondaryPlotlineId: secondary && plotlineIds.has(secondary) && secondary !== primary ? secondary : null,
components: sanitizeComponents(raw.components),
- setting: clampStr(raw.setting, SETTING_MAX),
+ setting: trimTo(raw.setting, SETTING_MAX),
charactersPresent: Array.isArray(raw.charactersPresent)
- ? raw.charactersPresent.map((n) => clampStr(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)
+ ? raw.charactersPresent.map((n) => trimTo(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)
: [],
};
}
@@ -382,27 +382,27 @@ export async function getStoredOutline(seriesId) {
// peer may not hold the drafted manuscript, and the issues sync separately.
function sanitizeSyncedScene(raw, idx, plotlineIds) {
if (!raw || typeof raw !== 'object') return null;
- const summary = clampStr(raw.summary, SUMMARY_MAX);
- const heading = clampStr(raw.heading, LABEL_MAX);
+ const summary = trimTo(raw.summary, SUMMARY_MAX);
+ const heading = trimTo(raw.heading, LABEL_MAX);
if (!summary && !heading) return null;
- const primary = clampStr(raw.plotlineId, PLOTLINE_ID_MAX);
- const secondary = clampStr(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);
+ const primary = trimTo(raw.plotlineId, PLOTLINE_ID_MAX);
+ const secondary = trimTo(raw.secondaryPlotlineId, PLOTLINE_ID_MAX);
return {
id: `scene-${String(idx + 1).padStart(3, '0')}`,
sequence: idx,
issueNumber: Number.isInteger(raw.issueNumber) ? raw.issueNumber : null,
- issueId: clampStr(raw.issueId, ISSUE_ID_MAX) || null,
- issueTitle: clampStr(raw.issueTitle, LABEL_MAX),
+ issueId: trimTo(raw.issueId, ISSUE_ID_MAX) || null,
+ issueTitle: trimTo(raw.issueTitle, LABEL_MAX),
heading: heading || summary.slice(0, LABEL_MAX),
summary,
- anchorQuote: clampStr(raw.anchorQuote, ANCHOR_MAX),
- povCharacter: clampStr(raw.povCharacter, NAME_MAX) || null,
+ anchorQuote: trimTo(raw.anchorQuote, ANCHOR_MAX),
+ povCharacter: trimTo(raw.povCharacter, NAME_MAX) || null,
plotlineId: plotlineIds.has(primary) ? primary : UNASSIGNED_PLOTLINE.id,
secondaryPlotlineId: secondary && plotlineIds.has(secondary) && secondary !== primary ? secondary : null,
components: sanitizeComponents(raw.components),
- setting: clampStr(raw.setting, SETTING_MAX),
+ setting: trimTo(raw.setting, SETTING_MAX),
charactersPresent: Array.isArray(raw.charactersPresent)
- ? raw.charactersPresent.map((n) => clampStr(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)
+ ? raw.charactersPresent.map((n) => trimTo(n, NAME_MAX)).filter(Boolean).slice(0, MAX_CHARS_PRESENT)
: [],
};
}
@@ -433,11 +433,11 @@ function sanitizeSyncedOutline(raw) {
return {
schemaVersion: SCHEMA_VERSION,
status: 'complete',
- sourceContentHash: clampStr(raw.sourceContentHash, HASH_MAX) || null,
+ sourceContentHash: trimTo(raw.sourceContentHash, HASH_MAX) || null,
truncated: raw.truncated === true,
- providerId: clampStr(raw.providerId, PROVIDER_MAX) || null,
- model: clampStr(raw.model, PROVIDER_MAX) || null,
- runId: clampStr(raw.runId, PROVIDER_MAX) || null,
+ providerId: trimTo(raw.providerId, PROVIDER_MAX) || null,
+ model: trimTo(raw.model, PROVIDER_MAX) || null,
+ runId: trimTo(raw.runId, PROVIDER_MAX) || null,
generatedAt,
plotlines,
scenes,
diff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.js
index 7efbcfe8bb..ffc3ca2122 100644
--- a/server/services/pipeline/seasons.js
+++ b/server/services/pipeline/seasons.js
@@ -12,10 +12,10 @@
*/
import { ARC_LIMITS, buildSeason, sanitizeSeason } from '../../lib/storyArc.js';
-import { isStr } from '../../lib/storyBible.js';
import * as seriesSvc from './series.js';
import * as issuesSvc from './issues.js';
import { emitRecordUpdated, withReexportSuppressed } from '../sharing/recordEvents.js';
+import { isStr } from '../../lib/textUtils.js';
export const ERR_NOT_FOUND = 'PIPELINE_SEASON_NOT_FOUND';
export const ERR_VALIDATION = 'PIPELINE_SEASON_VALIDATION';
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index e1288dc1ac..77a47a7fae 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -13,7 +13,6 @@
import { randomUUID } from 'crypto';
import { getSeriesStore } from './seriesStore/store.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';
import { sanitizeStyleGuide } from '../../lib/styleGuide.js';
@@ -35,6 +34,7 @@ import {
autoSubscribeRecordToAllPeers, unsubscribeAllForRecord,
} from '../sharing/recordEvents.js';
import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
// Storage backend dispatcher (#1015). Series records moved from per-record
// `data/pipeline-series/{id}/index.json` (collectionStore) to one-row-per-series
diff --git a/server/services/pipeline/seriesAutopilot/diagnosisCore.js b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
index a88da9ba10..ade2db8fa2 100644
--- a/server/services/pipeline/seriesAutopilot/diagnosisCore.js
+++ b/server/services/pipeline/seriesAutopilot/diagnosisCore.js
@@ -21,8 +21,8 @@
import { PORTOS_APP_ID } from '../../../lib/appIdentity.js';
import { PR_COMPLETIONS } from '../../../lib/prDisposition.js';
-import { trimToClause } from '../../../lib/storyBible.js';
import { slugify } from '../../../lib/planIds.js';
+import { trimToClause } from '../../../lib/textUtils.js';
// The verdict vocabulary. `pipeline` is the only one that files anything;
// `content` means the manuscript, not the code, needs work, and `none` means
diff --git a/server/services/pipeline/seriesAutopilot/observer.js b/server/services/pipeline/seriesAutopilot/observer.js
index 82569f4c3c..6ad03f61dd 100644
--- a/server/services/pipeline/seriesAutopilot/observer.js
+++ b/server/services/pipeline/seriesAutopilot/observer.js
@@ -43,7 +43,6 @@
import * as cosTaskStore from '../../cosTaskStore.js';
import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';
import { runStagedLLM } from '../../stageRunner.js';
-import { trimToClause } from '../../../lib/storyBible.js';
import { getSettings } from '../../settings.js';
import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';
import { getSeries } from '../series.js';
@@ -54,6 +53,7 @@ import {
diagnosisEnabled, isActionableDiagnosis, isAutomationSignal, shapeDiagnosis,
terminalWarrantsDiagnosis,
} from './diagnosisCore.js';
+import { trimToClause } from '../../../lib/textUtils.js';
const OBSERVER_STAGE = 'pipeline-observer';
diff --git a/server/services/pipeline/seriesAutopilot/selfImprove.js b/server/services/pipeline/seriesAutopilot/selfImprove.js
index 2a85815e45..16345cb455 100644
--- a/server/services/pipeline/seriesAutopilot/selfImprove.js
+++ b/server/services/pipeline/seriesAutopilot/selfImprove.js
@@ -51,7 +51,6 @@
import * as cosTaskStore from '../../cosTaskStore.js';
import { getDomainBudgetStatus, recordDomainUsage } from '../../domainUsage.js';
import { runStagedLLM } from '../../stageRunner.js';
-import { trimToClause } from '../../../lib/storyBible.js';
import { getSettings } from '../../settings.js';
import { buildEditorialCheckPlan } from '../editorial/checkRunner.js';
import { getSeries } from '../series.js';
@@ -61,6 +60,7 @@ import {
SELF_IMPROVE_AREAS, buildDiagnosisStageVars, buildDiagnosisTask, diagnosisEnabled,
hasAutomationSignals, isActionableDiagnosis, shapeDiagnosis, terminalWarrantsDiagnosis,
} from './diagnosisCore.js';
+import { trimToClause } from '../../../lib/textUtils.js';
// Re-export the shared diagnosis vocabulary under this module's established
// import surface (tests and the barrel reach it here).
diff --git a/server/services/pipeline/seriesGenerate.js b/server/services/pipeline/seriesGenerate.js
index 1fe8538e14..864371cefd 100644
--- a/server/services/pipeline/seriesGenerate.js
+++ b/server/services/pipeline/seriesGenerate.js
@@ -47,6 +47,7 @@ import { renderCharacterNarrativeContext } from '../../lib/universePromptRendere
import { runStagedLLM, resolveJudgeForStage } from '../stageRunner.js';
import { getStage } from '../promptService.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { trimTo } from '../../lib/textUtils.js';
const CANON_LIST_MAX = 24; // cap per canon kind in the brief — keeps the prompt tight
// Cap on the authored-psychology block. The roster above stays a scannable
@@ -80,8 +81,6 @@ export const ANTI_GENERIC_BANLIST = Object.freeze([
'a mentor who dies to motivate the hero',
]);
-const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
-
const rangeIndices = (n) => Array.from({ length: n }, (_, i) => i);
// Clamp a caller-supplied concept count into [MIN, MAX], defaulting when absent
@@ -190,20 +189,20 @@ function buildContext(universe, existingSeries) {
// picker UI and fed to the judge, not persisted on the series record.
function normalizeCandidate(raw) {
if (raw == null || typeof raw !== 'object') return null;
- const name = str(raw.name, NAME_MAX);
+ const name = trimTo(raw.name, NAME_MAX);
if (!name) return null;
const shapeRaw = typeof raw.shape === 'string' ? raw.shape.trim() : '';
return {
name,
- logline: str(raw.logline, LOGLINE_MAX),
- premise: str(raw.premise, PREMISE_MAX),
+ logline: trimTo(raw.logline, LOGLINE_MAX),
+ premise: trimTo(raw.premise, PREMISE_MAX),
shape: ARC_SHAPE_IDS.includes(shapeRaw) ? shapeRaw : null,
- hook: str(raw.hook, FACET_MAX),
- world: str(raw.world, FACET_MAX),
- conflictEngine: str(raw.conflictEngine, FACET_MAX),
- cost: str(raw.cost, FACET_MAX),
- tension: str(raw.tension, FACET_MAX),
- theme: str(raw.theme, FACET_MAX),
+ hook: trimTo(raw.hook, FACET_MAX),
+ world: trimTo(raw.world, FACET_MAX),
+ conflictEngine: trimTo(raw.conflictEngine, FACET_MAX),
+ cost: trimTo(raw.cost, FACET_MAX),
+ tension: trimTo(raw.tension, FACET_MAX),
+ theme: trimTo(raw.theme, FACET_MAX),
};
}
@@ -309,7 +308,7 @@ export function parseConceptPick(content, n) {
// Ensure the winner leads the ranking, and every candidate appears once.
const ordered = [index, ...ranking.filter((i) => i !== index)];
for (const i of rangeIndices(n)) if (!ordered.includes(i)) ordered.push(i);
- const rationale = str(content.rationale, 600);
+ const rationale = trimTo(content.rationale, 600);
return { index, ranking: ordered, rationale };
}
diff --git a/server/services/recordMerge.js b/server/services/recordMerge.js
index f5fb44a32d..1a20e73313 100644
--- a/server/services/recordMerge.js
+++ b/server/services/recordMerge.js
@@ -29,7 +29,7 @@ import {
normalizeLabelKey,
VARIATIONS_PER_CATEGORY_MAX, COMPOSITE_SHEETS_MAX, INFLUENCES_PER_LIST_MAX, IMAGE_REFS_PER_ENTRY_MAX,
} from './universeBuilder.js';
-import { mergeExtractedBible, BIBLE_KIND, isStr } from '../lib/storyBible.js';
+import { mergeExtractedBible, BIBLE_KIND } from '../lib/storyBible.js';
import { canonicalStringify, isEmptyScalar } from '../lib/objects.js';
import { getSeries, updateSeries, deleteSeries, listSeries } from './pipeline/series.js';
import { reassignIssuesToSeries, recomputeIssueNumbersForSeries, listIssues } from './pipeline/issues.js';
@@ -38,6 +38,7 @@ import {
findCollectionBySeriesId, findOrCreateSeriesCollection,
bulkUpdateCollectionItems, deleteCollection,
} from './mediaCollections.js';
+import { isStr } from '../lib/textUtils.js';
// Own error code (both the universe-builder and pipeline routers map it to
// 400). get*() NOT_FOUND errors propagate with their own per-record codes,
diff --git a/server/services/recordMergeAI.js b/server/services/recordMergeAI.js
index 987d98405f..552a71b8dd 100644
--- a/server/services/recordMergeAI.js
+++ b/server/services/recordMergeAI.js
@@ -12,6 +12,7 @@ import { ServerError } from '../lib/errorHandler.js';
import { extractJson as extractJsonShared } from '../lib/jsonExtract.js';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
import { stripPromptControlChars, buildUniverseStyleContext } from './universeBuilder.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
export const ERR_NO_PROVIDER = 'MERGE_AI_NO_PROVIDER';
export const ERR_NO_MERGEABLE_FIELDS = 'MERGE_AI_NO_MERGEABLE_FIELDS';
@@ -19,8 +20,6 @@ export const ERR_INVALID_JSON = 'LLM_INVALID_JSON';
const MAX_FIELD_CHARS = 4000;
-const isMergeableString = (v) => typeof v === 'string' && v.trim().length > 0;
-
const buildPrompt = ({ kind, survivor, loser, fields }) => {
const fieldBlocks = fields.map(({ field, survivorValue, loserValue }) => {
const a = stripPromptControlChars(String(survivorValue)).slice(0, MAX_FIELD_CHARS);
@@ -88,7 +87,7 @@ export async function mergeFieldsWithAI({ kind, survivor, loser, fields, provide
if (typeof field !== 'string' || !field) continue;
const sv = survivor[field];
const lv = loser[field];
- if (isMergeableString(sv) && isMergeableString(lv)) {
+ if (isNonBlankStr(sv) && isNonBlankStr(lv)) {
mergeable.push({ field, survivorValue: sv, loserValue: lv });
} else {
skipped.push(field);
diff --git a/server/services/rigging/retargetReport.js b/server/services/rigging/retargetReport.js
index 681689f278..2f2a210821 100644
--- a/server/services/rigging/retargetReport.js
+++ b/server/services/rigging/retargetReport.js
@@ -26,6 +26,7 @@
* is NOT declared here: a retarget report rides the Phase 2 `AUTO_SKIN_REPORT_VERSION`
* that `publishRigArtifacts` stamps, because there is one rigging report format.
*/
+import { isNonBlankStr } from '../../lib/textUtils.js';
export const RETARGET_REPORT_KIND = 'retarget';
/**
@@ -95,7 +96,6 @@ export const RETARGET_FAILURE_REASONS = Object.freeze({
const isCount = (value) => Number.isInteger(value) && value >= 0;
const isNonNegative = (value) => Number.isFinite(value) && value >= 0;
-const isNamed = (value) => typeof value === 'string' && value.trim().length > 0;
const formatPercent = (fraction) => `${(Number(fraction) * 100).toFixed(1)}%`;
/**
@@ -109,8 +109,8 @@ function readMeasurements(report) {
const motion = report?.motion;
const roundTrip = report?.round_trip;
if (!isCount(report?.vertices?.total)) return null;
- if (!isNamed(skeleton?.hint) || !Array.isArray(skeleton?.unmapped_bones) || !isCount(skeleton?.mapped_bones)) return null;
- if (!isNamed(cleanup?.mode) || !isCount(cleanup?.proposed_vertices) || !isCount(cleanup?.changed_vertices)) return null;
+ if (!isNonBlankStr(skeleton?.hint) || !Array.isArray(skeleton?.unmapped_bones) || !isCount(skeleton?.mapped_bones)) return null;
+ if (!isNonBlankStr(cleanup?.mode) || !isCount(cleanup?.proposed_vertices) || !isCount(cleanup?.changed_vertices)) return null;
if (!isCount(motion?.sampled_frames) || !isNonNegative(motion?.max_joint_translation)) return null;
if (!roundTrip || typeof roundTrip !== 'object') return null;
return { skeleton, cleanup, motion, roundTrip, totalVertices: report.vertices.total };
@@ -170,7 +170,7 @@ export function reduceRetargetGate(report, { thresholds = RETARGET_DEFAULTS, mod
changedCleanupVertices: measured.cleanup.changed_vertices,
cleanupCapVertices: capVertices,
cleanupOverCap: measured.cleanup.proposed_vertices > capVertices,
- exportedClipName: isNamed(measured.roundTrip.clip_name) ? measured.roundTrip.clip_name : null,
+ exportedClipName: isNonBlankStr(measured.roundTrip.clip_name) ? measured.roundTrip.clip_name : null,
exportedClipDuration: Number.isFinite(measured.roundTrip.clip_duration) ? measured.roundTrip.clip_duration : 0,
sampledFrames: measured.motion.sampled_frames,
maxJointTranslation: measured.motion.max_joint_translation,
diff --git a/server/services/sceneExtractor.js b/server/services/sceneExtractor.js
index 6a65417732..725487499d 100644
--- a/server/services/sceneExtractor.js
+++ b/server/services/sceneExtractor.js
@@ -19,8 +19,9 @@
*/
import { runStagedLLM } from './stageRunner.js';
-import { BIBLE_KIND, pickPromptFields, isStr, trimTo } from '../lib/storyBible.js';
+import { BIBLE_KIND, pickPromptFields } from '../lib/storyBible.js';
import { normalizeShotType, normalizeScreenDirection } from '../lib/shotGrammar.js';
+import { isStr, trimTo } from '../lib/textUtils.js';
export const SOURCE_KIND = Object.freeze({ PROSE: 'prose', TELEPLAY: 'teleplay' });
diff --git a/server/services/sharing/annotationIdentity.js b/server/services/sharing/annotationIdentity.js
index 82f3f92e76..d797574982 100644
--- a/server/services/sharing/annotationIdentity.js
+++ b/server/services/sharing/annotationIdentity.js
@@ -22,7 +22,7 @@
import * as os from 'os';
import { getSettings, settingsEvents } from '../settings.js';
-import { isStr } from '../../lib/storyBible.js';
+import { isStr } from '../../lib/textUtils.js';
const CACHE_TTL_MS = 30_000;
let cachedName = null;
diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.js
index b1ea194c1b..73005aeccb 100644
--- a/server/services/sharing/buckets.js
+++ b/server/services/sharing/buckets.js
@@ -14,8 +14,8 @@ import { randomUUID } from 'crypto';
import { join, basename } from 'path';
import { access, constants, stat } from 'fs/promises';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
-import { isStr, trimTo } from '../../lib/storyBible.js';
import { SHARING_SCHEMA_VERSION } from './version.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
const REGISTRY_PATH = () => join(PATHS.data, 'sharing', 'buckets.json');
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index b27efac2ab..f6cc5cfc26 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -35,8 +35,9 @@ import { getInstanceId } from '../instanceIdentity.js';
import { getSettings } from '../settings.js';
import { getProducedByVersion } from './version.js';
import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';
-import { isStr, listSheetPointers } from '../../lib/storyBible.js';
+import { listSheetPointers } from '../../lib/storyBible.js';
import { resolveBucketSourceName as resolveSourceName } from './annotationIdentity.js';
+import { isStr } from '../../lib/textUtils.js';
/**
* Best-effort cap on the bucket's manifest directory after each export.
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 693237f732..f14d1c5dcf 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -42,9 +42,10 @@ import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem a
import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';
import { mergePeerAnnotations } from '../mediaAnnotations.js';
-import { isStr, preserveLegacyCharacterFields } from '../../lib/storyBible.js';
+import { preserveLegacyCharacterFields } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { maybeJournalBeforeOverwrite, flushBaseHashes, setSyncBaseHash, contentHashForRecord } from '../../lib/conflictJournal.js';
+import { isStr } from '../../lib/textUtils.js';
// Record kinds that participate in the non-blocking conflict journal. Universe,
// series, AND issue all seed a base hash on first import and archive a losing
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 1d1223a445..8306f2c39a 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -21,9 +21,9 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { isPlainObject } from '../../lib/objects.js';
import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';
-import { isStr } from '../../lib/storyBible.js';
import { universeCollectionNameFor, seriesCollectionNameFor } from '../mediaCollections.js';
import { UNKNOWN_INSTANCE_ID } from '../instanceIdentity.js';
+import { isStr } from '../../lib/textUtils.js';
export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'media-annotations']);
diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.js
index bd188eba4d..3c81f6032b 100644
--- a/server/services/sharing/peerCosSync.js
+++ b/server/services/sharing/peerCosSync.js
@@ -14,7 +14,6 @@ import { existsSync } from 'fs';
import { readdir } from 'fs/promises';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, ensureDir, sha256File, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
-import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
@@ -35,6 +34,7 @@ import {
ASSET_PULL_TIMEOUT_MS,
} from './peerSyncAssets.js';
import { findPeerById, FORCE_REVALIDATE_EVERY, peerSyncEvents } from './peerSyncShared.js';
+import { isStr } from '../../lib/textUtils.js';
// --- Completed-agent CoS history federation (#1650) ---------------------
diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.js
index 59fc9afc06..b09190c907 100644
--- a/server/services/sharing/peerMediaLibrarySync.js
+++ b/server/services/sharing/peerMediaLibrarySync.js
@@ -14,7 +14,6 @@ import { readdir, stat } from 'fs/promises';
import { createHash } from 'crypto';
import { PATHS } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
-import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
@@ -30,7 +29,8 @@ import {
pullMissingAssetsFromPeer,
ASSET_PULL_TIMEOUT_MS,
} from './peerSyncAssets.js';
-import { findPeerById, isNonEmptyStr, FORCE_REVALIDATE_EVERY } from './peerSyncShared.js';
+import { findPeerById, FORCE_REVALIDATE_EVERY } from './peerSyncShared.js';
+import { isStr, isNonBlankStr } from '../../lib/textUtils.js';
// --- Standalone media-library federation (#1566) ------------------------
diff --git a/server/services/sharing/peerSubscriptions.js b/server/services/sharing/peerSubscriptions.js
index f071c5beaa..4787dcc960 100644
--- a/server/services/sharing/peerSubscriptions.js
+++ b/server/services/sharing/peerSubscriptions.js
@@ -18,7 +18,6 @@ import {
ERR_NOT_FOUND,
ERR_VALIDATION,
makeErr,
- isNonEmptyStr,
subscriptionId,
readState,
writeState,
@@ -26,6 +25,7 @@ import {
KIND_TO_CATEGORY,
} from './peerSyncShared.js';
import { pushRecordToPeer } from './peerSyncPush.js';
+import { isNonBlankStr } from '../../lib/textUtils.js';
// subId → Timeout for the debounced push scheduler. Lives beside the
// subscription rows because `unsubscribePeer` must cancel a pending timer as
@@ -109,11 +109,11 @@ export async function getOutboundCoverageForPeer(peerId) {
// NOT add an `authors` key here (it would have no consumer in dataSync's
// snapshot exclude path and would imply a snapshot category that doesn't exist).
const coverage = { universe: new Set(), pipeline: new Set(), mediaCollections: new Set() };
- if (!isNonEmptyStr(peerId)) return coverage;
+ if (!isNonBlankStr(peerId)) return coverage;
const subs = await listPeerSubscriptions({ peerId });
for (const sub of subs) {
const category = KIND_TO_CATEGORY[sub.recordKind];
- if (!category || !isNonEmptyStr(sub.recordId)) continue;
+ if (!category || !isNonBlankStr(sub.recordId)) continue;
coverage[category]?.add(sub.recordId);
}
return coverage;
@@ -144,7 +144,7 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})
if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) {
throw makeErr(`subscribable kinds are ${PEER_SUBSCRIBABLE_KINDS.join(', ')} (got "${recordKind}")`, ERR_VALIDATION);
}
- if (!isNonEmptyStr(peerId) || !isNonEmptyStr(recordId)) {
+ if (!isNonBlankStr(peerId) || !isNonBlankStr(recordId)) {
throw makeErr('peerId and recordId are required', ERR_VALIDATION);
}
@@ -232,7 +232,7 @@ export async function subscribePeer({ peerId, recordKind, recordId }, opts = {})
}
export async function unsubscribePeer(id) {
- if (!isNonEmptyStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);
+ if (!isNonBlankStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);
const { sub, stillSubscribed } = await withStateLock(async () => {
const state = await readState();
const idx = state.subscriptions.findIndex((s) => s.id === id);
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index b94eeda53e..624082bb8b 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -46,7 +46,6 @@ import { listCommissionsForSync } from '../creativeCommissions/store.js';
import { initCursor } from './peerTombstoneCursors.js';
import {
PEER_SUBSCRIBABLE_KINDS,
- isNonEmptyStr,
readState,
drainWriteTail,
DEBOUNCE_MS,
@@ -67,6 +66,7 @@ import {
subscribePeer,
unsubscribePeer,
} from './peerSubscriptions.js';
+import { isNonBlankStr } from '../../lib/textUtils.js';
// Re-export the decomposed modules' public surface so existing deep importers
// keep working without a re-import. (#1830)
@@ -117,9 +117,9 @@ export {
* per-peer failures so a single offline peer can't block the creation path.
*/
export async function autoSubscribeRecordToAllPeers(recordKind, recordId) {
- if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonEmptyStr(recordId)) return [];
+ if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonBlankStr(recordId)) return [];
const peers = await getPeers().catch(() => []);
- const targets = peers.filter(p => isNonEmptyStr(p.instanceId) && peerAllowsOutbound(p) && peerHasCategory(p, recordKind));
+ const targets = peers.filter(p => isNonBlankStr(p.instanceId) && peerAllowsOutbound(p) && peerHasCategory(p, recordKind));
if (targets.length === 0) return [];
// Only track + log subscriptions that were *newly created* on this call.
// `subscribePeer` is idempotent, so a re-run against already-subscribed
@@ -218,11 +218,11 @@ const RECORD_KIND_LISTERS = {
*/
async function listRecordsForKind(recordKind) {
const records = await (RECORD_KIND_LISTERS[recordKind]?.() ?? []);
- return records.filter(r => r?.ephemeral !== true && isNonEmptyStr(r?.id));
+ return records.filter(r => r?.ephemeral !== true && isNonBlankStr(r?.id));
}
export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
- if (!isNonEmptyStr(peerId) || !PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) return [];
+ if (!isNonBlankStr(peerId) || !PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) return [];
// Re-check the peer is enabled + outbound-capable + still has the category
// turned on. The caller (instances.updatePeer) already saw the false→true
// flip inside withData, but this helper is also reachable from other
@@ -243,7 +243,7 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
// running only for records that genuinely need a new sub.
const existingSubs = await listPeerSubscriptions({ peerId, recordKind });
const existingIds = new Set(existingSubs.map(s => s.recordId));
- const missing = records.filter(r => isNonEmptyStr(r.id) && !existingIds.has(r.id));
+ const missing = records.filter(r => isNonBlankStr(r.id) && !existingIds.has(r.id));
if (missing.length === 0) return [];
// Initialize the tombstone cursor for this peer ONCE up front. Each
// subsequent subscribePeer call passes `skipCursorInit: true` ONLY when
@@ -290,7 +290,7 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {
*/
export async function getFullSyncCoverageForPeer(peerId) {
const empty = { total: 0, confirmed: 0, pending: 0, fullyMirrored: true, byKind: {} };
- if (!isNonEmptyStr(peerId)) return empty;
+ if (!isNonBlankStr(peerId)) return empty;
// Each kind's record list + subscription list are independent I/O — fetch all
// kinds (and the two lists within a kind) concurrently.
const perKind = await Promise.all(PEER_SUBSCRIBABLE_KINDS.map(async (kind) => {
@@ -360,7 +360,7 @@ export async function unsubscribeAllForPeer(peerId) {
* future caller that DOES want to verify completion can.
*/
export async function unsubscribeAllForRecord(recordKind, recordId) {
- if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonEmptyStr(recordId)) {
+ if (!PEER_SUBSCRIBABLE_KINDS.includes(recordKind) || !isNonBlankStr(recordId)) {
return { removed: [], failed: [] };
}
const matching = await listPeerSubscriptions({ recordKind, recordId });
@@ -409,7 +409,7 @@ export async function pruneOrphanedPeerSubscriptions(resolver) {
const subs = await listPeerSubscriptions();
const removed = [];
for (const sub of subs) {
- if (!isNonEmptyStr(sub?.recordKind) || !isNonEmptyStr(sub?.recordId)) continue;
+ if (!isNonBlankStr(sub?.recordKind) || !isNonBlankStr(sub?.recordId)) continue;
const exists = await resolver(sub.recordKind, sub.recordId).catch(() => true);
if (exists) continue;
const ok = await unsubscribePeer(sub.id).then(() => true).catch((err) => {
@@ -512,9 +512,9 @@ export async function collectSubscriptionsForUpdate(recordKind, recordId) {
// list is small (per-install), so a full scan on the debounce path is fine —
// same posture as getIssueSeriesId's issue scan below.
async function collectMusicVideoSubsForTrack(trackId) {
- if (!isNonEmptyStr(trackId)) return [];
+ if (!isNonBlankStr(trackId)) return [];
const projects = await listMusicVideoProjects({ includeDeleted: false }).catch(() => []);
- const linked = projects.filter((p) => p?.trackId === trackId && isNonEmptyStr(p?.id));
+ const linked = projects.filter((p) => p?.trackId === trackId && isNonBlankStr(p?.id));
if (linked.length === 0) return [];
const subLists = await Promise.all(
linked.map((p) => listPeerSubscriptions({ recordKind: 'musicVideoProject', recordId: p.id })),
@@ -550,7 +550,7 @@ async function getIssueSeriesId(issueId) {
* edit) gets another attempt.
*/
export async function retryPendingPushesForPeer(peerId) {
- if (!isNonEmptyStr(peerId)) return { walked: 0, pushed: 0 };
+ if (!isNonBlankStr(peerId)) return { walked: 0, pushed: 0 };
const subs = await listPeerSubscriptions({ peerId });
if (subs.length === 0) return { walked: 0, pushed: 0 };
// Separate counter for the log line — only count subs that were never
@@ -615,7 +615,7 @@ export async function getRecordPayloadForPeer(recordKind, recordId) {
// sourceInstanceId would 500 here or poison the puller (applyIncomingPush
// rejects sourceInstanceId='unknown'). Return null → the route 404s.
const instanceId = await getInstanceId().catch(() => null);
- if (!isNonEmptyStr(instanceId) || instanceId === UNKNOWN_INSTANCE_ID) return null;
+ if (!isNonBlankStr(instanceId) || instanceId === UNKNOWN_INSTANCE_ID) return null;
return buildPushPayload({ recordKind, recordId }, instanceId);
}
diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.js
index c108801e97..b7e5df8e47 100644
--- a/server/services/sharing/peerSyncAssets.js
+++ b/server/services/sharing/peerSyncAssets.js
@@ -13,7 +13,6 @@ import { join } from 'path';
import { existsSync } from 'fs';
import { createHash } from 'crypto';
import { PATHS, atomicWrite, readJSONFile, ensureDir, sha256File } from '../../lib/fileUtils.js';
-import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
@@ -38,7 +37,8 @@ import { WRITERS_ROOM_DRAFT_ASSET_KIND } from '../writersRoom/syncLogic.js';
import { WORK_ID_RE, DRAFT_ID_RE, wrWorkDir, wrDraftPath } from '../writersRoom/_shared.js';
import { getWorkForSync } from '../writersRoom/sync.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
-import { peerSyncEvents, findPeerById, isNonEmptyStr } from './peerSyncShared.js';
+import { peerSyncEvents, findPeerById } from './peerSyncShared.js';
+import { isStr, isNonBlankStr } from '../../lib/textUtils.js';
// --- Asset manifest -----------------------------------------------------
@@ -129,7 +129,7 @@ function summarizeAssetManifest(manifest) {
const entries = Array.isArray(manifest) ? manifest : [];
return {
assetHashes: entries.map((e) => e.sha256).filter(Boolean).sort(),
- metadataMissing: entries.some((e) => e?.kind === 'image' && !isNonEmptyStr(e.sidecarSha256)),
+ metadataMissing: entries.some((e) => e?.kind === 'image' && !isNonBlankStr(e.sidecarSha256)),
};
}
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index 4cd7e3e3d2..b169f8edae 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -9,7 +9,6 @@
*
* Split out of the former 4,004-line peerSync.js (#1830).
*/
-import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
@@ -60,7 +59,6 @@ import {
buildMusicVideoAssetManifest,
} from './peerSyncAssets.js';
import {
- isNonEmptyStr,
peerAllowsOutbound,
peerHasCategory,
findPeerById,
@@ -72,6 +70,7 @@ import {
ERR_SCHEMA_VERSION_AHEAD,
PEER_SUBSCRIBABLE_KINDS,
} from './peerSyncShared.js';
+import { isStr, isNonBlankStr } from '../../lib/textUtils.js';
// --- Push pipeline (sender side) ----------------------------------------
@@ -169,9 +168,9 @@ async function isSubscriptionRecordTombstone(sub) {
export async function pushRecordToPeer(sub, options = {}) {
if (
!isPlainObject(sub)
- || !isNonEmptyStr(sub.peerId)
- || !isNonEmptyStr(sub.recordKind)
- || !isNonEmptyStr(sub.recordId)
+ || !isNonBlankStr(sub.peerId)
+ || !isNonBlankStr(sub.recordKind)
+ || !isNonBlankStr(sub.recordId)
) {
return { pushed: false, reason: 'invalid-subscription' };
}
@@ -203,7 +202,7 @@ export async function pushRecordToPeer(sub, options = {}) {
if (!peerHasCategory(peer, sub.recordKind)) return { pushed: false, reason: 'category-disabled' };
const ourInstanceId = await getInstanceId().catch(() => null);
- if (!isNonEmptyStr(ourInstanceId) || ourInstanceId === UNKNOWN_INSTANCE_ID) {
+ if (!isNonBlankStr(ourInstanceId) || ourInstanceId === UNKNOWN_INSTANCE_ID) {
return { pushed: false, reason: 'unknown-local-instance' };
}
@@ -554,7 +553,7 @@ async function persistPushSuccess(subId, hash, { confirmedAtMs = Date.now(), tra
// with a newer top-level key stripped for an older peer; cleared on every
// other successful push so a peer that has since upgraded (or a record
// whose content moved) can never be held back by a stale entry.
- sub.lastPushedLegacyHash = isNonEmptyStr(legacyStrippedHash) ? legacyStrippedHash : null;
+ sub.lastPushedLegacyHash = isNonBlankStr(legacyStrippedHash) ? legacyStrippedHash : null;
sub.updatedAt = now;
// Advance the per-record confirmed-delivery water-mark monotonically — an
// out-of-order retry must not retract it (mirrors ackDeletesUpTo's
diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.js
index db224cbe4c..d2a84ba596 100644
--- a/server/services/sharing/peerSyncReceive.js
+++ b/server/services/sharing/peerSyncReceive.js
@@ -9,7 +9,6 @@
*
* Split out of the former 4,004-line peerSync.js (#1830).
*/
-import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import {
PORTOS_SCHEMA_VERSIONS,
@@ -54,13 +53,13 @@ import {
import { findPeerSubscription, subscribePeer } from './peerSubscriptions.js';
import {
makeErr,
- isNonEmptyStr,
findPeerById,
peerSyncEvents,
ERR_VALIDATION,
ERR_SCHEMA_VERSION_AHEAD,
PEER_SUBSCRIBABLE_KINDS,
} from './peerSyncShared.js';
+import { isStr, isNonBlankStr } from '../../lib/textUtils.js';
/**
@@ -124,10 +123,10 @@ export async function applyIncomingPush(payload) {
// it to callers that haven't even identified themselves correctly. Move
// the cheap shape validation first so unidentified or malformed requests
// get a clean 400 with no version information.
- if (!isNonEmptyStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {
+ if (!isNonBlankStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {
throw makeErr('sourceInstanceId required (and not "unknown")', ERR_VALIDATION);
}
- if (!isPlainObject(record) || !isNonEmptyStr(record.id)) {
+ if (!isPlainObject(record) || !isNonBlankStr(record.id)) {
throw makeErr('record must be an object with a string id', ERR_VALIDATION);
}
diff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.js
index df698ece9d..a8585a92c6 100644
--- a/server/services/sharing/peerSyncShared.js
+++ b/server/services/sharing/peerSyncShared.js
@@ -15,7 +15,6 @@ import { EventEmitter } from 'events';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
import { getPeers, resolveEffectiveCategories } from '../instances.js';
-
export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);
/**
@@ -51,8 +50,6 @@ const STATE_PATH = () => join(PATHS.data, 'sharing', 'peer_subscriptions.json');
export const DEBOUNCE_MS = 3000;
export const PUSH_TIMEOUT_MS = 30000;
-export const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
-
export function subscriptionId({ peerId, recordKind, recordId }) {
return `peer-${recordKind}-${recordId}-${peerId}`;
}
diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.js
index c10316037e..171a7d0cbc 100644
--- a/server/services/sharing/subscriptions.js
+++ b/server/services/sharing/subscriptions.js
@@ -24,7 +24,6 @@ import { unlink } from 'fs/promises';
import { existsSync } from 'fs';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
-import { isStr } from '../../lib/storyBible.js';
import { getBucket } from './buckets.js';
import { exportSeries, exportUniverse } from './exporter.js';
import {
@@ -39,6 +38,7 @@ import {
export { withReexportSuppressed };
import { subscriptionFilename, legacySubscriptionFilename } from './manifest.js';
import { getInstanceId } from '../instanceIdentity.js';
+import { isStr } from '../../lib/textUtils.js';
// Re-export from the canonical source so other modules can import the
// filename helper from either side without forcing a manifest.js import.
diff --git a/server/services/storyBuilder.js b/server/services/storyBuilder.js
index 8cd7dd6b8b..32ed2cdba3 100644
--- a/server/services/storyBuilder.js
+++ b/server/services/storyBuilder.js
@@ -37,7 +37,7 @@
*/
import { randomUUID } from 'crypto';
-import { isStr, trimTo, pickPromptFields, BIBLE_KIND } from '../lib/storyBible.js';
+import { pickPromptFields, BIBLE_KIND } from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../lib/syncWire.js';
import { runStagedLLM } from './stageRunner.js';
@@ -60,6 +60,7 @@ import {
collectIssueSourceText, generateSeasonEpisodes, commitEpisodesToIssues,
ERR_VALIDATION as ARC_ERR_VALIDATION,
} from './pipeline/arcPlanner.js';
+import { isStr, trimTo } from '../lib/textUtils.js';
// Storage backend dispatcher (#1016): the facade is a drop-in for the
// collectionStore surface this service used to call directly, so every method
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index 0759baf88e..8ffe789087 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -25,13 +25,13 @@ import * as dataSync from './dataSync.js';
import { getBackendName } from './memoryBackend.js';
import { withAbortTimeout } from '../lib/abortTimeout.js';
import { isManifestEnvelope, diffManifestSlots, MAX_MANIFEST_SLOTS } from '../lib/syncManifest.js';
+import { isNonBlankStr } from '../lib/textUtils.js';
const CURSORS_FILE = dataPath('instances_sync_cursors.json');
const SYNC_INTERVAL_MS = 60000;
const FETCH_TIMEOUT_MS = 15000;
const withLock = createMutex();
-const isNonEmptyStr = (v) => typeof v === 'string' && v.length > 0;
let syncTimer = null;
let peerOnlineHandler = null;
const syncingPeers = new Set();
@@ -144,7 +144,7 @@ export async function getSyncStatus({ includeChecksums = false, forPeer = null }
// (universe/pipeline/mediaCollections) — making them read "behind" forever,
// even when both sides are empty. An absent `forPeer` (self-view, older peer)
// keeps the unscoped global checksum (forPeerId: undefined).
- const forPeerId = isNonEmptyStr(forPeer) ? forPeer : undefined;
+ const forPeerId = isNonBlankStr(forPeer) ? forPeer : undefined;
const [brainSeq, memorySeq, catalogSeqs, cursors, ...checksumResults] = await Promise.all([
Promise.resolve(brainSyncLog.getCurrentSeq()),
isPostgres ? memorySync.getMaxSequence() : Promise.resolve(null),
@@ -165,7 +165,7 @@ export async function getSyncStatus({ includeChecksums = false, forPeer = null }
// far we've consumed from it. That cursor IS the peer's push-frontier toward
// us, so the requesting peer can render an outbound "N to push" count without
// us tracking its local max. Null when we've never synced that peer.
- if (isNonEmptyStr(forPeer)) {
+ if (isNonBlankStr(forPeer)) {
result.cursorForYou = cursors[forPeer] ?? null;
}
return result;
@@ -223,7 +223,7 @@ async function syncBrainFromPeer(peer, cursor) {
cursor.brainChecksumTypes === typesSignature ? (cursor.brainChecksum ?? null) : null;
let brainChecksum = cachedChecksum;
const remote = await fetchPeer(peer, '/api/brain/reconcile/checksum');
- const remoteChecksum = isNonEmptyStr(remote?.checksum) ? remote.checksum : null;
+ const remoteChecksum = isNonBlankStr(remote?.checksum) ? remote.checksum : null;
if (remoteChecksum && remoteChecksum !== cachedChecksum) {
const localChecksum = await brainReconcile.getBrainChecksum().catch(() => null);
if (remoteChecksum === localChecksum) {
@@ -238,7 +238,7 @@ async function syncBrainFromPeer(peer, cursor) {
// at step 2 next cycle. (Our post-merge local checksum may differ from
// the peer's if WE hold records THEY lack — that asymmetry is fine; the
// peer reconciles those from us on its own cycle.)
- brainChecksum = isNonEmptyStr(snapshot.checksum) ? snapshot.checksum : remoteChecksum;
+ brainChecksum = isNonBlankStr(snapshot.checksum) ? snapshot.checksum : remoteChecksum;
}
}
}
@@ -476,7 +476,7 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums,
// applied idempotently. The query string is only appended for the three
// peer-record-subscribable categories; for goals/character/etc. it's inert
// server-side, but we still pass it uniformly to keep the URL builder simple.
- const forPeerQs = isNonEmptyStr(ourInstanceId) ? `?forPeer=${encodeURIComponent(ourInstanceId)}` : '';
+ const forPeerQs = isNonBlankStr(ourInstanceId) ? `?forPeer=${encodeURIComponent(ourInstanceId)}` : '';
// Lightweight checksum check first
const checksumRes = await fetchPeer(peer, `/api/sync/${category}/checksum${forPeerQs}`);
if (!checksumRes?.checksum) return { totalApplied: 0, checksum: null };
@@ -676,12 +676,12 @@ export async function categoriesCoveredByPeerSync(peerId, peer = null, ourInstan
// instanceId yields the records it pushes to us. Best-effort — a null
// response (older peer / offline) leaves inbound empty → full snapshot.
const inbound = emptyCoverage();
- if (peer && isNonEmptyStr(ourInstanceId)) {
+ if (peer && isNonBlankStr(ourInstanceId)) {
const res = await fetchPeer(peer, `/api/peer-sync/subscriptions?peerId=${encodeURIComponent(ourInstanceId)}`);
const subs = Array.isArray(res?.subscriptions) ? res.subscriptions : [];
for (const sub of subs) {
const cat = RECORD_KIND_TO_CATEGORY[sub?.recordKind];
- if (cat && isNonEmptyStr(sub?.recordId)) inbound[cat].add(sub.recordId);
+ if (cat && isNonBlankStr(sub?.recordId)) inbound[cat].add(sub.recordId);
}
}
return { outbound, inbound };
@@ -728,7 +728,7 @@ export async function syncWithPeer(peer) {
// per-record). Resolved once per sync, best-effort; null/UNKNOWN → no
// scoping (full snapshots, legacy behavior).
const ourInstanceId = await getInstanceId().catch(() => null);
- const scopedInstanceId = isNonEmptyStr(ourInstanceId) && ourInstanceId !== UNKNOWN_INSTANCE_ID
+ const scopedInstanceId = isNonBlankStr(ourInstanceId) && ourInstanceId !== UNKNOWN_INSTANCE_ID
? ourInstanceId
: null;
@@ -818,7 +818,7 @@ export async function syncWithPeer(peer) {
// short-circuits the snapshot fetch next cycle (#1077). Only overwrite
// when we actually resolved one — a failed/legacy probe (null) leaves
// the prior value so we don't lose the skip-optimization on a blip.
- if (isNonEmptyStr(brainResult.brainChecksum)) {
+ if (isNonBlankStr(brainResult.brainChecksum)) {
cursors[peerId].brainChecksum = brainResult.brainChecksum;
// Stamp the entity-type signature the cache is valid for — an
// enrollment change (new brain type) invalidates the cached checksum
diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.js
index 90501df671..794a75ba37 100644
--- a/server/services/tracks/logic.js
+++ b/server/services/tracks/logic.js
@@ -40,6 +40,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeChiptuneScore } from '../../lib/chiptuneScore.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
export const TRACK_ID_RE = /^track-[A-Za-z0-9-]{1,64}$/;
@@ -66,9 +67,6 @@ export const DURATION_MAX_SEC = 3600;
const RENDER_ID_RE = /^[A-Za-z0-9_-]{1,80}$/;
-const isStr = (v) => typeof v === 'string';
-const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');
-
function sanitizeDuration(v) {
if (typeof v !== 'number' || !Number.isFinite(v)) return null;
const s = Math.round(v);
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index e4e8dc934c..3f3ceda238 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -12,9 +12,7 @@
import { randomUUID } from 'crypto';
import { PATHS, ensureDir, resolveImageRef } from '../../lib/fileUtils.js';
-import {
- BIBLE_KEYS, pruneStaleReferenceSheets, mergePreservedSheetPointers, isStr, trimTo,
-} from '../../lib/storyBible.js';
+import { BIBLE_KEYS, pruneStaleReferenceSheets, mergePreservedSheetPointers } from '../../lib/storyBible.js';
import { store } from './storeFacade.js';
import {
sanitizeTemplate, sanitizeRun, sanitizeImageRefFilename, resolveInfluences,
@@ -36,6 +34,7 @@ import {
// series.js does NOT import universeBuilder (one-directional), so this static
// import is cycle-safe — unlike canonUsage.js, which back-imports this module.
import { listSeries } from '../pipeline/series.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
// Once-per-process flag for the canon-backfill log — readState() runs in both
// the queue and from un-queued readers, and the in-memory migration is cheap
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index 9d791d0424..12e04b7530 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -12,16 +12,14 @@
import { randomUUID } from 'crypto';
import { basename } from 'path';
-import {
- sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,
- normalizeBibleName, isStr, trimTo,
-} from '../../lib/storyBible.js';
+import { sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE, normalizeBibleName } from '../../lib/storyBible.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import {
LOGLINE_MAX, PREMISE_MAX, STYLE_NOTES_MAX, INFLUENCE_ENTRY_MAX, INFLUENCES_PER_LIST_MAX, STYLE_REFERENCES_MAX, LOCKABLE_FIELDS,
} from '../../lib/universeBibleLimits.js';
import { persistedRenderPinFields } from '../../lib/renderTargets.js';
+import { isStr, trimTo } from '../../lib/textUtils.js';
// RECORD-shape schema version, stamped INSIDE each universe record. Distinct
// from the type-level (storage layout) schemaVersion carried by
diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.js
index 955b159621..7c52a34abf 100644
--- a/server/services/universeBuilder/sync.js
+++ b/server/services/universeBuilder/sync.js
@@ -8,7 +8,7 @@
* re-exports this module so existing import paths keep working.
*/
-import { isStr, preserveLegacyCharacterFields } from '../../lib/storyBible.js';
+import { preserveLegacyCharacterFields } from '../../lib/storyBible.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
deleteSyncBaseHash, withBaseHashFlushBatch,
@@ -19,6 +19,7 @@ import { store } from './storeFacade.js';
import { emitRecordDeleted } from '../sharing/recordEvents.js';
import { unlinkCollectionsForUniverse } from '../mediaCollections.js';
import { clearPendingSheetSlotsForUniverse } from '../universeCharacterSheetSlot.js';
+import { isStr } from '../../lib/textUtils.js';
/**
* Cascade orphan cleanup for a universe whose soft-delete arrived via peer
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index f3772f3ac9..4d44e124b1 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -41,7 +41,7 @@ import {
sanitizeInfluences,
sanitizeLocked,
} from "./universeBuilder.js";
-import { trimTo } from "../lib/storyBible.js";
+import { trimTo } from "../lib/textUtils.js";
const MAX_FEEDBACK = 3000;
const MAX_RATIONALE = 1200;
diff --git a/server/services/universeStyleReference.js b/server/services/universeStyleReference.js
index 169fbcfe46..04b6b88021 100644
--- a/server/services/universeStyleReference.js
+++ b/server/services/universeStyleReference.js
@@ -10,7 +10,6 @@ import { randomUUID } from 'crypto';
import { parseLLMJSON, resolveAPIProvider } from './aiProvider.js';
import { ServerError } from '../lib/errorHandler.js';
import { assertProvider, assertVisionRunUsedImages, runPromptThroughProvider } from './promptRunner.js';
-import { trimTo } from '../lib/storyBible.js';
import {
sanitizeInfluences,
sanitizeLocked,
@@ -18,6 +17,7 @@ import {
STYLE_REFERENCE_PROMPT_MAX,
STYLE_REFERENCE_TITLE_MAX,
} from './universeBuilder.js';
+import { trimTo } from '../lib/textUtils.js';
const listDiff = (before, after) => {
const beforeKeys = new Set(before.map((value) => value.toLowerCase()));
diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.js
index 2768878f1c..5567636c7c 100644
--- a/server/services/voice/profiles.js
+++ b/server/services/voice/profiles.js
@@ -14,6 +14,7 @@ import { query } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS } from '../../lib/paths.js';
import { writeFileGuarded } from '../../lib/fileUtils.js';
+import { trimTo } from '../../lib/textUtils.js';
export const VOICE_PROFILE_ENGINES = new Set(['kokoro', 'piper', 'qwen3-tts']);
export const VOICE_PROFILE_KINDS = new Set(['preset', 'designed', 'cloned', 'fine-tuned']);
@@ -29,13 +30,12 @@ const DEFAULT_DELIVERY = Object.freeze({ rate: 1, pitchSemitones: null, formantS
const DEFAULT_MASTERING = Object.freeze({ chain: ['preset-output:unprocessed'] });
const SAFE_ASSET_BASENAME = /^[a-z0-9][a-z0-9._-]{0,159}$/i;
-const trim = (value, max) => typeof value === 'string' ? value.trim().slice(0, max) : '';
const timestamp = () => new Date().toISOString();
const positiveInteger = (value, fallback = 1) =>
Number.isInteger(value) && value > 0 ? value : fallback;
export function parsePresetVoiceId(voiceId) {
- const value = trim(voiceId, MAX_ID);
+ const value = trimTo(voiceId, MAX_ID);
const match = /^([a-z][a-z0-9-]*):([^:\s]+)$/i.exec(value);
if (!match) return null;
const engine = match[1].toLowerCase();
@@ -64,31 +64,31 @@ const sanitizeDelivery = (raw) => ({
const sanitizeMastering = (raw) => ({
chain: Array.isArray(raw?.chain)
- ? raw.chain.map((step) => trim(step, 80)).filter(Boolean).slice(0, 12)
+ ? raw.chain.map((step) => trimTo(step, 80)).filter(Boolean).slice(0, 12)
: [...DEFAULT_MASTERING.chain],
});
const sanitizeInference = (raw) => ({
seed: Number.isInteger(raw?.seed) ? raw.seed : 42,
- instructions: trim(raw?.instructions, 2000) || null,
+ instructions: trimTo(raw?.instructions, 2000) || null,
rate: boundedNumber(raw?.rate, 0.25, 4, 1.0),
- checkpointPath: trim(raw?.checkpointPath, 500) || null,
- modelId: trim(raw?.modelId, 160) || null,
+ checkpointPath: trimTo(raw?.checkpointPath, 500) || null,
+ modelId: trimTo(raw?.modelId, 160) || null,
});
const sanitizeBenchmark = (raw) => {
if (!raw || typeof raw !== 'object') return null;
- const renderedAt = trim(raw.renderedAt, 64);
+ const renderedAt = trimTo(raw.renderedAt, 64);
const lines = Array.isArray(raw.lines) ? raw.lines.map((line) => {
- const filename = trim(line?.filename, 200);
+ const filename = trimTo(line?.filename, 200);
if (!filename) return null;
return {
- key: trim(line.key, 64),
- text: trim(line.text, 1000),
+ key: trimTo(line.key, 64),
+ text: trimTo(line.text, 1000),
filename,
latencyMs: Number.isFinite(line.latencyMs) ? Math.max(0, Math.round(line.latencyMs)) : null,
engine: VOICE_PROFILE_ENGINES.has(line.engine) ? line.engine : null,
- modelRevision: trim(line.modelRevision, MAX_REVISION) || null,
+ modelRevision: trimTo(line.modelRevision, MAX_REVISION) || null,
effectiveControls: {
rate: Number.isFinite(line?.effectiveControls?.rate) ? line.effectiveControls.rate : null,
},
@@ -107,15 +107,15 @@ const sanitizeBenchmark = (raw) => {
const sanitizeSourceAssets = (raw) => Array.isArray(raw)
? raw.map((asset) => {
- const filename = trim(asset?.filename, 160);
+ const filename = trimTo(asset?.filename, 160);
if (!SAFE_ASSET_BASENAME.test(filename)) return null;
return {
filename,
- sha256: /^[a-f0-9]{64}$/i.test(trim(asset?.sha256, 64)) ? trim(asset.sha256, 64).toLowerCase() : null,
- transcript: trim(asset?.transcript, 4000) || null,
- rightsConfirmedAt: trim(asset?.rightsConfirmedAt, 64) || null,
+ sha256: /^[a-f0-9]{64}$/i.test(trimTo(asset?.sha256, 64)) ? trimTo(asset.sha256, 64).toLowerCase() : null,
+ transcript: trimTo(asset?.transcript, 4000) || null,
+ rightsConfirmedAt: trimTo(asset?.rightsConfirmedAt, 64) || null,
performerConsentConfirmed: asset?.performerConsentConfirmed === true,
- licensePosture: trim(asset?.licensePosture, 160) || null,
+ licensePosture: trimTo(asset?.licensePosture, 160) || null,
};
}).filter(Boolean).slice(0, 24)
: [];
@@ -123,9 +123,9 @@ const sanitizeSourceAssets = (raw) => Array.isArray(raw)
/** Turn a raw DB JSON payload into the durable public profile shape. */
export function sanitizeVoiceProfile(raw) {
if (!raw || typeof raw !== 'object') return null;
- const id = trim(raw.id, 80);
- const universeId = trim(raw?.binding?.universeId, MAX_ID);
- const characterId = trim(raw?.binding?.characterId, MAX_ID);
+ const id = trimTo(raw.id, 80);
+ const universeId = trimTo(raw?.binding?.universeId, MAX_ID);
+ const characterId = trimTo(raw?.binding?.characterId, MAX_ID);
const kind = VOICE_PROFILE_KINDS.has(raw.kind) ? raw.kind : 'preset';
const engine = VOICE_PROFILE_ENGINES.has(raw.engine)
? raw.engine
@@ -136,19 +136,19 @@ export function sanitizeVoiceProfile(raw) {
const approvalStatus = raw?.approval?.status === 'approved'
? 'approved'
: raw?.approval?.status === 'retired' ? 'retired' : 'draft';
- const createdAt = trim(raw.createdAt, 64) || timestamp();
- const updatedAt = trim(raw.updatedAt, 64) || createdAt;
- const voiceId = trim(raw.voiceId, MAX_ID) || `${engine}:${kind}`;
+ const createdAt = trimTo(raw.createdAt, 64) || timestamp();
+ const updatedAt = trimTo(raw.updatedAt, 64) || createdAt;
+ const voiceId = trimTo(raw.voiceId, MAX_ID) || `${engine}:${kind}`;
return {
id,
version: positiveInteger(raw.version),
binding: { universeId, characterId },
- label: trim(raw.label, MAX_LABEL) || null,
+ label: trimTo(raw.label, MAX_LABEL) || null,
kind,
engine,
voiceId,
- modelRevision: trim(raw.modelRevision, MAX_REVISION) || (engine === 'qwen3-tts' ? 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign' : 'configured-preset'),
+ modelRevision: trimTo(raw.modelRevision, MAX_REVISION) || (engine === 'qwen3-tts' ? 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign' : 'configured-preset'),
sourceAssets: sanitizeSourceAssets(raw.sourceAssets),
inference: sanitizeInference(raw.inference),
routes: sanitizeRoutes(raw.routes),
@@ -156,7 +156,7 @@ export function sanitizeVoiceProfile(raw) {
mastering: sanitizeMastering(raw.mastering),
approval: {
status: approvalStatus,
- approvedAt: approvalStatus === 'approved' ? trim(raw?.approval?.approvedAt, 64) || updatedAt : null,
+ approvedAt: approvalStatus === 'approved' ? trimTo(raw?.approval?.approvedAt, 64) || updatedAt : null,
benchmarkRevision: positiveInteger(raw?.approval?.benchmarkRevision),
},
benchmark: sanitizeBenchmark(raw.benchmark),
@@ -198,7 +198,7 @@ const persist = async (profile) => {
};
export async function getVoiceProfile(id) {
- const profileId = trim(id, 80);
+ const profileId = trimTo(id, 80);
if (!PROFILE_ID_RE.test(profileId)) return null;
const { rows } = await query('SELECT data FROM voice_profiles WHERE id = $1', [profileId]);
return sanitizeVoiceProfile(rows[0]?.data);
@@ -215,8 +215,8 @@ export async function getVoiceProfileRequired(id) {
export async function listVoiceProfiles({ universeId, characterId } = {}) {
const clauses = [];
const params = [];
- const universe = trim(universeId, MAX_ID);
- const character = trim(characterId, MAX_ID);
+ const universe = trimTo(universeId, MAX_ID);
+ const character = trimTo(characterId, MAX_ID);
if (universe) { params.push(universe); clauses.push(`universe_id = $${params.length}`); }
if (character) { params.push(character); clauses.push(`character_id = $${params.length}`); }
const { rows } = await query(
@@ -272,8 +272,8 @@ export async function createVoiceDesignCandidate({
delivery = DEFAULT_DELIVERY,
rate = 1.0,
} = {}) {
- const universe = trim(universeId, MAX_ID);
- const character = trim(characterId, MAX_ID);
+ const universe = trimTo(universeId, MAX_ID);
+ const character = trimTo(characterId, MAX_ID);
if (!universe || !character) {
throw new ServerError('universeId and characterId are required', { status: 400 });
}
@@ -284,15 +284,15 @@ export async function createVoiceDesignCandidate({
id: profileId,
version: 1,
binding: { universeId: universe, characterId: character },
- label: trim(characterName, MAX_LABEL) || null,
+ label: trimTo(characterName, MAX_LABEL) || null,
kind: 'designed',
engine: 'qwen3-tts',
voiceId: `qwen3:design-${profileId.slice(0, 8)}`,
- modelRevision: trim(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
+ modelRevision: trimTo(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
sourceAssets: [],
inference: {
seed: Number.isInteger(seed) ? seed : 42,
- instructions: trim(instructions, 2000),
+ instructions: trimTo(instructions, 2000),
rate: boundedNumber(rate, 0.25, 4, 1.0),
modelId,
},
@@ -328,9 +328,9 @@ export async function createClonedVoiceCandidate({
modelId = 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',
rate = 1.0,
} = {}) {
- const universe = trim(universeId, MAX_ID);
- const character = trim(characterId, MAX_ID);
- const cleanFilename = trim(filename, 160);
+ const universe = trimTo(universeId, MAX_ID);
+ const character = trimTo(characterId, MAX_ID);
+ const cleanFilename = trimTo(filename, 160);
if (!universe || !character) {
throw new ServerError('universeId and characterId are required', { status: 400 });
@@ -362,21 +362,21 @@ export async function createClonedVoiceCandidate({
const sourceAssets = [{
filename: cleanFilename,
sha256,
- transcript: trim(transcript, 4000) || null,
+ transcript: trimTo(transcript, 4000) || null,
rightsConfirmedAt: now,
performerConsentConfirmed: true,
- licensePosture: trim(licensePosture, 160) || 'consented-performance',
+ licensePosture: trimTo(licensePosture, 160) || 'consented-performance',
}];
const next = sanitizeVoiceProfile({
id: profileId,
version: 1,
binding: { universeId: universe, characterId: character },
- label: trim(characterName, MAX_LABEL) || null,
+ label: trimTo(characterName, MAX_LABEL) || null,
kind: 'cloned',
engine: 'qwen3-tts',
voiceId: `qwen3:clone-${profileId.slice(0, 8)}`,
- modelRevision: trim(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',
+ modelRevision: trimTo(modelId, MAX_REVISION) || 'Qwen/Qwen3-TTS-12Hz-1.7B-Base',
sourceAssets,
inference: {
seed: 42,
@@ -424,7 +424,7 @@ export async function promoteFineTunedProfile({
kind: 'fine-tuned',
engine: 'qwen3-tts',
voiceId: `qwen3:fine-tuned-step-${step}`,
- modelRevision: trim(modelRevision, MAX_REVISION) || `qwen3-tts:checkpoint-${step}`,
+ modelRevision: trimTo(modelRevision, MAX_REVISION) || `qwen3-tts:checkpoint-${step}`,
inference: {
...current?.inference,
checkpointPath,
@@ -489,8 +489,8 @@ export async function promotePresetProfile({
modelRevision = 'configured-preset',
delivery = DEFAULT_DELIVERY,
} = {}) {
- const universe = trim(universeId, MAX_ID);
- const character = trim(characterId, MAX_ID);
+ const universe = trimTo(universeId, MAX_ID);
+ const character = trimTo(characterId, MAX_ID);
const preset = parsePresetVoiceId(voiceId);
if (!universe || !character || !preset) {
throw new ServerError('A universe, character, and valid preset are required', {
@@ -507,11 +507,11 @@ export async function promotePresetProfile({
id: profileId,
version: current ? (samePreset ? current.version : current.version + 1) : 1,
binding: { universeId: universe, characterId: character },
- label: trim(characterName, MAX_LABEL) || current?.label || null,
+ label: trimTo(characterName, MAX_LABEL) || current?.label || null,
kind: 'preset',
engine: preset.engine,
voiceId: preset.voiceId,
- modelRevision: trim(modelRevision, MAX_REVISION) || 'configured-preset',
+ modelRevision: trimTo(modelRevision, MAX_REVISION) || 'configured-preset',
routes: current?.routes || { studio: { enabled: true }, interactive: { enabled: true, maxFirstAudioMs: 900 } },
delivery: current?.delivery || delivery,
mastering: current?.mastering || DEFAULT_MASTERING,
@@ -550,10 +550,10 @@ export async function recordVoiceProfileRender({
durationMs,
provenance,
} = {}) {
- const issue = trim(issueId, MAX_RENDER_ID);
- const line = trim(lineId, MAX_RENDER_ID);
- const filename = trim(audioFilename, 500);
- const profileId = trim(provenance?.profileId, 80);
+ const issue = trimTo(issueId, MAX_RENDER_ID);
+ const line = trimTo(lineId, MAX_RENDER_ID);
+ const filename = trimTo(audioFilename, 500);
+ const profileId = trimTo(provenance?.profileId, 80);
const profileRevision = positiveInteger(provenance?.profileRevision, 0);
const engine = VOICE_PROFILE_ENGINES.has(provenance?.engine) ? provenance.engine : null;
if (!issue || !line || !filename || !PROFILE_ID_RE.test(profileId) || !profileRevision || !engine) {
@@ -567,7 +567,7 @@ export async function recordVoiceProfileRender({
profileId,
profileRevision,
engine,
- modelRevision: trim(provenance?.modelRevision, MAX_REVISION) || null,
+ modelRevision: trimTo(provenance?.modelRevision, MAX_REVISION) || null,
effectiveControls: {
rate: Number.isFinite(provenance?.effectiveControls?.rate) ? provenance.effectiveControls.rate : null,
},
@@ -592,8 +592,8 @@ export async function recordVoiceProfileRender({
}
export async function clearVoiceProfileRender({ issueId, lineId } = {}) {
- const issue = trim(issueId, MAX_RENDER_ID);
- const line = trim(lineId, MAX_RENDER_ID);
+ const issue = trimTo(issueId, MAX_RENDER_ID);
+ const line = trimTo(lineId, MAX_RENDER_ID);
if (!issue || !line) return;
await query('DELETE FROM voice_profile_renders WHERE issue_id = $1 AND line_id = $2', [issue, line]);
}
@@ -626,8 +626,8 @@ export async function resolveCharacterVoice({
route = 'studio',
} = {}) {
assertRoute(route);
- const universe = trim(universeId, MAX_ID);
- const character = trim(characterId, MAX_ID);
+ const universe = trimTo(universeId, MAX_ID);
+ const character = trimTo(characterId, MAX_ID);
let unavailableProfile = null;
if (universe && character) {
const profiles = await listVoiceProfiles({ universeId: universe, characterId: character });
@@ -647,7 +647,7 @@ export async function resolveCharacterVoice({
unavailableProfile = profiles.find((item) => item.approval.status === 'approved') || null;
}
const preset = parsePresetVoiceId(characterVoiceId);
- const legacyVoice = trim(characterVoiceId, MAX_ID);
+ const legacyVoice = trimTo(characterVoiceId, MAX_ID);
if (preset || legacyVoice) {
return {
source: 'character-preset',
diff --git a/server/services/writersRoom/syncLogic.js b/server/services/writersRoom/syncLogic.js
index 6b2f9ae396..bd89fc55aa 100644
--- a/server/services/writersRoom/syncLogic.js
+++ b/server/services/writersRoom/syncLogic.js
@@ -18,8 +18,7 @@
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import { WORK_ID_RE, DRAFT_ID_RE, FOLDER_ID_RE, EXERCISE_ID_RE } from './_shared.js';
-
-const isStr = (v) => typeof v === 'string';
+import { isStr } from '../../lib/textUtils.js';
// The peer-sync record kind + the asset kind its draft bodies ride. Exported so
// peerSync.js / sync.js reference one source of truth instead of bare strings.