Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
import { describe, expect, it } from 'vitest';
import {
analyzeSeriesStoryOutlines,
analyzeStoryOutline,
analyzeStoryOutlineTeleplaySync,
describeStoryOutlineForPrompt,
sanitizeStoryOutline,
} from './fableLoomOutline.js';
const validOutline = {
startKey: 's1',
scenes: [
{
key: 's1',
title: 'Signal',
summary: 'The protagonist catches a signal that proves the missing ship is still alive.',
playbackMode: 'cut',
audienceConnection: 'disconnected',
transitions: [{ targetKey: 's2', intent: 'follow the signal' }],
},
{
key: 's2',
title: 'The choice',
summary: 'The signal offers two routes, each demanding a different sacrifice.',
playbackMode: 'decision',
audienceConnection: 'connected',
transitions: [
{ targetKey: 's3', intent: 'protect the survivors' },
{ targetKey: 's4', intent: 'take the shortcut' },
],
},
{
key: 's3',
title: 'A costly rescue',
summary: 'The rescue succeeds but strands the protagonist beyond the safe corridor.',
playbackMode: 'cut',
audienceConnection: 'connected',
isEnding: true,
endingLabel: 'The long way home',
transitions: [],
},
{
key: 's4',
title: 'The shortcut',
summary: 'The shortcut opens the corridor while leaving one unanswered voice behind.',
playbackMode: 'cut',
audienceConnection: 'connected',
isEnding: true,
endingLabel: 'The open door',
transitions: [],
},
],
};
describe('FableLoom story beat outlines', () => {
it('accepts a reachable arc with real choices and distinct endings', () => {
const outline = sanitizeStoryOutline(validOutline);
const result = analyzeStoryOutline(outline, { participationMode: 'helper', requireAudienceIntroduction: true });
expect(result.issues).toEqual([]);
expect(result.stats).toMatchObject({
sceneCount: 4,
automaticCutCount: 1,
decisionCount: 1,
endingCount: 2,
reachableCount: 4,
reachableEndingCount: 2,
errorCount: 0,
});
});
it('surfaces missing summaries, unreachable beats, invalid paths, and disconnected choices', () => {
const outline = sanitizeStoryOutline({
startKey: 's1',
scenes: [
{ key: 's1', title: 'Opening', playbackMode: 'cut', audienceConnection: 'disconnected', transitions: [{ targetKey: 's2', intent: 'continue' }] },
{ key: 's2', title: 'Choice', summary: 'A choice.', playbackMode: 'decision', audienceConnection: 'disconnected', transitions: [{ targetKey: 'missing', intent: '' }] },
{ key: 's3', title: 'Lost', summary: 'Never reached.', playbackMode: 'cut', isEnding: true },
],
});
const result = analyzeStoryOutline(outline, { participationMode: 'helper', requireAudienceIntroduction: true });
const codes = result.issues.map((issue) => issue.code);
expect(codes).toEqual(expect.arrayContaining([
'EMPTY_SUMMARY', 'DECISION_TRANSITION_COUNT', 'DISCONNECTED_DECISION',
'EMPTY_INTENT', 'DANGLING_TRANSITION', 'UNREACHABLE_SCENE', 'NO_AUDIENCE_CONNECTION',
]));
expect(result.stats.errorCount).toBeGreaterThan(0);
});
it('requires every playable challenge to map setup, decision, outcomes, and recovery into reachable scenes', () => {
const challenge = { id: 'plot-lock', kind: 'challenge', title: 'Open the sealed door' };
const challengeOutline = sanitizeStoryOutline({
startKey: 'setup',
scenes: [
{
key: 'setup', title: 'The keypad', summary: 'A prior clue makes the sealed keypad actionable.',
plotPointId: challenge.id, challengePhase: 'setup', playbackMode: 'cut',
transitions: [{ targetKey: 'decision', intent: 'try the keypad' }],
},
{
key: 'decision', title: 'Choose the code', summary: 'The viewer chooses which remembered code to enter.',
plotPointId: challenge.id, challengePhase: 'decision', playbackMode: 'decision',
transitions: [
{ targetKey: 'success', intent: 'enter the remembered code' },
{ targetKey: 'failure', intent: 'guess under pressure' },
],
},
{
key: 'success', title: 'The lock opens', summary: 'The correct code opens the door quietly.',
plotPointId: challenge.id, challengePhase: 'success', playbackMode: 'cut',
transitions: [{ targetKey: 'recovery', intent: 'slip through' }],
},
{
key: 'failure', title: 'The alarm chirps', summary: 'The wrong code alerts a guard but leaves an escape route.',
plotPointId: challenge.id, challengePhase: 'failure', playbackMode: 'cut',
transitions: [{ targetKey: 'recovery', intent: 'improvise a distraction' }],
},
{
key: 'recovery', title: 'Beyond the door', summary: 'Both routes continue with distinct costs into the next blockade.',
plotPointId: challenge.id, challengePhase: 'recovery', playbackMode: 'cut',
transitions: [{ targetKey: 'ending', intent: 'move deeper inside' }],
},
{
key: 'ending', title: 'Inside', summary: 'The viewer gets the character safely inside.',
isEnding: true, endingLabel: 'Through the first blockade', transitions: [],
},
],
});
const ready = analyzeStoryOutline(challengeOutline, { challenges: [challenge] });
expect(ready.stats).toMatchObject({ challengeCount: 1, readyChallengeCount: 1, errorCount: 0 });
const missingFailure = structuredClone(challengeOutline);
missingFailure.scenes.find((scene) => scene.key === 'failure').challengePhase = null;
expect(analyzeStoryOutline(missingFailure, { challenges: [challenge] }).issues)
.toContainEqual(expect.objectContaining({ code: 'CHALLENGE_PHASE_MISSING' }));
});
it('keeps outline rendering compact for the AI prompt', () => {
const outline = sanitizeStoryOutline(validOutline);
const digest = describeStoryOutlineForPrompt(outline);
expect(digest).toContain('[s1] Signal (START) (AUTO CUT)');
expect(digest).toContain('-> [s2] follow the signal (The choice)');
expect(digest).toContain('The shortcut opens the corridor');
});
it('defaults connected decision beats off-screen only for helper stories', () => {
const protagonistOutline = sanitizeStoryOutline(validOutline, { participationMode: 'protagonist' });
const helperOutline = sanitizeStoryOutline(validOutline, { participationMode: 'helper' });
expect(protagonistOutline.scenes.find((scene) => scene.key === 's2').protagonistPresence)
.toBe('onscreen');
expect(helperOutline.scenes.find((scene) => scene.key === 's2').protagonistPresence)
.toBe('offscreen');
});
it('requires every episode outline and configured delivery handoff before the series is ready', () => {
const loom = {
participationMode: 'protagonist',
episodes: [
{ id: 'ep-1', number: 1, storyOutline: { ...sanitizeStoryOutline(validOutline), validation: { status: 'valid', issues: [] } } },
{ id: 'ep-2', number: 2 },
],
seriesPlan: {
deliveryOptions: { overnightVoicemails: true, nextSeasonTeaser: true },
interEpisodeVoicemails: [{ fromEpisodeId: 'ep-1', toEpisodeId: 'ep-2', transcript: '' }],
nextSeasonTeaser: { title: 'Beyond', transcript: '' },
},
};
const result = analyzeSeriesStoryOutlines(loom);
const codes = result.issues.map((issue) => issue.code);
expect(codes).toEqual(expect.arrayContaining([
'MISSING_EPISODE_OUTLINE', 'EMPTY_OVERNIGHT_VOICEMAIL', 'MISSING_NEXT_SEASON_TEASER',
]));
expect(result.stats.ready).toBe(false);
});
it('does not count a claimed-valid outline as ready when the expanded teleplay has drifted', () => {
const storyOutline = {
...sanitizeStoryOutline(validOutline),
validation: { status: 'valid', issues: [] },
};
const episode = {
id: 'ep-1',
number: 1,
startNodeId: 's1',
storyOutline,
nodes: storyOutline.scenes.map((scene) => ({
id: scene.key,
title: scene.title,
playbackMode: scene.playbackMode,
audienceConnection: scene.audienceConnection,
protagonistPresence: scene.protagonistPresence,
isEnding: scene.isEnding,
endingLabel: scene.endingLabel,
transitions: scene.transitions.map((item) => ({
targetNodeId: item.targetKey,
intent: item.intent,
})),
})),
};
episode.nodes.push({
id: 'new-scene', title: 'New scene', playbackMode: 'decision',
audienceConnection: 'connected', protagonistPresence: 'onscreen',
isEnding: true, endingLabel: 'New ending', transitions: [],
});
const sync = analyzeStoryOutlineTeleplaySync(episode, storyOutline);
const series = analyzeSeriesStoryOutlines({
participationMode: 'protagonist', episodes: [episode], seriesPlan: {},
});
expect(sync.stats.matches).toBe(false);
expect(sync.issues).toContainEqual(expect.objectContaining({
code: 'TELEPLAY_SCENE_MEMBERSHIP_MISMATCH',
}));
expect(series.stats).toMatchObject({ ready: false, readyEpisodeCount: 0 });
});
it('ignores playbackMode on endings and names differing fields in the mismatch message', () => {
const storyOutline = sanitizeStoryOutline({
...validOutline,
scenes: validOutline.scenes.map((scene) => {
if (!scene.isEnding) return scene;
const { playbackMode: _omitted, ...rest } = scene;
return rest;
}),
});
expect(storyOutline.scenes.find((scene) => scene.isEnding).playbackMode).toBe('decision');
const nodes = storyOutline.scenes.map((scene) => ({
id: scene.key,
title: scene.title,
playbackMode: scene.isEnding ? 'cut' : scene.playbackMode,
audienceConnection: scene.audienceConnection,
protagonistPresence: scene.protagonistPresence,
isEnding: scene.isEnding,
endingLabel: scene.endingLabel,
transitions: scene.transitions.map((item) => ({ targetNodeId: item.targetKey, intent: item.intent })),
}));
const episode = { id: 'ep-1', number: 1, startNodeId: storyOutline.startKey, storyOutline, nodes };
expect(analyzeStoryOutlineTeleplaySync(episode, storyOutline).stats.matches).toBe(true);
const other = nodes.find((node) => !node.isEnding);
other.audienceConnection = other.audienceConnection === 'connected' ? 'disconnected' : 'connected';
const sync = analyzeStoryOutlineTeleplaySync(episode, storyOutline);
expect(sync.issues[0].message).toContain('audienceConnection: outline=');
expect(sync.issues[0]).toMatchObject({ sceneKey: other.id, fields: [expect.objectContaining({ field: 'audienceConnection' })] });
});
it('allows one structurally sound outline to replace its older teleplay explicitly', () => {
const storyOutline = {
...sanitizeStoryOutline(validOutline),
validation: {
status: 'invalid',
issues: [{
code: 'TELEPLAY_SCENE_CONTRACT_MISMATCH',
severity: 'error',
message: 'The edited beat differs from the old scene.',
sceneKey: 's1',
}],
},
};
const episode = {
id: 'ep-1',
number: 1,
startNodeId: 's1',
storyOutline,
nodes: storyOutline.scenes.map((scene) => ({
id: scene.key,
title: scene.key === 's1' ? 'Old signal' : scene.title,
playbackMode: scene.playbackMode,
audienceConnection: scene.audienceConnection,
protagonistPresence: scene.protagonistPresence,
isEnding: scene.isEnding,
endingLabel: scene.endingLabel,
transitions: scene.transitions.map((item) => ({
targetNodeId: item.targetKey,
intent: item.intent,
})),
})),
};
const loom = { participationMode: 'protagonist', episodes: [episode], seriesPlan: {} };
expect(analyzeSeriesStoryOutlines(loom).stats.ready).toBe(false);
const replacement = analyzeSeriesStoryOutlines(loom, { replacingEpisodeId: episode.id });
expect(replacement.stats).toMatchObject({ ready: true, readyEpisodeCount: 1, errorCount: 0 });
expect(replacement.issues).toContainEqual(expect.objectContaining({
code: 'TELEPLAY_REPLACEMENT_PENDING',
severity: 'warning',
}));
});
});
it('measures audience introduction in dramatic scenes after a shot split', () => {
const scenes = Array.from({ length: 6 }, (_, index) => ({ key: `shot-${index}`, title: `Shot ${index}`, summary: 'An opening action.', playbackMode: 'cut', audienceConnection: index >= 4 ? 'connected' : 'disconnected', isEnding: index === 5, transitions: index < 5 ? [{ targetKey: `shot-${index + 1}`, intent: 'continue' }] : [] }));
const outline = { startKey: 'shot-0', scenes };
const options = { participationMode: 'helper', requireAudienceIntroduction: true };
expect(analyzeStoryOutline(outline, options).issues.some((issue) => issue.code === 'LATE_AUDIENCE_CONNECTION')).toBe(true);
const nodes = scenes.map((scene, index) => ({ id: scene.key, shot: { dramaticSceneId: index < 4 ? 'opening' : 'invitation' } }));
expect(analyzeStoryOutline(outline, { ...options, nodes }).issues.some((issue) => issue.code === 'LATE_AUDIENCE_CONNECTION')).toBe(false);
});
it('uses a same-scene shortcut discovered after a multi-scene detour for audience introduction', () => {
const edges = {
opening: ['detour-1', 'cut-1'],
'detour-1': ['detour-2'],
'detour-2': ['detour-3'],
'detour-3': ['join'],
'cut-1': ['cut-2'],
'cut-2': ['cut-3'],
'cut-3': ['cut-4'],
'cut-4': ['join', 'cut-1'],
join: ['invitation'],
invitation: [],
};
const scenes = Object.entries(edges).map(([key, targets]) => ({
key,
title: key,
summary: 'The signal travels through the opening sequence.',
playbackMode: 'cut',
audienceConnection: key === 'invitation' ? 'connected' : 'disconnected',
isEnding: key === 'invitation',
transitions: targets.map((targetKey) => ({ targetKey, intent: `Follow ${targetKey}` })),
}));
const outline = { startKey: 'opening', scenes };
const options = { participationMode: 'helper', requireAudienceIntroduction: true };
const ungrouped = analyzeStoryOutline(outline, options);
expect(ungrouped.issues).toContainEqual(expect.objectContaining({ code: 'LATE_AUDIENCE_CONNECTION' }));
const nodes = scenes.map(({ key }) => ({
id: key,
shot: { dramaticSceneId: key.startsWith('detour-') ? key : 'opening' },
}));
const result = analyzeStoryOutline(outline, { ...options, nodes });
expect(result.issues).not.toContainEqual(expect.objectContaining({ code: 'LATE_AUDIENCE_CONNECTION' }));
expect(result.stats.maxDepth).toBe(ungrouped.stats.maxDepth);
expect(result.stats.reachableCount).toBe(ungrouped.stats.reachableCount);
});