/** * Run-surface discovery: gather the live-run state that backs the `run` * dashboard. PURE except for filesystem reads (no provider calls). Every reader * degrades gracefully on absence — an absent show-bible / run-contract / * events.jsonl just narrows the dashboard, never crashes it. * * Pieces: * - per-generation STATUS (done/rendering/failed/pending) from * scene-candidates.json + execution-report.json + outputs/scene-N.mp4 * - the DIFF-VS-CONTRACT alarm: the persisted submitted contract * (run-contract.json) vs the CURRENT contract derived from the discovered * storyboard scene (renderPrompt + referenceSlots) — flags @tag-hijack drift * - the playable in-progress CLIP per generation (outputs/scene-N.mp4) * - the EVENT LOG (events/events.jsonl, last N) * - the SHOW header/nav (show-bible.json) * - the SPEND estimate (cost-estimate + generation telemetry) */ import { existsSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { join, relative } from 'node:path'; import { buildProjectCostEstimate } from '../cost-estimate.js'; import { readProjectGenerationTelemetry } from '../generation-telemetry.js'; import { readRunContract, hashRunContractScene, type RunContractScene } from '../run-status.js'; import { readShowBible } from '../show-bible.js'; import { ensureProjectWorkspace } from '../workspace.js'; import type { SceneCandidate, SceneCandidatesArtifact, VideoExecutionReport, } from '../types.js'; import type { PreviewPortalGeneration, PreviewPortalProject, PreviewPortalRunEvent, PreviewPortalRunState, PreviewPortalScene, PreviewPortalShow, PreviewPortalSpend, } from './types.js'; const DEFAULT_REFRESH_SECONDS = 15; const EVENT_LOG_LIMIT = 22; export async function discoverRunState( root: string, projectSlug: string, projectDir: string, project: PreviewPortalProject, ): Promise { const candidates = await readSceneCandidatesArtifactSafe(projectDir); const report = await readExecutionReportSafe(projectDir); const runContract = await readRunContractSafe(root, projectSlug); const scenes = project.storyboard?.scenes ?? []; const generations = await buildGenerations({ projectDir, scenes, candidates, report, runContractByScene: runContract, }); const events = await discoverRunEvents(root, projectSlug); const show = await discoverShow(root, projectSlug); const spend = await discoverSpend(root, projectSlug); return { generations, events, ...(show ? { show } : {}), ...(spend ? { spend } : {}), refreshSeconds: DEFAULT_REFRESH_SECONDS, }; } /* ── Per-generation status + diff-vs-contract ──────────────────────────────── */ async function buildGenerations(args: { projectDir: string; scenes: PreviewPortalScene[]; candidates: SceneCandidatesArtifact | null; report: VideoExecutionReport | null; runContractByScene: Map; }): Promise { const { projectDir, scenes, candidates, report, runContractByScene } = args; const candidateByScene = new Map(); for (const entry of candidates?.scenes ?? []) { const latest = entry.candidates[entry.candidates.length - 1]; if (latest) candidateByScene.set(entry.sceneIndex, latest); } // The set of scene indices to render generation cards for: every storyboard // scene, union every scene that has a candidate (covers projects with no // storyboard artifact but live candidates). const sceneIndices = new Set(); for (const scene of scenes) sceneIndices.add(scene.sceneIndex); for (const index of candidateByScene.keys()) sceneIndices.add(index); const sceneByIndex = new Map(scenes.map((scene) => [scene.sceneIndex, scene])); const out: PreviewPortalGeneration[] = []; for (const sceneIndex of [...sceneIndices].sort((a, b) => a - b)) { const candidate = candidateByScene.get(sceneIndex); const clipPath = await findSceneClip(projectDir, sceneIndex, candidate); const { status, externalJobId, error } = deriveGenerationStatus({ sceneIndex, candidate, report, hasClip: Boolean(clipPath), }); const diff = diffAgainstContract( runContractByScene.get(sceneIndex), sceneByIndex.get(sceneIndex), ); out.push({ sceneIndex, status, ...(externalJobId ? { externalJobId } : {}), ...(error ? { error } : {}), ...(clipPath ? { clipPath } : {}), ...(diff.diverged ? { contractDiverged: true, divergenceReason: diff.reason, divergedFields: diff.fields, } : {}), }); } return out; } /** * Status precedence ladder (highest wins): done → failed → rendering → pending. * Candidate-truth is preferred over file existence; we fall back to the * on-disk clip when there is no candidate artifact at all. */ function deriveGenerationStatus(args: { sceneIndex: number; candidate?: SceneCandidate; report: VideoExecutionReport | null; hasClip: boolean; }): { status: PreviewPortalGeneration['status']; externalJobId?: string; error?: string } { const { sceneIndex, candidate, report, hasClip } = args; const externalJobId = candidate?.source.externalJobId ?? report?.submission?.externalJobId ?? undefined; // 1. done if (candidate?.status === 'completed' && candidate.outputs.some((o) => o.kind === 'video')) { return { status: 'done', ...(externalJobId ? { externalJobId } : {}) }; } if (!candidate && hasClip) { return { status: 'done' }; } // 2. failed if (candidate?.status === 'failed' || candidate?.status === 'cancelled') { return { status: 'failed', ...(externalJobId ? { externalJobId } : {}), ...(sceneError(report, sceneIndex) ? { error: sceneError(report, sceneIndex) as string } : {}), }; } if (report?.status === 'blocked' && report.blockers.length > 0) { return { status: 'failed', ...(externalJobId ? { externalJobId } : {}), error: report.blockers.join('; '), }; } // 3. rendering — an in-flight job to poll if (candidate && candidate.status === 'pending' && candidate.source.externalJobId) { return { status: 'rendering', externalJobId: candidate.source.externalJobId }; } // 4. pending — a contract task with no candidate yet (or a still-rendering // candidate without a job id to poll) if (candidate || hasClip) { return { status: 'pending', ...(externalJobId ? { externalJobId } : {}) }; } return { status: 'pending' }; } /** Provider error for this scene: poll issues are prefixed `scene :` by * pollPendingSceneCandidates; fall back to report blockers. */ function sceneError(report: VideoExecutionReport | null, sceneIndex: number): string | undefined { if (!report) return undefined; const prefix = `scene ${sceneIndex}`; const fromPoll = (report.poll?.issues ?? []).filter((issue) => issue.startsWith(prefix)); if (fromPoll.length) return fromPoll.join('; '); if (report.blockers.length) return report.blockers.join('; '); return undefined; } /** * Compare the FROZEN submitted contract for a scene vs the CURRENT contract * derived from the discovered storyboard scene (renderPrompt + referenceSlots). * Returns the diverged-field list when the hash differs. The reference-path set * diff is the loud signal (an @tag silently resolving to a different/extra * Asset:// URI, a dropped chain seed). Pure string/set comparison — no provider * calls. Absent contract OR absent current scene → no divergence (graceful). */ function diffAgainstContract( submitted: RunContractScene | undefined, current: PreviewPortalScene | undefined, ): { diverged: boolean; reason?: string; fields?: string[] } { if (!submitted || !current) return { diverged: false }; const currentPrompt = current.renderPrompt ?? ''; const currentRefs = currentReferencePaths(current); // If the current scene carries no resolved contract yet (no renderPrompt and // no reference slots), we cannot meaningfully diff — treat as no divergence. if (!current.renderPrompt && currentRefs.length === 0) return { diverged: false }; const currentHash = hashRunContractScene({ prompt: currentPrompt, referencePaths: currentRefs, ...(submitted.submittedReferenceRole ? { referenceRole: submitted.submittedReferenceRole } : {}), inputKind: submitted.submittedInputKind, ...(typeof submitted.submittedDurationSeconds === 'number' ? { durationSeconds: submitted.submittedDurationSeconds } : {}), characters: submitted.submittedCharacters, ...(submitted.submittedChainedFromCandidateId ? { chainedFromCandidateId: submitted.submittedChainedFromCandidateId } : {}), }); if (currentHash === submitted.contractHash) return { diverged: false }; const fields: string[] = []; if (currentPrompt !== submitted.submittedPrompt) fields.push('prompt'); const submittedSet = new Set(submitted.submittedReferencePaths); const currentSet = new Set(currentRefs); const added = currentRefs.filter((p) => !submittedSet.has(p)); const removed = submitted.submittedReferencePaths.filter((p) => !currentSet.has(p)); const reordered = added.length === 0 && removed.length === 0 && currentRefs.join('') !== submitted.submittedReferencePaths.join(''); if (added.length || removed.length || reordered) fields.push('referencePaths'); if (fields.length === 0) { // Hash differed but no observable field diff (e.g. a scalar like // referenceRole/inputKind we cannot re-derive from the discovered scene). // Stay quiet rather than fire a false alarm. return { diverged: false }; } const reason = fields.includes('referencePaths') ? 'submitted payload diverged from the contract — an @tag may have hijacked the references' : 'submitted prompt diverged from the contract'; return { diverged: true, reason, fields }; } /** The CURRENT resolved reference set for a discovered scene: the slot bindings * (Asset:// URI preferred, else local path) in slot order. Mirrors what the * contract panel renders, so the diff compares apples to apples. */ function currentReferencePaths(scene: PreviewPortalScene): string[] { return (scene.referenceSlots ?? []) .map((slot) => slot.assetUri ?? slot.path) .filter((value): value is string => Boolean(value)); } /* ── Clips ─────────────────────────────────────────────────────────────────── */ /** Find the in-progress rendered clip for a scene: a completed candidate's * video output, else outputs/scene-.mp4 on disk. Project-relative path. */ async function findSceneClip( projectDir: string, sceneIndex: number, candidate?: SceneCandidate, ): Promise { const videoOutput = candidate?.outputs.find((o) => o.kind === 'video'); if (videoOutput?.path) { const rel = toProjectRelative(projectDir, videoOutput.path); if (rel && existsSync(join(projectDir, rel))) return rel; } const onDisk = join(projectDir, 'outputs', `scene-${sceneIndex}.mp4`); if (existsSync(onDisk)) return `outputs/scene-${sceneIndex}.mp4`; return undefined; } function toProjectRelative(projectDir: string, value: string): string | undefined { const normalized = value.replaceAll('\\', '/'); if (!normalized.startsWith('/')) { // Already relative — but strip a leading `projects//` if present. const slug = projectDir.split('/').pop() ?? ''; const prefix = `projects/${slug}/`; return normalized.startsWith(prefix) ? normalized.slice(prefix.length) : normalized; } const rel = relative(projectDir, normalized).replaceAll('\\', '/'); return rel.startsWith('..') ? undefined : rel; } /* ── Event log ─────────────────────────────────────────────────────────────── */ async function discoverRunEvents(root: string, projectSlug: string): Promise { let events; try { const workspace = await ensureProjectWorkspace(projectSlug, root); const { readProjectEvents } = await import('../events.js'); events = await readProjectEvents(workspace); } catch { return []; } return events.slice(-EVENT_LOG_LIMIT).reverse().map((event) => ({ recordedAt: event.recordedAt, type: event.type, ...(summarizeEventPayload(event.payload) ? { summary: summarizeEventPayload(event.payload) as string } : {}), })); } function summarizeEventPayload(payload?: Record): string | undefined { if (!payload) return undefined; const parts: string[] = []; if (typeof payload.sceneIndex === 'number') parts.push(`scene ${payload.sceneIndex}`); if (typeof payload.status === 'string') parts.push(payload.status); if (typeof payload.externalJobId === 'string') parts.push(`job ${payload.externalJobId.slice(-12)}`); if (typeof payload.outputsIngested === 'number' && payload.outputsIngested > 0) { parts.push(`${payload.outputsIngested} output${payload.outputsIngested === 1 ? '' : 's'}`); } return parts.length ? parts.join(' · ') : undefined; } /* ── Show header / nav ─────────────────────────────────────────────────────── */ async function discoverShow(root: string, projectSlug: string): Promise { let bible; try { bible = await readShowBible(root, projectSlug); } catch { return undefined; } if (!bible || !bible.showTitle) return undefined; return { showTitle: bible.showTitle, ...(bible.premise ? { premise: bible.premise } : {}), ...(bible.style ? { style: bible.style } : {}), episodes: (bible.episodes ?? []).map((ep) => ({ id: ep.id, title: ep.title, ...(ep.logline ? { logline: ep.logline } : {}), })), }; } /* ── Spend ─────────────────────────────────────────────────────────────────── */ async function discoverSpend(root: string, projectSlug: string): Promise { let estimate; try { estimate = await buildProjectCostEstimate({ projectSlug, root }); } catch { return undefined; } let actualUsd: number | undefined; try { const workspace = await ensureProjectWorkspace(projectSlug, root); const telemetry = await readProjectGenerationTelemetry(workspace); const sum = telemetry .filter((entry) => entry.status === 'completed' && typeof entry.cost?.usd === 'number') .reduce((acc, entry) => acc + (entry.cost?.usd ?? 0), 0); if (sum > 0) actualUsd = Math.round(sum * 100) / 100; } catch { // telemetry is best-effort; the estimate chip still renders } return { estimateUsd: estimate.totalUsd, estimateSource: estimate.estimateSource, wallTimeMinutes: estimate.wallTimeMinutes, ...(actualUsd !== undefined ? { actualUsd } : {}), }; } /* ── Safe artifact readers ─────────────────────────────────────────────────── */ async function readSceneCandidatesArtifactSafe( projectDir: string, ): Promise { const path = join(projectDir, 'artifacts', 'scene-candidates.json'); if (!existsSync(path)) return null; try { return JSON.parse(await readFile(path, 'utf-8')) as SceneCandidatesArtifact; } catch { return null; } } async function readExecutionReportSafe(projectDir: string): Promise { const path = join(projectDir, 'artifacts', 'execution-report.json'); if (!existsSync(path)) return null; try { return JSON.parse(await readFile(path, 'utf-8')) as VideoExecutionReport; } catch { return null; } } async function readRunContractSafe(root: string, projectSlug: string): Promise> { const out = new Map(); let artifact; try { artifact = await readRunContract(root, projectSlug); } catch { return out; } for (const scene of artifact?.scenes ?? []) out.set(scene.sceneIndex, scene); return out; }