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

feat([issue-13109]): export opt-in FableLoom character and voice packages (#13447)

[._.]/062a90b8c5e3
diff --git a/docs/features/fableloom-export-v1.md b/docs/features/fableloom-export-v1.md
index 841355dd6e..9c328ae9af 100644
--- a/docs/features/fableloom-export-v1.md
+++ b/docs/features/fableloom-export-v1.md
@@ -22,9 +22,11 @@ authority, including valid delegated agent sessions. Jobs cannot be read or
downloaded through a different loom. Instance authentication retains its existing
optional policy; no export endpoint is always-public.
-This core version explicitly refuses `includePlayer:true`,
-`includeCharacters:true` and `includeVoice:true`. Their implementation belongs
-to the linked export slices. Unknown media profiles are rejected at validation.
+`includePlayer:true`, and `includeWebm:true` on the source profile, are refused
+(`EXPORT_OPTION_UNSUPPORTED`). `includeVoice:true` without
+`includeCharacters:true` is refused (`EXPORT_VOICE_REQUIRES_CHARACTERS`).
+Character files and voice reference audio are explicit opt-ins, off by default.
+Unknown media profiles are rejected at validation.
`DELETE /api/fableloom/:id/export/:jobId` cancels a queued/running export and
waits for worker and encoder shutdown before returning its failed status
(`EXPORT_CANCELLED`). Completed jobs remain completed.
@@ -46,6 +48,54 @@ graph, outline, production, missing media, encoding, occupancy, path or size
failures. Enabled live holds require verified speech-safe occupancy; intervals
cannot exceed the actual clip duration.
+## Character and voice opt-ins
+
+The default package has no `characters/` members and no voice bytes.
+`includeCharacters:true` adds `characters/<id>.json` for the canonical cast:
+the loom protagonist, when one is set, and characters staged on reachable
+scenes (visual appearances and interaction speakers). Unreachable scenes and
+other universe characters stay out. Each file projects persona and speech
+notes (`personality`, `speechAccent`, `speechPattern`, `mannerisms`),
+pronunciation anchors (`term` and `pronunciation` only), safety/never-say
+notes, and play-turn inputs for contract 1.0.0 (prompt id
+`fableloom-play-turn`). Scene prose and choices stay in the manifest.
+Background, secrets, visual identity, engine voice presets, adapters, LoRAs,
+local paths and session history are not projected.
+
+Portable character approval is `voiceCanon.approved`. A missing or unapproved
+canon fails with `EXPORT_CHARACTER_DRAFT` unless `allowDraft:true`, which
+records `draftFlags` of `unapproved` (a voice-canon object exists) or
+`unknown` (it does not) and still does not invent approval. An empty cast
+(`EXPORT_CAST_MISSING`), a character missing from the universe
+(`EXPORT_CHARACTER_MISSING`), or a non-portable id (`EXPORT_CHARACTER_ID`)
+still fails. Those findings do not echo a non-portable id.
+
+`includeVoice:true` requires the character opt-in. For each exported character
+it selects exactly one voice profile whose approval status is `approved`,
+whose universe and character binding match, and whose interactive route is
+enabled. Zero matches fail with `EXPORT_VOICE_UNAPPROVED`. More than one fails
+with `EXPORT_VOICE_AMBIGUOUS`. Reference bytes must be a managed audio
+basename (`wav`, `mp3`, `flac`, `ogg`, or `m4a`) inside that profile's source
+directory, and the bytes must match the recorded sha256. The package stores
+`media/<sha256>.<ext>` plus a `voices` row: character id, relative file,
+content hash, byte count, approval, consent, license posture and voice-canon
+source policy. It does not store the profile id, engine, model, transcript,
+checkpoint, local path or approval timestamp.
+
+A reference is exportable when performer consent is confirmed, or when its
+license posture is `generated-original-voice`, `licensed`, or `designed`. A
+cloned profile, or a `consented-performance` posture, without confirmed
+consent fails with `EXPORT_VOICE_CONSENT_MISSING`. Unlabeled or absent audio
+fails with `EXPORT_VOICE_REFERENCE_MISSING`. A hash mismatch fails with
+`EXPORT_VOICE_REFERENCE_MISMATCH`. A path that leaves the voice library fails
+with `EXPORT_VOICE_REFERENCE_INVALID`. `allowDraft` does not package
+unapproved, unconsented, ambiguous or missing voice bytes.
+
+The host README states that character files and any voice bytes are inputs for
+the host's own resolver and TTS. The package does not grant PortOS access and
+contains no PortOS URL, credential or callback. The reference player remains
+unavailable.
+
Media reads accept basenames only, resolve inside the appropriate gallery/video
root, refuse escaping symlinks and snapshot bounded regular-file bytes. No
history ID is reconstructed as a filename. Input changes during a read fail
@@ -94,19 +144,28 @@ accepted as completed encodes. Source media remains untouched.
- `manifest.json`: export schema, playback runtime and PortOS versions; explicit
authored metadata, ordered episodes, reachable graphs and playback roles.
Media uses only content hashes and relative `media/<sha256>.<ext>` references,
- with `durationMs`, `loopable` and projected audio occupancy.
+ with `durationMs`, `loopable` and projected audio occupancy. With
+ `includeCharacters`, `characters` lists each cast member's id, role and
+ `characters/<id>.json` path. The default manifest omits that key.
+- `characters/<id>.json`: the portable character projection, only when
+ `includeCharacters` is set.
- `provenance.json`: per-use content hash, provider/model labels, parameter hash,
approval and conditioning status, draft flags, and encoding provenance.
-- `media/`: deduplicated, metadata-free media.
+ `characters` is present only with the character opt-in. `voices` is present
+ only with `includeVoice`.
+- `media/`: deduplicated, metadata-free scene media, plus approved voice
+ reference audio when `includeVoice` is set.
- `runtime-v1.md` and `README.md`: the versioned playback and hosting contracts.
+ The README tells the host that it owns TTS and that the package grants no
+ PortOS access.
All JSON object keys and ZIP member order are stable. ZIP timestamps are fixed.
The same source bytes and authored snapshot, with the same PortOS/media-tool
versions, produce identical manifest, media hashes and ZIP bytes. There are no
job IDs, timestamps, instance/peer IDs, local paths, credentials, provider
configuration, adapters, LoRAs, source prompts, sessions or transcripts in the
-package. Only authored scene/choice text and the documented projections leave
-the authoring record.
+package. Only authored scene/choice text, the documented character projection
+and approved voice-reference bytes leave the authoring record.
## Lifecycle and failures
diff --git a/docs/features/fableloom.md b/docs/features/fableloom.md
index 2e77fd1f27..0228c1f97a 100644
--- a/docs/features/fableloom.md
+++ b/docs/features/fableloom.md
@@ -9,8 +9,9 @@ feedback—when that story's audience role permits it. A loom holds one or more
rehearse the same experience at any of those three production stages.
The [runtime v1 contract](fableloom-runtime-v1.md) documents traversal, live-input
-gates and the mapping from portable events to private hosted sessions. External
-package export is tracked in #13104; the contract alone does not provide an exporter.
+gates and the mapping from portable events to private hosted sessions. The
+[portable export](fableloom-export-v1.md) packages authored episodes for an
+external host and, only when asked, cast inputs and approved voice references.
## Planning a series
diff --git a/server/lib/README.md b/server/lib/README.md
index dd344b8831..e2d1d7829f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -64,7 +64,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `fableLoomBoard.js` | FableLoom Board view: `fableLoomBoardPath` walks one path from an episode's start scene (first choice at each fork unless a picked transition in `via`) into storyboard beats of panels with each fork's choices, stopping at an ending, a loop or a dead end; `fableLoomBoardPick` swaps a fork's pick. Browser-safe. |
| `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. |
| `fableLoomMediaProfiles.js` | Versioned portable media presets with resolution, bitrate, frame-rate and loudness targets. |
-| `fableLoomExport.js` | Portable package schema/limits, graph/outline/production preflight, required media roles and explicit path-free playback/occupancy projections. |
+| `fableLoomExport.js` | Portable package schema/limits, graph/outline/production preflight, canonical cast and approved-voice projections, required media roles and explicit path-free playback/occupancy projections. |
| `cameraMovements.js` | Shared camera-movement vocabulary (#10589): `CAMERA_MOVEMENTS` (stable ids with `family`, `energy`, `snap`/`still` flags, start/end framing and the four-part movement/speed/framing/end prose), `normalizeCameraMovement`/`cameraMovementId`/`cameraMovementFromText`, `shotCameraPrompt(camera)` (the four-part i2v camera block for a structured shot camera) and `cameraMovementCatalogForPrompt`. Used by FableLoom, Music Video planning/review and the layered template's `cameraRig.js`. |
| `fableLoomCameraMovements.js` | FableLoom names for the shared `cameraMovements.js` catalog (generated cut direction and the manual scene editor selector); persisted ids are unchanged. |
| `fableLoomPlayback.js` | FableLoom runtime version, node playback modes, audio occupancy and `evaluateFableLoomLiveInput`: shared live-input admission for connected decision holds, offscreen presence and safe audio, with legacy playback defaults. |
diff --git a/server/lib/fableLoomExport.js b/server/lib/fableLoomExport.js
index 26f14021d6..6fe52f8618 100644
--- a/server/lib/fableLoomExport.js
+++ b/server/lib/fableLoomExport.js
@@ -1,3 +1,5 @@
+import { BIBLE_LIMITS } from './bibleLimits.js';
+import { narrationFormatContract } from './fableLoomFormats.js';
import { analyzeEpisodeGraph, computeGraphLayers } from './fableLoomGraph.js';
import { analyzeSeriesStoryOutlines } from './fableLoomOutline.js';
import {
@@ -5,6 +7,7 @@ import {
inspectEpisodeProductionReadiness, resolveFableLoomProtagonistPresence,
sanitizeInteractionWindow, validateAudioOccupancy,
} from './fableLoomPlayback.js';
+import { trimTo } from './textUtils.js';
export const FABLELOOM_EXPORT_SCHEMA_VERSION = '1.0.0';
export const FABLELOOM_EXPORT_LIMITS = Object.freeze({
@@ -111,6 +114,249 @@ export function projectFableLoomExportManifest(loom, episodes, portosVersion) {
};
}
+const PORTABLE_CHARACTER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
+const VOICE_PROFILE_ID = /^[a-z0-9][a-z0-9-]{0,79}$/;
+const VOICE_AUDIO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(wav|mp3|flac|ogg|m4a)$/i;
+const VOICE_REFERENCE_POSTURES = new Set([
+ 'generated-original-voice', 'licensed', 'designed', 'consented-performance',
+]);
+// Same portable postures as Universe voiceCanon.sourcePolicy. Duplicated so this
+// projection does not import the story-bible sanitizer (crypto + file IO).
+const VOICE_CANON_SOURCE_POLICIES = new Set(['designed', 'consented-performance', 'licensed']);
+
+const text = (value, max) => trimTo(value, max);
+const textList = (value, itemMax, max) => {
+ if (!Array.isArray(value)) return [];
+ const out = [];
+ for (const item of value) {
+ const line = text(item, itemMax);
+ if (!line) continue;
+ out.push(line);
+ if (out.length >= max) break;
+ }
+ return out;
+};
+
+/**
+ * Canonical cast for one export: the loom protagonist plus characters staged
+ * on reachable scenes (visual bindings and interaction speakers). Unreachable
+ * scenes and the rest of the universe stay out — a universe is not the cast.
+ */
+function fableLoomExportCastIds(loom, episodes) {
+ const ids = new Set();
+ if (typeof loom?.protagonistCharacterId === 'string' && loom.protagonistCharacterId) {
+ ids.add(loom.protagonistCharacterId);
+ }
+ for (const episode of episodes || []) {
+ const reachable = computeGraphLayers(episode).depthById;
+ for (const node of episode?.nodes || []) {
+ if (!reachable.has(node?.id)) continue;
+ for (const appearance of node.visualCanon?.characterAppearances || []) {
+ if (typeof appearance?.characterId === 'string' && appearance.characterId) ids.add(appearance.characterId);
+ }
+ const speaker = node.interactionWindow?.protagonistCharacterId;
+ if (typeof speaker === 'string' && speaker) ids.add(speaker);
+ }
+ }
+ return [...ids].sort();
+}
+
+function projectCharacter(character, { role, narrationFormat, draftFlags }) {
+ const canon = character.voiceCanon && typeof character.voiceCanon === 'object' ? character.voiceCanon : {};
+ const pronunciations = [];
+ for (const item of Array.isArray(canon.pronunciations) ? canon.pronunciations : []) {
+ const term = text(item?.term, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_TERM_MAX);
+ const pronunciation = text(item?.pronunciation, BIBLE_LIMITS.VOICE_CANON_PRONUNCIATION_VALUE_MAX);
+ if (!term || !pronunciation) continue;
+ pronunciations.push({ term, pronunciation });
+ if (pronunciations.length >= BIBLE_LIMITS.VOICE_CANON_PRONUNCIATIONS_MAX) break;
+ }
+ const sourcePolicy = VOICE_CANON_SOURCE_POLICIES.has(canon.sourcePolicy) ? canon.sourcePolicy : null;
+ const version = Number.isInteger(canon.version) && canon.version > 0
+ && canon.version <= BIBLE_LIMITS.VOICE_CANON_VERSION_MAX ? canon.version : null;
+ const approved = canon.approved === true;
+ const persona = {
+ personality: text(character.personality, BIBLE_LIMITS.PERSONALITY_MAX),
+ speechAccent: text(character.speechAccent, BIBLE_LIMITS.SPEECH_ACCENT_MAX),
+ speechPattern: text(character.speechPattern, BIBLE_LIMITS.SPEECH_PATTERN_MAX),
+ mannerisms: text(character.mannerisms, BIBLE_LIMITS.MANNERISMS_MAX),
+ };
+ const speech = {
+ description: text(canon.description, BIBLE_LIMITS.VOICE_CANON_DESCRIPTION_MAX),
+ defaultDelivery: text(canon.defaultDelivery, BIBLE_LIMITS.VOICE_CANON_DELIVERY_MAX),
+ emotionalRange: textList(canon.emotionalRange, BIBLE_LIMITS.VOICE_CANON_RANGE_ITEM_MAX, BIBLE_LIMITS.VOICE_CANON_RANGE_MAX),
+ };
+ const neverSay = textList(canon.avoid, BIBLE_LIMITS.VOICE_CANON_AVOID_ITEM_MAX, BIBLE_LIMITS.VOICE_CANON_AVOID_MAX);
+ return {
+ schemaVersion: FABLELOOM_EXPORT_SCHEMA_VERSION,
+ id: character.id,
+ name: text(character.name, BIBLE_LIMITS.NAME_MAX),
+ role,
+ persona,
+ speech,
+ pronunciations,
+ safety: { neverSay },
+ playTurn: {
+ promptId: 'fableloom-play-turn',
+ contractVersion: FABLELOOM_RUNTIME_VERSION,
+ inputs: {
+ characterId: character.id,
+ name: text(character.name, BIBLE_LIMITS.NAME_MAX),
+ role,
+ ...persona,
+ voiceDescription: speech.description,
+ defaultDelivery: speech.defaultDelivery,
+ emotionalRange: speech.emotionalRange,
+ pronunciations,
+ neverSay,
+ narrationFormat,
+ },
+ },
+ approval: {
+ voiceCanonVersion: version,
+ approved,
+ sourcePolicy,
+ draftFlags,
+ },
+ };
+}
+
+/**
+ * Project the canonical cast. voiceCanon.approved is the portable approval
+ * contract. allowDraft records the same unapproved/unknown flags as scene
+ * media and still emits the projection; it does not invent approval.
+ */
+export function inspectFableLoomExportCharacters(loom, episodes, universe, { allowDraft = false } = {}) {
+ const findings = [];
+ const characters = [];
+ const ids = fableLoomExportCastIds(loom, episodes);
+ if (!ids.length) {
+ findings.push({
+ gate: 'cast', severity: 'error', code: 'EXPORT_CAST_MISSING',
+ message: 'Character export needs a protagonist or a character staged on a reachable scene.',
+ });
+ return { findings, characters };
+ }
+ const byId = new Map();
+ for (const character of Array.isArray(universe?.characters) ? universe.characters : []) {
+ if (character && typeof character.id === 'string' && !byId.has(character.id)) byId.set(character.id, character);
+ }
+ const narrationFormat = narrationFormatContract(loom?.format);
+ for (const id of ids) {
+ if (!PORTABLE_CHARACTER_ID.test(id)) {
+ findings.push({
+ gate: 'cast', severity: 'error', code: 'EXPORT_CHARACTER_ID',
+ message: 'Character identifiers must be portable identifiers.',
+ });
+ continue;
+ }
+ const character = byId.get(id);
+ if (!character) {
+ findings.push({
+ gate: 'cast', severity: 'error', code: 'EXPORT_CHARACTER_MISSING', characterId: id,
+ message: `Character "${id}" is not in the linked universe.`,
+ });
+ continue;
+ }
+ const canon = character.voiceCanon;
+ const knownCanon = Boolean(canon && typeof canon === 'object' && !Array.isArray(canon));
+ const draftFlags = canon?.approved === true ? [] : [knownCanon ? 'unapproved' : 'unknown'];
+ if (draftFlags.length) {
+ findings.push({
+ gate: 'approval', severity: allowDraft ? 'warning' : 'error', code: 'EXPORT_CHARACTER_DRAFT',
+ characterId: id,
+ message: `Character "${id}" has no approved voice canon.`,
+ });
+ }
+ characters.push(projectCharacter(character, {
+ role: id === loom?.protagonistCharacterId ? 'protagonist' : 'cast',
+ narrationFormat,
+ draftFlags,
+ }));
+ }
+ return { findings, characters };
+}
+
+const referencePosture = (asset, sourcePolicy, kind) => {
+ const license = typeof asset?.licensePosture === 'string' ? asset.licensePosture : '';
+ // A clone or a consented-performance claim needs the performer's consent even
+ // when another posture label is also present. Designed and licensed references
+ // are the postures that can travel without that confirmation.
+ const needsConsent = kind === 'cloned'
+ || sourcePolicy === 'consented-performance'
+ || license === 'consented-performance';
+ if (needsConsent) return asset?.performerConsentConfirmed === true ? 'ok' : 'consent-missing';
+ if (asset?.performerConsentConfirmed === true) return 'ok';
+ if (license === 'generated-original-voice' || license === 'licensed' || license === 'designed') return 'ok';
+ return 'skip';
+};
+
+/**
+ * One approved interactive profile, matching the live-voice approval check.
+ * Reference bytes export only with consent or an allowlisted designed/licensed
+ * posture. Unlabeled and unconsented recordings are never packaged.
+ */
+export function selectFableLoomExportVoice(profiles, { universeId, characterId, sourcePolicy = null } = {}) {
+ const approved = (Array.isArray(profiles) ? profiles : []).filter(profile => (
+ profile?.approval?.status === 'approved'
+ && profile?.binding?.characterId === characterId
+ && profile?.binding?.universeId === universeId
+ && profile?.routes?.interactive?.enabled === true
+ ));
+ if (approved.length === 0) {
+ return {
+ ok: false, gate: 'approval', code: 'EXPORT_VOICE_UNAPPROVED',
+ message: `Character "${characterId}" has no approved interactive voice profile.`,
+ };
+ }
+ if (approved.length > 1) {
+ return {
+ ok: false, gate: 'approval', code: 'EXPORT_VOICE_AMBIGUOUS',
+ message: `Character "${characterId}" has more than one approved interactive voice profile.`,
+ };
+ }
+ const profile = approved[0];
+ if (!VOICE_PROFILE_ID.test(profile.id || '')) {
+ return {
+ ok: false, gate: 'media', code: 'EXPORT_VOICE_REFERENCE_INVALID',
+ message: `Character "${characterId}" approved voice reference is not a managed audio asset.`,
+ };
+ }
+ const assets = [];
+ let rejectedConsent = false;
+ for (const asset of Array.isArray(profile.sourceAssets) ? profile.sourceAssets : []) {
+ const filename = typeof asset?.filename === 'string' ? asset.filename : '';
+ const sha256 = typeof asset?.sha256 === 'string' ? asset.sha256.toLowerCase() : '';
+ if (!VOICE_AUDIO_NAME.test(filename) || !/^[a-f0-9]{64}$/.test(sha256)) continue;
+ const posture = referencePosture(asset, sourcePolicy, profile.kind);
+ if (posture === 'consent-missing') {
+ rejectedConsent = true;
+ continue;
+ }
+ if (posture !== 'ok') continue;
+ const licensePosture = VOICE_REFERENCE_POSTURES.has(asset.licensePosture) ? asset.licensePosture : null;
+ assets.push({
+ filename, sha256, consentConfirmed: asset.performerConsentConfirmed === true, licensePosture,
+ });
+ }
+ assets.sort((a, b) => a.sha256.localeCompare(b.sha256) || a.filename.localeCompare(b.filename));
+ const unique = [];
+ for (const asset of assets) {
+ if (unique.some(item => item.sha256 === asset.sha256)) continue;
+ unique.push(asset);
+ }
+ if (!unique.length) {
+ return rejectedConsent ? {
+ ok: false, gate: 'approval', code: 'EXPORT_VOICE_CONSENT_MISSING',
+ message: `Character "${characterId}" voice reference has no confirmed consent.`,
+ } : {
+ ok: false, gate: 'media', code: 'EXPORT_VOICE_REFERENCE_MISSING',
+ message: `Character "${characterId}" has no approved voice reference audio.`,
+ };
+ }
+ return { ok: true, profileId: profile.id, assets: unique };
+}
+
/** Occupancy keys refer to packaged bytes, and never to a local history record. */
export function fableLoomExportOccupancy(node, sourceId) {
const raw = node.playbackAssets?.audioOccupancy?.[sourceId];
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
index c742d1548c..91d1d63ce1 100644
--- a/server/lib/promptStageCallSites.generated.json
+++ b/server/lib/promptStageCallSites.generated.json
@@ -56,6 +56,7 @@
"server/services/fableLoom/shots.js"
],
"fableloom-play-turn": [
+ "server/lib/fableLoomExport.js",
"server/services/fableLoom/weave.js"
],
"fableloom-reformat-scenes": [
diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.md
index 0b191bdd95..3959dafd49 100644
--- a/server/services/fableLoom/README.md
+++ b/server/services/fableLoom/README.md
@@ -20,6 +20,7 @@ intent to a transition and moves them through the graph until an ending.
| `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |
| `exports.js` | Immutable authored snapshots, readiness/approval gates, deterministic portable ZIP packages and bounded persistent export jobs. |
| `exportMedia.js` | Root-confined bounded media reads, metadata-free PNG stills and H.264/AAC MP4 stream copies; no network or generation. |
+| `exportVoice.js` | Root-confined reads of one approved voice-reference basename from that profile's source directory. Transcripts, engines and local paths stay out of the package. |
| `db.js` | PostgreSQL leaf I/O. |
Pure graph analysis (validation, BFS layering, prompt rendering) lives in
diff --git a/server/services/fableLoom/exportVoice.js b/server/services/fableLoom/exportVoice.js
new file mode 100644
index 0000000000..a53ca4efaa
--- /dev/null
+++ b/server/services/fableLoom/exportVoice.js
@@ -0,0 +1,70 @@
+import { constants } from 'node:fs';
+import { open, realpath } from 'node:fs/promises';
+import { join } from 'node:path';
+import { PATHS } from '../../lib/paths.js';
+import { isPathInsideDir } from '../../lib/pathSafety.js';
+import { FABLELOOM_EXPORT_LIMITS } from '../../lib/fableLoomExport.js';
+import { ServerError } from '../../lib/errorHandler.js';
+
+const refusal = (code, message) => new ServerError(message, { status: 422, code });
+const PROFILE_ID = /^[a-z0-9][a-z0-9-]{0,79}$/;
+const AUDIO_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(wav|mp3|flac|ogg|m4a)$/i;
+
+/**
+ * Snapshot one approved voice-reference basename. The resolved source directory
+ * has to stay inside the voice library, and the file inside that directory.
+ * Callers receive bytes only.
+ */
+export async function readFableLoomVoiceReference(profileId, filename) {
+ if (!PROFILE_ID.test(profileId || '') || !AUDIO_NAME.test(filename || '')) {
+ throw refusal('EXPORT_VOICE_REFERENCE_INVALID', 'Approved voice reference must be a managed audio basename.');
+ }
+ let library;
+ try {
+ library = await realpath(PATHS.voiceProfiles);
+ } catch {
+ throw refusal('EXPORT_VOICE_REFERENCE_MISSING', 'Approved voice reference audio is not in the managed voice library.');
+ }
+ let root;
+ try {
+ root = await realpath(join(library, profileId, 'source'));
+ } catch {
+ throw refusal('EXPORT_VOICE_REFERENCE_MISSING', 'Approved voice reference audio is not in the managed voice library.');
+ }
+ // The profile source directory is the trust anchor. A symlink that leaves
+ // the voice library must not become that anchor.
+ if (!isPathInsideDir(library, root)) {
+ throw refusal('EXPORT_VOICE_REFERENCE_INVALID', 'Approved voice reference resolves outside its profile library.');
+ }
+ let path;
+ try {
+ path = await realpath(join(root, filename));
+ } catch {
+ throw refusal('EXPORT_VOICE_REFERENCE_MISSING', 'Approved voice reference audio is not in the managed voice library.');
+ }
+ if (!isPathInsideDir(root, path)) {
+ throw refusal('EXPORT_VOICE_REFERENCE_INVALID', 'Approved voice reference resolves outside its profile library.');
+ }
+ const handle = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));
+ try {
+ const before = await handle.stat();
+ if (!before.isFile() || before.size <= 0 || before.size > FABLELOOM_EXPORT_LIMITS.maxAssetBytes) {
+ throw refusal('EXPORT_VOICE_REFERENCE_INVALID', 'Approved voice reference is empty, not a regular file, or exceeds the 64 MiB asset limit.');
+ }
+ const buffer = Buffer.alloc(before.size + 1);
+ let offset = 0;
+ while (offset < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
+ if (!bytesRead) break;
+ offset += bytesRead;
+ }
+ const after = await handle.stat();
+ if (offset !== before.size || before.size !== after.size
+ || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
+ throw refusal('EXPORT_VOICE_REFERENCE_INVALID', 'Approved voice reference changed while taking the export snapshot. Start a new export.');
+ }
+ return buffer.subarray(0, offset);
+ } finally {
+ await handle.close();
+ }
+}
diff --git a/server/services/fableLoom/exports.js b/server/services/fableLoom/exports.js
index 728ccc3924..dee8727391 100644
--- a/server/services/fableLoom/exports.js
+++ b/server/services/fableLoom/exports.js
@@ -14,12 +14,14 @@ import { computeGraphLayers } from '../../lib/fableLoomGraph.js';
import {
FABLELOOM_EXPORT_LIMITS, FABLELOOM_EXPORT_SCHEMA_VERSION,
fableLoomExportAssetRequests, fableLoomExportOccupancy, inspectFableLoomExport,
- projectFableLoomExportManifest, projectFableLoomExportNode,
+ inspectFableLoomExportCharacters, projectFableLoomExportManifest, projectFableLoomExportNode,
+ selectFableLoomExportVoice,
} from '../../lib/fableLoomExport.js';
import { getUniverse } from '../universeBuilder.js';
import { loadHistory } from '../videoGen/history.js';
import { getLoom } from './records.js';
import { checkExportCancelled, readFableLoomExportSource } from './exportMedia.js';
+import { readFableLoomVoiceReference } from './exportVoice.js';
import { createFableLoomMediaCache } from './exportMediaCache.js';
const uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
@@ -173,12 +175,34 @@ function createMediaStore(maxBytes = FABLELOOM_EXPORT_LIMITS.maxPackageBytes) {
};
}
-const packageReadme = `# FableLoom portable package
+function packageReadme(options) {
+ const characters = options.includeCharacters ? `
+characters/<id>.json is included for each canonical cast member: the loom
+protagonist, when set, and characters staged on reachable scenes. Each file
+carries persona and speech notes, pronunciation anchors, safety/never-say
+notes, and play-turn inputs for contract 1.0.0 (prompt id fableloom-play-turn).
+Scene prose and choices stay in manifest.json. The reader's message and
+conversation stay with your host. Do not send these files to PortOS.
+` : `
+Character inputs were not included. A later export can add them with
+includeCharacters. This package has no persona notes or pronunciation anchors.
+`;
+ const voice = options.includeVoice ? `
+provenance.json "voices" lists approved reference audio at media/<sha256>.<ext>,
+with a content hash and portable provenance (approval, consent, license posture,
+and voice-canon source policy). Use it only as a reference for your own TTS or
+voice engine. It is not an engine adapter, LoRA, transcript, credential, or
+PortOS session.
+` : `
+Voice reference audio was not included. Supply TTS on your own host.
+`;
+ return `# FableLoom portable package
Package schema: 1.0.0. Playback runtime: 1.0.0 (see runtime-v1.md).
Serve these files on your own static host. PortOS is an authoring tool and is
-never the public server, relay, or live resolver for this package.
+never the public server, relay, or live resolver for this package. This package
+does not grant PortOS access and includes no PortOS URL, credential, or callback.
manifest.json contains the ordered episodes and reachable scene graphs. Media
references name only media/<sha256>.<extension>, with durationMs and loopable.
@@ -188,22 +212,32 @@ Occupancy intervals are milliseconds relative to that packaged clip.
provenance.json records each media use, provider/model, parameter hash, approval
state and draftFlags. An allowDraft export does not certify production approval.
-
+${characters}${voice}
The source profile remuxes H.264/AAC. Web profiles resize without upscaling,
encode H.264/AAC with bitrate caps, normalize the authored audio mix and include
poster PNGs. Explicitly requested WebM alternatives use VP9/Opus. Encoding
profiles, encoder identities and byte counts are recorded in provenance.json.
-The player, character and voice opt-ins are not
-available in this package version. Your host owns free-text resolution, TTS and
-transport, following runtime-v1.md; no PortOS URL or credential is needed.
+The reference player is not in this package. Your host owns free-text
+resolution, TTS and transport, following runtime-v1.md.
`;
+}
+
+// Voice profiles live in Postgres. Keep that module off the default export path.
+async function loadVoiceProfiles(universeId, characterId) {
+ const { listVoiceProfiles } = await import('../voice/profiles.js');
+ return listVoiceProfiles({ universeId, characterId });
+}
async function build(job, snapshot, episodes, history, universe, signal) {
checkExportCancelled(signal);
job.status = 'validating';
job.findings = inspectFableLoomExport(snapshot, episodes, universe);
+ const characterProjection = job.options.includeCharacters
+ ? inspectFableLoomExportCharacters(snapshot, episodes, universe, { allowDraft: job.options.allowDraft })
+ : null;
+ if (characterProjection) job.findings.push(...characterProjection.findings);
if (job.findings.some(f => f.severity === 'error')) {
- throw error('EXPORT_VALIDATION_FAILED', 'Resolve the graph, outline and production findings before exporting.');
+ throw error('EXPORT_VALIDATION_FAILED', 'Resolve the graph, outline, production and character findings before exporting.');
}
const requests = episodes.flatMap(episode => {
const reachable = computeGraphLayers(episode).depthById;
@@ -224,8 +258,69 @@ async function build(job, snapshot, episodes, history, universe, signal) {
message: `The ${request.role} asset is unapproved or has draft, degraded or unknown provenance.`,
});
}
+ const voicePlans = [];
+ if (job.options.includeVoice) {
+ const universeId = typeof universe?.id === 'string' && universe.id
+ ? universe.id
+ : (typeof snapshot.universeId === 'string' ? snapshot.universeId : '');
+ for (const character of characterProjection?.characters || []) {
+ checkExportCancelled(signal);
+ let profiles;
+ try {
+ profiles = await loadVoiceProfiles(universeId, character.id);
+ } catch {
+ // The driver error can name a socket or query. The finding stays path-free.
+ console.error('❌ Approved voice profiles could not be read for a FableLoom export.');
+ job.findings.push({
+ gate: 'approval', severity: 'error', code: 'EXPORT_VOICE_UNAVAILABLE', characterId: character.id,
+ message: `Approved voice profiles could not be read for character "${character.id}".`,
+ });
+ continue;
+ }
+ const selection = selectFableLoomExportVoice(profiles, {
+ universeId, characterId: character.id, sourcePolicy: character.approval?.sourcePolicy || null,
+ });
+ if (!selection.ok) {
+ job.findings.push({
+ gate: selection.gate, severity: 'error', code: selection.code, characterId: character.id,
+ message: selection.message,
+ });
+ continue;
+ }
+ for (const asset of selection.assets) {
+ let bytes;
+ try {
+ bytes = await readFableLoomVoiceReference(selection.profileId, asset.filename);
+ } catch (failure) {
+ job.findings.push({
+ gate: 'media', severity: 'error',
+ code: typeof failure.code === 'string' && failure.code.startsWith('EXPORT_')
+ ? failure.code : 'EXPORT_VOICE_REFERENCE_INVALID',
+ characterId: character.id,
+ message: typeof failure.code === 'string' && failure.code.startsWith('EXPORT_')
+ ? failure.message : 'Approved voice reference audio could not be read.',
+ });
+ continue;
+ }
+ const sha256 = hash(bytes);
+ if (sha256 !== asset.sha256) {
+ job.findings.push({
+ gate: 'media', severity: 'error', code: 'EXPORT_VOICE_REFERENCE_MISMATCH', characterId: character.id,
+ message: `Character "${character.id}" voice reference does not match its recorded content hash.`,
+ });
+ continue;
+ }
+ voicePlans.push({
+ characterId: character.id, bytes, sha256,
+ extension: asset.filename.slice(asset.filename.lastIndexOf('.') + 1).toLowerCase(),
+ consentConfirmed: asset.consentConfirmed, licensePosture: asset.licensePosture,
+ sourcePolicy: character.approval?.sourcePolicy || null,
+ });
+ }
+ }
+ }
if (job.findings.some(f => f.severity === 'error')) {
- throw error('EXPORT_VALIDATION_FAILED', 'Resolve missing media or approval findings, or explicitly allow draft assets.');
+ throw error('EXPORT_VALIDATION_FAILED', 'Resolve missing media, approval, character or voice findings, or explicitly allow draft assets.');
}
job.status = 'packing';
job.progress = { completed: 0, total: requests.length };
@@ -281,16 +376,44 @@ async function build(job, snapshot, episodes, history, universe, signal) {
job.progress.completed++;
await save(job);
}
+ const voiceProvenance = voicePlans.map(plan => {
+ const prepared = media.add({ bytes: plan.bytes, extension: plan.extension, durationMs: null });
+ return {
+ characterId: plan.characterId, file: prepared.file, sha256: prepared.sha256, bytes: prepared.bytes,
+ approved: true, draftFlags: [], consentConfirmed: plan.consentConfirmed,
+ licensePosture: plan.licensePosture, sourcePolicy: plan.sourcePolicy,
+ };
+ });
const portos = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8'));
const manifest = projectFableLoomExportManifest(snapshot, episodes.map(episode => ({
id: episode.id, number: episode.number, title: episode.title, synopsis: episode.synopsis, startNodeId: episode.startNodeId,
nodes: episode.nodes.filter(n => nodeAssets.has(`${episode.id}:${n.id}`))
.map(node => projectFableLoomExportNode(node, snapshot, nodeAssets.get(`${episode.id}:${node.id}`))),
})), portos.version);
+ if (characterProjection) {
+ manifest.characters = characterProjection.characters.map(character => ({
+ id: character.id, role: character.role, file: `characters/${character.id}.json`,
+ }));
+ }
+ const provenanceDocument = {
+ schemaVersion: FABLELOOM_EXPORT_SCHEMA_VERSION,
+ assets: provenance,
+ ...(characterProjection ? {
+ characters: characterProjection.characters.map(character => ({
+ id: character.id, file: `characters/${character.id}.json`,
+ approved: character.approval.approved, draftFlags: character.approval.draftFlags,
+ voiceCanonVersion: character.approval.voiceCanonVersion,
+ })),
+ } : {}),
+ ...(job.options.includeVoice ? { voices: voiceProvenance } : {}),
+ };
const entries = [
{ name: 'manifest.json', data: json(manifest) },
- { name: 'provenance.json', data: json({ schemaVersion: FABLELOOM_EXPORT_SCHEMA_VERSION, assets: provenance }) },
- { name: 'README.md', data: packageReadme },
+ { name: 'provenance.json', data: json(provenanceDocument) },
+ { name: 'README.md', data: packageReadme(job.options) },
+ ...(characterProjection ? characterProjection.characters.map(character => ({
+ name: `characters/${character.id}.json`, data: json(character),
+ })) : []),
{ name: 'runtime-v1.md', data: await readFile(new URL('../../../docs/features/fableloom-runtime-v1.md', import.meta.url)) },
...[...media.entries()].map(([name, data]) => ({ name, data })),
].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
@@ -336,8 +459,11 @@ async function run(job, context, permit) {
export async function startFableLoomExport(loomId, input = {}) {
const options = exportOptionsSchema.parse(input);
- if (options.includePlayer || options.includeCharacters || options.includeVoice || (options.mediaProfile === 'source' && options.includeWebm)) {
- throw error('EXPORT_OPTION_UNSUPPORTED', 'Player, character and voice packages are unavailable. WebM requires a web media profile.', 400);
+ if (options.includePlayer || (options.mediaProfile === 'source' && options.includeWebm)) {
+ throw error('EXPORT_OPTION_UNSUPPORTED', 'The reference player is unavailable. WebM requires a web media profile.', 400);
+ }
+ if (options.includeVoice && !options.includeCharacters) {
+ throw error('EXPORT_VOICE_REQUIRES_CHARACTERS', 'Voice export requires character opt-in (includeCharacters).', 400);
}
const jobId = randomUUID();
const permit = maintenance.admit('media', jobId);
diff --git a/server/services/fableLoom/exports.test.js b/server/services/fableLoom/exports.test.js
index 8d11b3fad9..1926f651e2 100644
--- a/server/services/fableLoom/exports.test.js
+++ b/server/services/fableLoom/exports.test.js
@@ -11,7 +11,9 @@ import { errorMiddleware } from '../../lib/errorHandler.js';
import { readZipArchive } from '../../lib/zipArchive.js';
import * as ffmpeg from '../../lib/ffmpeg.js';
import { findFfmpeg, findFfprobe, runFfmpegProcess } from '../../lib/ffmpeg.js';
-import { FABLELOOM_EXPORT_LIMITS } from '../../lib/fableLoomExport.js';
+import {
+ FABLELOOM_EXPORT_LIMITS, inspectFableLoomExportCharacters,
+} from '../../lib/fableLoomExport.js';
import { execFileSync } from '../../lib/childProcess.js';
vi.mock('../../lib/paths.js', async original => makePathsProxy(await original(), {
@@ -20,6 +22,7 @@ vi.mock('../../lib/paths.js', async original => makePathsProxy(await original(),
vi.mock('./records.js', () => ({ getLoom: vi.fn() }));
vi.mock('../videoGen/history.js', () => ({ loadHistory: vi.fn() }));
vi.mock('../universeBuilder.js', () => ({ getUniverse: vi.fn() }));
+vi.mock('../voice/profiles.js', () => ({ listVoiceProfiles: vi.fn() }));
vi.mock('./index.js', () => ({}));
vi.mock('./shotRuns.js', () => ({}));
@@ -27,6 +30,7 @@ import { PATHS } from '../../lib/paths.js';
import { getLoom } from './records.js';
import { loadHistory } from '../videoGen/history.js';
import { getUniverse } from '../universeBuilder.js';
+import { listVoiceProfiles } from '../voice/profiles.js';
import * as media from './exportMedia.js';
import {
__testing, startFableLoomExport, getFableLoomExport, getFableLoomExportDownload,
@@ -109,6 +113,76 @@ async function archive(id) {
} finally { artifact.release(); }
}
+const packageSentinels = [
+ privateMarker, sourcePath, 'SECRET_TOKEN_SENTINEL', 'SESSION_TRANSCRIPT_SENTINEL',
+ 'SECRET_CAST_SENTINEL', 'SECRET_ENGINE_SENTINEL', 'kokoro:SECRET_PRESET',
+ 'SECRET_APPROVED_AT', '/example-private/checkpoint', 'example-voice',
+];
+function assertPackageClean(packed) {
+ for (const marker of packageSentinels) {
+ expect(packed.bytes.includes(Buffer.from(marker)), marker).toBe(false);
+ for (const bytes of packed.files.values()) expect(bytes.includes(Buffer.from(marker)), marker).toBe(false);
+ }
+}
+function approvedCharacter(overrides = {}) {
+ return {
+ id: 'example-character', name: 'Ada Example',
+ personality: 'Calm and precise.', speechAccent: 'Neutral example accent.',
+ speechPattern: 'Short sentences.', mannerisms: 'Pauses before answers.',
+ background: privateMarker, secrets: 'SECRET_TOKEN_SENTINEL', psychology: privateMarker,
+ voiceId: 'kokoro:SECRET_PRESET', prompt: privateMarker,
+ adapters: [{ filename: sourcePath }], loras: [sourcePath], imageRefs: [sourcePath],
+ sessions: ['SESSION_TRANSCRIPT_SENTINEL'],
+ voiceCanon: {
+ version: 2, approved: true, sourcePolicy: 'designed',
+ description: 'Warm mid register.', defaultDelivery: 'Measured.',
+ emotionalRange: ['steady'], avoid: ['never shout'],
+ pronunciations: [{ term: 'Fable', pronunciation: 'FAY-bul', recordingPath: sourcePath }],
+ recordingPath: sourcePath,
+ },
+ ...overrides,
+ };
+}
+function useCast(characters = [approvedCharacter()]) {
+ loom.protagonistCharacterId = 'example-character';
+ getUniverse.mockResolvedValue({
+ id: 'example-universe',
+ characters: [...characters, { id: 'unbound-extra', name: 'SECRET_CAST_SENTINEL', personality: privateMarker }],
+ });
+}
+async function writeVoiceReference(bytes, filename = 'reference.wav') {
+ const dir = join(PATHS.voiceProfiles, 'example-voice', 'source');
+ await mkdir(dir, { recursive: true });
+ await writeFile(join(dir, filename), bytes);
+ return hash(bytes);
+}
+function voiceProfile({ sha256, filename = 'reference.wav', id = 'example-voice', kind = 'designed', sourceAssets } = {}) {
+ return {
+ id, kind, engine: 'SECRET_ENGINE_SENTINEL', voiceId: 'kokoro:SECRET_PRESET',
+ binding: { universeId: 'example-universe', characterId: 'example-character' },
+ approval: { status: 'approved', approvedAt: 'SECRET_APPROVED_AT' },
+ routes: { interactive: { enabled: true } },
+ inference: { checkpointPath: '/example-private/checkpoint' },
+ sourceAssets: sourceAssets || [{
+ filename, sha256, transcript: 'SESSION_TRANSCRIPT_SENTINEL',
+ performerConsentConfirmed: false, licensePosture: 'generated-original-voice', path: sourcePath,
+ }],
+ };
+}
+async function expectVoiceRefusal(profiles, code, options = { includeCharacters: true, includeVoice: true }) {
+ listVoiceProfiles.mockResolvedValue(profiles);
+ const result = await terminal(await begin({ episodeIds: ['episode-one'], ...options }));
+ expect(result).toMatchObject({ status: 'failed', error: { code: 'EXPORT_VALIDATION_FAILED' } });
+ expect(result.findings).toContainEqual(expect.objectContaining({ code, severity: 'error' }));
+ expect(result).not.toHaveProperty('downloadUrl');
+ expect(JSON.stringify(result)).not.toContain(sourcePath);
+ expect(JSON.stringify(result)).not.toContain('SESSION_TRANSCRIPT_SENTINEL');
+ expect(JSON.stringify(result)).not.toContain('example-voice');
+ expect(JSON.stringify(result)).not.toContain('/example-private/checkpoint');
+ await expect(stat(join(PATHS.data, 'cache/fableloom-exports', jobIds.at(-1), 'package.zip'))).rejects.toMatchObject({ code: 'ENOENT' });
+ return result;
+}
+
beforeAll(async () => {
await mkdir(PATHS.images, { recursive: true });
await mkdir(PATHS.videos, { recursive: true });
@@ -139,6 +213,8 @@ beforeEach(async () => {
sessionTranscripts: privateMarker, peerId: privateMarker, providerConfig: { apiKey: privateMarker } };
getLoom.mockImplementation(async id => id === loom.id || id === 'another-loom' ? loom : null);
getUniverse.mockResolvedValue({ characters: [{ id: 'example-character' }] });
+ listVoiceProfiles.mockResolvedValue([]);
+ await rm(PATHS.voiceProfiles, { recursive: true, force: true });
loadHistory.mockResolvedValue(['entry-record', 'hold-record', 'exit-record'].map(id => ({
id, filename: 'independent-name.mp4', absolutePath: sourcePath, prompt: privateMarker, apiKey: privateMarker,
})));
@@ -160,6 +236,16 @@ describe('portable FableLoom export boundary', () => {
expect(manifest).toMatchObject({ schemaVersion: '1.0.0', runtimeVersion: '1.0.0',
loom: { name: 'The quiet gate', episodes: [{ id: 'episode-two' }] } });
expect(manifest.loom.episodes).toHaveLength(1);
+ expect(manifest.characters).toBeUndefined();
+ expect([...first.files.keys()].some(name => name.startsWith('characters/'))).toBe(false);
+ const defaultProvenance = JSON.parse(first.files.get('provenance.json'));
+ expect(defaultProvenance.characters).toBeUndefined();
+ expect(defaultProvenance.voices).toBeUndefined();
+ const defaultReadme = first.files.get('README.md').toString();
+ expect(defaultReadme).toContain('does not grant PortOS access');
+ expect(defaultReadme).toContain('Voice reference audio was not included');
+ expect(defaultReadme).toContain('Your host owns free-text');
+ expect(listVoiceProfiles).not.toHaveBeenCalled();
const [start, end] = manifest.loom.episodes[0].nodes;
expect(start.playbackAssets.holds[0]).toMatchObject({ loopable: true, durationMs: 1000,
audioOccupancy: { safeForLiveVoice: true } });
@@ -391,15 +477,222 @@ describe('portable FableLoom export boundary', () => {
});
it('refuses unsupported and malformed options before creating jobs', async () => {
- for (const input of [{ includePlayer: true }, { includeCharacters: true }, { includeVoice: true },
+ for (const input of [{ includePlayer: true },
{ mediaProfile: 'webm' }, { includeWebm: true }, { includeWebm: 'yes' }, { mediaProfile: { width: 100 } }, { allowDraft: 'yes' },
{ episodeIds: [] }, { episodeIds: ['episode-one', 'episode-one'] }, { destination: sourcePath }]) {
const response = await request(app()).post('/api/fableloom/example-loom/export').send(input);
expect(response.status, JSON.stringify(input)).toBe(400);
}
+ const voiceOnly = await request(app()).post('/api/fableloom/example-loom/export').send({ includeVoice: true });
+ expect(voiceOnly.status).toBe(400);
+ expect(voiceOnly.body.code).toBe('EXPORT_VOICE_REQUIRES_CHARACTERS');
+ expect(listVoiceProfiles).not.toHaveBeenCalled();
await expect(startFableLoomExport(loom.id, { episodeIds: ['unknown-episode'] })).rejects.toMatchObject({ code: 'EXPORT_EPISODES_INVALID' });
});
+ it('limits the cast to the protagonist and reachable staged characters', () => {
+ const episodes = [{
+ startNodeId: 'a',
+ nodes: [
+ { id: 'a', visualCanon: { characterAppearances: [{ characterId: 'hero' }, { characterId: 'on-stage' }] },
+ interactionWindow: { protagonistCharacterId: 'speaker' },
+ transitions: [{ targetNodeId: 'b' }] },
+ { id: 'b', transitions: [] },
+ { id: 'orphan', visualCanon: { characterAppearances: [{ characterId: 'secret-extra' }] }, transitions: [] },
+ ],
+ }];
+ const loomCast = { protagonistCharacterId: 'hero', format: 'prose' };
+ const universe = { characters: [
+ { id: 'hero', name: 'Ada Example', personality: 'Calm.', background: privateMarker,
+ secrets: 'SECRET_TOKEN_SENTINEL', voiceId: 'kokoro:SECRET_PRESET',
+ adapters: [sourcePath], sessions: ['SESSION_TRANSCRIPT_SENTINEL'],
+ voiceCanon: { version: 2, approved: true, sourcePolicy: 'designed', description: 'Warm.',
+ defaultDelivery: 'Measured.', emotionalRange: ['steady'], avoid: ['never shout'],
+ pronunciations: [{ term: 'Fable', pronunciation: 'FAY-bul', recordingPath: sourcePath }],
+ recordingPath: sourcePath } },
+ { id: 'on-stage', name: 'Draft', voiceCanon: { approved: false, description: 'rough' } },
+ { id: 'speaker', name: 'Speaker' },
+ { id: 'secret-extra', name: 'SECRET_CAST_SENTINEL', personality: privateMarker },
+ ]};
+ const blocked = inspectFableLoomExportCharacters(loomCast, episodes, universe);
+ expect(blocked.characters.map(character => character.id)).toEqual(['hero', 'on-stage', 'speaker']);
+ expect(blocked.findings.map(finding => finding.characterId)).toEqual(['on-stage', 'speaker']);
+ expect(blocked.findings.every(finding => finding.severity === 'error' && finding.code === 'EXPORT_CHARACTER_DRAFT')).toBe(true);
+ const hero = blocked.characters.find(character => character.id === 'hero');
+ expect(hero.approval).toEqual({ voiceCanonVersion: 2, approved: true, sourcePolicy: 'designed', draftFlags: [] });
+ expect(hero.pronunciations).toEqual([{ term: 'Fable', pronunciation: 'FAY-bul' }]);
+ expect(hero.playTurn).toMatchObject({ promptId: 'fableloom-play-turn', contractVersion: '1.0.0' });
+ expect(hero.role).toBe('protagonist');
+ const drafted = inspectFableLoomExportCharacters(loomCast, episodes, universe, { allowDraft: true });
+ expect(drafted.findings.every(finding => finding.severity === 'warning')).toBe(true);
+ expect(drafted.characters.find(character => character.id === 'on-stage').approval.draftFlags).toEqual(['unapproved']);
+ expect(drafted.characters.find(character => character.id === 'speaker').approval.draftFlags).toEqual(['unknown']);
+ const packed = JSON.stringify(drafted.characters);
+ for (const marker of [privateMarker, sourcePath, 'SECRET_TOKEN_SENTINEL', 'SESSION_TRANSCRIPT_SENTINEL', 'SECRET_CAST_SENTINEL', 'kokoro:', 'recordingPath']) {
+ expect(packed.includes(marker), marker).toBe(false);
+ }
+ });
+
+ it('fails closed when character approval, membership or identifiers are not portable', async () => {
+ const unapproved = await terminal(await begin({ episodeIds: ['episode-one'], includeCharacters: true }));
+ expect(unapproved).toMatchObject({ status: 'failed', error: { code: 'EXPORT_VALIDATION_FAILED' } });
+ expect(unapproved.findings).toContainEqual(expect.objectContaining({
+ code: 'EXPORT_CHARACTER_DRAFT', severity: 'error', characterId: 'example-character',
+ }));
+ expect(listVoiceProfiles).not.toHaveBeenCalled();
+ getUniverse.mockResolvedValue({ characters: [] });
+ const missing = await terminal(await begin({ episodeIds: ['episode-one'], includeCharacters: true }));
+ expect(missing.findings).toContainEqual(expect.objectContaining({ code: 'EXPORT_CHARACTER_MISSING', severity: 'error' }));
+ loom.episodes = [episode('episode-one')];
+ loom.episodes[0].nodes[0].interactionWindow.protagonistCharacterId = 'not/portable';
+ const badId = await terminal(await begin({ episodeIds: ['episode-one'], includeCharacters: true }));
+ const idFinding = badId.findings.find(finding => finding.code === 'EXPORT_CHARACTER_ID');
+ expect(idFinding).toMatchObject({ severity: 'error', message: 'Character identifiers must be portable identifiers.' });
+ expect(idFinding).not.toHaveProperty('characterId');
+ expect(badId).not.toHaveProperty('downloadUrl');
+ await expect(stat(join(PATHS.data, 'cache/fableloom-exports', jobIds.at(-1), 'package.zip'))).rejects.toMatchObject({ code: 'ENOENT' });
+ loom.episodes = [episode('episode-one')];
+ loom.episodes[0].nodes[0].interactionWindow.protagonistCharacterId = '';
+ const empty = await terminal(await begin({ episodeIds: ['episode-one'], includeCharacters: true }));
+ expect(empty.findings).toContainEqual(expect.objectContaining({ code: 'EXPORT_CAST_MISSING', severity: 'error' }));
+ await expect(getFableLoomExportDownload(loom.id, jobIds.at(-1))).rejects.toMatchObject({ code: 'EXPORT_NOT_READY' });
+ });
+
+ it('refuses unapproved, ambiguous, unconsented and unlabeled voice references even when drafts are allowed', async () => {
+ useCast();
+ const digest = 'ab'.repeat(32);
+ await expectVoiceRefusal([], 'EXPORT_VOICE_UNAPPROVED', { includeCharacters: true, includeVoice: true, allowDraft: true });
+ await expectVoiceRefusal([
+ voiceProfile({ sha256: digest, id: 'example-voice' }),
+ voiceProfile({ sha256: 'cd'.repeat(32), id: 'example-voice-two' }),
+ ], 'EXPORT_VOICE_AMBIGUOUS');
+ await expectVoiceRefusal([voiceProfile({
+ sha256: digest, kind: 'cloned',
+ sourceAssets: [{ filename: 'reference.wav', sha256: digest, performerConsentConfirmed: false,
+ licensePosture: 'generated-original-voice', transcript: 'SESSION_TRANSCRIPT_SENTINEL', path: sourcePath }],
+ })], 'EXPORT_VOICE_CONSENT_MISSING');
+ await expectVoiceRefusal([voiceProfile({
+ sha256: digest,
+ sourceAssets: [{ filename: 'notes.txt', sha256: digest, transcript: 'SESSION_TRANSCRIPT_SENTINEL' }],
+ })], 'EXPORT_VOICE_REFERENCE_MISSING');
+ const invalidProfile = await expectVoiceRefusal([voiceProfile({
+ sha256: digest, id: 'Not A Profile',
+ })], 'EXPORT_VOICE_REFERENCE_INVALID');
+ expect(JSON.stringify(invalidProfile)).not.toContain('Not A Profile');
+ const wrongUniverse = voiceProfile({ sha256: digest });
+ wrongUniverse.binding.universeId = 'other-universe';
+ await expectVoiceRefusal([wrongUniverse], 'EXPORT_VOICE_UNAPPROVED');
+ });
+
+ it('keeps a voice-profile read failure path-free', async () => {
+ useCast();
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => {});
+ listVoiceProfiles.mockRejectedValue(Object.assign(
+ new Error('password at /example-private/voice.db'), { code: 'ECONNREFUSED' },
+ ));
+ const result = await terminal(await begin({
+ episodeIds: ['episode-one'], includeCharacters: true, includeVoice: true,
+ }));
+ expect(result.findings).toContainEqual(expect.objectContaining({
+ code: 'EXPORT_VOICE_UNAVAILABLE', severity: 'error',
+ }));
+ expect(result).not.toHaveProperty('downloadUrl');
+ const visible = `${JSON.stringify(result)}\n${errorLog.mock.calls.flat().join('\n')}`;
+ expect(visible).not.toContain('/example-private/voice.db');
+ expect(visible).not.toContain('ECONNREFUSED');
+ expect(visible).not.toContain('password');
+ await expect(stat(join(PATHS.data, 'cache/fableloom-exports', jobIds.at(-1), 'package.zip'))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('keeps a voice-reference hash mismatch and an escaping symlink out of the package', async () => {
+ useCast();
+ const bytes = Buffer.from('approved-reference-audio');
+ const recorded = await writeVoiceReference(bytes);
+ await expectVoiceRefusal([voiceProfile({ sha256: 'aa'.repeat(32) })], 'EXPORT_VOICE_REFERENCE_MISMATCH');
+ expect(JSON.stringify(await getFableLoomExport(loom.id, jobIds.at(-1)))).not.toContain(recorded);
+ await rm(PATHS.voiceProfiles, { recursive: true, force: true });
+ const outsideDir = join(PATHS.data, 'outside-voice');
+ await mkdir(outsideDir, { recursive: true });
+ await writeFile(join(outsideDir, 'reference.wav'), bytes);
+ await mkdir(join(PATHS.voiceProfiles, 'example-voice'), { recursive: true });
+ await symlink(outsideDir, join(PATHS.voiceProfiles, 'example-voice', 'source'));
+ const escaped = await expectVoiceRefusal([voiceProfile({ sha256: hash(bytes) })], 'EXPORT_VOICE_REFERENCE_INVALID');
+ expect(JSON.stringify(escaped)).not.toContain('outside-voice');
+ expect(JSON.stringify(escaped)).not.toContain('reference.wav');
+ });
+
+ videoIt('exports approved character inputs without voice bytes', async () => {
+ useCast();
+ const packed = await archive(await begin({ episodeIds: ['episode-one'], includeCharacters: true }));
+ const character = JSON.parse(packed.files.get('characters/example-character.json'));
+ expect(character).toMatchObject({
+ schemaVersion: '1.0.0', id: 'example-character', name: 'Ada Example', role: 'protagonist',
+ persona: { personality: 'Calm and precise.', speechAccent: 'Neutral example accent.',
+ speechPattern: 'Short sentences.', mannerisms: 'Pauses before answers.' },
+ speech: { description: 'Warm mid register.', defaultDelivery: 'Measured.', emotionalRange: ['steady'] },
+ pronunciations: [{ term: 'Fable', pronunciation: 'FAY-bul' }],
+ safety: { neverSay: ['never shout'] },
+ playTurn: { promptId: 'fableloom-play-turn', contractVersion: '1.0.0', inputs: { characterId: 'example-character', role: 'protagonist' } },
+ approval: { voiceCanonVersion: 2, approved: true, sourcePolicy: 'designed', draftFlags: [] },
+ });
+ expect(Object.keys(character.pronunciations[0]).sort()).toEqual(['pronunciation', 'term']);
+ const manifest = JSON.parse(packed.files.get('manifest.json'));
+ expect(manifest.characters).toEqual([{ id: 'example-character', role: 'protagonist', file: 'characters/example-character.json' }]);
+ const provenance = JSON.parse(packed.files.get('provenance.json'));
+ expect(provenance.characters).toEqual([{
+ id: 'example-character', file: 'characters/example-character.json',
+ approved: true, draftFlags: [], voiceCanonVersion: 2,
+ }]);
+ expect(provenance.voices).toBeUndefined();
+ expect([...packed.files.keys()].filter(name => name.startsWith('media/'))).toHaveLength(2);
+ expect([...packed.files.keys()].some(name => name.endsWith('.wav'))).toBe(false);
+ const readme = packed.files.get('README.md').toString();
+ expect(readme).toContain('characters/<id>.json');
+ expect(readme).toContain('Voice reference audio was not included');
+ expect(readme).toContain('does not grant PortOS access');
+ expect(readme).toContain('Your host owns free-text');
+ assertPackageClean(packed);
+ expect(listVoiceProfiles).not.toHaveBeenCalled();
+ });
+
+ videoIt('exports approved voice references with provenance and stable hashes', async () => {
+ useCast();
+ const bytes = Buffer.from('approved-reference-audio');
+ const digest = await writeVoiceReference(bytes);
+ listVoiceProfiles.mockResolvedValue([voiceProfile({ sha256: digest })]);
+ const options = { episodeIds: ['episode-one'], includeCharacters: true, includeVoice: true };
+ const first = await archive(await begin(options));
+ const second = await archive(await begin(options));
+ expect(second.bytes.equals(first.bytes)).toBe(true);
+ const provenance = JSON.parse(first.files.get('provenance.json'));
+ expect(provenance.voices).toEqual([{
+ characterId: 'example-character', file: `media/${digest}.wav`, sha256: digest, bytes: bytes.length,
+ approved: true, draftFlags: [], consentConfirmed: false,
+ licensePosture: 'generated-original-voice', sourcePolicy: 'designed',
+ }]);
+ expect(first.files.get(`media/${digest}.wav`).equals(bytes)).toBe(true);
+ expect(hash(first.files.get(`media/${digest}.wav`))).toBe(digest);
+ const readme = first.files.get('README.md').toString();
+ expect(readme).toContain('your own TTS');
+ expect(readme).toContain('does not grant PortOS access');
+ expect(readme).toContain('no PortOS URL, credential, or callback');
+ assertPackageClean(first);
+ useCast([approvedCharacter({ voiceCanon: { approved: false, description: 'rough' } })]);
+ const drafted = await archive(await begin({ episodeIds: ['episode-one'], includeCharacters: true, allowDraft: true }));
+ const draftCharacter = JSON.parse(drafted.files.get('characters/example-character.json'));
+ expect(draftCharacter.approval).toMatchObject({ approved: false, draftFlags: ['unapproved'] });
+ expect(JSON.parse(drafted.files.get('provenance.json')).voices).toBeUndefined();
+ expect([...drafted.files.keys()].some(name => name.endsWith('.wav'))).toBe(false);
+ assertPackageClean(drafted);
+ listVoiceProfiles.mockResolvedValue([]);
+ const voiceDraft = await terminal(await begin({
+ episodeIds: ['episode-one'], includeCharacters: true, includeVoice: true, allowDraft: true,
+ }));
+ expect(voiceDraft).toMatchObject({ status: 'failed', error: { code: 'EXPORT_VALIDATION_FAILED' } });
+ expect(voiceDraft.findings).toContainEqual(expect.objectContaining({ code: 'EXPORT_VOICE_UNAPPROVED', severity: 'error' }));
+ expect(voiceDraft.findings).toContainEqual(expect.objectContaining({ code: 'EXPORT_CHARACTER_DRAFT', severity: 'warning' }));
+ });
+
it('never follows a remote, traversing or escaping symlink source and keeps failures path-free', async () => {
for (const bad of ['https://example.com/movie.mp4', '../private.mp4', sourcePath + '.mp4']) {
loadHistory.mockResolvedValue([{ id: 'entry-record', filename: bad }]);