/** * 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, canonicalReferenceHash, canonicalReferenceSlot, type RunContractReferenceHash, type RunContractScene, type RunContractReferenceSlot, } from '../run-status.js'; import { anchorManifestAssetPath } from '../asset-spec.js'; import { captureFilmReferenceEvidence } from '../film-reference-evidence.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 submitted = runContractByScene.get(sceneIndex); const diff = diffAgainstContract( submitted, sceneByIndex.get(sceneIndex), await currentReferenceHashes(projectDir, submitted), projectDir, ); out.push({ sceneIndex, status, ...(externalJobId ? { externalJobId } : {}), ...(error ? { error } : {}), ...(clipPath ? { clipPath } : {}), ...(submitted?.submittedProviderWire ? { submittedProviderWire: submitted.submittedProviderWire } : {}), ...(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, currentHashes?: RunContractReferenceHash[], projectDir?: string, ): { diverged: boolean; reason?: string; fields?: string[] } { if (!submitted) return { diverged: false }; // The BYTES check stands on its own: it re-measures the very paths that were // submitted, so it needs nothing from the current scene. That matters because // the early return below covers exactly the projects it exists for — a project // with no filmmaking-prompts packet has no renderPrompt to diff, and a swapped // keyframe there used to read "unchanged". const bytesChanged = referenceBytesChanged(submitted, currentHashes); const bytesOnly = bytesChanged ? { diverged: true, reason: REFERENCE_BYTES_REASON, fields: ['referenceBytes'] } : { diverged: false }; if (!current) return bytesOnly; const currentPrompt = current.renderPrompt ?? ''; // The render anchors a packet's relative reference to the project file // (anchorPacketReferences), so that is the form a contract now freezes. A // contract frozen BEFORE it did holds the strings as typed: read that one in // its own terms, or every delivered project with a relative packet path would // read "diverged" for a file that never moved. // Decided per list: a seedance scene's paths are Asset:// URIs (nothing to // anchor) while its slot plan still carries the local sheet paths. const anchor = (path: string) => (projectDir ? anchorManifestAssetPath(projectDir, path) : path); const typedRefs = currentReferencePaths(current); const currentRefs = typedRefs.join('\u0000') === submitted.submittedReferencePaths.join('\u0000') ? typedRefs : typedRefs.map(anchor); // If the current scene carries no resolved contract yet (no renderPrompt and // no reference slots), we cannot meaningfully diff the rest. if (!current.renderPrompt && currentRefs.length === 0) return bytesOnly; // The rule for every re-derivable field: it joins the current hash and the // field diff ONLY when the frozen contract carries it. A legacy contract on // disk has none of the provider-setting fields, so it must stay silent // against a packet that now carries resolution and variant. The current // duration is packet-first, exactly as execution-runtime built the task. const typedSlots = currentReferenceSlots(current); const currentSlots = submitted.submittedReferenceSlots && JSON.stringify(typedSlots) === JSON.stringify(submitted.submittedReferenceSlots.map(canonicalReferenceSlot)) ? typedSlots : typedSlots.map((slot) => (slot.path ? { ...slot, path: anchor(slot.path) } : slot)); const currentDuration = current.packetDurationSeconds ?? current.durationSeconds; const currentHash = hashRunContractScene({ prompt: currentPrompt, referencePaths: currentRefs, ...(submitted.submittedReferenceSlots ? { referenceSlots: currentSlots } : {}), ...(submitted.submittedReferenceRole ? { referenceRole: submitted.submittedReferenceRole } : {}), inputKind: submitted.submittedInputKind, ...(typeof submitted.submittedDurationSeconds === 'number' ? { durationSeconds: currentDuration } : {}), characters: submitted.submittedCharacters, ...(submitted.submittedChainedFromCandidateId ? { chainedFromCandidateId: submitted.submittedChainedFromCandidateId } : {}), ...(submitted.submittedResolution ? { resolution: current.renderResolution } : {}), ...(submitted.submittedPromptPacketVariant ? { promptPacketVariant: current.promptPacketVariant } : {}), // Resolved inside execution-runtime, not re-derivable from the discovered // scene: hashed on the submitted value so they cancel out (provenance only). ...(submitted.submittedEndKeyframePath ? { endKeyframePath: submitted.submittedEndKeyframePath } : {}), ...(submitted.submittedVoicePreset ? { voicePreset: submitted.submittedVoicePreset } : {}), ...(submitted.submittedReferenceVideoMediaId ? { referenceVideoMediaId: submitted.submittedReferenceVideoMediaId } : {}), ...(submitted.submittedFirstFrame !== undefined ? { firstFrame: submitted.submittedFirstFrame } : {}), ...(submitted.submittedCharacterRefs ? { characterRefs: submitted.submittedCharacterRefs } : {}), // Re-measured bytes when we have them; the frozen ones when the files could // not be read (best-effort, like everything here), so they cancel out. ...(submitted.submittedReferenceHashes ? { referenceHashes: bytesChanged ? currentHashes : submitted.submittedReferenceHashes } : {}), }); 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('\u0000') !== submitted.submittedReferencePaths.join('\u0000'); if (added.length || removed.length || reordered) fields.push('referencePaths'); if (submitted.submittedReferenceSlots && JSON.stringify(currentSlots) !== JSON.stringify(submitted.submittedReferenceSlots.map(canonicalReferenceSlot))) { fields.push('referenceSlots'); } if (typeof submitted.submittedDurationSeconds === 'number' && currentDuration !== submitted.submittedDurationSeconds) { fields.push('durationSeconds'); } if (submitted.submittedResolution && current.renderResolution !== submitted.submittedResolution) { fields.push('resolution'); } if (submitted.submittedPromptPacketVariant && current.promptPacketVariant !== submitted.submittedPromptPacketVariant) { fields.push('promptPacketVariant'); } if (bytesChanged) fields.push('referenceBytes'); 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 settingsMoved = fields.some((field) => field !== 'prompt'); const reason = fields.includes('referencePaths') || fields.includes('referenceSlots') ? 'submitted payload diverged from the contract — an @tag may have hijacked the references' : fields.includes('referenceBytes') ? REFERENCE_BYTES_REASON : !settingsMoved ? 'submitted prompt diverged from the contract' : fields.includes('prompt') ? 'submitted prompt and provider settings diverged from the contract' : 'submitted provider settings diverged from the contract'; return { diverged: true, reason, fields }; } // What this can and cannot say: the contract is rewritten by every run, so the // baseline is the LAST SUBMIT (a live run overwrites its own dry run). A file // swapped between a dry-run review and the live submit is therefore frozen with // its new bytes and reads as unchanged; what this catches is a file changed // AFTER the submit the dashboard is showing. const REFERENCE_BYTES_REASON = 'a submitted reference file changed on disk — same path, different bytes, so a re-render would not match what was submitted'; /** * Re-measure the files the frozen contract names. Only when it carries hashes * (a legacy contract has none and stays silent), and never fatally: an * unreadable file is no verdict, not a broken dashboard. */ async function currentReferenceHashes( projectDir: string, submitted: RunContractScene | undefined, ): Promise { const frozen = submitted?.submittedReferenceHashes; if (!submitted || !frozen?.some((entry) => entry.status === 'hashed')) return undefined; try { const evidence = await captureFilmReferenceEvidence(projectDir, [{ sceneIndex: submitted.sceneIndex, references: frozen.map((entry) => ({ path: entry.path })), }]); return evidence.map(({ path, status, sha256 }) => canonicalReferenceHash({ path, status, ...(sha256 ? { sha256 } : {}) })); } catch { return undefined; } } /** * True when a file that WAS hashed at submit hashes differently now. A file that * has gone missing is not reported here (nothing to compare; the path diff owns * absence), and a remote handle never had bytes to measure. */ function referenceBytesChanged(submitted: RunContractScene, current: RunContractReferenceHash[] | undefined): boolean { if (!current || !submitted.submittedReferenceHashes) return false; const now = new Map(current.map((entry) => [entry.path, entry])); return submitted.submittedReferenceHashes.some((was) => { const is = now.get(was.path); return was.status === 'hashed' && is?.status === 'hashed' && is.sha256 !== was.sha256; }); } /** The CURRENT slot plan in contract shape (see `canonicalReferenceSlot`). */ function currentReferenceSlots(scene: PreviewPortalScene): RunContractReferenceSlot[] { return (scene.referenceSlots ?? []).map(canonicalReferenceSlot); } /** 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; }