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

27.6 KB
Raw Blame
/**
 * FableLoom episode beat outlines — the story-first contract between a
 * series plan and a fully written teleplay.
 *
 * An outline is deliberately smaller than a scene graph: one short log-line
 * per camera-cut beat, the intended audience contract, and the paths between
 * beats. This module stays pure so the same deterministic checks can run
 * before an outline is expanded and whenever an author edits it by hand.
 */

import { asArray } from './arrayUtils.js';
import { LOOM_LIMITS } from './fableLoomLimits.js';
import { FABLELOOM_PROTAGONIST_PRESENCE } from './fableLoomPlayback.js';
import { trimTo, isNonBlankStr } from './textUtils.js';

const isObject = (value) => value && typeof value === 'object';

export const OUTLINE_ISSUE_CODES = Object.freeze({
  NO_SCENES: 'NO_SCENES',
  WRONG_EPISODE_PLOT_POINT: 'WRONG_EPISODE_PLOT_POINT',
  MISSING_START: 'MISSING_START',
  START_NOT_FOUND: 'START_NOT_FOUND',
  NO_ENDINGS: 'NO_ENDINGS',
  UNREACHABLE_SCENE: 'UNREACHABLE_SCENE',
  DEAD_END: 'DEAD_END',
  DANGLING_TRANSITION: 'DANGLING_TRANSITION',
  SELF_LOOP: 'SELF_LOOP',
  ENDING_WITH_TRANSITIONS: 'ENDING_WITH_TRANSITIONS',
  EMPTY_SUMMARY: 'EMPTY_SUMMARY',
  EMPTY_INTENT: 'EMPTY_INTENT',
  DUPLICATE_INTENT: 'DUPLICATE_INTENT',
  CUT_TRANSITION_COUNT: 'CUT_TRANSITION_COUNT',
  DECISION_TRANSITION_COUNT: 'DECISION_TRANSITION_COUNT',
  DISCONNECTED_DECISION: 'DISCONNECTED_DECISION',
  NO_AUDIENCE_CONNECTION: 'NO_AUDIENCE_CONNECTION',
  LATE_AUDIENCE_CONNECTION: 'LATE_AUDIENCE_CONNECTION',
  MISSING_EPISODE_OUTLINE: 'MISSING_EPISODE_OUTLINE',
  EPISODE_OUTLINE_NOT_VALIDATED: 'EPISODE_OUTLINE_NOT_VALIDATED',
  TELEPLAY_SCENE_MEMBERSHIP_MISMATCH: 'TELEPLAY_SCENE_MEMBERSHIP_MISMATCH',
  TELEPLAY_START_MISMATCH: 'TELEPLAY_START_MISMATCH',
  TELEPLAY_SCENE_CONTRACT_MISMATCH: 'TELEPLAY_SCENE_CONTRACT_MISMATCH',
  TELEPLAY_REPLACEMENT_PENDING: 'TELEPLAY_REPLACEMENT_PENDING',
  MISSING_OVERNIGHT_VOICEMAIL: 'MISSING_OVERNIGHT_VOICEMAIL',
  EMPTY_OVERNIGHT_VOICEMAIL: 'EMPTY_OVERNIGHT_VOICEMAIL',
  MISSING_NEXT_SEASON_TEASER: 'MISSING_NEXT_SEASON_TEASER',
  CHALLENGE_PHASE_MISSING: 'CHALLENGE_PHASE_MISSING',
  CHALLENGE_PATH_MISSING: 'CHALLENGE_PATH_MISSING',
  CHALLENGE_DECISION_INVALID: 'CHALLENGE_DECISION_INVALID',
});

export const STORY_OUTLINE_TELEPLAY_SYNC_CODES = Object.freeze([
  OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_MEMBERSHIP_MISMATCH,
  OUTLINE_ISSUE_CODES.TELEPLAY_START_MISMATCH,
  OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_CONTRACT_MISMATCH,
]);

const storyOutlineTeleplaySyncCodeSet = new Set(STORY_OUTLINE_TELEPLAY_SYNC_CODES);

export const isStoryOutlineTeleplaySyncIssue = (issue) => (
  storyOutlineTeleplaySyncCodeSet.has(issue?.code)
);

const OUTLINE_STATUSES = new Set(['draft', 'valid', 'invalid']);

export const FABLELOOM_PLOT_POINT_KINDS = Object.freeze(['beat', 'challenge']);
export const FABLELOOM_CHALLENGE_PHASES = Object.freeze([
  'setup', 'decision', 'success', 'failure', 'recovery',
]);
const challengePhaseSet = new Set(FABLELOOM_CHALLENGE_PHASES);

export const fableLoomPlotPointKind = (item) => (
  item?.kind === 'challenge'
    || (item?.kind == null && /^challenge\s*(?:[-—:]|$)/i.test(item?.title?.trim() || ''))
    ? 'challenge'
    : 'beat'
);

export const fableLoomEpisodeChallenges = (loom, episodeId) => asArray(loom?.seriesPlan?.plotPoints)
  .filter((item) => item?.episodeId === episodeId && fableLoomPlotPointKind(item) === 'challenge');

const uniqueKey = (candidate, index, seen) => {
  const base = isNonBlankStr(candidate)
    ? candidate.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
    : `s${index + 1}`;
  let key = base || `s${index + 1}`;
  let suffix = 2;
  while (seen.has(key)) {
    const stem = base.slice(0, Math.max(1, LOOM_LIMITS.OUTLINE_KEY_MAX - String(suffix).length - 1));
    key = `${stem}-${suffix}`;
    suffix += 1;
  }
  seen.add(key);
  return key;
};

const sanitizeValidation = (raw) => {
  if (!isObject(raw)) return { status: 'draft', issues: [] };
  const status = OUTLINE_STATUSES.has(raw.status) ? raw.status : 'draft';
  const issues = asArray(raw.issues)
    .filter(isObject)
    .slice(0, LOOM_LIMITS.OUTLINE_ISSUES_MAX)
    .map((issue) => ({
      code: trimTo(issue.code, 80),
      severity: issue.severity === 'warning' ? 'warning' : 'error',
      message: trimTo(issue.message, LOOM_LIMITS.OUTLINE_ISSUE_MESSAGE_MAX),
      ...(isNonBlankStr(issue.sceneKey) ? { sceneKey: issue.sceneKey.slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX) } : {}),
      ...(Number.isInteger(issue.transitionIndex) && issue.transitionIndex >= 0
        ? { transitionIndex: issue.transitionIndex }
        : {}),
    }))
    .filter((issue) => issue.message);
  return {
    status,
    issues,
    ...(isNonBlankStr(raw.validatedAt) ? { validatedAt: raw.validatedAt.slice(0, 80) } : {}),
  };
};

/**
 * Normalize an AI- or author-provided outline into the bounded persisted
 * shape. Unknown target keys are intentionally retained so validation can
 * explain the broken edge instead of silently changing the author's arc.
 */
export function sanitizeStoryOutline(raw, { participationMode = 'protagonist' } = {}) {
  if (!isObject(raw)) return null;
  const rawScenes = asArray(raw.scenes).slice(0, LOOM_LIMITS.OUTLINE_SCENES_MAX);
  const seen = new Set();
  const keyByRawKey = new Map();
  const scenes = rawScenes.map((scene, index) => {
    const key = uniqueKey(scene?.key, index, seen);
    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: isNonBlankStr(transition.targetKey)
          ? transition.targetKey.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
          : '',
        intent: trimTo(transition.intent, LOOM_LIMITS.INTENT_MAX),
      }));
    return {
      key,
      title: trimTo(scene?.title, LOOM_LIMITS.NODE_TITLE_MAX),
      summary: trimTo(scene?.summary, LOOM_LIMITS.OUTLINE_SUMMARY_MAX),
      plotPointId: isNonBlankStr(scene?.plotPointId)
        ? scene.plotPointId.trim().slice(0, LOOM_LIMITS.OUTLINE_KEY_MAX)
        : null,
      challengePhase: challengePhaseSet.has(scene?.challengePhase) ? scene.challengePhase : null,
      playbackMode: scene?.playbackMode === 'cut' ? 'cut' : 'decision',
      audienceConnection: scene?.audienceConnection === 'connected' ? 'connected' : 'disconnected',
      protagonistPresence: FABLELOOM_PROTAGONIST_PRESENCE.includes(scene?.protagonistPresence)
        ? scene.protagonistPresence
        : participationMode === 'helper'
          && scene?.audienceConnection === 'connected'
          && scene?.playbackMode !== 'cut'
          ? 'offscreen'
          : 'onscreen',
      isEnding: scene?.isEnding === true,
      endingLabel: trimTo(scene?.endingLabel, LOOM_LIMITS.ENDING_LABEL_MAX),
      transitions,
    };
  });
  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,
    startKey,
    scenes,
    validation: sanitizeValidation(raw.validation),
  };
}

const outlineIssue = (issues, code, severity, message, extra = {}) => {
  issues.push({ code, severity, message, ...extra });
};

/** Deterministic validation for the log-line graph, independent of an LLM. */
export function analyzeStoryOutline(outline, {
  participationMode = 'protagonist', requireAudienceIntroduction = false, challenges = [], plotPoints = [], episodeId = null, nodes = [],
} = {}) {
  const scenes = asArray(outline?.scenes);
  const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
  const issues = [];
  const push = (code, severity, message, extra = {}) => outlineIssue(issues, code, severity, message, extra);

  if (!scenes.length) {
    push(OUTLINE_ISSUE_CODES.NO_SCENES, 'error', 'The story outline has no scene beats yet.');
  }
  const startKey = outline?.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.');
  }

  const reachable = new Set();
  const depthByKey = new Map();
  const dramaticDepthByKey = new Map();
  const groupByKey = new Map(asArray(nodes).map((node) => [node.id, node.shot?.dramaticSceneId || node.id]));
  if (byKey.has(startKey)) {
    const queue = [startKey];
    depthByKey.set(startKey, 0);
    let cursor = 0;
    while (cursor < queue.length) {
      const key = queue[cursor];
      cursor += 1;
      if (reachable.has(key)) continue;
      reachable.add(key);
      for (const transition of asArray(byKey.get(key)?.transitions)) {
        if (byKey.has(transition.targetKey) && !depthByKey.has(transition.targetKey)) {
          depthByKey.set(transition.targetKey, depthByKey.get(key) + 1);
          queue.push(transition.targetKey);
        }
      }
    }
  }

  // 0-1 BFS: extra camera cuts cost nothing; relax previously discovered
  // beats so a later same-scene shortcut can lower their dramatic depth.
  if (byKey.has(startKey)) {
    dramaticDepthByKey.set(startKey, 0);
    const deque = [startKey];
    while (deque.length) {
      const key = deque.shift();
      const base = dramaticDepthByKey.get(key);
      for (const transition of asArray(byKey.get(key)?.transitions)) {
        const target = transition.targetKey;
        if (!byKey.has(target)) continue;
        const sameScene = groupByKey.has(key) && groupByKey.get(key) === groupByKey.get(target);
        const cost = sameScene ? 0 : 1;
        if (!dramaticDepthByKey.has(target) || base + cost < dramaticDepthByKey.get(target)) {
          dramaticDepthByKey.set(target, base + cost);
          if (cost === 0) deque.unshift(target); else deque.push(target);
        }
      }
    }
  }

  const endings = scenes.filter((scene) => scene.isEnding);
  if (scenes.length && !endings.length) {
    push(OUTLINE_ISSUE_CODES.NO_ENDINGS, 'error', 'The story outline has no ending beat.');
  }
  const reachableEndings = endings.filter((scene) => reachable.has(scene.key));
  if (endings.length && !reachableEndings.length) {
    push(OUTLINE_ISSUE_CODES.NO_ENDINGS, 'error', 'No ending beat is reachable from the opening.');
  }

  if (participationMode === 'helper' && requireAudienceIntroduction && scenes.length) {
    const connected = scenes.filter((scene) => scene.audienceConnection === 'connected' && reachable.has(scene.key));
    if (!connected.length) {
      push(
        OUTLINE_ISSUE_CODES.NO_AUDIENCE_CONNECTION,
        'error',
        'The outline never activates the audience communication channel.',
      );
    } else {
      const firstDepth = Math.min(...connected.map((scene) => dramaticDepthByKey.get(scene.key)));
      if (firstDepth > 3) {
        push(
          OUTLINE_ISSUE_CODES.LATE_AUDIENCE_CONNECTION,
          'warning',
          'The audience communication channel is not activated until late in the opening sequence.',
          { sceneKey: connected.find((scene) => dramaticDepthByKey.get(scene.key) === firstDepth)?.key },
        );
      }
    }
  }

  for (const scene of scenes) {
    const transitions = asArray(scene.transitions);
    const label = scene.title || scene.key || 'Untitled beat';
    const assignedPlot = asArray(plotPoints).find((item) => item.id === scene.plotPointId);
    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 (!isNonBlankStr(scene.summary)) {
      push(OUTLINE_ISSUE_CODES.EMPTY_SUMMARY, 'error', `"${label}" has no scene log-line.`, { sceneKey: scene.key });
    }
    if (!reachable.has(scene.key)) {
      push(OUTLINE_ISSUE_CODES.UNREACHABLE_SCENE, 'error', `"${label}" cannot be reached from the opening beat.`, { sceneKey: scene.key });
    }
    if (!scene.isEnding && !transitions.length) {
      push(OUTLINE_ISSUE_CODES.DEAD_END, 'error', `"${label}" has no path to a later beat.`, { sceneKey: scene.key });
    }
    if (scene.isEnding && transitions.length) {
      push(OUTLINE_ISSUE_CODES.ENDING_WITH_TRANSITIONS, 'error', `Ending "${label}" must not have outgoing paths.`, { sceneKey: scene.key });
    }
    if (!scene.isEnding && scene.playbackMode === 'cut' && transitions.length !== 1) {
      push(
        OUTLINE_ISSUE_CODES.CUT_TRANSITION_COUNT,
        'error',
        `Automatic beat "${label}" must have exactly one next beat.`,
        { sceneKey: scene.key },
      );
    }
    if (!scene.isEnding && scene.playbackMode !== 'cut'
      && (transitions.length < 2 || transitions.length > 4)) {
      push(
        OUTLINE_ISSUE_CODES.DECISION_TRANSITION_COUNT,
        'error',
        `Decision beat "${label}" needs 2–4 distinct viewer paths.`,
        { sceneKey: scene.key },
      );
    }
    if (participationMode === 'helper' && !scene.isEnding
      && scene.audienceConnection !== 'connected' && scene.playbackMode !== 'cut') {
      push(
        OUTLINE_ISSUE_CODES.DISCONNECTED_DECISION,
        'error',
        `"${label}" asks for viewer input while the communication channel is disconnected.`,
        { sceneKey: scene.key },
      );
    }

    const seenIntents = new Set();
    transitions.forEach((transition, transitionIndex) => {
      const intent = isNonBlankStr(transition.intent) ? transition.intent.trim().toLowerCase() : '';
      if (!intent) {
        push(
          OUTLINE_ISSUE_CODES.EMPTY_INTENT,
          'error',
          `A path out of "${label}" has no choice label.`,
          { sceneKey: scene.key, transitionIndex },
        );
      } else if (seenIntents.has(intent)) {
        push(
          OUTLINE_ISSUE_CODES.DUPLICATE_INTENT,
          'warning',
          `"${label}" repeats the choice label "${transition.intent}".`,
          { sceneKey: scene.key, transitionIndex },
        );
      } else {
        seenIntents.add(intent);
      }
      if (!byKey.has(transition.targetKey)) {
        push(
          OUTLINE_ISSUE_CODES.DANGLING_TRANSITION,
          'error',
          `A path out of "${label}" points at a missing beat.`,
          { sceneKey: scene.key, transitionIndex },
        );
      } else if (transition.targetKey === scene.key) {
        push(
          OUTLINE_ISSUE_CODES.SELF_LOOP,
          'warning',
          `"${label}" loops straight back to itself.`,
          { sceneKey: scene.key, transitionIndex },
        );
      }
    });
  }

  const pathExists = (fromScenes, toScenes) => {
    const targets = new Set(toScenes.map((scene) => scene.key));
    const queue = fromScenes.map((scene) => scene.key);
    const seen = new Set();
    while (queue.length) {
      const key = queue.shift();
      if (seen.has(key)) continue;
      seen.add(key);
      if (targets.has(key)) return true;
      for (const transition of asArray(byKey.get(key)?.transitions)) {
        if (byKey.has(transition.targetKey) && !seen.has(transition.targetKey)) {
          queue.push(transition.targetKey);
        }
      }
    }
    return false;
  };
  let readyChallengeCount = 0;
  for (const challenge of asArray(challenges)) {
    const label = challenge.title || challenge.id || 'Untitled challenge';
    const mapped = scenes.filter((scene) => scene.plotPointId === challenge.id);
    const byPhase = Object.fromEntries(FABLELOOM_CHALLENGE_PHASES.map((phase) => [
      phase, mapped.filter((scene) => scene.challengePhase === phase),
    ]));
    let challengeReady = true;
    for (const phase of FABLELOOM_CHALLENGE_PHASES) {
      if (byPhase[phase].length) continue;
      challengeReady = false;
      push(
        OUTLINE_ISSUE_CODES.CHALLENGE_PHASE_MISSING,
        'error',
        `Playable challenge "${label}" needs a mapped ${phase} beat.`,
      );
    }
    const invalidDecision = byPhase.decision.find((scene) => scene.playbackMode !== 'decision'
      || asArray(scene.transitions).length < 2);
    if (invalidDecision) {
      challengeReady = false;
      push(
        OUTLINE_ISSUE_CODES.CHALLENGE_DECISION_INVALID,
        'error',
        `Playable challenge "${label}" needs a decision-loop beat with at least two viewer paths.`,
        { sceneKey: invalidDecision.key },
      );
    }
    const requiredPaths = [
      ['setup', 'decision'],
      ['decision', 'success'],
      ['decision', 'failure'],
      ['success', 'recovery'],
      ['failure', 'recovery'],
    ];
    for (const [fromPhase, toPhase] of requiredPaths) {
      if (!byPhase[fromPhase].length || !byPhase[toPhase].length
        || pathExists(byPhase[fromPhase], byPhase[toPhase])) continue;
      challengeReady = false;
      push(
        OUTLINE_ISSUE_CODES.CHALLENGE_PATH_MISSING,
        'error',
        `Playable challenge "${label}" has no path from its ${fromPhase} beat to its ${toPhase} beat.`,
        { sceneKey: byPhase[fromPhase][0]?.key },
      );
    }
    if (challengeReady) readyChallengeCount += 1;
  }

  const stats = {
    sceneCount: scenes.length,
    automaticCutCount: scenes.filter((scene) => !scene.isEnding && scene.playbackMode === 'cut').length,
    decisionCount: scenes.filter((scene) => !scene.isEnding && scene.playbackMode !== 'cut').length,
    endingCount: endings.length,
    reachableCount: reachable.size,
    reachableEndingCount: reachableEndings.length,
    maxDepth: depthByKey.size ? Math.max(...depthByKey.values()) : 0,
    errorCount: issues.filter((issue) => issue.severity === 'error').length,
    warningCount: issues.filter((issue) => issue.severity === 'warning').length,
    challengeCount: asArray(challenges).length,
    readyChallengeCount,
  };
  return { issues, stats };
}

const sortedTransitionContract = (transitions, targetKey) => asArray(transitions)
  .map((transition) => `${transition?.[targetKey] || ''}\u0000${transition?.intent || ''}`)
  .sort();

/** Validate that a persisted beat outline still mirrors an expanded teleplay. */
export function analyzeStoryOutlineTeleplaySync(episode, outline, {
  participationMode = 'protagonist',
} = {}) {
  const nodes = asArray(episode?.nodes);
  if (!nodes.length) return { issues: [], stats: { errorCount: 0, matches: true } };
  const scenes = asArray(outline?.scenes);
  const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
  const nodeIds = new Set(nodes.map((node) => node.id));
  const issues = [];
  const push = (code, message, extra = {}) => outlineIssue(issues, code, 'error', message, extra);

  if (scenes.length !== nodes.length
    || byKey.size !== nodes.length
    || scenes.some((scene) => !nodeIds.has(scene.key))) {
    push(
      OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_MEMBERSHIP_MISMATCH,
      'The beat outline does not cover every expanded teleplay scene exactly once.',
    );
  }
  if (outline?.startKey !== episode?.startNodeId) {
    push(
      OUTLINE_ISSUE_CODES.TELEPLAY_START_MISMATCH,
      'The beat outline opening does not match the expanded teleplay opening scene.',
      { sceneKey: outline?.startKey || undefined },
    );
  }
  for (const node of nodes) {
    const scene = byKey.get(node.id);
    if (!scene) continue;
    const expectedProtagonistPresence = node.protagonistPresence
      || (participationMode === 'helper'
        && node.audienceConnection === 'connected'
        && node.playbackMode !== 'cut'
        ? 'offscreen'
        : 'onscreen');
    // An ending has no outgoing paths, so its playbackMode carries no meaning.
    const comparePlayback = !scene.isEnding || !node.isEnding;
    const fieldChecks = [
      ['title', scene.title, node.title],
      ['plotPointId', scene.plotPointId || null, node.plotPointId || null],
      ['challengePhase', scene.challengePhase || null, node.challengePhase || null],
      ['playbackMode', comparePlayback ? scene.playbackMode : null, comparePlayback ? node.playbackMode : null],
      ['audienceConnection', scene.audienceConnection, node.audienceConnection],
      ['protagonistPresence', scene.protagonistPresence, expectedProtagonistPresence],
      ['isEnding', scene.isEnding, node.isEnding],
      ['endingLabel', scene.endingLabel || '', node.endingLabel || ''],
    ];
    const differingFields = fieldChecks
      .filter(([, expected, actual]) => expected !== actual)
      .map(([field, expected, actual]) => ({ field, outline: expected, teleplay: actual }));
    const outlineTransitions = sortedTransitionContract(scene.transitions, 'targetKey');
    const nodeTransitions = sortedTransitionContract(node.transitions, 'targetNodeId');
    if (JSON.stringify(outlineTransitions) !== JSON.stringify(nodeTransitions)) {
      differingFields.push({
        field: 'transitions',
        outline: outlineTransitions.map((item) => item.replace('\u0000', ' -> ')),
        teleplay: nodeTransitions.map((item) => item.replace('\u0000', ' -> ')),
      });
    }
    if (differingFields.length) {
      const detail = differingFields
        .map(({ field, outline: o, teleplay: t }) => `${field}: outline=${JSON.stringify(o)}, teleplay=${JSON.stringify(t)}`)
        .join('; ');
      push(
        OUTLINE_ISSUE_CODES.TELEPLAY_SCENE_CONTRACT_MISMATCH,
        `Beat "${scene.title || scene.key}" no longer matches its expanded teleplay scene contract (${detail}).`,
        { sceneKey: node.id, fields: differingFields },
      );
    }
  }

  return {
    issues,
    stats: { errorCount: issues.length, matches: issues.length === 0 },
  };
}

/**
 * Validate outline coverage for the complete series. This is the hard gate
 * used by teleplay expansion: authors can draft episodes in order, but no
 * episode is expanded until the whole series has a validated beat arc and its
 * optional delivery handoffs are authored.
 */
export function analyzeSeriesStoryOutlines(loom, { replacingEpisodeId = null } = {}) {
  const episodes = asArray(loom?.episodes);
  const issues = [];
  const readyEpisodeIds = new Set();
  const push = (code, severity, message, extra = {}) => outlineIssue(issues, code, severity, message, extra);
  const validVoicemails = new Map(asArray(loom?.seriesPlan?.interEpisodeVoicemails)
    .filter((item) => item?.fromEpisodeId && item?.toEpisodeId)
    .map((item) => [`${item.fromEpisodeId}::${item.toEpisodeId}`, item]));

  episodes.forEach((episode, index) => {
    if (!episode?.storyOutline) {
      push(
        OUTLINE_ISSUE_CODES.MISSING_EPISODE_OUTLINE,
        'error',
        `Episode ${episode?.number || index + 1} has no beat outline yet.`,
        { episodeId: episode?.id },
      );
      return;
    }
    const validation = analyzeStoryOutline(episode.storyOutline, {
      nodes: episode.nodes,
      participationMode: loom?.participationMode,
      requireAudienceIntroduction: index === 0,
      challenges: fableLoomEpisodeChallenges(loom, episode.id),
      plotPoints: loom?.seriesPlan?.plotPoints,
      episodeId: episode.id,
    });
    validation.issues.forEach((issue) => {
      push(issue.code, issue.severity, `Episode ${episode.number || index + 1}: ${issue.message}`, {
        episodeId: episode.id,
        ...(issue.sceneKey ? { sceneKey: issue.sceneKey } : {}),
        ...(Number.isInteger(issue.transitionIndex) ? { transitionIndex: issue.transitionIndex } : {}),
      });
    });
    const teleplaySync = analyzeStoryOutlineTeleplaySync(episode, episode.storyOutline, {
      participationMode: loom?.participationMode,
    });
    const replacingThisEpisode = episode.id === replacingEpisodeId
      && validation.stats.errorCount === 0
      && !teleplaySync.stats.matches;
    if (replacingThisEpisode) {
      push(
        OUTLINE_ISSUE_CODES.TELEPLAY_REPLACEMENT_PENDING,
        'warning',
        `Episode ${episode.number || index + 1}'s validated beat outline will replace its older teleplay scenes.`,
        { episodeId: episode.id },
      );
    } else {
      teleplaySync.issues.forEach((issue) => {
        push(
          issue.code,
          issue.severity,
          `Episode ${episode.number || index + 1}: ${issue.message}`,
          {
            episodeId: episode.id,
            ...(issue.sceneKey ? { sceneKey: issue.sceneKey } : {}),
          },
        );
      });
    }
    if (episode.storyOutline.validation?.status !== 'valid' && !replacingThisEpisode) {
      push(
        OUTLINE_ISSUE_CODES.EPISODE_OUTLINE_NOT_VALIDATED,
        'error',
        `Episode ${episode.number || index + 1}'s beat outline must be validated before teleplay expansion.`,
        { episodeId: episode.id },
      );
    } else if (validation.stats.errorCount === 0
      && (teleplaySync.stats.matches || replacingThisEpisode)) {
      readyEpisodeIds.add(episode.id);
    }
  });

  const delivery = loom?.seriesPlan?.deliveryOptions || {};
  if (delivery.overnightVoicemails === true) {
    episodes.slice(0, -1).forEach((fromEpisode, index) => {
      const toEpisode = episodes[index + 1];
      const key = `${fromEpisode.id}::${toEpisode.id}`;
      const voicemail = validVoicemails.get(key);
      if (!voicemail) {
        push(
          OUTLINE_ISSUE_CODES.MISSING_OVERNIGHT_VOICEMAIL,
          'error',
          `The handoff from Episode ${fromEpisode.number} to Episode ${toEpisode.number} needs an overnight voicemail.`,
          { episodeId: fromEpisode.id },
        );
      } else if (!isNonBlankStr(voicemail.transcript)) {
        push(
          OUTLINE_ISSUE_CODES.EMPTY_OVERNIGHT_VOICEMAIL,
          'error',
          `The overnight voicemail from Episode ${fromEpisode.number} to Episode ${toEpisode.number} has no transcript.`,
          { episodeId: fromEpisode.id },
        );
      }
    });
  }
  if (delivery.nextSeasonTeaser === true && !isNonBlankStr(loom?.seriesPlan?.nextSeasonTeaser?.transcript)) {
    push(
      OUTLINE_ISSUE_CODES.MISSING_NEXT_SEASON_TEASER,
      'error',
      'The final episode needs a next-season teaser or cliffhanger transcript.',
      { episodeId: episodes.at(-1)?.id },
    );
  }

  const readyEpisodeCount = readyEpisodeIds.size;
  return {
    issues,
    stats: {
      episodeCount: episodes.length,
      readyEpisodeCount,
      errorCount: issues.filter((issue) => issue.severity === 'error').length,
      warningCount: issues.filter((issue) => issue.severity === 'warning').length,
      ready: episodes.length > 0 && issues.every((issue) => issue.severity !== 'error'),
    },
  };
}

export const outlineValidationStatus = (validation) => {
  if (!validation?.stats) return 'draft';
  return validation.stats.errorCount ? 'invalid' : 'valid';
};

/** Compact outline rendering for the outline-review and expansion prompts. */
export function describeStoryOutlineForPrompt(outline) {
  const scenes = asArray(outline?.scenes);
  const byKey = new Map(scenes.map((scene) => [scene.key, scene]));
  return scenes.map((scene, index) => {
    const flags = [
      scene.key === outline?.startKey ? 'START' : null,
      scene.isEnding ? `ENDING${scene.endingLabel ? `: ${scene.endingLabel}` : ''}` : null,
      scene.isEnding ? null : scene.playbackMode === 'cut' ? 'AUTO CUT' : 'DECISION',
      scene.audienceConnection === 'connected' ? 'AUDIENCE CONNECTED' : 'AUDIENCE DISCONNECTED',
      scene.protagonistPresence === 'offscreen' ? 'PROTAGONIST OFF-SCREEN' : 'PROTAGONIST ON-SCREEN',
      scene.plotPointId ? `PLOT POINT: ${scene.plotPointId}` : null,
      scene.challengePhase ? `CHALLENGE ${scene.challengePhase.toUpperCase()}` : null,
    ].filter(Boolean);
    const paths = asArray(scene.transitions).map((transition) => {
      const target = byKey.get(transition.targetKey);
      return `-> [${transition.targetKey || '?'}] ${transition.intent || '(unlabeled)'}${target?.title ? ` (${target.title})` : ''}`;
    });
    return [
      `${index + 1}. [${scene.key}] ${scene.title || 'Untitled beat'}${flags.length ? ` (${flags.join(') (')})` : ''}`,
      scene.summary || '(no log-line)',
      ...paths,
    ].join('\n');
  }).join('\n\n');
}