Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
refactor: make Studio edits follow author provenance
kashorine4683bae3a39
diff --git a/package.json b/package.jsonindex 53ed5f85..7b1f62e5 100644--- a/package.json+++ b/package.json@@ -75,6 +75,7 @@"@hypit/deck-track-studio": "workspace:*","@hypit/estimate": "workspace:*","@hypit/film": "workspace:*",+ "@hypit/film-studio": "workspace:*","@hypit/fonts-open": "workspace:*","@hypit/generation": "workspace:*","@hypit/gpt-image": "workspace:*",@@ -111,10 +112,12 @@"@hypit/screen-overlay": "workspace:*","@hypit/screen-overlay-studio": "workspace:*","@hypit/script": "workspace:*",+ "@hypit/script-studio": "workspace:*","@hypit/seedance": "workspace:*","@hypit/seedance-kits": "workspace:*","@hypit/seedream": "workspace:*","@hypit/semantic-track": "workspace:*",+ "@hypit/semantic-take-estimate": "workspace:*","@hypit/spatial": "workspace:*","@hypit/speech": "workspace:*","@hypit/speech-alignment": "workspace:*",@@ -125,6 +128,7 @@"@hypit/studio-adapter": "workspace:*","@hypit/svs": "workspace:*","@hypit/temporal": "workspace:*",+ "@hypit/temporal-markup": "workspace:*","@hypit/text": "workspace:*","@hypit/typography-track": "workspace:*","@hypit/typography-track-studio": "workspace:*",diff --git a/packages/audio-track-studio/package.json b/packages/audio-track-studio/package.jsonindex 3842cde6..e1a8190a 100644--- a/packages/audio-track-studio/package.json+++ b/packages/audio-track-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/audio-track": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/audio-track-studio/src/activation.ts b/packages/audio-track-studio/src/activation.tsindex 6e8d10a7..62605d0c 100644--- a/packages/audio-track-studio/src/activation.ts+++ b/packages/audio-track-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { audioTrackStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { audioTrackStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(audioTrackStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(audioTrackStudioTrackCompanions)],};diff --git a/packages/audio-track-studio/src/index.ts b/packages/audio-track-studio/src/index.tsindex 32e5e281..7504f4d5 100644--- a/packages/audio-track-studio/src/index.ts+++ b/packages/audio-track-studio/src/index.ts@@ -1,8 +1,10 @@+import { audioTrackModuleRef, audioTrackTypes } from "@hypit/audio-track";import type { AudioTrackProgram } from "@hypit/audio-track";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft } from "@hypit/studio-adapter";-import { artifactPreview, childEntities, previewLayer, projectedWindowTimelineEdits, requiredSurfaceValue, temporalLineageFor } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft } from "@hypit/studio-adapter";+import { artifactPreview, childEntities, previewLayer, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";-function projectAudio(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectAudio(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as AudioTrackProgram;const items = program.items.map((item) => ({id: item.id,@@ -10,33 +12,31 @@ function projectAudio(context: StudioAdapterContext): readonly StudioEntityDraftstartFrame: item.window.startFrame,endFrameExclusive: item.window.endFrameExclusive,stackOrder: Number.MIN_SAFE_INTEGER,+ sourceTypes: [audioTrackTypes.clipSpec],preview: artifactPreview("audio", item.source.artifact.digest),}));return childEntities(context, items, "audio-clip", "standard").map((entity, index) => {const item = items[index]!;const temporal = temporalLineageFor(context, item.id, "window");+ const semanticSource = temporalSemanticSource(temporal);return {...entity,display: { ...entity.display, layers: [previewLayer(item.preview, "waveform")] },- ...(temporal?.source.kind === "program" || temporal?.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),...(temporal === undefined ? {} : { temporal }),};});}-export const audioTrackStudioAdapters: readonly StudioAdapter[] = [+export const audioTrackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "AudioTrack", surface: "track", modules: ["@hypit/audio-track"] },+ output: { type: compositionTypes.audioTrack, surface: "track", modules: [audioTrackModuleRef] },family: "audio", tone: "green", icon: "waveform",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: [{ name: "source" },- { name: "start", writable: true },- { name: "end", writable: true },- { name: "for", writable: true },{ name: "trim-start", writable: true },{ name: "trim-end", writable: true },{ name: "playback", writable: true },diff --git a/packages/caption-fine-studio/package.json b/packages/caption-fine-studio/package.jsonindex 067cccb8..96a7fd5c 100644--- a/packages/caption-fine-studio/package.json+++ b/packages/caption-fine-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/caption-fine": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/narrative": "workspace:*","@hypit/studio-adapter": "workspace:*"}diff --git a/packages/caption-fine-studio/src/activation.ts b/packages/caption-fine-studio/src/activation.tsindex a69980f4..b78ec14f 100644--- a/packages/caption-fine-studio/src/activation.ts+++ b/packages/caption-fine-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { captionFineStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { captionFineStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(captionFineStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(captionFineStudioTrackCompanions)],};diff --git a/packages/caption-fine-studio/src/index.ts b/packages/caption-fine-studio/src/index.tsindex 41b60212..6c996adb 100644--- a/packages/caption-fine-studio/src/index.ts+++ b/packages/caption-fine-studio/src/index.ts@@ -1,13 +1,15 @@-import { captionFineMarkupSurfaces } from "@hypit/caption-fine";+import { captionFineMarkupSurfaces, captionFineModuleRef } from "@hypit/caption-fine";import type { FineCaptionSchedule } from "@hypit/caption-fine";+import { compositionTypes } from "@hypit/composition";+import { narrativeTypes } from "@hypit/narrative";import type { CaptionDocument } from "@hypit/narrative";import type {- StudioAdapter,- StudioAdapterContext,+ StudioTrackCompanion,+ StudioTrackCompanionContext,StudioEntityDraft,StudioInspectorFieldDeclaration,} from "@hypit/studio-adapter";-import { requiredSurfaceValue, temporalLineageFor, textLayer } from "@hypit/studio-adapter";+import { requiredReferencedValue, requiredSurfaceValue, textLayer } from "@hypit/studio-adapter";const styleSurface = captionFineMarkupSurfaces.find((surface) => surface.name === "style");const recipeVocabulary = styleSurface?.vocabulary.attributes@@ -95,17 +97,6 @@ export const captionFineInspectorFields: readonly StudioInspectorFieldDeclaratio};});-function captionDocument(context: StudioAdapterContext, id: string): CaptionDocument | undefined {- for (const value of context.values.values()) {- if (value === null || typeof value !== "object" || Array.isArray(value)) continue;- const candidate = value as Partial<CaptionDocument>;- if (candidate.id === id && Array.isArray(candidate.units) && Array.isArray(candidate.words)) {- return candidate as CaptionDocument;- }- }- return undefined;-}-function cueText(document: CaptionDocument | undefined, unitIds: readonly string[]): string {if (document === undefined) return "";const selected = new Set(unitIds);@@ -117,15 +108,15 @@ function cueText(document: CaptionDocument | undefined, unitIds: readonly string.trim();}-function projectCaption(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectCaption(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const schedule = requiredSurfaceValue(context, "schedule") as FineCaptionSchedule;- const document = captionDocument(context, schedule.documentId);+ const document = requiredReferencedValue(context, "document", narrativeTypes.captionDocument) as CaptionDocument;+ if (document.id !== schedule.documentId) throw new Error("Caption Studio Schedule belongs to another CaptionDocument.");const rendered = new Map(context.generic().flatMap((entity) =>entity.presentId === undefined ? [] : [[entity.presentId, entity] as const]));return schedule.cues.map((cue): StudioEntityDraft => {const base = rendered.get(cue.id);const label = cueText(document, cue.units.map((unit) => unit.unitId));- const temporal = temporalLineageFor(context, cue.id);const authoredId = context.placement?.id ?? cue.id;return {...(base ?? {@@ -148,15 +139,14 @@ function projectCaption(context: StudioAdapterContext): readonly StudioEntityDraendFrameExclusive: cue.visibleEndFrameExclusive,presentation: { entity: "caption-cue", chrome: "standard" },parameterReferences: { program: cue.styleId },- ...(temporal === undefined ? {} : { temporal }),};});}-export const captionFineStudioAdapters: readonly StudioAdapter[] = [+export const captionFineStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/caption-fine"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [captionFineModuleRef] },family: "caption", tone: "magenta", icon: "captions",bindings: [{diff --git a/packages/caption-fine-studio/test/adapter.test.ts b/packages/caption-fine-studio/test/adapter.test.tsindex 3bab822e..01b5b1cf 100644--- a/packages/caption-fine-studio/test/adapter.test.ts+++ b/packages/caption-fine-studio/test/adapter.test.ts@@ -2,10 +2,12 @@ import assert from "node:assert/strict";import test from "node:test";import type { FineCaptionSchedule } from "@hypit/caption-fine";+import { compositionTypes } from "@hypit/composition";+import { narrativeTypes } from "@hypit/narrative";import type { CaptionDocument } from "@hypit/narrative";-import type { StudioAdapterContext, StudioEntityDraft } from "@hypit/studio-adapter";+import type { StudioTrackCompanionContext, StudioEntityDraft } from "@hypit/studio-adapter";-import { captionFineInspectorFields, captionFineStudioAdapters } from "../src/index.js";+import { captionFineInspectorFields, captionFineStudioTrackCompanions } from "../src/index.js";test("Caption Companion owns Inspector grouping", () => {const declared = (name: string) => captionFineInspectorFields.find((field) => field.binding === `program.${name}`);@@ -18,6 +20,8 @@ test("Caption Companion owns Inspector grouping", () => {test("Caption Companion projects Cue text and Style from public domain values", () => {const schedule: FineCaptionSchedule = {+ spaceId: "speech",+ narrativeId: "story",documentId: "story.caption",cues: [{id: "cue-1",@@ -31,6 +35,7 @@ test("Caption Companion projects Cue text and Style from public domain values",};const document: CaptionDocument = {id: "story.caption",+ narrativeId: "story",units: [{ id: "unit-1", segmentId: "segment-1", turnId: "turn-1", wordIds: ["word-1", "word-2"], sourceTokenIds: ["token-1"] }],words: [{ id: "word-1", unitId: "unit-1", segmentId: "segment-1", turnId: "turn-1", text: "真实", attributes: [] },@@ -45,22 +50,25 @@ test("Caption Companion projects Cue text and Style from public domain values",};const context = {track: {- name: "captions.track", type: "VisualTrack", outputRef: "captions.track",+ name: "captions.track", type: "VisualTrack", typeRef: compositionTypes.visualTrack, outputRef: "captions.track",candidateOrigin: "source", role: "track",trace: {- surface: "track", module: "@hypit/caption-fine", authoredId: "captions",+ surface: "track", module: { name: "@hypit/caption-fine", version: "1" }, authoredId: "captions",outputPorts: [{ name: "schedule", ref: "captions.schedule", type: "FineCaptionSchedule" }],- references: [],+ references: [{+ input: "document", name: "story.caption", ref: "story.caption", type: "CaptionDocument",+ typeRef: narrativeTypes.captionDocument,+ }],},value: { visualIr: "hypit.visual-ir@1", id: "captions", presents: [] },},spans: [{ id: "cue-1", startFrame: 8, endFrameExclusive: 24, stackOrder: 70 }],values: new Map<string, unknown>([["captions.schedule", schedule], ["story.caption", document]]),temporalBindings: [],- semantic: { presentation: { family: "speech", tone: "teal", icon: "timeline", lane: { heightPx: 45 } }, anchors: [], segments: [], tokens: [], selections: [], moments: [], provenance: { output: "speech", outputRef: "speech", origin: "source", status: "resolved", errors: [] } },+ semantic: { spaceId: "speech", narrativeId: "story", presentation: { family: "speech", tone: "teal", icon: "timeline", lane: { heightPx: 45 } }, anchors: [], segments: [], tokens: [], selections: [], moments: [], provenance: { output: "speech", outputRef: "speech", origin: "source", status: "resolved", errors: [] } },generic: () => [base],- } satisfies StudioAdapterContext;- const adapter = captionFineStudioAdapters.find((candidate) => candidate.id === "track")!;+ } satisfies StudioTrackCompanionContext;+ const adapter = captionFineStudioTrackCompanions.find((candidate) => candidate.id === "track")!;const [cue] = adapter.project!(context);assert.deepEqual(cue?.display, {title: "Caption",diff --git a/packages/comment-sticker-studio/package.json b/packages/comment-sticker-studio/package.jsonindex d6963fbf..598cd2ff 100644--- a/packages/comment-sticker-studio/package.json+++ b/packages/comment-sticker-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/comment-sticker": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/comment-sticker-studio/src/activation.ts b/packages/comment-sticker-studio/src/activation.tsindex b5cf0887..018fdf64 100644--- a/packages/comment-sticker-studio/src/activation.ts+++ b/packages/comment-sticker-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { commentStickerStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { commentStickerStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(commentStickerStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(commentStickerStudioTrackCompanions)],};diff --git a/packages/comment-sticker-studio/src/index.ts b/packages/comment-sticker-studio/src/index.tsindex d6a6ad1c..7f6e9792 100644--- a/packages/comment-sticker-studio/src/index.ts+++ b/packages/comment-sticker-studio/src/index.ts@@ -1,7 +1,8 @@-import { commentStickerMarkupSurfaces } from "@hypit/comment-sticker";+import { commentStickerMarkupSurfaces, commentStickerModuleRef, commentStickerTypes } from "@hypit/comment-sticker";import type { CommentStickerProgram } from "@hypit/comment-sticker";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";-import { artifactPreview, childEntities, previewLayer, projectedWindowTimelineEdits, requiredSurfaceValue, temporalLineageFor, textLayer } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";+import { artifactPreview, childEntities, previewLayer, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource, textLayer } from "@hypit/studio-adapter";const frameParameters: readonly StudioSourceBindingDeclaration[] = [{ name: "within" },@@ -67,7 +68,7 @@ const commentInspector: readonly StudioInspectorFieldDeclaration[] = commentProp};});-function projectComments(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectComments(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as CommentStickerProgram;const items = program.items.map((item) => ({id: item.id,@@ -75,11 +76,13 @@ function projectComments(context: StudioAdapterContext): readonly StudioEntityDrstartFrame: item.span.startFrame,endFrameExclusive: item.span.endFrameExclusive,stackOrder: item.style.stackingOrder,+ sourceTypes: [commentStickerTypes.itemSpec],}));return childEntities(context, items, "comment-sticker", "standard").map((entity, index) => {const item = program.items[index];if (item === undefined) return entity;const temporal = temporalLineageFor(context, item.id, "window");+ const semanticSource = temporalSemanticSource(temporal);return {...entity,display: {@@ -89,20 +92,19 @@ function projectComments(context: StudioAdapterContext): readonly StudioEntityDrtextLayer(item.content.comment),],},- ...(temporal?.source.kind === "program" || temporal?.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),...(temporal === undefined ? {} : { temporal }),};});}-export const commentStickerStudioAdapters: readonly StudioAdapter[] = [+export const commentStickerStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/comment-sticker"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [commentStickerModuleRef] },family: "comment-sticker", tone: "orange", icon: "component",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: [{ name: "frame", referenced: frameParameters },{@@ -111,7 +113,6 @@ export const commentStickerStudioAdapters: readonly StudioAdapter[] = [},...["comment", "author", "header", "meta"].map((name) => ({ name, writable: true })),{ name: "avatar" },- ...["start", "end", "for"].map((name) => ({ name, writable: true })),],inspector: [...frameParameters.filter(({ writable }) => writable === true).map(({ name }) => ({diff --git a/packages/deck-track-studio/package.json b/packages/deck-track-studio/package.jsonindex bcb9cbde..b586c88d 100644--- a/packages/deck-track-studio/package.json+++ b/packages/deck-track-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/deck-track": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/deck-track-studio/src/activation.ts b/packages/deck-track-studio/src/activation.tsindex e544c187..7d4b4d93 100644--- a/packages/deck-track-studio/src/activation.ts+++ b/packages/deck-track-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { deckTrackStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { deckTrackStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(deckTrackStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(deckTrackStudioTrackCompanions)],};diff --git a/packages/deck-track-studio/src/index.ts b/packages/deck-track-studio/src/index.tsindex 4f5d7bdd..26a54bb7 100644--- a/packages/deck-track-studio/src/index.ts+++ b/packages/deck-track-studio/src/index.ts@@ -1,7 +1,8 @@-import { depthStackMarkupSurfaces } from "@hypit/deck-track";+import { depthStackMarkupSurfaces, depthStackModuleRef } from "@hypit/deck-track";import type { DepthStackProgram } from "@hypit/deck-track";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";-import { projectedPointTimelineEdits, requiredSurfaceValue, temporalLineageFor } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";+import { requiredSurfaceValue, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";const deckProperties = (depthStackMarkupSurfaces.find((surface) => surface.name === "track")?.vocabulary.attributes@@ -75,7 +76,7 @@ function cardTitle(card: DepthStackProgram["cards"][number]): string {return text || card.id;}-function projectDeck(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectDeck(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as DepthStackProgram;if (context.placement === undefined) return context.generic();const children = new Map(context.placement.children.flatMap((child) =>@@ -83,7 +84,7 @@ function projectDeck(context: StudioAdapterContext): readonly StudioEntityDraft[return program.cards.map((card, index): StudioEntityDraft => {const child = children.get(card.id);const temporal = temporalLineageFor(context, card.id, "activation");- const markerId = temporal?.source.id;+ const markerId = temporalSemanticSource(temporal)?.id;const endFrameExclusive = program.cards[index + 1]?.activationFrame ?? program.terminalFrame;const renders = context.spans.filter((span) => span.id === card.id || span.subjectId === card.id);const render = renders[0];@@ -106,12 +107,11 @@ function projectDeck(context: StudioAdapterContext): readonly StudioEntityDraft[});}-export const deckTrackStudioAdapters: readonly StudioAdapter[] = [+export const deckTrackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/deck-track"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [depthStackModuleRef] },family: "deck", tone: "orange", icon: "layers", requiredValues: ["program"],- timelineEdits: projectedPointTimelineEdits(),bindings: [{ name: "source" },{ name: "extent" },diff --git a/packages/elaborator/README.md b/packages/elaborator/README.mdindex bb570117..f5b7b765 100644--- a/packages/elaborator/README.md+++ b/packages/elaborator/README.md@@ -30,6 +30,13 @@ edges remain covered. Every source asset actually requested during decode is alsauthor-written locator and exact content-addressed `BlobRef`; raw bytes remain a Host transferconcern and never enter the parser-independent AuthorModule or Core BuildState.+The same hygienic pass emits an ephemeral `hypit.author-provenance@1` sidecar. A Frontend may retain+the structural ranges of author elements and inputs; Elaborator qualifies their Record, component,+output and endpoint identities together with the graph. This is a compiler result, not a Source+file, lock, digest inventory or editor database. It carries no domain or Studio presentation and+lets any diagnostic/editor join a graph value back to the exact author endpoint without matching a+local name after compilation.+The orchestration ABI is asynchronous even when a local Text/SVS implementation is synchronous.This lets a browser, sandbox or remote repository provide SourceUnits without changing thecompilation contract. The Host resolver is the authority for path canonicalization, workspacediff --git a/packages/elaborator/src/index.ts b/packages/elaborator/src/index.tsindex 9d48bce6..40562f65 100644--- a/packages/elaborator/src/index.ts+++ b/packages/elaborator/src/index.ts@@ -25,6 +25,11 @@ export {export type { AuthorFrontendHostFacet } from "./frontend-facet.js";export type {AuthorFrontend,+ AuthorElementProvenance,+ AuthorElementProvenanceDraft,+ AuthorInputProvenance,+ AuthorInputProvenanceDraft,+ AuthorProvenance,AuthorFrontendSourceUnit,AuthorFrontendRegistryLike,AuthorSourceDecodeContext,@@ -32,6 +37,7 @@ export type {AuthorSourceAssetRequest,AuthorSourceAssetResolver,AuthorSourceExport,+ AuthorSourceIdentity,AuthorSourceImport,AuthorSourceResolver,AuthorSourceUnit,diff --git a/packages/elaborator/src/source.ts b/packages/elaborator/src/source.tsindex b7e1bab4..4b4dcb55 100644--- a/packages/elaborator/src/source.ts+++ b/packages/elaborator/src/source.ts@@ -57,6 +57,36 @@ export type AuthorSourceExport = {readonly type: TypeRef;};+/**+ * One author-visible identity whose uniqueness is part of a domain's public+ * contract. The Frontend only carries the declaration; the owning Surface+ * chooses the Type namespace and the Source closure enforces it generically.+ */+export type AuthorSourceIdentity = {+ readonly namespace: TypeRef;+ readonly id: string;+};++/** One author input before Source-local graph identities are hygienized. */+export type AuthorInputProvenanceDraft = {+ readonly name: string;+ readonly range: import("@hypit/protocol").SourceRange;+ readonly kind: "literal" | "reference";+ readonly ref?: AuthorValueRef;+};++/**+ * Structural origin retained by a Frontend while it lowers author syntax.+ * It contains no editor presentation and is never persisted beside the Source.+ */+export type AuthorElementProvenanceDraft = {+ readonly range: import("@hypit/protocol").SourceRange;+ readonly records: readonly string[];+ readonly components: readonly string[];+ readonly outputs: readonly { readonly component: string; readonly name: string; readonly id: string }[];+ readonly inputs: readonly AuthorInputProvenanceDraft[];+};+export type ResolvedAuthorSourceImport = {readonly request: AuthorSourceImport;readonly source: string;@@ -77,6 +107,8 @@ export type DecodedAuthorSource = {readonly components: readonly AuthorComponent[];readonly fragments: readonly GraphFragment[];readonly exports: readonly AuthorSourceExport[];+ readonly identities?: readonly AuthorSourceIdentity[];+ readonly provenance?: readonly AuthorElementProvenanceDraft[];};export type Awaitable<T> = T | Promise<T>;@@ -119,6 +151,7 @@ export type AuthorRecordAdmitter = (export type SourceClosureUnit = {readonly id: string;+ readonly name: string;readonly frontend: string;readonly imports: readonly {readonly alias: string;@@ -126,6 +159,38 @@ export type SourceClosureUnit = {}[];};+export type AuthorInputProvenance = {+ /** Compilation-local identity; authors never write or maintain it. */+ readonly id: string;+ readonly name: string;+ readonly range: import("@hypit/protocol").SourceRange;+ readonly kind: "literal" | "reference";+ readonly ref?: AuthorValueRef;+};++export type AuthorElementProvenance = {+ readonly id: string;+ readonly source: string;+ readonly sourceName: string;+ readonly frontend: string;+ readonly range: import("@hypit/protocol").SourceRange;+ readonly records: readonly { readonly local: string; readonly id: string }[];+ readonly components: readonly { readonly local: string; readonly id: string }[];+ readonly outputs: readonly {+ readonly component: string;+ readonly name: string;+ readonly local: string;+ readonly id: string;+ }[];+ readonly inputs: readonly AuthorInputProvenance[];+};++/** Ephemeral Source-to-graph lineage emitted with one compilation. */+export type AuthorProvenance = {+ readonly format: "hypit.author-provenance@1";+ readonly elements: readonly AuthorElementProvenance[];+};+export type SourceClosure = {readonly entry: string;readonly units: readonly SourceClosureUnit[];@@ -142,6 +207,7 @@ export type CompiledSourceClosure = {readonly program: LinkedProgram;readonly graph: CompiledGraph;readonly exports: readonly CompiledSourceExport[];+ readonly provenance: AuthorProvenance;};export type CompileSourceClosureRequest = {@@ -211,6 +277,8 @@ type HygienicSource = {readonly components: readonly AuthorComponent[];readonly fragments: readonly GraphFragment[];readonly exports: readonly AuthorSourceExport[];+ readonly identities: readonly AuthorSourceIdentity[];+ readonly provenance: readonly AuthorElementProvenance[];};function hygienicId(kind: string, unit: string, local: string): string {@@ -304,6 +372,7 @@ function hygienizeSource(const exports = decoded.exports.map((item) => ({ ...item, ref: mapRef(item.ref) }));const unitContent = {id: source.id,+ name: source.name,frontend: frontend.id,imports: imports.map((item) => ({@@ -318,6 +387,29 @@ function hygienizeSource(components,fragments: decoded.fragments,exports,+ identities: decoded.identities ?? [],+ provenance: (decoded.provenance ?? []).map((element) => ({+ id: hygienicId("element", source.id, `${element.range.start}:${element.range.end}`),+ source: source.id,+ sourceName: source.name,+ frontend: frontend.id,+ range: { ...element.range },+ records: element.records.map((id) => ({ local: id, id: recordIds.get(id) ?? id })),+ components: element.components.map((id) => ({ local: id, id: componentIds.get(id) ?? id })),+ outputs: element.outputs.map((output) => ({+ component: componentIds.get(output.component) ?? output.component,+ name: output.name,+ local: output.id,+ id: outputIds.get(output.id) ?? output.id,+ })),+ inputs: element.inputs.map((input) => ({+ id: hygienicId("endpoint", source.id, `${element.range.start}:${input.name}`),+ name: input.name,+ range: { ...input.range },+ kind: input.kind,+ ...(input.ref === undefined ? {} : { ref: mapRef(input.ref) }),+ })),+ })),};}@@ -436,6 +528,21 @@ export async function compileSourceClosure(};const entry = await compile(request.entry);+ const identities = new Map<string, { readonly source: string; readonly identity: AuthorSourceIdentity }>();+ for (const unit of ordered) {+ for (const identity of unit.identities) {+ assert(identity.id.length > 0, "EMPTY_SOURCE_IDENTITY", `${unit.unit.id} declares an empty public identity`);+ const key = `${typeName(identity.namespace)}\u0000${identity.id}`;+ const existing = identities.get(key);+ assert(+ existing === undefined,+ "DUPLICATE_SOURCE_IDENTITY",+ `${typeName(identity.namespace)} identity ${identity.id} is declared by both ${existing?.source ?? unit.unit.id} and ${unit.unit.id}`,+ identity.id,+ );+ identities.set(key, { source: unit.unit.id, identity });+ }+ }const records = ordered.flatMap((unit) => unit.records);const recordIds = new Set<string>();for (const record of records) {@@ -466,6 +573,10 @@ export async function compileSourceClosure(closure: sourceClosure,program,graph,+ provenance: {+ format: "hypit.author-provenance@1",+ elements: ordered.flatMap((unit) => unit.provenance),+ },exports: entry.exports.map((item) => ({name: item.name,diff --git a/packages/elaborator/test/source.test.ts b/packages/elaborator/test/source.test.tsnew file mode 100644index 00000000..2621353e--- /dev/null+++ b/packages/elaborator/test/source.test.ts@@ -0,0 +1,106 @@+import assert from "node:assert/strict";+import test from "node:test";++import { createResolvedClosure } from "@hypit/core";+import {+ AuthorFrontendRegistry,+ SourceClosureError,+ compileSourceClosure,+} from "@hypit/elaborator";+import type { AuthorSourceUnit } from "@hypit/elaborator";+import type { ModuleManifest, TypeRef } from "@hypit/protocol";++const moduleRef = { name: "example.identity", version: "1" } as const;+const identityType = { module: moduleRef, name: "PublicIdentity" } satisfies TypeRef;+const manifest: ModuleManifest = {+ format: "hypit.module@1",+ name: moduleRef.name,+ version: moduleRef.version,+ dependencies: [],+ types: [{ name: identityType.name }],+ capabilities: [],+ producers: [],+};+const frontendId = "example.identity-frontend@1";++function source(id: string, name: string): AuthorSourceUnit {+ return { id, name, text: `<?svml using="${frontendId}"?>\nidentity` };+}++test("Source Closure rejects a repeated domain-declared public identity", async () => {+ const frontends = new AuthorFrontendRegistry();+ frontends.register({+ id: frontendId,+ discover(unit) {+ return {+ modules: [],+ sources: unit.name === "main"+ ? [{ from: "./child", alias: "child", range: { start: 0, end: 0 } }]+ : [],+ };+ },+ decode() {+ return {+ records: [],+ components: [],+ fragments: [],+ exports: [],+ identities: [{ namespace: identityType, id: "story" }],+ };+ },+ });+ await assert.rejects(+ compileSourceClosure({+ entry: source("/project/main", "main"),+ closure: createResolvedClosure([manifest]),+ frontends,+ resolveSource() {+ return source("/project/child", "child");+ },+ }),+ (error: unknown) => error instanceof SourceClosureError+ && error.code === "DUPLICATE_SOURCE_IDENTITY"+ && error.subject === "story",+ );+});++test("Source Closure hygienizes author provenance across imported Sources", async () => {+ const frontends = new AuthorFrontendRegistry();+ frontends.register({+ id: frontendId,+ discover(unit) {+ return {+ modules: [],+ sources: unit.name === "main"+ ? [{ from: "./child", alias: "child", range: { start: 0, end: 0 } }]+ : [],+ };+ },+ decode(unit) {+ return {+ records: [{ id: "value", type: identityType, value: { kind: "inline", value: unit.name } }],+ components: [],+ fragments: [],+ exports: [{ name: "value", ref: { kind: "record", id: "value" }, type: identityType }],+ provenance: [{+ range: { start: 1, end: 9 },+ records: ["value"],+ components: [],+ outputs: [],+ inputs: [{ name: "label", range: { start: 2, end: 7 }, kind: "literal" }],+ }],+ };+ },+ });+ const compiled = await compileSourceClosure({+ entry: source("/project/main", "main"),+ closure: createResolvedClosure([manifest]),+ frontends,+ resolveSource() { return source("/project/child", "child"); },+ });+ assert.equal(compiled.provenance.elements.length, 2);+ const bySource = new Map(compiled.provenance.elements.map((item) => [item.sourceName, item] as const));+ assert.equal(bySource.get("main")?.records[0]?.id, "/project/main::record::value");+ assert.equal(bySource.get("child")?.records[0]?.id, "/project/child::record::value");+ assert.notEqual(bySource.get("main")?.inputs[0]?.id, bySource.get("child")?.inputs[0]?.id);+});diff --git a/packages/film-studio/package.json b/packages/film-studio/package.jsonnew file mode 100644index 00000000..2880d5a6--- /dev/null+++ b/packages/film-studio/package.json@@ -0,0 +1,15 @@+{+ "name": "@hypit/film-studio",+ "version": "0.0.0-dev",+ "license": "SEE LICENSE IN LICENSE",+ "private": true,+ "type": "module",+ "exports": { ".": "./src/index.ts" },+ "hypit": { "activation": "./src/activation.ts" },+ "dependencies": {+ "@hypit/composition": "workspace:*",+ "@hypit/film": "workspace:*",+ "@hypit/semantic-track": "workspace:*",+ "@hypit/studio-adapter": "workspace:*"+ }+}diff --git a/packages/film-studio/src/activation.ts b/packages/film-studio/src/activation.tsnew file mode 100644index 00000000..e3845808--- /dev/null+++ b/packages/film-studio/src/activation.ts@@ -0,0 +1,8 @@+import { createStudioCompanionHostFacet } from "@hypit/studio-adapter";++import { filmStudioCompanions } from "./index.js";++export default {+ format: "hypit.node-package@1" as const,+ hostFacets: [createStudioCompanionHostFacet({ films: filmStudioCompanions })],+};diff --git a/packages/film-studio/src/index.ts b/packages/film-studio/src/index.tsnew file mode 100644index 00000000..fdbca4f9--- /dev/null+++ b/packages/film-studio/src/index.ts@@ -0,0 +1,16 @@+import type { StudioFilmCompanion } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import { filmModuleRef } from "@hypit/film";+import { semanticTrackTypes } from "@hypit/semantic-track";++/** Film alone owns the author vocabulary that selects one semantic axis and its peer Tracks. */+export const filmStudioCompanions: readonly StudioFilmCompanion[] = [{+ id: "film",+ match: { module: filmModuleRef, surface: "film", outputType: compositionTypes.composition },+ semantic: { attribute: "semantic", type: semanticTrackTypes.track },+ tracks: {+ childSurface: "Track",+ sourceAttribute: "source",+ types: [compositionTypes.visualTrack, compositionTypes.audioTrack],+ },+}];diff --git a/packages/markup/src/frontend.ts b/packages/markup/src/frontend.tsindex fccfa141..ad0fe667 100644--- a/packages/markup/src/frontend.ts+++ b/packages/markup/src/frontend.ts@@ -6,7 +6,9 @@ import type {} from "@hypit/protocol";import type {AuthorComponent,+ AuthorElementProvenanceDraft,AuthorSourceExport,+ AuthorSourceIdentity,AuthorValueRef,GraphFragment,} from "@hypit/elaborator";@@ -32,6 +34,7 @@ import type {MarkupAuthorFrontend,MarkupAuthorFrontendOptions,MarkupImportRequest,+ StructuredElement,} from "./types.js";export const markupAuthorFrontendId = "@hypit/markup@1";@@ -174,6 +177,49 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCoconst recordIds = new Set<string>();const componentIds = new Set<string>();const privateBindings = new Set<string>();+ const identities: AuthorSourceIdentity[] = [];+ const provenance: AuthorElementProvenanceDraft[] = [];+ const sameRange = (+ left: { readonly start: number; readonly end: number },+ right: { readonly start: number; readonly end: number },+ ): boolean => left.start === right.start && left.end === right.end;+ const resolvedReference = (path: string): SurfaceResolvedReference | undefined => {+ const imported = importedReferences.get(path);+ if (imported !== undefined) return imported;+ const record = recordsById.get(path);+ if (record !== undefined) {+ return { path, ref: { kind: "record", id: record.id }, type: record.type, record };+ }+ return componentReferences.get(path);+ };+ const retainElementProvenance = (element: StructuredElement, output: SurfaceDecodeOutput): void => {+ const exactComponents = output.components.filter((draft) => sameRange(draft.range, element.range));+ provenance.push({+ range: { ...element.range },+ records: output.records.filter((draft) => sameRange(draft.range, element.range)).map((draft) => draft.id),+ components: exactComponents.map((draft) => draft.id),+ outputs: exactComponents.flatMap((draft) => Object.entries(draft.outputs).map(([name, id]) => ({+ component: draft.id,+ name,+ id,+ }))),+ inputs: Object.entries(element.attributes).flatMap(([name, value]): readonly import("@hypit/elaborator").AuthorInputProvenanceDraft[] => {+ const range = element.attributeValueRanges?.[name];+ if (range === undefined) return [];+ if (typeof value === "string") return [{ name, range: { ...range }, kind: "literal" as const }];+ const found = resolvedReference(value.path);+ return [{+ name,+ range: { ...range },+ kind: "reference" as const,+ ...(found === undefined ? {} : { ref: found.ref }),+ }];+ }),+ });+ for (const child of element.children) {+ if (child.kind === "element") retainElementProvenance(child, output);+ }+ };let cursor = discovery.bodyStart;let closed = false;while (cursor < source.text.length) {@@ -194,6 +240,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCoif (!bound) fail(source, "MARKUP_UNKNOWN_SURFACE", `No imported module declares <${opening.name}>.`, cursor);const registered = bound.surface;let output: SurfaceDecodeOutput;+ let structuredElement: StructuredElement | undefined;if (registered.mode === "raw") {if (opening.selfClosing) fail(source, "MARKUP_RAW_SELF_CLOSING", `Raw Surface <${opening.name}> cannot be self-closing.`, cursor);const rawOutput = await (registered.handler as RawSurfaceHandler)({@@ -217,6 +264,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCooutput = rawOutput;} else {const parsed = parseStructuredElement(source, cursor);+ structuredElement = parsed.element;output = await (registered.handler as StructuredSurfaceHandler)({sourceName: source.name,element: parsed.element,@@ -275,6 +323,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCo}for (const name of generated) if (!published.has(name)) privateBindings.add(name);}+ identities.push(...(output.identities ?? []));for (const draft of output.records) {if (!Number.isInteger(draft.range.start)@@ -368,6 +417,7 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCofor (const component of waitingComponents.get(fragment.id) ?? []) indexComponent(component, fragment);waitingComponents.delete(fragment.id);}+ if (structuredElement !== undefined) retainElementProvenance(structuredElement, output);}if (!closed) {fail(source, "MARKUP_ROOT_UNCLOSED", "Document is missing </svml>.", source.text.length);@@ -421,6 +471,8 @@ export async function decodeMarkup(source: MarkupSource, context: MarkupDecodeCocomponents: resolvedComponents,fragments: [...fragments.values()].sort((left, right) => left.id.localeCompare(right.id)),exports: exports.sort((left, right) => left.name.localeCompare(right.name)),+ identities,+ provenance,};}@@ -458,6 +510,8 @@ export function createMarkupAuthorFrontend(options: MarkupAuthorFrontendOptions)components: result.components,fragments: result.fragments,exports: result.exports,+ identities: result.identities,+ provenance: result.provenance,};},};diff --git a/packages/markup/src/types.ts b/packages/markup/src/types.tsindex f8621886..8e20c37a 100644--- a/packages/markup/src/types.ts+++ b/packages/markup/src/types.ts@@ -13,6 +13,8 @@ import type {AuthorFrontend,AuthorSourceAssetRequest,AuthorSourceExport,+ AuthorSourceIdentity,+ AuthorElementProvenanceDraft,AuthorValueRef,Awaitable,GraphFragment,@@ -78,6 +80,8 @@ export type SurfaceDecodeOutput = {readonly records: readonly SurfaceRecordDraft[];readonly components: readonly SurfaceComponentDraft[];readonly fragments: readonly GraphFragment[];+ /** Domain-owned public identities that must be unique in the Source closure. */+ readonly identities?: readonly AuthorSourceIdentity[];/*** Public source bindings contributed by this Surface invocation. Omit to* publish every generated binding; use an explicit list to keep plumbing@@ -224,6 +228,8 @@ export type MarkupDecodeResult = {readonly components: readonly AuthorComponent[];readonly fragments: readonly GraphFragment[];readonly exports: readonly AuthorSourceExport[];+ readonly identities: readonly AuthorSourceIdentity[];+ readonly provenance: readonly AuthorElementProvenanceDraft[];};export type MarkupAuthorFrontendOptions = {diff --git a/packages/media-track-studio/package.json b/packages/media-track-studio/package.jsonindex 0596b56c..8c77eb12 100644--- a/packages/media-track-studio/package.json+++ b/packages/media-track-studio/package.json@@ -8,6 +8,8 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/media-track": "workspace:*",+ "@hypit/composition": "workspace:*",+ "@hypit/protocol": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/media-track-studio/src/activation.ts b/packages/media-track-studio/src/activation.tsindex 77dc96fd..ccff3581 100644--- a/packages/media-track-studio/src/activation.ts+++ b/packages/media-track-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { mediaTrackStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { mediaTrackStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(mediaTrackStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(mediaTrackStudioTrackCompanions)],};diff --git a/packages/media-track-studio/src/index.ts b/packages/media-track-studio/src/index.tsindex 39b6cee6..c5601557 100644--- a/packages/media-track-studio/src/index.ts+++ b/packages/media-track-studio/src/index.ts@@ -1,14 +1,16 @@-import { mediaTrackMarkupSurfaces } from "@hypit/media-track";+import { mediaTrackMarkupSurfaces, mediaTrackModuleRef, mediaTrackTypes } from "@hypit/media-track";import type { MediaLayerProgram, MediaTrackProgram } from "@hypit/media-track";+import { compositionTypes } from "@hypit/composition";+import { sameType } from "@hypit/protocol";import type {- StudioAdapter,- StudioAdapterContext,+ StudioTrackCompanion,+ StudioTrackCompanionContext,StudioEntityDraft,StudioInspectorFieldDeclaration,StudioMaterialPreview,StudioSourceBindingDeclaration,} from "@hypit/studio-adapter";-import { artifactPreview, childEntities, previewLayer, projectedWindowTimelineEdits, requiredSurfaceValue, temporalLineageFor } from "@hypit/studio-adapter";+import { artifactPreview, childEntities, previewLayer, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";const frameParameters: readonly StudioSourceBindingDeclaration[] = [{ name: "within" },@@ -111,9 +113,9 @@ function materialPreview(return artifactPreview(layer.source.kind === "still" ? "image" : "video", layer.source.artifact.digest);}-function projectMedia(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectMedia(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as MediaTrackProgram;- const facet = context.track.type === "AudioTrack" ? "audio" : "visual";+ const facet = sameType(context.track.typeRef, compositionTypes.audioTrack) ? "audio" : "visual";const items = [...program.items.map((item) => ({id: item.id,@@ -123,6 +125,7 @@ function projectMedia(context: StudioAdapterContext): readonly StudioEntityDraftstackOrder: item.stacking.order,preview: materialPreview(item.layers, facet, item.sourceAudio?.fromLayer),temporalInput: "window",+ sourceTypes: [mediaTrackTypes.itemSpec],})),...program.sequences.map((sequence) => ({id: sequence.id,@@ -134,6 +137,7 @@ function projectMedia(context: StudioAdapterContext): readonly StudioEntityDraft? undefined: materialPreview(sequence.members[0].layers, facet, sequence.members[0].sourceAudio?.fromLayer),temporalInput: "terminal",+ sourceTypes: [mediaTrackTypes.sequenceSpec],})),];return childEntities(context, items, "media-item", "standard")@@ -141,11 +145,12 @@ function projectMedia(context: StudioAdapterContext): readonly StudioEntityDraftconst item = items[index];if (item === undefined) return entity;const temporal = temporalLineageFor(context, item.id, item.temporalInput);+ const semanticSource = temporalSemanticSource(temporal);return {...entity,- ...(temporal?.source.kind === "program" || temporal?.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),...(item.preview === undefined ? {} : {display: {...entity.display,@@ -158,9 +163,6 @@ function projectMedia(context: StudioAdapterContext): readonly StudioEntityDraft}const commonBindings: readonly StudioSourceBindingDeclaration[] = [- { name: "start", writable: true },- { name: "end", writable: true },- { name: "for", writable: true },{ name: "source-audio", writable: true },{ name: "audio-gain", writable: true },{ name: "until" },@@ -181,12 +183,11 @@ const commonInspector: readonly StudioInspectorFieldDeclaration[] = [const frameSizeParameters = new Set(["width", "height"]);-export const mediaTrackStudioAdapters: readonly StudioAdapter[] = [+export const mediaTrackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "visual", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/media-track"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [mediaTrackModuleRef] },family: "media", tone: "blue", icon: "video",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: [...commonBindings,{ name: "extent", referenced: extentParameters },@@ -224,9 +225,8 @@ export const mediaTrackStudioAdapters: readonly StudioAdapter[] = [},{id: "audio", role: "track",- output: { type: "AudioTrack", surface: "track", modules: ["@hypit/media-track"] },+ output: { type: compositionTypes.audioTrack, surface: "track", modules: [mediaTrackModuleRef] },family: "media-audio", tone: "green", icon: "waveform",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: commonBindings,inspector: commonInspector,requiredValues: ["program"], project: projectMedia,diff --git a/packages/ranking-studio/package.json b/packages/ranking-studio/package.jsonindex f45ede96..e600def4 100644--- a/packages/ranking-studio/package.json+++ b/packages/ranking-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/ranking": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/ranking-studio/src/activation.ts b/packages/ranking-studio/src/activation.tsindex dc29d869..88363116 100644--- a/packages/ranking-studio/src/activation.ts+++ b/packages/ranking-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { rankingStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { rankingStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(rankingStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(rankingStudioTrackCompanions)],};diff --git a/packages/ranking-studio/src/index.ts b/packages/ranking-studio/src/index.tsindex 1e654dd7..f4d91b58 100644--- a/packages/ranking-studio/src/index.ts+++ b/packages/ranking-studio/src/index.ts@@ -1,7 +1,8 @@-import { rankingMarkupSurfaces } from "@hypit/ranking";+import { rankingMarkupSurfaces, rankingModuleRef, rankingTypes } from "@hypit/ranking";import type { RankingProgram, RankingSchedule } from "@hypit/ranking";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";-import { artifactPreview, previewLayer, projectedPointTimelineEdits, requiredSurfaceValue, selectionWindowTimelineEdits, temporalLineageFor } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";+import { artifactPreview, authoredChildFor, previewLayer, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";const frameParameters: readonly StudioSourceBindingDeclaration[] = [{ name: "within" },@@ -34,6 +35,8 @@ const rankingInspectorPlacement = {"font-size": place("how", "Text", "Typography"),"font-weight": place("how", "Text", "Typography"),"text-color": place("how", "Text", "Typography"),+ "label-text-color": place("how", "Labels", "Typography"),+ "label-size": place("how", "Labels", "Typography"),"line-height": place("how", "Text", "Typography"),"board-background": place("how", "Board", "Board Paint"),"board-border-color": place("how", "Board", "Board Paint"),@@ -54,6 +57,7 @@ const rankingInspectorPlacement = {"cell-gap": place("where", "Layout", "Rows"),"icon-size": place("where", "Layout", "Items"),"icon-radius": place("how", "Board", "Items"),+ "icon-radius-ratio": place("how", "Board", "Items"),"icon-fit": place("how", "Board", "Items"),"stage-x": place("where", "Stage", "Position"),"stage-y": place("where", "Stage", "Position"),@@ -95,17 +99,18 @@ function rankingStyle(surface: "column-style" | "tier-style" | "top-three-style"};}-function projectRanking(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectRanking(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const placement = context.placement;const schedule = requiredSurfaceValue(context, "schedule") as RankingSchedule;const program = requiredSurfaceValue(context, "program") as RankingProgram;if (placement === undefined) return context.generic();const boardId = placement.id ?? context.track.outputRef;const outerTemporal = temporalLineageFor(context, boardId, "outer");+ const outerSemanticSource = temporalSemanticSource(outerTemporal);const group: StudioEntityDraft = {id: `${context.track.outputRef}:entity:${boardId}`,authoredId: boardId,- ...(outerTemporal?.source.id === undefined ? {} : { markerId: outerTemporal.source.id }),+ ...(outerSemanticSource?.id === undefined ? {} : { markerId: outerSemanticSource.id }),display: { title: boardId, layers: [] },startFrame: schedule.outer.startFrame,endFrameExclusive: schedule.outer.endFrameExclusive,@@ -115,21 +120,20 @@ function projectRanking(context: StudioAdapterContext): readonly StudioEntityDrapresentation: { entity: "ranking", chrome: "group" },...(outerTemporal === undefined ? {} : { temporal: outerTemporal }),};- const children = new Map(placement.children.flatMap((child) =>- child.id === undefined ? [] : [[child.id, child] as const]));const programItems = new Map(program?.items.map((item) => [item.id, item] as const) ?? []);const reveals = schedule.entries.flatMap((entry): readonly StudioEntityDraft[] => {if ("mode" in entry && entry.mode !== "reveal") return [];- const child = children.get(entry.itemId);+ const child = authoredChildFor(context, entry.itemId, [rankingTypes.itemSpec, rankingTypes.textItemShell]);const item = programItems.get(entry.itemId);const temporal = temporalLineageFor(context, entry.itemId, "mode" in entry ? "window" : "activation");+ const semanticSource = temporalSemanticSource(temporal);const visible = "mode" in entry ? entry.window : entry.cumulative;const icon = item?.icon;const label = item !== undefined && "label" in item ? item.label : child?.attributes.label ?? entry.itemId;return [{id: `${context.track.outputRef}:entity:${entry.itemId}`,authoredId: entry.itemId,- ...(temporal?.source.id === undefined ? {} : { markerId: temporal.source.id }),+ ...(semanticSource?.id === undefined ? {} : { markerId: semanticSource.id }),display: {title: label,layers: icon === undefined ? [] : [previewLayer(artifactPreview("image", icon.digest), "repeat-x")],@@ -159,12 +163,11 @@ const frameInspector: readonly StudioInspectorFieldDeclaration[] = frameParametepage: { id: "frame", label: "Frame" }, section: { id: "frame", label: "Frame" }, control: "text",}));-export const rankingStudioAdapters: readonly StudioAdapter[] = [+export const rankingStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "column", role: "track",- output: { type: "VisualTrack", surface: "column", modules: ["@hypit/ranking"] },+ output: { type: compositionTypes.visualTrack, surface: "column", modules: [rankingModuleRef] },family: "ranking", tone: "orange", label: "Ranking", icon: "ranking", requiredValues: ["schedule", "program"],- timelineEdits: selectionWindowTimelineEdits(),bindings: [...commonBindings,rankingStyle("column-style"),@@ -181,62 +184,72 @@ export const rankingStudioAdapters: readonly StudioAdapter[] = [{ name: "label", writable: true },{ name: "icon" },{ name: "rank", writable: true },- { name: "preset", writable: true },{ name: "stack", writable: true },],inspector: [{ binding: "label", label: "Label", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "text" },{ binding: "rank", label: "Rank", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "number" },- { binding: "preset", label: "Preset", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "boolean" },{ binding: "stack", label: "Stack", domain: "where", page: { id: "stacking", label: "Stacking" }, section: { id: "stacking", label: "Stacking" }, control: "number" },],- timelineEdits: selectionWindowTimelineEdits(),}],project: projectRanking,},- ...([[- "tier", "tier", "Tier Board",- ], [- "top-three", "top-three", "Top Three",- ]] as const).map(([id, surface, label]): StudioAdapter => ({- id, role: "track",- output: { type: "VisualTrack", surface, modules: ["@hypit/ranking"] },- family: "ranking", tone: "orange", label, icon: "ranking", requiredValues: ["schedule", "program"],- timelineEdits: selectionWindowTimelineEdits(),+ {+ id: "tier", role: "track",+ output: { type: compositionTypes.visualTrack, surface: "tier", modules: [rankingModuleRef] },+ family: "ranking", tone: "orange", label: "Tier Board", icon: "ranking", requiredValues: ["schedule", "program"],bindings: [...commonBindings,- rankingStyle(surface === "tier" ? "tier-style" : "top-three-style"),- { name: "terminal" },+ rankingStyle("tier-style"),],inspector: [...frameInspector,- ...rankingInspector(surface === "tier" ? "tier-style" : "top-three-style"),+ ...rankingInspector("tier-style"),],poster: { source: "surface-preview" },- lane: { heightPx: 80, groupId: `${id}-activations` },+ lane: { heightPx: 80, groupId: "tier-reveals" },attachments: [{- id: "activation", family: "ranking-reveal", tone: "orange-muted", label: "Activations", icon: "ranking", facet: "visual",+ id: "reveal", family: "ranking-reveal", tone: "orange-muted", label: "Reveals", icon: "ranking", facet: "visual",lane: { heightPx: 40 },- bindings: id === "tier" ? [+ bindings: [{ name: "tier", writable: true },{ name: "entry", writable: true },{ name: "icon" },{ name: "stack", writable: true },- ] : [+ ],+ inspector: [+ { binding: "tier", label: "Tier", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "text" },+ { binding: "entry", label: "Entry", domain: "when", page: { id: "entrance", label: "Entrance" }, section: { id: "entrance", label: "Entrance" }, control: "select", options: ["direct", "drop"] },+ { binding: "stack", label: "Stack", domain: "where", page: { id: "stacking", label: "Stacking" }, section: { id: "stacking", label: "Stacking" }, control: "number" },+ ],+ }],+ project: projectRanking,+ },+ {+ id: "top-three", role: "track",+ output: { type: compositionTypes.visualTrack, surface: "top-three", modules: [rankingModuleRef] },+ family: "ranking", tone: "orange", label: "Top Three", icon: "ranking", requiredValues: ["schedule", "program"],+ bindings: [+ ...commonBindings,+ rankingStyle("top-three-style"),+ { name: "terminal" },+ ],+ inspector: [...frameInspector, ...rankingInspector("top-three-style")],+ poster: { source: "surface-preview" },+ lane: { heightPx: 80, groupId: "top-three-activations" },+ attachments: [{+ id: "activation", family: "ranking-reveal", tone: "orange-muted", label: "Activations", icon: "ranking", facet: "visual",+ lane: { heightPx: 40 },+ bindings: [{ name: "label", writable: true },{ name: "icon" },{ name: "stack", writable: true },],- inspector: id === "tier" ? [- { binding: "tier", label: "Tier", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "text" },- { binding: "entry", label: "Entry", domain: "when", page: { id: "activation", label: "Activation" }, section: { id: "activation", label: "Activation" }, control: "select", options: ["direct", "stage"] },- { binding: "stack", label: "Stack", domain: "where", page: { id: "stacking", label: "Stacking" }, section: { id: "stacking", label: "Stacking" }, control: "number" },- ] : [+ inspector: [{ binding: "label", label: "Label", domain: "how", page: { id: "item", label: "Item" }, section: { id: "item", label: "Item" }, control: "text" },{ binding: "stack", label: "Stack", domain: "where", page: { id: "stacking", label: "Stacking" }, section: { id: "stacking", label: "Stacking" }, control: "number" },],- timelineEdits: projectedPointTimelineEdits(),}],project: projectRanking,- })),+ },];diff --git a/packages/screen-overlay-studio/package.json b/packages/screen-overlay-studio/package.jsonindex 0c0cbb2e..6a52f061 100644--- a/packages/screen-overlay-studio/package.json+++ b/packages/screen-overlay-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/screen-overlay": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/screen-overlay-studio/src/activation.ts b/packages/screen-overlay-studio/src/activation.tsindex 2772eb7f..3b956509 100644--- a/packages/screen-overlay-studio/src/activation.ts+++ b/packages/screen-overlay-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { screenOverlayStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { screenOverlayStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(screenOverlayStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(screenOverlayStudioTrackCompanions)],};diff --git a/packages/screen-overlay-studio/src/index.ts b/packages/screen-overlay-studio/src/index.tsindex bb497de2..7a90a3e0 100644--- a/packages/screen-overlay-studio/src/index.ts+++ b/packages/screen-overlay-studio/src/index.ts@@ -1,8 +1,10 @@+import { screenOverlayModuleRef, screenOverlayTypes } from "@hypit/screen-overlay";import type { ScreenOverlayProgram } from "@hypit/screen-overlay";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";-import { childEntities, projectedWindowTimelineEdits, requiredSurfaceValue, temporalLineageFor } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";+import { childEntities, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";-function projectOverlays(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectOverlays(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as ScreenOverlayProgram;const items = program.items.map((item) => ({id: item.id,@@ -10,17 +12,19 @@ function projectOverlays(context: StudioAdapterContext): readonly StudioEntityDrstartFrame: item.span.startFrame,endFrameExclusive: item.span.endFrameExclusive,stackOrder: item.stacking.order,+ sourceTypes: [screenOverlayTypes.itemSpec],}));return childEntities(context, items, "screen-overlay", "standard").map((entity, index) => {const item = program.items[index];if (item === undefined) return entity;const temporal = temporalLineageFor(context, item.id, "window");+ const semanticSource = temporalSemanticSource(temporal);return {...entity,display: { title: item.content.kind.replaceAll("-", " "), layers: [] },- ...(temporal?.source.kind === "program" || temporal?.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),...(temporal === undefined ? {} : { temporal }),};});@@ -60,14 +64,12 @@ const overlayInspector: readonly StudioInspectorFieldDeclaration[] = overlayName};});-export const screenOverlayStudioAdapters: readonly StudioAdapter[] = [+export const screenOverlayStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/screen-overlay"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [screenOverlayModuleRef] },family: "screen-overlay", tone: "orange", icon: "component",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: [- { name: "start", writable: true }, { name: "end", writable: true }, { name: "for", writable: true },...overlayNames.map((name) => ({ name, writable: true })),],inspector: overlayInspector,diff --git a/packages/script-studio/package.json b/packages/script-studio/package.jsonnew file mode 100644index 00000000..d7377766--- /dev/null+++ b/packages/script-studio/package.json@@ -0,0 +1,13 @@+{+ "name": "@hypit/script-studio",+ "version": "0.0.0-dev",+ "license": "SEE LICENSE IN LICENSE",+ "private": true,+ "type": "module",+ "exports": { ".": "./src/index.ts" },+ "hypit": { "activation": "./src/activation.ts" },+ "dependencies": {+ "@hypit/script": "workspace:*",+ "@hypit/studio-adapter": "workspace:*"+ }+}diff --git a/packages/script-studio/src/activation.ts b/packages/script-studio/src/activation.tsnew file mode 100644index 00000000..7089f75c--- /dev/null+++ b/packages/script-studio/src/activation.ts@@ -0,0 +1,8 @@+import { createStudioCompanionHostFacet } from "@hypit/studio-adapter";++import { scriptStudioCompanions } from "./index.js";++export default {+ format: "hypit.node-package@1" as const,+ hostFacets: [createStudioCompanionHostFacet({ scripts: scriptStudioCompanions })],+};diff --git a/packages/script-studio/src/index.ts b/packages/script-studio/src/index.tsnew file mode 100644index 00000000..b81640c4--- /dev/null+++ b/packages/script-studio/src/index.ts@@ -0,0 +1,61 @@+import { adjustScriptMoment, adjustScriptSelection, parseScript, scriptModuleRef } from "@hypit/script";+import type { StudioScriptCompanion } from "@hypit/studio-adapter";++export const scriptStudioCompanions: readonly StudioScriptCompanion[] = [{+ id: "script",+ match: { module: scriptModuleRef, surface: "script" },+ observe(input) {+ const narrativeId = input.attributes.id ?? "script";+ if (typeof narrativeId !== "string" || narrativeId.length === 0) return undefined;+ const closing = `</${input.tag}>`;+ const closeEnd = input.nextOffset;+ if (closeEnd === undefined) return undefined;+ const end = closeEnd - closing.length;+ if (end < input.contentStart || input.source.slice(end, closeEnd) !== closing) return undefined;+ const parsed = parseScript(+ input.sourceName,+ input.source.slice(input.contentStart, end),+ input.contentStart,+ );+ return {+ narrativeId,+ sourcePath: input.sourceName,+ range: { start: input.openingStart, end: closeEnd },+ content: { start: input.contentStart, end },+ segments: parsed.segments.map((segment) => ({ id: segment.id, range: segment.range })),+ selections: parsed.selections.map((selection) => ({+ id: selection.id,+ startAnchorId: selection.startAnchorId,+ endAnchorId: selection.endAnchorId,+ open: selection.open.range,+ close: selection.close.range,+ })),+ moments: parsed.moments.map((moment) => ({+ id: moment.id,+ anchorId: moment.anchorId,+ range: moment.range,+ })),+ tokens: parsed.tokens.map((token) => ({ id: token.id, range: token.range })),+ };+ },+ adjust(input) {+ const parsed = parseScript(input.sourceName, input.source);+ return input.adjustment.kind === "selection"+ ? adjustScriptSelection({+ sourceName: input.sourceName,+ source: input.source,+ parsed,+ adjustment: {+ id: input.adjustment.id,+ startAnchorId: input.adjustment.startAnchorId,+ endAnchorId: input.adjustment.endAnchorId,+ },+ })+ : adjustScriptMoment({+ sourceName: input.sourceName,+ source: input.source,+ parsed,+ adjustment: { id: input.adjustment.id, anchorId: input.adjustment.anchorId },+ });+ },+}];diff --git a/packages/speech-track-studio/package.json b/packages/speech-track-studio/package.jsonindex 6bfc95c5..0ddfbe0b 100644--- a/packages/speech-track-studio/package.json+++ b/packages/speech-track-studio/package.json@@ -8,6 +8,7 @@"hypit": { "activation": "./src/activation.ts" },"dependencies": {"@hypit/speech-track": "workspace:*",+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*"}}diff --git a/packages/speech-track-studio/src/activation.ts b/packages/speech-track-studio/src/activation.tsindex 1eb84d37..065b7e4f 100644--- a/packages/speech-track-studio/src/activation.ts+++ b/packages/speech-track-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { speechTrackStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { speechTrackStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(speechTrackStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(speechTrackStudioTrackCompanions)],};diff --git a/packages/speech-track-studio/src/index.ts b/packages/speech-track-studio/src/index.tsindex 590c81c7..ca8fc46b 100644--- a/packages/speech-track-studio/src/index.ts+++ b/packages/speech-track-studio/src/index.ts@@ -1,5 +1,6 @@-import { speechTrackMarkupSurfaces } from "@hypit/speech-track";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";+import { speechTrackMarkupSurfaces, speechTrackModuleRef } from "@hypit/speech-track";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration, StudioSourceBindingDeclaration } from "@hypit/studio-adapter";import { artifactPreview, previewLayer } from "@hypit/studio-adapter";const frameParameters: readonly StudioSourceBindingDeclaration[] = [@@ -56,7 +57,7 @@ type SpeechAudioTrack = {}[];};-function projectSpeechVisual(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectSpeechVisual(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const presents = new Map(((context.track.value as SpeechVisualTrack).presents ?? []).map((present) => [present.id, present] as const));return context.generic().map((entity) => {@@ -78,7 +79,7 @@ function projectSpeechVisual(context: StudioAdapterContext): readonly StudioEnti});}-function projectSpeechAudio(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectSpeechAudio(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const clips = new Map(((context.track.value as SpeechAudioTrack).clips ?? []).map((clip) => [clip.id, clip] as const));return context.generic().map((entity) => {@@ -97,10 +98,10 @@ function projectSpeechAudio(context: StudioAdapterContext): readonly StudioEntit});}-export const speechTrackStudioAdapters: readonly StudioAdapter[] = [+export const speechTrackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "visual", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/speech-track"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [speechTrackModuleRef] },family: "speech-visual", tone: "blue", label: "Speech Visual", icon: "video",bindings: [{ name: "visual-frame", referenced: frameParameters },@@ -116,7 +117,7 @@ export const speechTrackStudioAdapters: readonly StudioAdapter[] = [},{id: "audio", role: "track",- output: { type: "AudioTrack", surface: "track", modules: ["@hypit/speech-track"] },+ output: { type: compositionTypes.audioTrack, surface: "track", modules: [speechTrackModuleRef] },family: "speech-audio", tone: "green", label: "Speech Audio", icon: "waveform",bindings: [], inspector: [], project: projectSpeechAudio,lane: { heightPx: 48 },diff --git a/packages/studio-adapter/README.md b/packages/studio-adapter/README.mdindex 9456a05e..ab7c8977 100644--- a/packages/studio-adapter/README.md+++ b/packages/studio-adapter/README.md@@ -4,17 +4,36 @@ The stable companion-package ABI understood by Hypit Studio. It carries onlypresentation, lineage, inspector and interaction DTOs plus helpers that do notencode the official video UI policy. Domain packages do not depend on it.-`StudioAdapterContext.temporalBindings` exposes the executed Point/Window records in the selected+`StudioTrackCompanionContext.temporalBindings` exposes the executed Instant/Window records in the selectedTrack closure, including projection expressions, source identity and direct consumer inputs.`temporalLineageFor()` joins a domain entity to those edges through the identity of a value consumed-beside the projection; it does not inspect author attribute names.+beside the projection; it does not inspect author attribute names. No match is read-only, one match+is used, and several matches are an error rather than a first-result guess. The generic terminal+fallback tries only the terminal object's exact `subjectId`/`authoredId`; renderer ids and marker ids+are not alternate guesses.-A project companion contributes package-local adapter ids through-`createStudioAdapterHostFacet()`. The Host qualifies them with the selected+Track Companions match terminal outputs by complete `TypeRef` and their authoring origin by complete+`ModuleRef + Surface`; Film and Script companions use the same versioned origin match. Short Type+and module names remain available for UI text and diagnostics but never decide which Companion is+allowed to interpret a value.++Trace references retain the exact author input name and resolved TypeRef. A Companion that needs a+CaptionDocument or another referenced domain value selects that declared edge; it never scans all+values for a familiar object shape. Child entities follow the same rule: when an optional Source id+was omitted, a Companion may name the exact domain Spec Type whose public `id` owns that child.+Studio then recovers the Source range from the typed observed Record, without ordinal matching.++A project companion contributes package-local Track Companion ids through+`createStudioTrackCompanionHostFacet()`. The Host qualifies them with the selectedphysical package identity, so executable package code cannot impersonate an-official adapter. Project profiles select those packages explicitly; Studio+official Companion. Project profiles select those packages explicitly; Studiodoes not scan `node_modules` for plugins.+The same host facet can contribute Film and Script boundary companions. A Film companion declares+the references that select one semantic axis and its terminal Tracks. A Script companion owns raw+source observation and marker adjustment. Studio core only matches and invokes these declarations;+it does not import either domain package.+Inspector editing deliberately has two declarations:- `bindings` names exact author endpoints, including explicit reference paths@@ -32,7 +51,7 @@ current Source closure, publishes only real writable fields, renders all DOMand CSS itself, and commits changes through `parameter.adjust`.Structured controls keep a local draft and commit one complete canonical value.-Their codec is the author language (`@hypit/svs` for Recipe values), not an-adapter callback. Companions cannot inject DOM, CSS, parsing code or filesystem+Their codec is the author language (`@hypit/svs` for Recipe values), not a+Companion callback. Companions cannot inject DOM, CSS, parsing code or filesystemmutations. Official companions also use explicit field tables: an undeclared-new domain property fails adapter loading instead of inheriting UI from its name.+new domain property fails Companion loading instead of inheriting UI from its name.diff --git a/packages/studio-adapter/src/index.ts b/packages/studio-adapter/src/index.tsindex af7d7502..d40ec124 100644--- a/packages/studio-adapter/src/index.ts+++ b/packages/studio-adapter/src/index.ts@@ -1,7 +1,8 @@import type { HostFacet } from "@hypit/host";-import type { CanonicalValue, ValueSchema } from "@hypit/protocol";+import { sameType } from "@hypit/protocol";+import type { CanonicalValue, ModuleRef, TypeRef, ValueSchema } from "@hypit/protocol";-export const studioAdapterHostAbi = "hypit.studio-adapter@1";+export const studioCompanionHostAbi = "hypit.studio-adapter@1";/** UTF-16 offsets into the exact author source. */export type Range = { readonly start: number; readonly end: number };@@ -35,25 +36,47 @@ export type StudioTimelinePresentation = {};export type StudioTemporalSource = {- readonly kind: "program" | "selection" | "segment" | "moment" | "parent-schedule";- readonly id?: string;+ readonly spaceId: string;+ readonly narrativeId: string;+ readonly kind: "program" | "selection" | "segment" | "moment";+ readonly id: string;};-export type StudioTemporalPointProjection = {- readonly kind: "point";+export type StudioTemporalAuthority =+ | {+ readonly kind: "semantic";+ readonly source: StudioTemporalSource;+ readonly boundary: "start" | "end" | "cue";+ }+ | {+ readonly kind: "parameter";+ readonly binding: string;+ readonly relation: "direct" | "after-start" | "before-end";+ }+ | { readonly kind: "fixed" };++export type StudioTemporalInstantProjection = {+ readonly kind: "instant";readonly expression: string;+ readonly reference:+ | "program.start" | "program.end"+ | "selection.start" | "selection.end"+ | "segment.start" | "segment.end"+ | "moment.cue" | "absolute";readonly frame: number;+ readonly source: StudioTemporalSource;+ readonly authority: StudioTemporalAuthority;};export type StudioTemporalWindowProjection = {readonly kind: "window";- readonly startExpression: string;- readonly endExpression: string;+ readonly start: StudioTemporalInstantProjection;+ readonly end: StudioTemporalInstantProjection;readonly startFrame: number;readonly endFrameExclusive: number;};-export type StudioTemporalProjection = StudioTemporalPointProjection | StudioTemporalWindowProjection;+export type StudioTemporalProjection = StudioTemporalInstantProjection | StudioTemporalWindowProjection;export type StudioTemporalPhase = {readonly id: string;@@ -64,8 +87,7 @@ export type StudioTemporalPhase = {};export type StudioTemporalLineage = {- readonly source: StudioTemporalSource;- readonly projection?: StudioTemporalProjection;+ readonly projection: StudioTemporalProjection;readonly phases: readonly StudioTemporalPhase[];};@@ -80,21 +102,24 @@ export type StudioTemporalConsumer = {readonly step: string;readonly producer: { readonly module: { readonly name: string; readonly version: string }; readonly name: string };readonly input: string;+ /** Projection plumbing is classified by Studio's graph reader, never by a Companion name guess. */+ readonly role: "projection" | "domain";readonly inputs: readonly StudioTemporalConsumerInput[];};-/** One executed Point/Window and the graph edges that consumed that exact record. */+/** One executed Instant/Window and the graph edges that consumed that exact record. */export type StudioTemporalBinding = {readonly record: string;- readonly specRecord?: string;- readonly specId?: string;+ readonly subjectId: string;readonly id: string;- readonly source: StudioTemporalSource;readonly projection: StudioTemporalProjection;readonly consumers: readonly StudioTemporalConsumer[];};-export type StudioParameterControl = "text" | "number" | "boolean" | "select" | "color" | "list" | "record";+export const studioParameterControls = [+ "text", "number", "boolean", "select", "color", "list", "record",+] as const;+export type StudioParameterControl = typeof studioParameterControls[number];export type StudioParameterLanguage = "svml" | "svs" | "svrun";/** A real author endpoint. Its existence never implies Inspector visibility. */@@ -110,6 +135,8 @@ export type StudioSourceBinding = {readonly language: StudioParameterLanguage;readonly writable: boolean;readonly source: {+ /** Exact compilation-local author endpoint when the Frontend supplied one. */+ readonly endpoint?: string;readonly path: string;readonly range: Range;readonly preimage: string;@@ -157,7 +184,7 @@ export type StudioInspectorField = Omit<StudioInspectorFieldDeclaration, "controreadonly source: StudioSourceBinding["source"];};-/** Adapter-owned source allowlist. It contains no editor presentation. */+/** Companion-owned source allowlist. It contains no editor presentation. */export type StudioSourceBindingDeclaration = {readonly name: string;readonly writable?: boolean;@@ -212,12 +239,14 @@ export type StudioEditSource = {export type StudioSemanticEditTarget =| {readonly kind: "selection";+ readonly narrativeId: string;readonly id: string;readonly startAnchorId: string;readonly endAnchorId: string;}| {readonly kind: "moment";+ readonly narrativeId: string;readonly id: string;readonly anchorId: string;};@@ -237,44 +266,11 @@ export type StudioEditHandle = {readonly sources?: readonly StudioEditSource[];/** Shared Script identity adjusted by this rectangle; every consumer follows it. */readonly semantic?: StudioSemanticEditTarget;+ /** Exact endpoint authority used to validate and execute this inverse. */+ readonly temporal?: StudioTemporalProjection;readonly disabledReason?: string;};-export type StudioTimelineEditParameter = {- readonly role: Extract<StudioEditSourceRole, "start" | "end" | "duration">;- /** Exact Companion-declared parameter vocabulary name. */- readonly parameter: string;-};--export type StudioTimelineEditTargetDeclaration =- | {- readonly kind: "semantic-source";- readonly source: "selection" | "moment";- readonly moveEffect?: "translate-window" | "move-start";- }- | {- readonly kind: "source-parameters";- readonly when: {- readonly source: StudioTemporalSource["kind"];- readonly projection?: StudioTemporalProjection["kind"];- };- readonly parameters: readonly StudioTimelineEditParameter[];- }- | {- readonly kind: "disabled";- readonly when: {- readonly source: StudioTemporalSource["kind"];- readonly projection?: StudioTemporalProjection["kind"];- };- readonly reason: string;- };--/** Companion-owned inverse choices for one Studio timeline gesture. */-export type StudioTimelineEditDeclaration = {- readonly gesture: StudioTimelineGesture;- readonly targets: readonly StudioTimelineEditTargetDeclaration[];-};-/** A source descriptor; Companion packages never depend on Studio's HTTP routes. */export type StudioPreviewSource =| { readonly kind: "artifact"; readonly digest: string }@@ -329,9 +325,9 @@ export type StudioCandidateProvenance = {export type StudioSemanticAnchor = {readonly id: string;- readonly kind: "segment-start" | "segment-end" | "token-start" | "token-end";+ readonly kind: "program-start" | "segment-start" | "segment-end" | "token-start" | "token-end" | "program-end";readonly frame: number;- readonly segmentId: string;+ readonly segmentId?: string;readonly tokenId?: string;};@@ -352,6 +348,8 @@ export type StudioSemanticToken = {};export type StudioSemanticTimeline = {+ readonly spaceId: string;+ readonly narrativeId: string;readonly presentation: {readonly family: StudioTrackFamily;readonly tone: StudioTimelineTone;@@ -384,6 +382,9 @@ export type StudioObservedValue = {};export type StudioPlacementChild = {+ /** Exact compilation-local author element identity from AuthorProvenance. */+ readonly authorElement?: string;+ readonly authorEndpoints?: Readonly<Record<string, string>>;readonly sourcePath: string;readonly tag: string;readonly id?: string;@@ -392,11 +393,18 @@ export type StudioPlacementChild = {readonly attributeValueRanges: Readonly<Record<string, Range>>;readonly references: readonly string[];readonly referenceAttributes: Readonly<Record<string, string>>;+ /** Resolved graph refs keyed by author input; raw written paths remain above. */+ readonly resolvedReferenceAttributes?: Readonly<Record<string, string>>;readonly referenceTypes: Readonly<Record<string, string>>;readonly values: readonly StudioObservedValue[];+ readonly records?: readonly string[];+ readonly outputs?: readonly string[];};export type StudioPlacement = {+ /** Exact compilation-local author element identity from AuthorProvenance. */+ readonly authorElement?: string;+ readonly authorEndpoints?: Readonly<Record<string, string>>;readonly sourcePath: string;readonly tag: string;readonly module: { readonly name: string; readonly version: string };@@ -411,6 +419,8 @@ export type StudioPlacement = {readonly attributes: Readonly<Record<string, string>>;readonly attributeValueRanges: Readonly<Record<string, Range>>;readonly referenceAttributes: Readonly<Record<string, string>>;+ /** Resolved graph refs keyed by author input; raw written paths remain above. */+ readonly resolvedReferenceAttributes?: Readonly<Record<string, string>>;readonly referenceTypes: Readonly<Record<string, string>>;readonly references: readonly string[];};@@ -418,29 +428,43 @@ export type StudioPlacement = {export type StudioTrackTrace = {readonly placement?: string;readonly surface?: string;- readonly module?: string;+ readonly module?: ModuleRef;readonly authoredId?: string;- readonly outputPorts: readonly { readonly name: string; readonly ref: string; readonly type?: string }[];- readonly references: readonly { readonly name: string; readonly ref: string; readonly type: string }[];+ readonly outputPorts: readonly {+ readonly name: string;+ readonly ref: string;+ readonly type?: string;+ readonly typeRef?: TypeRef;+ }[];+ readonly references: readonly {+ /** Exact authored input attribute when this is a direct Surface reference. */+ readonly input?: string;+ readonly name: string;+ readonly ref: string;+ readonly type: string;+ readonly typeRef: TypeRef;+ }[];};-/** Stable data view supplied to adapters; no Studio implementation object crosses the ABI. */+/** Stable data view supplied to Companions; no Studio implementation object crosses the ABI. */export type StudioResolvedTrack = {readonly name: string;+ /** Short display name retained for diagnostics and UI only. */readonly type: string;+ /** Exact protocol identity used for every Companion decision. */+ readonly typeRef: TypeRef;readonly outputRef: string;readonly candidateId?: string;readonly candidateOrigin: "run" | "source" | "none";- readonly role: StudioProjectionRole;+ readonly role: StudioViewRole;readonly trace: StudioTrackTrace;readonly surfacePreview?: StudioMaterialPreview;readonly value: unknown;};-export type StudioProjectionRole =- | "semantic-take"+export type StudioViewRole =| "semantic-track"- | "realization"+ | "supporting-value"| "track";export type StudioSpan = {@@ -469,11 +493,9 @@ export type StudioEntityDraft = {readonly temporal?: StudioTemporalLineage;/** Studio-local lane partition; omitted means the root lane. */readonly lane?: string;- /** Optional per-entity override of the owning lane's declared inverses. */- readonly timelineEdits?: readonly StudioTimelineEditDeclaration[];};-export type StudioAdapterContext = {+export type StudioTrackCompanionContext = {readonly track: StudioResolvedTrack;readonly placement?: StudioPlacement;/** Package-owned Surface preview resolved by Studio from the selected domain. */@@ -486,14 +508,14 @@ export type StudioAdapterContext = {readonly generic: () => readonly StudioEntityDraft[];};-export type StudioAdapter = {+export type StudioTrackCompanion = {readonly id: string;- readonly role: StudioProjectionRole;+ readonly role: StudioViewRole;readonly output: {- readonly type: string;+ readonly type: TypeRef;readonly surface?: string;- readonly modules?: readonly string[];- readonly siblingType?: string;+ readonly modules?: readonly ModuleRef[];+ readonly siblingType?: TypeRef;};readonly family?: StudioTrackFamily;/** Visual token selected from Studio's finite palette. */@@ -510,51 +532,155 @@ export type StudioAdapter = {readonly bindings?: readonly StudioSourceBindingDeclaration[];/** Visible field table. Undeclared bindings remain invisible. */readonly inspector?: readonly StudioInspectorFieldDeclaration[];- /** Exact inverse choices this adapter understands for its entities. */- readonly timelineEdits?: readonly StudioTimelineEditDeclaration[];- readonly project?: (context: StudioAdapterContext) => readonly StudioEntityDraft[];+ readonly project?: (context: StudioTrackCompanionContext) => readonly StudioEntityDraft[];};-export type StudioAdapterContribution = {- readonly format: "hypit.studio-adapters@1";- readonly adapters: readonly StudioAdapter[];+export type StudioCompanionContribution = {+ readonly format: "hypit.studio-companions@1";+ readonly tracks: readonly StudioTrackCompanion[];+ readonly films?: readonly StudioFilmCompanion[];+ readonly scripts?: readonly StudioScriptCompanion[];};-export type StudioAdapterHostFacet = HostFacet & {- readonly abi: typeof studioAdapterHostAbi;- readonly implementation: StudioAdapterContribution;+/** Declarative Film boundary. Studio follows only the references named here. */+export type StudioFilmCompanion = {+ readonly id: string;+ readonly match: {+ readonly module: ModuleRef;+ readonly surface: string;+ readonly outputType: TypeRef;+ };+ readonly semantic: { readonly attribute: string; readonly type: TypeRef };+ readonly tracks: {+ readonly childSurface: string;+ readonly sourceAttribute: string;+ readonly types: readonly TypeRef[];+ };};-export function createStudioAdapterHostFacet(adapters: readonly StudioAdapter[]): StudioAdapterHostFacet {+export type StudioScriptSourceMap = {+ readonly companion: string;+ readonly narrativeId: string;+ readonly sourcePath: string;+ readonly range: Range;+ readonly content: Range;+ readonly segments: readonly { readonly id: string; readonly range: Range }[];+ readonly selections: readonly {+ readonly id: string;+ readonly startAnchorId: string;+ readonly endAnchorId: string;+ readonly open: Range;+ readonly close: Range;+ }[];+ readonly moments: readonly { readonly id: string; readonly anchorId: string; readonly range: Range }[];+ readonly tokens: readonly { readonly id: string; readonly range: Range }[];+};++export type StudioScriptAdjustment =+ | { readonly kind: "selection"; readonly id: string; readonly startAnchorId: string; readonly endAnchorId: string }+ | { readonly kind: "moment"; readonly id: string; readonly anchorId: string };++/** Script grammar companion. It owns source observation and semantic inverse edits. */+export type StudioScriptCompanion = {+ readonly id: string;+ readonly match: { readonly module: ModuleRef; readonly surface: string };+ readonly observe: (input: {+ readonly sourceName: string;+ readonly source: string;+ readonly tag: string;+ readonly openingStart: number;+ readonly contentStart: number;+ /** Authoritative end returned by the raw Surface after it parsed its own grammar. */+ readonly nextOffset?: number;+ readonly attributes: Readonly<Record<string, unknown>>;+ }) => Omit<StudioScriptSourceMap, "companion"> | undefined;+ readonly adjust: (input: {+ readonly sourceName: string;+ readonly source: string;+ readonly adjustment: StudioScriptAdjustment;+ }) => string;+};++export type StudioCompanionHostFacet = HostFacet & {+ readonly abi: typeof studioCompanionHostAbi;+ readonly implementation: StudioCompanionContribution;+};++export function createStudioTrackCompanionHostFacet(tracks: readonly StudioTrackCompanion[]): StudioCompanionHostFacet {+ return {+ abi: studioCompanionHostAbi,+ implementation: { format: "hypit.studio-companions@1", tracks },+ };+}++export function createStudioCompanionHostFacet(input: {+ readonly tracks?: readonly StudioTrackCompanion[];+ readonly films?: readonly StudioFilmCompanion[];+ readonly scripts?: readonly StudioScriptCompanion[];+}): StudioCompanionHostFacet {return {- abi: studioAdapterHostAbi,- implementation: { format: "hypit.studio-adapters@1", adapters },+ abi: studioCompanionHostAbi,+ implementation: {+ format: "hypit.studio-companions@1",+ tracks: input.tracks ?? [],+ ...(input.films === undefined ? {} : { films: input.films }),+ ...(input.scripts === undefined ? {} : { scripts: input.scripts }),+ },};}+export type StudioPackageContribution = {+ readonly tracks: readonly StudioTrackCompanion[];+ readonly films: readonly StudioFilmCompanion[];+ readonly scripts: readonly StudioScriptCompanion[];+};++function qualify(owner: string, local: string, subject: string): string {+ if (local.length === 0 || local.includes("#")) {+ throw new Error(`${subject} ids are package-local names without '#': ${owner}#${local}`);+ }+ return `${owner}#${local}`;+}++export function studioContributionFromPackage(+ owner: string,+ facets: readonly HostFacet[],+): StudioPackageContribution {+ if (owner.length === 0 || owner.includes("#")) throw new Error(`Invalid Studio companion package identity: ${owner}`);+ const tracks: StudioTrackCompanion[] = [];+ const films: StudioFilmCompanion[] = [];+ const scripts: StudioScriptCompanion[] = [];+ for (const facet of facets) {+ if (facet.abi !== studioCompanionHostAbi) continue;+ const contribution = facet.implementation as Partial<StudioCompanionContribution>;+ if (contribution.format !== "hypit.studio-companions@1" || !Array.isArray(contribution.tracks)) {+ throw new Error(`Studio companion facet from ${owner} has an invalid contribution`);+ }+ tracks.push(...contribution.tracks.map((track) => ({+ ...track,+ id: qualify(owner, track.id, "Studio Track companion"),+ })));+ films.push(...(contribution.films ?? []).map((film) => ({+ ...film,+ id: qualify(owner, film.id, "Studio Film companion"),+ })));+ scripts.push(...(contribution.scripts ?? []).map((script) => ({+ ...script,+ id: qualify(owner, script.id, "Studio Script companion"),+ })));+ }+ return { tracks, films, scripts };+}+/**- * Qualify package-local adapter names with identity established by the package loader.+ * Qualify package-local Companion names with identity established by the package loader.* The executable facet cannot choose or impersonate its physical owner.*/-export function studioAdaptersFromPackage(+export function studioTrackCompanionsFromPackage(owner: string,facets: readonly HostFacet[],-): readonly StudioAdapter[] {- if (owner.length === 0 || owner.includes("#")) throw new Error(`Invalid Studio adapter package identity: ${owner}`);- return facets.flatMap((facet) => {- if (facet.abi !== studioAdapterHostAbi) return [];- const contribution = facet.implementation as Partial<StudioAdapterContribution>;- if (contribution.format !== "hypit.studio-adapters@1" || !Array.isArray(contribution.adapters)) {- throw new Error(`Studio adapter facet from ${owner} has an invalid contribution`);- }- return contribution.adapters.map((adapter) => {- if (adapter.id.length === 0 || adapter.id.includes("#")) {- throw new Error(`Studio adapter ids are package-local names without '#': ${owner}#${adapter.id}`);- }- // The Host, not executable package code, establishes the global identity.- return { ...adapter, id: `${owner}#${adapter.id}` };- });- });+): readonly StudioTrackCompanion[] {+ return studioContributionFromPackage(owner, facets).tracks;}export type StudioLaneAttachment = {@@ -567,89 +693,14 @@ export type StudioLaneAttachment = {readonly lane: StudioLaneDescription;readonly bindings?: readonly StudioSourceBindingDeclaration[];readonly inspector?: readonly StudioInspectorFieldDeclaration[];- readonly timelineEdits?: readonly StudioTimelineEditDeclaration[];};-/**- * Reusable declaration for a component that consumes an externalized Window.- * The Companion still binds the component's exact author parameter names.- */-export function projectedWindowTimelineEdits(input: {- readonly start: string;- readonly end: string;- readonly duration?: string;-}): readonly StudioTimelineEditDeclaration[] {- const programWindow = { source: "program" as const };- const momentWindow = { source: "moment" as const };- return [- {- gesture: "move",- targets: [- { kind: "semantic-source", source: "selection", moveEffect: "translate-window" },- { kind: "semantic-source", source: "moment", moveEffect: "translate-window" },- {- kind: "source-parameters", when: programWindow,- parameters: [{ role: "start", parameter: input.start }, { role: "end", parameter: input.end }],- },- ],- },- {- gesture: "trim-start",- targets: [- { kind: "semantic-source", source: "selection" },- { kind: "disabled", when: momentWindow, reason: "起点由 Moment 决定;移动实体可以改 Moment,但不能单独裁起点。" },- {- kind: "source-parameters", when: programWindow,- parameters: [{ role: "start", parameter: input.start }],- },- ],- },- {- gesture: "trim-end",- targets: [- { kind: "semantic-source", source: "selection" },- ...(input.duration === undefined ? [{- kind: "disabled" as const, when: momentWindow,- reason: "该 Moment 消费没有声明独立的 duration 参数。",- }] : [{- kind: "source-parameters" as const, when: momentWindow,- parameters: [{ role: "duration" as const, parameter: input.duration }],- }]),- {- kind: "source-parameters", when: programWindow,- parameters: [{ role: "end", parameter: input.end }],- },- ...(input.duration === undefined ? [] : [{- kind: "source-parameters" as const, when: programWindow,- parameters: [{ role: "duration" as const, parameter: input.duration }],- }]),- ],- },- ];-}--/** Reusable declaration for a component entity activated by an externalized Point. */-export function projectedPointTimelineEdits(): readonly StudioTimelineEditDeclaration[] {- return [{- gesture: "move",- targets: [{ kind: "semantic-source", source: "moment", moveEffect: "move-start" }],- }];-}--/** A Window whose only reversible author source is an external Selection. */-export function selectionWindowTimelineEdits(): readonly StudioTimelineEditDeclaration[] {- return (["move", "trim-start", "trim-end"] as const).map((gesture) => ({- gesture,- targets: [{ kind: "semantic-source", source: "selection" }],- }));-}--export function sameSurfaceValue(context: StudioAdapterContext, port: string): unknown {+export function sameSurfaceValue(context: StudioTrackCompanionContext, port: string): unknown {const ref = context.track.trace.outputPorts.find((candidate) => candidate.name === port)?.ref;return ref === undefined ? undefined : context.values.get(ref);}-export function requiredSurfaceValue(context: StudioAdapterContext, port: string): unknown {+export function requiredSurfaceValue(context: StudioTrackCompanionContext, port: string): unknown {const value = sameSurfaceValue(context, port);if (value === undefined) {throw new Error(`Studio Companion ${context.track.type} requires same-Surface value port ${port}`);@@ -657,6 +708,24 @@ export function requiredSurfaceValue(context: StudioAdapterContext, port: stringreturn value;}+/** Resolve one direct authored reference by input name and exact public TypeRef. */+export function requiredReferencedValue(+ context: StudioTrackCompanionContext,+ input: string,+ type: TypeRef,+): unknown {+ const found = context.track.trace.references.filter((reference) =>+ reference.input === input && sameType(reference.typeRef, type));+ if (found.length !== 1) {+ throw new Error(`Studio Companion ${context.track.type} requires one ${input} reference of type ${type.module.name}@${type.module.version}#${type.name}`);+ }+ const value = context.values.get(found[0]!.ref);+ if (value === undefined) {+ throw new Error(`Studio Companion ${context.track.type} cannot resolve referenced value ${found[0]!.ref}`);+ }+ return value;+}+export function artifactPreview(kind: StudioMaterialPreview["kind"],digest: string,@@ -676,37 +745,74 @@ export function textLayer(text: string): StudioDisplayLayer {return { kind: "text", role: "content", text };}-function carriesIdentity(value: unknown, id: string): boolean {- return value !== null && typeof value === "object"- && !Array.isArray(value) && (value as { readonly id?: unknown }).id === id;-}--/** Find executed projections directly consumed beside a domain value with this identity. */+/** Find the executed projection that explicitly names this domain entity as its subject. */export function temporalBindingsFor(- context: StudioAdapterContext,+ context: StudioTrackCompanionContext,subjectId: string,input?: string,): readonly StudioTemporalBinding[] {- return context.temporalBindings.filter((binding) => binding.consumers.some((consumer) =>- (input === undefined || consumer.input === input)- && consumer.inputs.some((candidate) => carriesIdentity(candidate.value, subjectId))));+ return context.temporalBindings.filter((binding) =>+ binding.subjectId === subjectId+ && binding.consumers.some((consumer) =>+ consumer.role === "domain"+ && (input === undefined || consumer.input === input)));+}++/** Find the exact authored child whose typed public value owns a projected identity. */+export function authoredChildFor(+ context: StudioTrackCompanionContext,+ authoredId: string,+ types: readonly TypeRef[],+): StudioPlacementChild | undefined {+ const children = context.placement?.children ?? [];+ const explicit = children.filter((child) => child.id === authoredId);+ const typed = children.filter((child) => child.values.some((observed) =>+ types.some((type) => sameType(observed.type, type))+ && observed.value !== null+ && typeof observed.value === "object"+ && !Array.isArray(observed.value)+ && (observed.value as { readonly id?: unknown }).id === authoredId));+ const found = [...new Set([...explicit, ...typed])];+ if (found.length > 1) throw new Error(`Studio authored child identity ${authoredId} is ambiguous.`);+ return found[0];}export function temporalLineageFor(- context: StudioAdapterContext,+ context: StudioTrackCompanionContext,subjectId: string,input?: string,): StudioTemporalLineage | undefined {- const found = temporalBindingsFor(context, subjectId, input)[0];- return found === undefined ? undefined : {- source: found.source,- projection: found.projection,+ const found = temporalBindingsFor(context, subjectId, input);+ if (found.length > 1) {+ throw new Error(`Studio Temporal lineage is ambiguous for ${subjectId}${input === undefined ? "" : ` at ${input}`}.`);+ }+ const binding = found[0];+ return binding === undefined ? undefined : {+ projection: binding.projection,phases: [],};}+/** Unique semantic author identity carried by one projection, when there is one. */+export function temporalSemanticSource(lineage: StudioTemporalLineage | undefined): StudioTemporalSource | undefined {+ if (lineage === undefined) return undefined;+ const projection = lineage.projection;+ const endpoints = projection.kind === "instant" ? [projection] : [projection.start, projection.end];+ const semantic = endpoints.flatMap((endpoint) => endpoint.authority.kind === "semantic"+ ? [endpoint.authority.source]+ : []);+ const first = semantic[0];+ if (first === undefined) return undefined;+ return semantic.every((candidate) => candidate.kind === first.kind+ && candidate.id === first.id+ && candidate.spaceId === first.spaceId+ && candidate.narrativeId === first.narrativeId)+ ? first+ : undefined;+}+export function childEntities(- context: StudioAdapterContext,+ context: StudioTrackCompanionContext,items: readonly {/** Exact identity of the projected domain item consumed by Temporal/renderer bindings. */readonly id: string;@@ -715,15 +821,15 @@ export function childEntities(readonly startFrame: number;readonly endFrameExclusive: number;readonly stackOrder: number;+ /** Exact domain Spec types that may carry an omitted Source id. */+ readonly sourceTypes?: readonly TypeRef[];}[],entity: StudioTimelinePresentation["entity"],chrome: StudioTimelinePresentation["chrome"],): readonly StudioEntityDraft[] {- const children = new Map(context.placement?.children.flatMap((child) =>- child.id === undefined ? [] : [[child.id, child] as const]) ?? []);return items.map((item) => {const authoredId = item.subjectId ?? item.id;- const child = children.get(authoredId);+ const child = authoredChildFor(context, authoredId, item.sourceTypes ?? []);// Both correspondences are exact public facts: the Program item identity// and the renderer's declared subject. No renderer naming convention is// interpreted here.diff --git a/packages/studio-adapter/test/identity.test.ts b/packages/studio-adapter/test/identity.test.tsnew file mode 100644index 00000000..2c1c055c--- /dev/null+++ b/packages/studio-adapter/test/identity.test.ts@@ -0,0 +1,24 @@+import assert from "node:assert/strict";+import test from "node:test";++import { authoredChildFor } from "../src/index.js";+import type { StudioTrackCompanionContext } from "../src/index.js";++const itemType = { module: { name: "@example/media", version: "1" }, name: "ItemSpec" } as const;++test("typed child values recover an omitted authored id without ordinal guessing", () => {+ const child = {+ sourcePath: "main.svml", tag: "Item", range: { start: 10, end: 40 },+ attributes: {}, attributeValueRanges: {}, references: [], referenceAttributes: {}, referenceTypes: {},+ values: [{ id: "track.item.0001.spec", type: itemType, value: { id: "track.item.0001" } }],+ };+ const context = {+ placement: {+ sourcePath: "main.svml", tag: "Track", module: itemType.module, surface: "track", id: "track",+ range: { start: 0, end: 50 }, records: [], values: [], outputs: [], outputPorts: [], children: [child],+ attributes: {}, attributeValueRanges: {}, references: [], referenceAttributes: {}, referenceTypes: {},+ },+ } as unknown as StudioTrackCompanionContext;+ assert.equal(authoredChildFor(context, "track.item.0001", [itemType]), child);+ assert.equal(authoredChildFor(context, "track.item.0001", [{ ...itemType, module: { ...itemType.module, version: "2" } }]), undefined);+});diff --git a/packages/studio/README.md b/packages/studio/README.mdindex 5c2e636a..b9b35abe 100644--- a/packages/studio/README.md+++ b/packages/studio/README.md@@ -24,14 +24,14 @@ work while Tasks and Artifacts stay explicitly unavailable.Studio is an application boundary. Core and domain packages do not import it orregister UI metadata. The installed Distribution explicitly selects one independent-Studio Companion per supported official domain. An external project may add companion Adapter packages+Studio Companion per supported official domain. An external project may add Companion packagesthrough `hypit.studio.json`; the application assembles one immutable registry forthat project session.```json{"format": "hypit.studio-profile@1",- "adapterPackages": ["@my-project/local-example-studio"]+ "companionPackages": ["@my-project/local-example-studio"]}```@@ -53,7 +53,7 @@ source binding is never shown merely because Studio can reach it. Material layerArtifact digest or Surface identity, never a Studio HTTP URL. Studio always ownstime formatting and transport resolution, so chrome and material cannot hide atitle or its time.-Studio owns session-wide behavior and chrome: adapter selection, collision and+Studio owns session-wide behavior and chrome: Companion selection, collision andreplacement rules, fallback defaults, selection treatment, playback, zoom,scrolling, the finite Inspector control set and source mutation transport. Acompanion cannot ship arbitrary DOM or CSS into the application.@@ -71,10 +71,10 @@ the Studio menu and keyboard navigation. Values still commit only on anexplicit change through the normal revisioned mutation path.Temporal lineage comes from the exact executed graph selected by the Run. Studio indexes the-`TemporalPoint` and `TemporalWindow` records in each Track's dependency closure together with their-projection Spec and direct consumer edge, then passes that stable data view to adapters. Adapters-never infer a semantic source from SVML attribute names, Spec type names, runtime id prefixes or-coincident frame spans. Point and Window remain distinct in the inspector.+`TemporalInstant` and `TemporalWindow` records in each Track's dependency closure, including each+endpoint's author authority and direct consumer edge. Common timeline inverses come from that+authority rather than Companion declarations. Track Companions never infer semantic sources from SVML+attribute names, runtime id prefixes or coincident frame spans.Opening Studio never invokes a Provider and never creates a Build. Everyprojection needed for display must already be supplied by the Run or bediff --git a/packages/studio/package.json b/packages/studio/package.jsonindex a470edeb..c7fe91e2 100644--- a/packages/studio/package.json+++ b/packages/studio/package.json@@ -19,9 +19,11 @@"@hypit/driver-node": "workspace:*","@hypit/deck-track-studio": "workspace:*","@hypit/elaborator": "workspace:*",+ "@hypit/film-studio": "workspace:*","@hypit/hyperframes": "workspace:*","@hypit/markup": "workspace:*","@hypit/media-track-studio": "workspace:*",+ "@hypit/narrative": "workspace:*","@hypit/package-loader-node": "workspace:*","@hypit/program-space": "workspace:*","@hypit/protocol": "workspace:*",@@ -29,10 +31,12 @@"@hypit/run": "workspace:*","@hypit/runtime": "workspace:*","@hypit/runtime-host-node": "workspace:*",- "@hypit/script": "workspace:*",+ "@hypit/script-studio": "workspace:*","@hypit/screen-overlay-studio": "workspace:*",+ "@hypit/speech": "workspace:*","@hypit/semantic-track": "workspace:*","@hypit/svs": "workspace:*",+ "@hypit/temporal": "workspace:*","@hypit/studio-adapter": "workspace:*","@hypit/speech-track-studio": "workspace:*","@hypit/typography-track-studio": "workspace:*",diff --git a/packages/studio/preview-check.ts b/packages/studio/preview-check.tsindex fcc6c895..3e702f93 100644--- a/packages/studio/preview-check.ts+++ b/packages/studio/preview-check.ts@@ -4,7 +4,7 @@ import { dirname, resolve } from "node:path";import { videoCliDistribution } from "@hypit/video-cli";import { openStudioArchive } from "./src/archive.js";-import { loadStudioAdapterRegistry } from "./src/adapter-profile.js";+import { loadStudioCompanionRegistry } from "./src/companion-profile.js";import { loadStudioDomain } from "./src/domain.js";import { loadStudioRun } from "./src/run.js";import { readStudioSession } from "./src/session.js";@@ -24,7 +24,7 @@ if (runArgument === undefined) {const distributionPackageRoot = videoCliDistribution.packageRoot;if (distributionPackageRoot === undefined) throw new Error("active Hypit Distribution has no package root");- const registry = await loadStudioAdapterRegistry({ workspaceRoot, packageRoot, distributionPackageRoot });+ const registry = await loadStudioCompanionRegistry({ workspaceRoot, packageRoot, distributionPackageRoot });const domain = await loadStudioDomain({ run: runPath, workspaceRoot, packageRoot });const archive = await openStudioArchive(runtimePath, packageRoot, workspaceRoot, distributionPackageRoot);const awaitingPrefix = "the Studio projection closure requires unresolved capabilities:";@@ -36,6 +36,7 @@ if (runArgument === undefined) {const run = await loadStudioRun({run: runPath,domain,+ registry,...(archive === undefined ? {} : { archive }),});inspectStudioRun(registry, run.source, run);diff --git a/packages/studio/src/adapter-profile.ts b/packages/studio/src/companion-profile.tssimilarity index 51%rename from packages/studio/src/adapter-profile.tsrename to packages/studio/src/companion-profile.tsindex 91a5db9e..08488b7e 100644--- a/packages/studio/src/adapter-profile.ts+++ b/packages/studio/src/companion-profile.ts@@ -2,20 +2,22 @@ import { readFile } from "node:fs/promises";import { resolve } from "node:path";import { installDistributionPackageResolution, loadNodePackageSelection } from "@hypit/package-loader-node";-import { studioAdaptersFromPackage } from "@hypit/studio-adapter";-import type { StudioAdapter } from "@hypit/studio-adapter";+import { studioContributionFromPackage } from "@hypit/studio-adapter";+import type { StudioTrackCompanion, StudioFilmCompanion, StudioScriptCompanion } from "@hypit/studio-adapter";-import { fallbackStudioAdapters } from "./fallback-adapters.js";-import { StudioAdapterRegistry } from "./studio-registry.js";+import { fallbackStudioTrackCompanions } from "./fallback-companions.js";+import { StudioCompanionRegistry } from "./studio-registry.js";-export const officialStudioAdapterPackages = [+export const officialStudioCompanionPackages = ["@hypit/audio-track-studio","@hypit/caption-fine-studio","@hypit/comment-sticker-studio","@hypit/deck-track-studio",+ "@hypit/film-studio","@hypit/media-track-studio","@hypit/ranking-studio","@hypit/screen-overlay-studio",+ "@hypit/script-studio","@hypit/speech-track-studio","@hypit/typography-track-studio",] as const;@@ -24,7 +26,7 @@ export const studioProfileFilename = "hypit.studio.json";export type StudioProfile = {readonly format: "hypit.studio-profile@1";- readonly adapterPackages: readonly string[];+ readonly companionPackages: readonly string[];readonly replace: Readonly<Record<string, string>>;};@@ -40,33 +42,35 @@ function parseStudioProfile(value: unknown, path: string): StudioProfile {if (item.format !== "hypit.studio-profile@1") {throw new Error(`${path} has unsupported format ${String(item.format)}`);}- if (!Array.isArray(item.adapterPackages)- || item.adapterPackages.some((entry) => typeof entry !== "string" || entry.length === 0)) {- throw new Error(`${path}.adapterPackages must be an array of installed package names`);+ if (!Array.isArray(item.companionPackages)+ || item.companionPackages.some((entry) => typeof entry !== "string" || entry.length === 0)) {+ throw new Error(`${path}.companionPackages must be an array of installed package names`);}- const adapterPackages = item.adapterPackages as string[];- if (new Set(adapterPackages).size !== adapterPackages.length) {- throw new Error(`${path}.adapterPackages repeats a package`);+ const companionPackages = item.companionPackages as string[];+ if (new Set(companionPackages).size !== companionPackages.length) {+ throw new Error(`${path}.companionPackages repeats a package`);}const rawReplace = item.replace === undefined ? {} : object(item.replace, `${path}.replace`);const replace: Record<string, string> = {};for (const [target, replacement] of Object.entries(rawReplace)) {if (target.length === 0 || typeof replacement !== "string" || replacement.length === 0) {- throw new Error(`${path}.replace must map adapter ids to adapter ids`);+ throw new Error(`${path}.replace must map companion ids to companion ids`);}replace[target] = replacement;}- return { format: "hypit.studio-profile@1", adapterPackages, replace };+ return { format: "hypit.studio-profile@1", companionPackages, replace };}-/** Read only the explicit project profile. A missing conventional profile means no project adapters. */-export async function loadProjectStudioAdapters(input: {+/** Read only the explicit project profile. A missing conventional profile means no project Companions. */+export async function loadProjectStudioCompanions(input: {readonly workspaceRoot: string;readonly packageRoot: string;readonly distributionPackageRoot?: string;readonly profile?: string;}): Promise<{- readonly adapters: readonly StudioAdapter[];+ readonly tracks: readonly StudioTrackCompanion[];+ readonly films: readonly StudioFilmCompanion[];+ readonly scripts: readonly StudioScriptCompanion[];readonly replace: Readonly<Record<string, string>>;readonly profile?: string;}> {@@ -76,44 +80,56 @@ export async function loadProjectStudioAdapters(input: {text = await readFile(path, "utf8");} catch (error) {if (input.profile === undefined && error instanceof Error && "code" in error && error.code === "ENOENT") {- return { adapters: [], replace: {} };+ return { tracks: [], films: [], scripts: [], replace: {} };}throw error;}const profile = parseStudioProfile(JSON.parse(text), path);- const packages = await loadNodePackageSelection(profile.adapterPackages, input.packageRoot, {+ const packages = await loadNodePackageSelection(profile.companionPackages, input.packageRoot, {...(input.distributionPackageRoot === undefined? {}: { fallbackRoots: [input.distributionPackageRoot] }),});const bySpecifier = new Map(packages.map((item) => [item.specifier, item] as const));- const adapters = profile.adapterPackages.flatMap((specifier) => {+ const contributions = profile.companionPackages.map((specifier) => {const item = bySpecifier.get(specifier);- if (item === undefined) throw new Error(`${path} did not resolve selected Studio adapter package ${specifier}`);- const found = studioAdaptersFromPackage(item.specifier, item.contribution.hostFacets ?? []);- if (found.length === 0) throw new Error(`${path} selects ${item.specifier}, which provides no hypit.studio-adapter@1 facet`);+ if (item === undefined) throw new Error(`${path} did not resolve selected Studio companion package ${specifier}`);+ const found = studioContributionFromPackage(item.specifier, item.contribution.hostFacets ?? []);+ if (found.tracks.length + found.films.length + found.scripts.length === 0) {+ throw new Error(`${path} selects ${item.specifier}, which provides no Studio Companion facet`);+ }return found;});- return { adapters, replace: profile.replace, profile: path };+ return {+ tracks: contributions.flatMap((item) => item.tracks),+ films: contributions.flatMap((item) => item.films),+ scripts: contributions.flatMap((item) => item.scripts),+ replace: profile.replace,+ profile: path,+ };}/** Assemble the one immutable Registry shared by preflight, snapshot and UI for this session. */-export async function loadStudioAdapterRegistry(input: {+export async function loadStudioCompanionRegistry(input: {readonly workspaceRoot: string;readonly packageRoot: string;readonly distributionPackageRoot: string;readonly profile?: string;-}): Promise<StudioAdapterRegistry> {+}): Promise<StudioCompanionRegistry> {installDistributionPackageResolution([input.distributionPackageRoot]);const officialPackages = await loadNodePackageSelection(- officialStudioAdapterPackages,+ officialStudioCompanionPackages,input.distributionPackageRoot,);- const officialAdapters = officialPackages.flatMap((item) =>- studioAdaptersFromPackage(item.specifier, item.contribution.hostFacets ?? []));- const project = await loadProjectStudioAdapters(input);- return new StudioAdapterRegistry(- [...fallbackStudioAdapters, ...officialAdapters, ...project.adapters],- { replace: project.replace },+ const official = officialPackages.map((item) =>+ studioContributionFromPackage(item.specifier, item.contribution.hostFacets ?? []));+ const project = await loadProjectStudioCompanions(input);+ return new StudioCompanionRegistry(+ [...fallbackStudioTrackCompanions, ...official.flatMap((item) => item.tracks), ...project.tracks],+ {+ replace: project.replace,+ films: [...official.flatMap((item) => item.films), ...project.films],+ scripts: [...official.flatMap((item) => item.scripts), ...project.scripts],+ },);}diff --git a/packages/studio/src/compile.ts b/packages/studio/src/compile.tsindex b0858a7e..d8292a58 100644--- a/packages/studio/src/compile.ts+++ b/packages/studio/src/compile.ts@@ -1,7 +1,10 @@import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";+import type { AuthorElementProvenance, AuthorValueRef } from "@hypit/elaborator";import type { ArtifactAttachment } from "@hypit/workspace";+import type { TypeRef } from "@hypit/protocol";import type { Observations } from "./observe.js";+import type { Placement } from "./observe.js";export type ServedFile = {readonly mediaType: string;@@ -13,7 +16,12 @@ export type CompiledSource = {readonly compiled: NodeCompiledSourceClosure;readonly observations: Observations;readonly served: ReadonlyMap<string, ServedFile>;- readonly exports: readonly { readonly name: string; readonly type: string; readonly ref: string }[];+ readonly exports: readonly {+ readonly name: string;+ readonly type: string;+ readonly typeRef: TypeRef;+ readonly ref: string;+ }[];};/**@@ -32,17 +40,114 @@ export async function observedCompiledSource(bytes: await bytesOf(attachment),});}+ const normalized = normalizeObservations(compiled, observations);+ const names = new Map(compiled.provenance.elements.flatMap((element) =>+ element.outputs.map((output) => [output.id, output.local] as const)));return {compiled,- observations,+ observations: normalized,served,- exports: compiled.exports.flatMap((item) => {- if (!("id" in item.ref)) return [];- return [{ name: item.name, type: item.type.name, ref: item.ref.id }];- }),+ exports: compiled.graph.outputs.map((item) => ({+ name: compiled.exports.find((candidate) => "id" in candidate.ref && candidate.ref.id === item.id)?.name+ ?? names.get(item.id)+ ?? item.id,+ type: item.type.name,+ typeRef: item.type,+ ref: item.id,+ })),};}+function sameRange(+ left: { readonly start: number; readonly end: number },+ right: { readonly start: number; readonly end: number },+): boolean {+ return left.start === right.start && left.end === right.end;+}++function exactElement(+ compiled: NodeCompiledSourceClosure,+ sourcePath: string,+ range: { readonly start: number; readonly end: number },+): AuthorElementProvenance | undefined {+ return compiled.provenance.elements.find((element) =>+ element.sourceName === sourcePath && sameRange(element.range, range));+}++function resolvedRef(compiled: NodeCompiledSourceClosure, ref: AuthorValueRef): string | undefined {+ if (ref.kind === "record") return ref.id;+ return compiled.provenance.elements.flatMap((element) => element.outputs)+ .find((output) => output.component === ref.component && output.name === ref.output)?.id;+}++function decorate(+ compiled: NodeCompiledSourceClosure,+ sourcePath: string,+ range: { readonly start: number; readonly end: number },+): {+ readonly element?: AuthorElementProvenance;+ readonly records: ReadonlyMap<string, string>;+ readonly outputs: ReadonlyMap<string, string>;+ readonly references: Readonly<Record<string, string>>;+ readonly endpoints: Readonly<Record<string, string>>;+} {+ const element = exactElement(compiled, sourcePath, range);+ if (element === undefined) {+ return { records: new Map(), outputs: new Map(), references: {}, endpoints: {} };+ }+ return {+ element,+ records: new Map(element.records.map((record) => [record.local, record.id] as const)),+ outputs: new Map(element.outputs.map((output) => [output.local, output.id] as const)),+ references: Object.fromEntries(element.inputs.flatMap((input) => {+ if (input.ref === undefined) return [];+ const ref = resolvedRef(compiled, input.ref);+ return ref === undefined ? [] : [[input.name, ref]];+ })),+ endpoints: Object.fromEntries(element.inputs.map((input) => [input.name, input.id])),+ };+}++/** Join Studio presentation to compiler-owned identities without re-matching authored names. */+function normalizeObservations(+ compiled: NodeCompiledSourceClosure,+ observations: Observations,+): Observations {+ const placements: Placement[] = observations.placements.map((placement) => {+ const own = decorate(compiled, placement.sourcePath, placement.range);+ return {+ ...placement,+ ...(own.element === undefined ? {} : {+ authorElement: own.element.id,+ authorEndpoints: own.endpoints,+ resolvedReferenceAttributes: own.references,+ records: placement.records.map((id) => own.records.get(id) ?? id),+ outputs: placement.outputs.map((id) => own.outputs.get(id) ?? id),+ outputPorts: placement.outputPorts.map((port) => ({+ ...port,+ ref: own.outputs.get(port.ref) ?? port.ref,+ })),+ values: placement.values.map((value) => ({ ...value, id: own.records.get(value.id) ?? value.id })),+ }),+ children: placement.children.map((child) => {+ const held = decorate(compiled, child.sourcePath, child.range);+ return {+ ...child,+ ...(held.element === undefined ? {} : {+ authorElement: held.element.id,+ authorEndpoints: held.endpoints,+ resolvedReferenceAttributes: held.references,+ records: [...held.records.values()],+ outputs: [...held.outputs.values()],+ values: child.values.map((value) => ({ ...value, id: held.records.get(value.id) ?? value.id })),+ }),+ };+ }),+ };+ });+ return { placements, sourceMaps: observations.sourceMaps };+}+async function bytesOf(attachment: ArtifactAttachment): Promise<Uint8Array> {const chunks: Uint8Array[] = [];let size = 0;diff --git a/packages/studio/src/fallback-adapters.ts b/packages/studio/src/fallback-companions.tssimilarity index 72%rename from packages/studio/src/fallback-adapters.tsrename to packages/studio/src/fallback-companions.tsindex 2234c966..4834b325 100644--- a/packages/studio/src/fallback-adapters.ts+++ b/packages/studio/src/fallback-companions.ts@@ -1,5 +1,7 @@-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft } from "@hypit/studio-adapter";-import { artifactPreview, previewLayer, temporalLineageFor } from "@hypit/studio-adapter";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft } from "@hypit/studio-adapter";+import { artifactPreview, previewLayer, temporalLineageFor, temporalSemanticSource } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import { semanticTrackTypes } from "@hypit/semantic-track";type TerminalVisualTrack = {readonly presents?: readonly {@@ -21,28 +23,22 @@ type TerminalAudioTrack = {};function withTemporalLineage(- context: StudioAdapterContext,+ context: StudioTrackCompanionContext,entity: StudioEntityDraft,): StudioEntityDraft {- const identities = [- entity.authoredId,- entity.markerId,- entity.presentId,- ...(entity.renderIds ?? []),- ].filter((value): value is string => value !== undefined);- const temporal = identities.map((identity) => temporalLineageFor(context, identity))- .find((candidate) => candidate !== undefined);+ const temporal = temporalLineageFor(context, entity.authoredId);if (temporal === undefined) return entity;+ const semanticSource = temporalSemanticSource(temporal);return {...entity,- ...(temporal.source.kind === "program" || temporal.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),temporal,};}-function projectTerminalVisual(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectTerminalVisual(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const presents = new Map(((context.track.value as TerminalVisualTrack).presents ?? []).map((present) => [present.id, present] as const));return context.generic().map((entity) => {@@ -62,7 +58,7 @@ function projectTerminalVisual(context: StudioAdapterContext): readonly StudioEn});}-function projectTerminalAudio(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectTerminalAudio(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const clips = new Map(((context.track.value as TerminalAudioTrack).clips ?? []).map((clip) => [clip.id, clip] as const));return context.generic().map((entity, index) => {@@ -81,21 +77,20 @@ function projectTerminalAudio(context: StudioAdapterContext): readonly StudioEnt}/** Cross-domain terminal protocols understood even when no Companion is installed. */-export const fallbackStudioAdapters: readonly StudioAdapter[] = [- { id: "@hypit/studio#semantic-take", role: "semantic-take", output: { type: "SemanticTake" } },+export const fallbackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{- id: "@hypit/studio#semantic-track", role: "semantic-track", output: { type: "SemanticTrack" },+ id: "@hypit/studio#semantic-track", role: "semantic-track", output: { type: semanticTrackTypes.track },family: "semantic", tone: "teal", label: "Semantic", icon: "brand",lane: { heightPx: 45 },},{- id: "@hypit/studio#audio-track", role: "track", output: { type: "AudioTrack" },+ id: "@hypit/studio#audio-track", role: "track", output: { type: compositionTypes.audioTrack },family: "audio", tone: "green", icon: "waveform",project: projectTerminalAudio,lane: { heightPx: 48 },},{- id: "@hypit/studio#visual-track", role: "track", output: { type: "VisualTrack" },+ id: "@hypit/studio#visual-track", role: "track", output: { type: compositionTypes.visualTrack },family: "media", tone: "blue", icon: "video",project: projectTerminalVisual,lane: { heightPx: 76 },diff --git a/packages/studio/src/observe.ts b/packages/studio/src/observe.tsindex a5b838bc..56130ec6 100644--- a/packages/studio/src/observe.ts+++ b/packages/studio/src/observe.ts@@ -11,10 +11,10 @@ import type {MarkupSurfaceRegistryLike, RegisteredSurface, StructuredElement, StructuredSurfaceInput, SurfaceDecodeOutput,} from "@hypit/markup";import type { ModuleRef } from "@hypit/protocol";-import { parseScript } from "@hypit/script";-import type { StudioObservedValue, StudioPlacement } from "@hypit/studio-adapter";+import type { StudioObservedValue, StudioPlacement, StudioScriptSourceMap } from "@hypit/studio-adapter";import type { Range } from "./shared.js";+import type { StudioCompanionRegistry } from "./studio-registry.js";export type ObservedValue = StudioObservedValue;@@ -24,7 +24,7 @@ export type Placement = StudioPlacement;export type Observations = {readonly placements: readonly Placement[];/** Whatever the Surfaces mapped back onto the Source, such as a Script's markers. */- readonly sourceMaps: readonly Record<string, unknown>[];+ readonly sourceMaps: readonly StudioScriptSourceMap[];};export type Observer = {@@ -68,10 +68,10 @@ function referenceAttributes(element: StructuredElement): Record<string, string>export function createObserver(surfaces: MarkupSurfaceRegistryLike,- resolveModule: (request: { readonly from: string }) => ModuleRef,+ registry: StudioCompanionRegistry,): Observer {const placements: Placement[] = [];- const sourceMaps: Record<string, unknown>[] = [];+ const sourceMaps: StudioScriptSourceMap[] = [];// A Frontend may reach a Surface by name or by walking a module's whole list,// so both ways in are wrapped: an unwatched Surface decodes silently and the@@ -86,7 +86,15 @@ export function createObserver(...found,async handler(input: RawInput) {const output = await raw(input);- harvestScript(input, sourceMaps);+ const nextOffset = typeof output === "object" && output !== null+ && Number.isInteger((output as { readonly nextOffset?: unknown }).nextOffset)+ ? (output as { readonly nextOffset: number }).nextOffset+ : undefined;+ const sourceMap = registry.observeScript(module, found.surface, {+ ...input,+ ...(nextOffset === undefined ? {} : { nextOffset }),+ });+ if (sourceMap !== undefined) sourceMaps.push(sourceMap);return output;},} as RegisteredSurface;@@ -192,51 +200,3 @@ type RawInput = {readonly contentStart: number;readonly attributes: Readonly<Record<string, unknown>>;};--/**- * Where a Script wrote its markers.- *- * The compiler carries no Source map, and a Script is a raw Surface that parses- * its own body, so the same parser is asked again for the one thing the compile- * discards: the offsets. Nothing is decoded here that the package does not- * decode itself.- */-function harvestScript(input: RawInput, into: Record<string, unknown>[]): void {- if (input.tag.split(":").at(-1) !== "script") return;- const id = input.attributes.id;- if (typeof id !== "string") return;- const closing = `</${input.tag}>`;- const end = input.source.indexOf(closing, input.contentStart);- if (end < 0) return;- try {- const parsed = parseScript(- input.sourceName,- input.source.slice(input.contentStart, end),- input.contentStart,- );- into.push({- format: "hypit.script-source-map@1",- record: id,- sourcePath: input.sourceName,- range: { start: input.openingStart, end: end + closing.length },- content: { start: input.contentStart, end },- segments: parsed.segments.map((segment) => ({ id: segment.id, range: segment.range })),- selections: parsed.selections.map((selection) => ({- id: selection.id,- startAnchorId: selection.startAnchorId,- endAnchorId: selection.endAnchorId,- open: selection.open.range,- close: selection.close.range,- })),- moments: parsed.moments.map((moment) => ({- id: moment.id,- anchorId: moment.anchorId,- range: moment.range,- })),- tokens: parsed.tokens.map((token) => ({ id: token.id, range: token.range })),- });- } catch {- // A Script the parser refuses is a Source that will not compile either, and- // the compile is what should report it.- }-}diff --git a/packages/studio/src/parameters.ts b/packages/studio/src/parameters.tsindex ed2844b6..72ceccb3 100644--- a/packages/studio/src/parameters.ts+++ b/packages/studio/src/parameters.ts@@ -8,11 +8,13 @@ import type {StudioParameterControl,StudioRecipeReferenceBindingDeclaration,StudioEntityDraft,+ StudioEditSource,StudioPlacement,StudioEditHandle,StudioSemanticTimeline,+ StudioTemporalInstantProjection,StudioTemporalLineage,- StudioTimelineEditDeclaration,+ StudioTimelineGesture,} from "@hypit/studio-adapter";import { parseSvs } from "@hypit/svs";@@ -28,27 +30,42 @@ export type StudioSourceFile = {};type AuthorElement = {+ readonly authorElement?: string;+ readonly authorEndpoints: Readonly<Record<string, string>>;readonly id?: string;readonly sourcePath: string;readonly attributes: Readonly<Record<string, string>>;readonly references: Readonly<Record<string, string>>;+ readonly resolvedReferences: Readonly<Record<string, string>>;+ readonly records: readonly string[];+ readonly outputs: readonly string[];readonly attributeValueRanges: Readonly<Record<string, Range>>;};function authoredElements(placements: readonly Placement[]): readonly AuthorElement[] {return placements.flatMap((placement) => [{+ ...(placement.authorElement === undefined ? {} : { authorElement: placement.authorElement }),+ authorEndpoints: placement.authorEndpoints ?? {},...(placement.id === undefined ? {} : { id: placement.id }),sourcePath: placement.sourcePath,attributes: placement.attributes,references: placement.referenceAttributes,+ resolvedReferences: placement.resolvedReferenceAttributes ?? {},+ records: placement.records,+ outputs: placement.outputs,attributeValueRanges: placement.attributeValueRanges,},...placement.children.map((child) => ({+ ...(child.authorElement === undefined ? {} : { authorElement: child.authorElement }),+ authorEndpoints: child.authorEndpoints ?? {},...(child.id === undefined ? {} : { id: child.id }),sourcePath: child.sourcePath,attributes: child.attributes,references: child.referenceAttributes,+ resolvedReferences: child.resolvedReferenceAttributes ?? {},+ records: child.records ?? [],+ outputs: child.outputs ?? [],attributeValueRanges: child.attributeValueRanges,})),]);@@ -61,17 +78,27 @@ function sameRange(left: Range | undefined, right: Range | undefined): boolean {function elementFor(placement: StudioPlacement, draft: StudioEntityDraft): AuthorElement | undefined {const candidates: readonly (AuthorElement & { readonly id?: string; readonly range: Range })[] = [{+ ...(placement.authorElement === undefined ? {} : { authorElement: placement.authorElement }),+ authorEndpoints: placement.authorEndpoints ?? {},sourcePath: placement.sourcePath,attributes: placement.attributes,references: placement.referenceAttributes,+ resolvedReferences: placement.resolvedReferenceAttributes ?? {},+ records: placement.records,+ outputs: placement.outputs,attributeValueRanges: placement.attributeValueRanges,...(placement.id === undefined ? {} : { id: placement.id }),range: placement.range,},...placement.children.map((child) => ({+ ...(child.authorElement === undefined ? {} : { authorElement: child.authorElement }),+ authorEndpoints: child.authorEndpoints ?? {},sourcePath: child.sourcePath,attributes: child.attributes,references: child.referenceAttributes,+ resolvedReferences: child.resolvedReferenceAttributes ?? {},+ records: child.records ?? [],+ outputs: child.outputs ?? [],attributeValueRanges: child.attributeValueRanges,...(child.id === undefined ? {} : { id: child.id }),range: child.range,@@ -81,12 +108,6 @@ function elementFor(placement: StudioPlacement, draft: StudioEntityDraft): Autho?? candidates.find((candidate) => candidate.id === draft.authoredId);}-function languageOf(path: string): StudioSourceFile["language"] {- if (path.endsWith(".svs")) return "svs";- if (path.endsWith(".svrun")) return "svrun";- return "svml";-}-function sourceFor(root: string,path: string,@@ -117,20 +138,26 @@ function recipeParameters(input: {readonly draft: StudioEntityDraft;readonly referenceName: string;readonly referencePath: string;+ readonly referenceRef?: string;readonly placements: readonly Placement[];readonly recipe: StudioRecipeReferenceBindingDeclaration;readonly through: readonly string[];}): readonly StudioSourceBinding[] {const [attribute, ...remaining] = input.through;if (attribute !== undefined) {- const local = input.placements.find((candidate) => candidate.id === input.referencePath);+ const local = authoredElements(input.placements).find((candidate) => input.referenceRef !== undefined+ ? candidate.records.includes(input.referenceRef) || candidate.outputs.includes(input.referenceRef)+ : candidate.sourcePath === input.current.path && candidate.id === input.referencePath);if (local === undefined) return [];- const referencePath = local.referenceAttributes[attribute];+ const referencePath = local.references[attribute];if (referencePath === undefined || referencePath === input.referencePath) return [];return recipeParameters({...input,current: sourceFor(input.root, local.sourcePath, input.files) ?? input.current,referencePath,+ ...(local.resolvedReferences[attribute] === undefined+ ? {}+ : { referenceRef: local.resolvedReferences[attribute] }),through: remaining,});}@@ -198,11 +225,14 @@ function referencedParameters(input: {readonly draft: StudioEntityDraft;readonly referenceName: string;readonly referencePath: string;+ readonly referenceRef?: string;readonly declarations: readonly StudioSourceBindingDeclaration[];readonly placements: readonly Placement[];}): readonly StudioSourceBinding[] {const targetId = input.referencePath;- const target = authoredElements(input.placements).find((candidate) => candidate.id === targetId);+ const target = authoredElements(input.placements).find((candidate) => input.referenceRef !== undefined+ ? candidate.records.includes(input.referenceRef) || candidate.outputs.includes(input.referenceRef)+ : candidate.id === targetId);if (target === undefined) return [];const file = sourceFor(input.root, target.sourcePath, input.files);if (file === undefined) return [];@@ -219,9 +249,12 @@ function referencedParameters(input: {name: declaration.name,value,...(declaration.schema === undefined ? {} : { schema: declaration.schema }),- language: languageOf(target.sourcePath),+ language: file.language,writable,source: {+ ...(target.authorEndpoints[declaration.name] === undefined+ ? {}+ : { endpoint: target.authorEndpoints[declaration.name] }),path: relative(input.root, sourceAbsolute(input.root, target.sourcePath)),range,preimage,@@ -270,9 +303,10 @@ export function sourceBindingsForDraft(input: {name,value,...(declaration.schema === undefined ? {} : { schema: declaration.schema }),- language: languageOf(element.sourcePath),+ language: file.language,writable,source: {+ ...(element.authorEndpoints[name] === undefined ? {} : { endpoint: element.authorEndpoints[name] }),path: relative(input.root, sourceAbsolute(input.root, element.sourcePath)),range,preimage,@@ -294,6 +328,9 @@ export function sourceBindingsForDraft(input: {draft: input.draft,referenceName: declaration.name,referencePath,+ ...(element.resolvedReferences[declaration.name] === undefined+ ? {}+ : { referenceRef: element.resolvedReferences[declaration.name] }),declarations: declaration.referenced,placements: input.placements ?? [],});@@ -306,6 +343,9 @@ export function sourceBindingsForDraft(input: {draft: input.draft,referenceName: declaration.name,referencePath,+ ...(element.resolvedReferences[declaration.name] === undefined+ ? {}+ : { referenceRef: element.resolvedReferences[declaration.name] }),placements: input.placements ?? [],recipe: declaration.recipe,through: declaration.recipe.through ?? [],@@ -357,18 +397,22 @@ export function inspectorFieldsForBindings(});}-const ABSOLUTE_DURATION = /^\s*\d+(?:\.\d+)?(?:f|ms|s)\s*$/u;+/** Runtime authority, rather than a Companion allowlist, makes timing fields writable. */+export function temporalBindingDeclarations(+ temporal?: StudioTemporalLineage,+): readonly StudioSourceBindingDeclaration[] {+ if (temporal === undefined) return [];+ const endpoints = temporal.projection.kind === "instant"+ ? [temporal.projection]+ : [temporal.projection.start, temporal.projection.end];+ return [...new Set(endpoints.flatMap((endpoint) => endpoint.authority.kind === "parameter"+ ? [endpoint.authority.binding]+ : []))].map((name) => ({ name, writable: true }));+}-/**- * Resolve an adapter-declared gesture through the entity's actual temporal- * lineage. A Selection is the writable author identity, so every rectangle- * projected from it edits the same Script markers. Literal absolute Windows- * remain directly writable. Other projections stay visible but read-only- * until their package declares an unambiguous inverse.- */+/** Resolve finite timeline gestures from the exact endpoint authorities in the executed graph. */export function resolveTimelineEditHandles(bindings: readonly StudioSourceBinding[],- declarations: readonly StudioTimelineEditDeclaration[],temporal?: StudioTemporalLineage,semantic?: StudioSemanticTimeline,): readonly StudioEditHandle[] {@@ -379,98 +423,119 @@ export function resolveTimelineEditHandles(// window when a clip is being dragged.if (binding.language === "svml" && !byName.has(binding.binding)) byName.set(binding.binding, binding);}- const absolute = (binding: StudioSourceBinding | undefined): binding is StudioSourceBinding =>- binding !== undefined && binding.writable && typeof binding.value === "string" && ABSOLUTE_DURATION.test(binding.value);- const disabled = (gesture: StudioTimelineEditDeclaration["gesture"], reason: string): StudioEditHandle => ({+ const writable = (binding: StudioSourceBinding | undefined): binding is StudioSourceBinding =>+ binding !== undefined && binding.writable && binding.source.endpoint !== undefined;+ const disabled = (gesture: StudioTimelineGesture, reason: string): StudioEditHandle => ({id: `timeline.adjust:${gesture}`,operation: "timeline.adjust",gesture,enabled: false,disabledReason: reason,});- const handles: StudioEditHandle[] = [];- if (temporal === undefined) return handles;- const matches = (when: { readonly source: string; readonly projection?: string }): boolean =>- temporal.source.kind === when.source- && (when.projection === undefined || temporal.projection?.kind === when.projection);- for (const declaration of declarations) {- const before = handles.length;- let relevant = false;- let unavailable: string | undefined;- for (const target of declaration.targets) {- if (target.kind === "semantic-source") {- if (temporal.source.kind !== target.source) continue;- relevant = true;- const id = temporal.source.id;- if (id === undefined) {- unavailable = `该 ${target.source} 投影没有公共作者身份。`;- continue;- }- if (target.source === "selection") {- const selection = semantic?.selections.find((candidate) => candidate.id === id);- if (selection === undefined) {- unavailable = `Selection ${id} 没有出现在当前语义 Candidate 中。`;- continue;- }- handles.push({- id: `timeline.adjust:${declaration.gesture}`,- operation: "timeline.adjust",- gesture: declaration.gesture,- enabled: true,- coordinate: "semantic-anchor",- ...(target.moveEffect === undefined ? {} : { moveEffect: target.moveEffect }),- snapTo: ["semantic-anchor"],- semantic: {- kind: "selection",- id: selection.id,- startAnchorId: selection.startAnchorId,- endAnchorId: selection.endAnchorId,- },- });- } else {- const moment = semantic?.moments.find((candidate) => candidate.id === id);- if (moment === undefined) {- unavailable = `Moment ${id} 没有出现在当前语义 Candidate 中。`;- continue;- }- handles.push({- id: `timeline.adjust:${declaration.gesture}`,- operation: "timeline.adjust",- gesture: declaration.gesture,- enabled: true,- coordinate: "semantic-anchor",- ...(target.moveEffect === undefined ? {} : { moveEffect: target.moveEffect }),- snapTo: ["semantic-anchor"],- semantic: { kind: "moment", id: moment.id, anchorId: moment.anchorId },- });- }- break;- }- if (!matches(target.when)) continue;- relevant = true;- if (target.kind === "disabled") {- handles.push(disabled(declaration.gesture, target.reason));- break;- }- const resolved = target.parameters.map(({ role, parameter }) => ({ role, parameter: byName.get(parameter) }));- if (resolved.some((item) => !absolute(item.parameter))) {- unavailable = `Companion 声明的源码参数不可用:${target.parameters.map((item) => item.parameter).join(", ")}。`;+ if (temporal === undefined) return [];+ const projection = temporal.projection;++ const semanticTarget = (endpoints: readonly StudioTemporalInstantProjection[]) => {+ const sources = endpoints.flatMap((endpoint) => endpoint.authority.kind === "semantic"+ ? [endpoint.authority.source]+ : []);+ const first = sources[0];+ if (first === undefined+ || first.spaceId !== semantic?.spaceId+ || first.narrativeId !== semantic.narrativeId+ || !sources.every((candidate) => candidate.kind === first.kind+ && candidate.id === first.id+ && candidate.spaceId === first.spaceId+ && candidate.narrativeId === first.narrativeId)) return undefined;+ if (first.kind === "selection") {+ const selection = semantic?.selections.find((candidate) => candidate.id === first.id);+ return selection === undefined ? undefined : {+ kind: "selection" as const,+ narrativeId: first.narrativeId,+ id: selection.id,+ startAnchorId: selection.startAnchorId,+ endAnchorId: selection.endAnchorId,+ };+ }+ if (first.kind === "moment") {+ const moment = semantic?.moments.find((candidate) => candidate.id === first.id);+ return moment === undefined ? undefined : {+ kind: "moment" as const,+ narrativeId: first.narrativeId,+ id: moment.id,+ anchorId: moment.anchorId,+ };+ }+ return undefined;+ };++ const handle = (+ gesture: StudioTimelineGesture,+ affected: readonly { readonly endpoint: StudioTemporalInstantProjection; readonly role: "start" | "end" }[],+ moveEffect?: "translate-window" | "move-start",+ ): StudioEditHandle => {+ const unavailable = affected.find(({ endpoint }) => endpoint.authority.kind === "fixed");+ if (unavailable !== undefined) return disabled(gesture, "该端点由 Program 或 Segment 结构固定,不能从组件时间线反写。");+ const projected: ({ readonly missing: string } | StudioEditSource)[] = [];+ for (const { endpoint, role } of affected) {+ if (endpoint.authority.kind !== "parameter") continue;+ const binding = byName.get(endpoint.authority.binding);+ if (!writable(binding)) {+ projected.push({ missing: endpoint.authority.binding });continue;}- handles.push({- id: `timeline.adjust:${declaration.gesture}`,- operation: "timeline.adjust",- gesture: declaration.gesture,- enabled: true,- coordinate: "program-frame",- snapTo: ["frame", "semantic-anchor", "item-edge"],- sources: resolved.map((item) => ({ role: item.role, source: item.parameter!.source })),+ projected.push({+ role: endpoint.authority.relation === "direct" ? role : "duration" as const,+ source: binding.source,});- break;}- if (relevant && handles.length === before) {- handles.push(disabled(declaration.gesture, unavailable ?? "Companion 声明的作者逆变换在当前实体上不可用。"));+ const missing = projected.find((item) => "missing" in item);+ if (missing !== undefined && "missing" in missing) {+ return disabled(gesture, `投影参数 ${missing.missing} 在当前作者源码中不可写。`);+ }+ const semanticEndpoints = affected.filter(({ endpoint }) => endpoint.authority.kind === "semantic").map(({ endpoint }) => endpoint);+ const target = semanticTarget(semanticEndpoints);+ if (semanticEndpoints.length > 0 && target === undefined) {+ return disabled(gesture, "语义端点在当前 Candidate 中没有可写的作者身份。");}+ const sources = projected.filter((item): item is StudioEditSource => "source" in item);+ return {+ id: `timeline.adjust:${gesture}`,+ operation: "timeline.adjust",+ gesture,+ enabled: true,+ coordinate: target === undefined ? "program-frame" : "semantic-anchor",+ ...(moveEffect === undefined ? {} : { moveEffect }),+ snapTo: target === undefined ? ["frame", "semantic-anchor", "item-edge"] : ["semantic-anchor"],+ ...(sources.length === 0 ? {} : { sources }),+ ...(target === undefined ? {} : { semantic: target }),+ temporal: projection,+ };+ };++ if (projection.kind === "instant") {+ return [handle("move", [{ endpoint: projection, role: "start" }], "move-start")];}- return handles;+ const start = { endpoint: projection.start, role: "start" as const };+ const end = { endpoint: projection.end, role: "end" as const };+ const move = projection.end.authority.kind === "parameter" && projection.end.authority.relation === "after-start"+ ? [start]+ : projection.start.authority.kind === "parameter" && projection.start.authority.relation === "before-end"+ ? [end]+ : [start, end];+ const trimStart = projection.start.authority.kind === "parameter" && projection.start.authority.relation === "before-end"+ ? [start]+ : projection.end.authority.kind === "parameter" && projection.end.authority.relation === "after-start"+ ? [start, end]+ : [start];+ const trimEnd = projection.end.authority.kind === "parameter" && projection.end.authority.relation === "after-start"+ ? [end]+ : projection.start.authority.kind === "parameter" && projection.start.authority.relation === "before-end"+ ? [start, end]+ : [end];+ return [+ handle("move", move, "translate-window"),+ handle("trim-start", trimStart),+ handle("trim-end", trimEnd),+ ];}diff --git a/packages/studio/src/programme.ts b/packages/studio/src/programme.tsindex 7402147b..f5fb8f7c 100644--- a/packages/studio/src/programme.ts+++ b/packages/studio/src/programme.ts@@ -1,11 +1,16 @@import type { ArtifactAttachment } from "@hypit/workspace";import type { BlobRef, Digest, StoredValue } from "@hypit/protocol";+import { sameType } from "@hypit/protocol";import type { Composition } from "@hypit/composition";+import { compositionTypes } from "@hypit/composition";import {projectSemanticProgramSpace,+ semanticAnchorFrames,semanticTrackSpans,} from "@hypit/semantic-track";import type { SemanticTrack } from "@hypit/semantic-track";+import { semanticTrackTypes } from "@hypit/semantic-track";+import type { ProgramSpace } from "@hypit/program-space";import type { StudioResolvedTrack, StudioTemporalBinding } from "@hypit/studio-adapter";import type { StudioArchive } from "./archive.js";@@ -13,19 +18,20 @@ import type { CompiledSource, ServedFile } from "./compile.js";import type { StudioDomain } from "./domain.js";import { executeDeterministic, MemoryArtifactStore } from "./execute.js";import type { RunPlan } from "./run.js";-import type { StudioProjection } from "./studio-preflight.js";+import type { StudioViewRequirement } from "./studio-preflight.js";import { studioSurfacePreview } from "./surface-preview.js";import { executedTemporalBindings } from "./temporal-graph.js";-const PLAYABLE = new Set(["VisualTrack", "AudioTrack"]);-const TIMING = "SemanticTrack";+function playable(type: import("@hypit/protocol").TypeRef): boolean {+ return sameType(type, compositionTypes.visualTrack) || sameType(type, compositionTypes.audioTrack);+}export type BuiltTrack = StudioResolvedTrack;export type Preview = {readonly source: CompiledSource;readonly tracks: readonly BuiltTrack[];- /** Resolved adapter realizations keyed by exact graph output ref. */+ /** Resolved Companion realizations keyed by exact graph output ref. */readonly values: ReadonlyMap<string, unknown>;readonly temporalBindings: ReadonlyMap<string, readonly StudioTemporalBinding[]>;readonly composition: Composition;@@ -36,7 +42,7 @@ export type Preview = {readonly served: ReadonlyMap<string, ServedFile>;readonly canvas: { readonly width: number; readonly height: number; readonly clearColor: string };readonly frameRate: { readonly numerator: number; readonly denominator: number };- readonly space: unknown;+ readonly space: ProgramSpace;readonly anchors: ReadonlyMap<string, number>;readonly tokens: readonly {readonly id: string;@@ -103,7 +109,7 @@ export async function preview(input: {readonly domain: StudioDomain;readonly outputRefs: readonly string[];readonly compositionRef: string;- readonly projections: readonly StudioProjection[];+ readonly projections: readonly StudioViewRequirement[];readonly archive?: StudioArchive;}): Promise<Preview> {const exportsByRef = new Map(input.source.exports.map((item) => [item.ref, item] as const));@@ -153,7 +159,7 @@ export async function preview(input: {const satisfactions = new Map(input.run.run.graph.satisfactions.map((item) => [item.output, item.candidate]),);- const timingOutput = targets.find((target) => target.type === TIMING);+ const timingOutput = targets.find((target) => sameType(target.typeRef, semanticTrackTypes.track));const timingValue = timingOutput === undefined? undefined: selectedValue(executed.state, timingOutput.ref);@@ -162,8 +168,7 @@ export async function preview(input: {}const semantic = timingValue.value as unknown as SemanticTrack;const spans = semanticTrackSpans(semantic);- const anchors = new Map(spans.flatMap(({ item, startFrame }) =>- item.take.anchors.map((anchor) => [anchor.identity, startFrame + anchor.frame] as const)));+ const anchors = semanticAnchorFrames(semantic);const space = projectSemanticProgramSpace(semantic);const rate = space.frameRate;const compositionValue = selectedValue(executed.state, input.compositionRef);@@ -178,7 +183,7 @@ export async function preview(input: {}const projectionByRef = new Map(input.projections.map((projection) => [projection.ref, projection]));const tracks: BuiltTrack[] = targets.flatMap((target) => {- if (!PLAYABLE.has(target.type)) return [];+ if (!playable(target.typeRef)) return [];const stored = selectedValue(executed.state, target.ref);const candidateId = satisfactions.get(target.ref);if (stored?.kind !== "inline") {@@ -194,6 +199,7 @@ export async function preview(input: {return [{name: target.name,type: target.type,+ typeRef: target.typeRef,outputRef: target.ref,...(candidateId === undefined ? {} : { candidateId }),candidateOrigin: candidateId === undefined ? "source" as const : "run" as const,@@ -213,7 +219,7 @@ export async function preview(input: {if (stored?.kind === "inline") values.set(target.ref, stored.value);}// Author Records are already deterministic inline values from this exact- // compilation. Studio adapters may need them to name a resolved projection+ // compilation. Studio Track Companions may need them to name a resolved projection// (for example Caption cue text); exposing them here avoids recomputing the// domain value or turning a Record into a fake graph target.for (const placement of input.source.observations.placements) {diff --git a/packages/studio/src/run.ts b/packages/studio/src/run.tsindex 31c35c51..b98130f4 100644--- a/packages/studio/src/run.ts+++ b/packages/studio/src/run.ts@@ -39,6 +39,7 @@ export type RunPlan = {export async function loadStudioRun(input: {readonly run: string;readonly domain: StudioDomain;+ readonly registry: import("./studio-registry.js").StudioCompanionRegistry;readonly archive?: StudioArchive;}): Promise<RunPlan> {const fragments = new RunFragmentRegistry();@@ -49,11 +50,7 @@ export async function loadStudioRun(input: {frontends.register(frontend);}}- const observer = createObserver(input.domain.surfaces, (request) => {- const found = input.domain.resolveModule(request.from);- if (found === undefined) throw new Error(`No selected Source package satisfies ${request.from}.`);- return found;- });+ const observer = createObserver(input.domain.surfaces, input.registry);const compiler = new NodeRunCompiler({authorCompiler: input.domain.createCompiler(observer.surfaces),fragments,diff --git a/packages/studio/src/server.ts b/packages/studio/src/server.tsindex 0ff885c0..6c8fdcae 100644--- a/packages/studio/src/server.ts+++ b/packages/studio/src/server.ts@@ -1,16 +1,16 @@import { watch } from "node:fs";import type { FSWatcher } from "node:fs";import { existsSync } from "node:fs";-import { readFile, rename, writeFile, unlink } from "node:fs/promises";-import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";+import { readFile } from "node:fs/promises";+import { dirname, isAbsolute, relative, resolve } from "node:path";import type { Plugin, ViteDevServer } from "vite";-import { adjustScriptMoment, adjustScriptSelection, parseScript } from "@hypit/script";+import type { StudioTemporalInstantProjection } from "@hypit/studio-adapter";import type { StudioArchive } from "./archive.js";import type { ServedFile } from "./compile.js";import type { StudioDomain } from "./domain.js";-import type { StudioAdapterRegistry } from "./studio-registry.js";+import type { StudioCompanionRegistry } from "./studio-registry.js";import { loadStudioRun } from "./run.js";import { serializeParameterValue, validateParameterValue } from "./parameter-values.js";import { readStudioSession } from "./session.js";@@ -18,12 +18,13 @@ import type { Range, StudioFailure, StudioLibraryView, StudioMutation, StudioSnaimport { createStudioStoryboard } from "./storyboard.js";import type { StudioStoryboard } from "./storyboard.js";import { findSurfacePreview } from "./surface-preview.js";+import { replaceSourceFiles } from "./source-transaction.js";export type StudioPluginOptions = {readonly source: string;readonly runPath: string;readonly domain: StudioDomain;- readonly registry: StudioAdapterRegistry;+ readonly registry: StudioCompanionRegistry;readonly workspaceRoot: string;readonly archive?: StudioArchive;};@@ -61,11 +62,13 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {let server: ViteDevServer | undefined;let timer: ReturnType<typeof setTimeout> | undefined;let mutating = false;+ let publishing = 0;let requestedRevision = 0;let currentSource = options.source;let library: StudioLibraryView | undefined;let allowedSourceFiles = new Set<string>();const watched = new Map<string, FSWatcher>();+ const watchedFiles = new Set<string>();const storyboards = new Map<string, Promise<StudioStoryboard>>();const readLibrary = async (): Promise<StudioLibraryView> => {@@ -79,9 +82,15 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {};const watchSource = (path: string): void => {- if (watched.has(path)) return;+ const absolute = resolve(path);+ watchedFiles.add(absolute);+ const directory = dirname(absolute);+ if (watched.has(directory)) return;try {- watched.set(path, watch(path, () => { if (!mutating) schedule(); }));+ watched.set(directory, watch(directory, (_event, filename) => {+ const changed = filename === null ? undefined : resolve(directory, filename.toString());+ if (!mutating && (changed === undefined || watchedFiles.has(changed))) schedule();+ }));} catch {// Some Hosts may report virtual Source ids. They are still recompiled// whenever a real Source revision is scheduled; they simply emit no file event.@@ -89,6 +98,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {};const publish = async (attempt: number, notify = true): Promise<void> => {+ publishing += 1;try {// SVML and SVRun form one Studio source of truth. Recompile both for// every revision so a new Author graph is never executed through an old@@ -96,6 +106,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {const run = await loadStudioRun({run: options.runPath,domain: options.domain,+ registry: options.registry,...(options.archive === undefined ? {} : { archive: options.archive }),});currentSource = run.authorSource;@@ -131,13 +142,18 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {...(range === undefined ? {} : { range }),};if (notify) server?.ws.send({ type: "custom", event: "studio:error", data: failure });+ } finally {+ publishing -= 1;}};const schedule = (): void => {const attempt = ++requestedRevision;if (timer !== undefined) clearTimeout(timer);- timer = setTimeout(() => void publish(attempt), 80);+ timer = setTimeout(() => {+ timer = undefined;+ void publish(attempt);+ }, 80);};type Patch = {@@ -147,27 +163,14 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {readonly preimage: string;};- const replaceFiles = async (files: ReadonlyMap<string, string>): Promise<void> => {- const temporaries: { readonly path: string; readonly temporary: string }[] = [];- try {- for (const [absolute, text] of files) {- const temporary = join(dirname(absolute), `.${basename(absolute)}.hypit-studio.tmp`);- await writeFile(temporary, text, "utf8");- temporaries.push({ path: absolute, temporary });- }- for (const item of temporaries) await rename(item.temporary, item.path);- } finally {- for (const item of temporaries) {- try { await unlink(item.temporary); } catch { /* already renamed */ }- }- }- };-const applyTransaction = async (patches: readonly Patch[],expectedRevision: number,): Promise<ReadonlyMap<string, string>> => {- if (snapshot !== undefined && expectedRevision !== snapshot.revision) {+ const sourceRevision = failure !== undefined && (snapshot === undefined || failure.revision > snapshot.revision)+ ? failure.revision+ : snapshot?.revision;+ if (sourceRevision !== undefined && expectedRevision !== sourceRevision) {throw new Error("The Source changed outside Studio.");}const grouped = new Map<string, Patch[]>();@@ -208,7 +211,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {}if (next !== text) nextFiles.set(absolute, next);}- await replaceFiles(nextFiles);+ await replaceSourceFiles(nextFiles);return new Map([...previousFiles].filter(([absolute]) => nextFiles.has(absolute)));};@@ -228,23 +231,55 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {&& candidate.enabled);if (handle === undefined) throw new Error(`Entity ${mutation.entityId} does not allow ${mutation.gesture}.`);- if (mutation.target.kind === "selection" || mutation.target.kind === "moment") {- const target = mutation.target;- if (handle.semantic?.kind !== target.kind) {- throw new Error(`Entity ${mutation.entityId} is not bound to a writable ${target.kind}.`);+ const temporal = handle.temporal;+ if (temporal === undefined) throw new Error("This timeline entity has no authoring authority.");+ if (temporal.kind !== mutation.target.kind) {+ throw new Error(`This timeline entity requires a ${temporal.kind} mutation target.`);+ }+ const startFrame = mutation.target.kind === "instant" ? mutation.target.frame : mutation.target.startFrame;+ const endFrameExclusive = mutation.target.kind === "instant" ? mutation.target.frame + 1 : mutation.target.endFrameExclusive;+ if (!Number.isInteger(startFrame) || startFrame < 0+ || (mutation.target.kind === "window"+ && (!Number.isInteger(endFrameExclusive) || endFrameExclusive <= startFrame))) {+ throw new Error("A timeline target must use valid whole frames.");+ }+ if (temporal.kind === "window") {+ if (mutation.gesture === "move"+ && endFrameExclusive - startFrame !== clip.endFrameExclusive - clip.startFrame) {+ throw new Error("Move must preserve the Window duration.");+ }+ if (mutation.gesture === "trim-start" && endFrameExclusive !== clip.endFrameExclusive) {+ throw new Error("Trim start cannot change the Window end.");+ }+ if (mutation.gesture === "trim-end" && startFrame !== clip.startFrame) {+ throw new Error("Trim end cannot change the Window start.");+ }+ } else if (mutation.gesture !== "move") {+ throw new Error("An Instant only supports move.");+ }++ const patches: Patch[] = [];+ const semanticTarget = mutation.target.semantic;+ if (semanticTarget !== undefined) {+ if (handle.semantic?.kind !== semanticTarget.kind) {+ throw new Error(`Entity ${mutation.entityId} is not bound to a writable ${semanticTarget.kind}.`);}const current = snapshot;const script = current?.script;if (current === undefined || script === undefined) throw new Error("Studio has no writable Script source map.");- if (target.kind === "selection") {- const startIndex = current.semantic.anchors.findIndex((anchor) => anchor.id === target.startAnchorId);- const endIndex = current.semantic.anchors.findIndex((anchor) => anchor.id === target.endAnchorId);+ if (handle.semantic.narrativeId !== current.semantic.narrativeId+ || script.narrativeId !== current.semantic.narrativeId) {+ throw new Error("The timeline entity and writable Script do not belong to the selected Narrative.");+ }+ if (semanticTarget.kind === "selection") {+ const startIndex = current.semantic.anchors.findIndex((anchor) => anchor.id === semanticTarget.startAnchorId);+ const endIndex = current.semantic.anchors.findIndex((anchor) => anchor.id === semanticTarget.endAnchorId);if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex|| current.semantic.anchors[startIndex]!.frame >= current.semantic.anchors[endIndex]!.frame) {throw new Error("A Selection must span two ordered semantic Anchors with positive time.");}- } else if (!current.semantic.anchors.some((anchor) => anchor.id === target.anchorId)) {- throw new Error(`Moment Anchor ${target.anchorId} does not exist in the current semantic Candidate.`);+ } else if (!current.semantic.anchors.some((anchor) => anchor.id === semanticTarget.anchorId)) {+ throw new Error(`Moment Anchor ${semanticTarget.anchorId} does not exist in the current semantic Candidate.`);}const absolute = resolve(options.workspaceRoot, script.sourcePath);const source = await readFile(absolute, "utf8");@@ -252,64 +287,96 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {throw new Error("The current Script source range is invalid.");}const body = source.slice(script.content.start, script.content.end);- const parsed = parseScript(script.sourcePath, body);- const replacement = target.kind === "selection"- ? adjustScriptSelection({- sourceName: script.sourcePath,- source: body,- parsed,- adjustment: {+ const replacement = options.registry.adjustScript({+ companion: script.companion,+ sourceName: script.sourcePath,+ source: body,+ adjustment: semanticTarget.kind === "selection"+ ? {+ kind: "selection",id: handle.semantic.id,- startAnchorId: target.startAnchorId,- endAnchorId: target.endAnchorId,- },- })- : adjustScriptMoment({- sourceName: script.sourcePath,- source: body,- parsed,- adjustment: { id: handle.semantic.id, anchorId: target.anchorId },- });- return replacement === body ? [] : [{- path: relative(options.workspaceRoot, absolute),- range: script.content,- replacement,- preimage: body,- }];+ startAnchorId: semanticTarget.startAnchorId,+ endAnchorId: semanticTarget.endAnchorId,+ }+ : { kind: "moment", id: handle.semantic.id, anchorId: semanticTarget.anchorId },+ });+ if (replacement !== body) patches.push({+ path: relative(options.workspaceRoot, absolute), range: script.content, replacement, preimage: body,+ });}- if (handle.sources === undefined) throw new Error("This timeline projection has no direct Window inverse.");- const { startFrame, endFrameExclusive } = mutation.target;- if (!Number.isInteger(startFrame) || !Number.isInteger(endFrameExclusive)- || startFrame < 0 || endFrameExclusive <= startFrame) {- throw new Error("A timeline Window must contain positive whole frames.");- }- if (mutation.gesture === "move"- && endFrameExclusive - startFrame !== clip.endFrameExclusive - clip.startFrame) {- throw new Error("Move must preserve the Window duration.");- }- if (mutation.gesture === "trim-start" && endFrameExclusive !== clip.endFrameExclusive) {- throw new Error("Trim start cannot change the Window end.");- }- if (mutation.gesture === "trim-end" && startFrame !== clip.startFrame) {- throw new Error("Trim end cannot change the Window start.");- }const source = (role: "start" | "end" | "duration") =>handle.sources?.find((candidate) => candidate.role === role)?.source;const frame = (value: number): string => `${value}f`;- const patches = mutation.gesture === "move"- ? [- source("start") === undefined ? undefined : { ...source("start")!, replacement: frame(startFrame) },- source("end") === undefined ? undefined : { ...source("end")!, replacement: frame(endFrameExclusive) },- ]- : mutation.gesture === "trim-start"- ? [source("start") === undefined ? undefined : { ...source("start")!, replacement: frame(startFrame) }]- : source("duration") !== undefined- ? [{ ...source("duration")!, replacement: frame(endFrameExclusive - startFrame) }]- : [source("end") === undefined ? undefined : { ...source("end")!, replacement: frame(endFrameExclusive) }];- const resolved = patches.filter((patch): patch is Patch => patch !== undefined);- if (resolved.length === 0) throw new Error(`No Source endpoint implements ${mutation.gesture}.`);- return resolved.filter((patch) => patch.replacement !== patch.preimage);+ const semanticFrame = (endpoint: StudioTemporalInstantProjection): number | undefined => {+ if (endpoint.authority.kind !== "semantic" || semanticTarget === undefined || handle.semantic === undefined) return undefined;+ if (endpoint.source.kind === "selection" && semanticTarget.kind === "selection"+ && endpoint.source.id === handle.semantic.id) {+ const anchorId = endpoint.authority.boundary === "start"+ ? semanticTarget.startAnchorId+ : semanticTarget.endAnchorId;+ return snapshot?.semantic.anchors.find((anchor) => anchor.id === anchorId)?.frame;+ }+ if (endpoint.source.kind === "moment" && semanticTarget.kind === "moment"+ && endpoint.source.id === handle.semantic.id) {+ return snapshot?.semantic.anchors.find((anchor) => anchor.id === semanticTarget.anchorId)?.frame;+ }+ return undefined;+ };+ const projectionBaseFrame = (endpoint: StudioTemporalInstantProjection): number | undefined => {+ if (endpoint.reference === "absolute") return undefined;+ if (endpoint.reference === "program.start") return 0;+ if (endpoint.reference === "program.end") return snapshot?.space.frameCount;+ const id = endpoint.source.id;+ if (id === undefined) return undefined;+ if (endpoint.reference === "selection.start" || endpoint.reference === "selection.end") {+ const selection = snapshot?.semantic.selections.find((candidate) => candidate.id === id);+ return endpoint.reference === "selection.start" ? selection?.startFrame : selection?.endFrameExclusive;+ }+ if (endpoint.reference === "segment.start" || endpoint.reference === "segment.end") {+ const segment = snapshot?.semantic.segments.find((candidate) => candidate.id === id);+ return endpoint.reference === "segment.start" ? segment?.startFrame : segment?.endFrameExclusive;+ }+ return snapshot?.semantic.moments.find((candidate) => candidate.id === id)?.frame;+ };+ const projectedPointValue = (endpoint: StudioTemporalInstantProjection, desired: number): string => {+ if (endpoint.reference === "absolute") return frame(desired);+ const base = projectionBaseFrame(endpoint);+ if (base === undefined) throw new Error(`The ${endpoint.reference} projection base is unavailable.`);+ const offset = desired - base;+ return offset === 0 ? endpoint.reference : `${endpoint.reference}${offset > 0 ? "+" : ""}${offset}f`;+ };+ const writeEndpoint = (+ endpoint: StudioTemporalInstantProjection,+ desired: number,+ role: "start" | "end",+ ): void => {+ if (desired === endpoint.frame) return;+ if (endpoint.authority.kind === "fixed") throw new Error(`The ${role} endpoint is structurally fixed.`);+ if (endpoint.authority.kind === "semantic") {+ if (semanticFrame(endpoint) !== desired) throw new Error(`The ${role} endpoint does not match its semantic Anchor.`);+ return;+ }+ if (endpoint.authority.relation !== "direct") return;+ const author = source(role);+ if (author === undefined) throw new Error(`The ${role} projection has no writable Source binding.`);+ patches.push({ ...author, replacement: projectedPointValue(endpoint, desired) });+ };+ if (temporal.kind === "instant") {+ writeEndpoint(temporal, startFrame, "start");+ } else {+ writeEndpoint(temporal.start, startFrame, "start");+ writeEndpoint(temporal.end, endFrameExclusive, "end");+ const derived = [temporal.start, temporal.end].find((endpoint) =>+ endpoint.authority.kind === "parameter" && endpoint.authority.relation !== "direct");+ if (derived !== undefined+ && endFrameExclusive - startFrame !== temporal.endFrameExclusive - temporal.startFrame) {+ const author = source("duration");+ if (author === undefined) throw new Error("The projected duration has no writable Source binding.");+ patches.push({ ...author, replacement: frame(endFrameExclusive - startFrame) });+ }+ }+ return patches.filter((patch) => patch.replacement !== patch.preimage);};const mutationPatches = async (mutation: StudioMutation): Promise<readonly Patch[]> => {@@ -342,7 +409,9 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {const commitMutation = async (mutation: StudioMutation): Promise<number> => {if (mutating) throw new Error("A Studio author mutation is already in progress.");- if (snapshot === undefined || mutation.revision !== snapshot.revision) {+ if (timer !== undefined || publishing > 0 || snapshot === undefined+ || mutation.revision !== snapshot.revision || requestedRevision !== snapshot.revision+ || (failure !== undefined && failure.revision >= snapshot.revision)) {throw new Error("The Source changed outside Studio.");}if (timer !== undefined) {@@ -361,7 +430,7 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {return attempt;}const rejected = failure.error;- await replaceFiles(previous);+ await replaceSourceFiles(previous);await publish(++requestedRevision, false);server?.ws.send({ type: "custom", event: "studio:snapshot", data: snapshot });throw new StudioMutationRejected(rejected);@@ -380,8 +449,13 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {const url = new URL(request.url ?? "/", "http://studio.hypit.local");if (request.method === "PUT" && url.pathname === "/__studio/source") {void (async () => {+ let acquired = false;try {- if (mutating) throw new Error("A Studio author mutation is already in progress.");+ if (mutating || timer !== undefined || publishing > 0) {+ throw new Error("A Studio author mutation is already in progress.");+ }+ mutating = true;+ acquired = true;const chunks: Buffer[] = [];for await (const chunk of request) chunks.push(Buffer.from(chunk));const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as {@@ -394,7 +468,10 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {json(response, 400, { error: "Expected source path, text and revision." });return;}- if (snapshot !== undefined && body.revision !== snapshot.revision) {+ const sourceRevision = failure !== undefined && (snapshot === undefined || failure.revision > snapshot.revision)+ ? failure.revision+ : snapshot?.revision;+ if (sourceRevision !== undefined && body.revision !== sourceRevision) {json(response, 409, { error: "The Source changed outside Studio." });return;}@@ -410,11 +487,13 @@ export function studioPlugin(options: StudioPluginOptions): Plugin {replacement: body.text,preimage: current,}], body.revision);- schedule();- response.statusCode = 202;- response.end();+ const attempt = ++requestedRevision;+ await publish(attempt);+ json(response, 202, { revision: attempt });} catch (error) {json(response, conflict(error) ? 409 : 500, { error: error instanceof Error ? error.message : String(error) });+ } finally {+ if (acquired) mutating = false;}})();return;diff --git a/packages/studio/src/session.ts b/packages/studio/src/session.tsindex 6814083f..58d3e311 100644--- a/packages/studio/src/session.ts+++ b/packages/studio/src/session.ts@@ -1,6 +1,9 @@import { existsSync, readFileSync } from "node:fs";import { relative } from "node:path";+import { markupAuthorFrontendId } from "@hypit/markup";+import { svsFrontendId } from "@hypit/svs";+import type { StudioArchive } from "./archive.js";import type { ServedFile } from "./compile.js";import type { StudioDomain } from "./domain.js";@@ -9,10 +12,10 @@ import { preview } from "./programme.js";import { renderPreview } from "./preview/render.js";import type { RunPlan } from "./run.js";import type { StudioSnapshot } from "./shared.js";-import type { StudioAdapterRegistry } from "./studio-registry.js";+import type { StudioCompanionRegistry } from "./studio-registry.js";import { snapshot } from "./snapshot.js";import { inspectStudioRun } from "./studio-preflight.js";-import type { StudioProjection } from "./studio-preflight.js";+import type { StudioViewRequirement } from "./studio-preflight.js";import type { StudioSourceFile } from "./parameters.js";function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {@@ -20,8 +23,15 @@ function sourceFiles(run: RunPlan): readonly StudioSourceFile[] {return [...new Set(paths)].flatMap((path): StudioSourceFile[] => {if (!existsSync(path)) return [];try {- const language = path.endsWith(".svs") ? "svs" : path.endsWith(".svrun") ? "svrun" : "svml";const unit = run.source.compiled.closure.units.find((candidate) => candidate.id === path);+ const language = path === run.runPath+ ? "svrun" as const+ : unit?.frontend === svsFrontendId+ ? "svs" as const+ : unit?.frontend === markupAuthorFrontendId+ ? "svml" as const+ : undefined;+ if (language === undefined) return [];return [{path,text: readFileSync(path, "utf8"),@@ -39,12 +49,12 @@ export type StudioSession = {readonly snapshot: StudioSnapshot;readonly material: ReadonlyMap<string, ServedFile>;readonly observations: Observations;- readonly projections: readonly StudioProjection[];+ readonly projections: readonly StudioViewRequirement[];};export async function readStudioSession(input: {readonly domain: StudioDomain;- readonly registry: StudioAdapterRegistry;+ readonly registry: StudioCompanionRegistry;readonly run: RunPlan;readonly archive?: StudioArchive;readonly revision: number;diff --git a/packages/studio/src/shared.ts b/packages/studio/src/shared.tsindex fe88e6f3..a212d87f 100644--- a/packages/studio/src/shared.ts+++ b/packages/studio/src/shared.ts@@ -59,8 +59,8 @@ export type StudioTrackBinding = {/** Visual/audio facets from one authored element share this identity. */readonly groupId: string;readonly icon: StudioIcon;- /** Stable Studio-local adapter id; fallback adapters remain explicit too. */- readonly adapter: string;+ /** Stable Studio-local Track Companion id; fallbacks remain explicit too. */+ readonly companion: string;/** Studio-local partition key for an attached projection. */readonly attachmentId?: string;readonly lane: StudioLaneDescription;@@ -125,7 +125,8 @@ export type Track = {};export type ScriptMap = {- readonly recordId: string;+ readonly companion: string;+ readonly narrativeId: string;readonly sourcePath: string;readonly range: Range;readonly content: Range;@@ -279,18 +280,19 @@ export type StudioMutation =readonly gesture: StudioTimelineGesture;readonly target:| {- readonly kind: "selection";- readonly startAnchorId: string;- readonly endAnchorId: string;- }- | {- readonly kind: "moment";- readonly anchorId: string;+ readonly kind: "instant";+ readonly frame: number;+ readonly semantic?:+ | { readonly kind: "selection"; readonly startAnchorId: string; readonly endAnchorId: string }+ | { readonly kind: "moment"; readonly anchorId: string };}| {readonly kind: "window";readonly startFrame: number;readonly endFrameExclusive: number;+ readonly semantic?:+ | { readonly kind: "selection"; readonly startAnchorId: string; readonly endAnchorId: string }+ | { readonly kind: "moment"; readonly anchorId: string };};}| {diff --git a/packages/studio/src/snapshot.ts b/packages/studio/src/snapshot.tsindex 82d40f6c..d74969aa 100644--- a/packages/studio/src/snapshot.ts+++ b/packages/studio/src/snapshot.ts@@ -9,6 +9,9 @@import { relative } from "node:path";import type { MarkupSurfaceRegistryLike } from "@hypit/markup";+import { compositionTypes } from "@hypit/composition";+import { narrativeTypes } from "@hypit/narrative";+import { sameModule, sameType } from "@hypit/protocol";import type {CandidateProvenance,@@ -24,9 +27,9 @@ import type { Preview } from "./programme.js";import {sealStudioClip,} from "./studio-registry.js";-import type { StudioAdapterRegistry } from "./studio-registry.js";+import type { StudioCompanionRegistry } from "./studio-registry.js";import type { StudioEntityDraft } from "./studio-registry.js";-import { inspectorFieldsForBindings, resolveTimelineEditHandles, sourceBindingsForDraft } from "./parameters.js";+import { inspectorFieldsForBindings, resolveTimelineEditHandles, sourceBindingsForDraft, temporalBindingDeclarations } from "./parameters.js";import type { StudioSourceFile } from "./parameters.js";type Present = {@@ -93,19 +96,29 @@ function authored(placements: readonly Placement[]): readonly Located[] {}function scriptMap(- maps: readonly Record<string, unknown>[],+ maps: Preview["source"]["observations"]["sourceMaps"],built: Preview,+ narrativeId: string,): ScriptMap | undefined {- const found = maps.find((map) => map.format === "hypit.script-source-map@1");+ const candidates = maps.filter((map, index) => map.narrativeId === narrativeId+ && maps.findIndex((other) => other.narrativeId === map.narrativeId+ && other.sourcePath === map.sourcePath+ && other.range.start === map.range.start+ && other.range.end === map.range.end) === index);+ if (candidates.length > 1) {+ throw new Error(`Studio Narrative id ${narrativeId} is declared by more than one Script in the Source closure.`);+ }+ const found = candidates[0];if (found === undefined) return undefined;- const selections = (found.selections ?? []) as ScriptMap["selections"];- const segments = (found.segments ?? []) as ScriptMap["segments"];- const moments = (found.moments ?? []) as ScriptMap["moments"];+ const selections = found.selections;+ const segments = found.segments;+ const moments = found.moments;return {- recordId: String(found.record ?? ""),- sourcePath: String(found.sourcePath ?? ""),- range: (found.range ?? { start: 0, end: 0 }) as Range,- content: (found.content ?? { start: 0, end: 0 }) as Range,+ companion: found.companion,+ narrativeId: found.narrativeId,+ sourcePath: found.sourcePath,+ range: found.range,+ content: found.content,// A Segment is the outermost range a Script declares; a Selection written// inside one is a level down, and one inside that another.segments: segments.map((segment) => ({ ...segment, depth: 0 })),@@ -115,7 +128,7 @@ function scriptMap(})),moments,// A Script says where a word is written; the timings say when it is said.- tokens: ((found.tokens ?? []) as readonly { id: string; range: Range }[]).flatMap((token) => {+ tokens: found.tokens.flatMap((token) => {const placed = built.tokens.find((item) => item.id === token.id);const startFrame = placed === undefined ? undefined : built.anchors.get(placed.startAnchorId);const endFrame = placed === undefined ? undefined : built.anchors.get(placed.endAnchorId);@@ -126,6 +139,7 @@ function scriptMap(}type NarrativeValue = {+ readonly id?: string;readonly segments?: readonly {readonly id: string;readonly startAnchorId: string;@@ -150,36 +164,34 @@ type NarrativeValue = {readonly semanticIndex?: {readonly anchors?: readonly {readonly id: string;- readonly kind: "segment-start" | "segment-end" | "token-start" | "token-end";- readonly segmentId: string;+ readonly kind: "program-start" | "segment-start" | "segment-end" | "token-start" | "token-end" | "program-end";+ readonly segmentId?: string;readonly tokenId?: string;}[];};};-function inlineRecord(compiled: unknown, id: string): unknown {- const records = (compiled as {- readonly program: {- readonly records: readonly { readonly id: string; readonly value: { readonly kind: string; readonly value?: unknown } }[];- };- }).program.records;- const found = records.find((record) => record.id === id);- return found?.value.kind === "inline" ? found.value.value : undefined;-}-/*** Project the compiled Narrative into the frame domain that the preview is* already using. No frontend timing is invented here: if an anchor is absent* from the built SemanticTrack, the corresponding item is simply not drawable yet.*/function semanticTimeline(- registry: StudioAdapterRegistry,+ registry: StudioCompanionRegistry,built: Preview,script: ScriptMap | undefined,): SemanticTimeline {- const exported = built.source.exports.find((item) => item.type === "Narrative");- if (exported === undefined) throw new Error("Studio SemanticTrack has no traceable Narrative.");- const narrative = inlineRecord(built.source.compiled, exported.ref) as NarrativeValue | undefined;+ const records = built.source.compiled.program.records.filter((item) =>+ sameType(item.type, narrativeTypes.narrative)+ && item.value.kind === "inline"+ && (item.value.value as NarrativeValue).id === built.space.narrativeId);+ if (records.length > 1) {+ throw new Error(`Studio Narrative id ${built.space.narrativeId} resolves to more than one authored value.`);+ }+ const record = records[0];+ const narrative = record?.value.kind === "inline"+ ? record.value.value as NarrativeValue+ : undefined;if (narrative === undefined) throw new Error("Studio Narrative is not an inline authored value.");const segmentRanges = new Map((script?.segments ?? []).map((item) => [item.id, item.range]));@@ -217,7 +229,7 @@ function semanticTimeline(id: anchor.id,kind: anchor.kind,frame: at,- segmentId: anchor.segmentId,+ ...(anchor.segmentId === undefined ? {} : { segmentId: anchor.segmentId }),...(anchor.tokenId === undefined ? {} : { tokenId: anchor.tokenId }),}];});@@ -247,12 +259,14 @@ function semanticTimeline(errors: [],};return {+ spaceId: built.space.id,+ narrativeId: built.space.narrativeId,// Semantic is a Studio lane with its own registered meaning. Do not copy// the authored Speech Track id into this label: it is the timebase, not a// second Speech output.presentation: registry.semanticTimelinePresentation(),// Narrative order is the semantic ruler. Frame ties are common and must- // not erase the discrete 2M+2N anchor ordering used by writeback.+ // not erase the discrete 2M+2N+2 anchor ordering used by writeback.anchors,segments: segments.sort((left, right) => left.startFrame - right.startFrame || left.id.localeCompare(right.id)),tokens: tokens.sort((left, right) => left.startFrame - right.startFrame || left.id.localeCompare(right.id)),@@ -264,8 +278,8 @@ function semanticTimeline(/** The element an output belongs to: `take-opening.video` is `take-opening`. */function depthOf(- selection: ScriptMap["selections"][number],- all: readonly ScriptMap["selections"][number][],+ selection: Omit<ScriptMap["selections"][number], "depth">,+ all: readonly Omit<ScriptMap["selections"][number], "depth">[],): number {let depth = 1;for (const other of all) {@@ -275,7 +289,7 @@ function depthOf(return depth;}-export function snapshot(registry: StudioAdapterRegistry, built: Preview, input: {+export function snapshot(registry: StudioCompanionRegistry, built: Preview, input: {readonly revision: number;readonly path: string;readonly text: string;@@ -288,22 +302,23 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:readonly surfaces: MarkupSurfaceRegistryLike;}): StudioSnapshot {const located = authored(built.source.observations.placements);- const script = scriptMap(built.source.observations.sourceMaps, built);+ const script = scriptMap(built.source.observations.sourceMaps, built, built.space.narrativeId);const semantic = semanticTimeline(registry, built, script);const tracks: Track[] = [];for (const item of built.tracks) {const projectedSpans = spans(item.value, input.frameRate);const binding = registry.bindTrack(item);- const placement = built.source.observations.placements.find((candidate) =>- candidate.id === item.trace.authoredId- && candidate.module.name === item.trace.module- && candidate.surface === item.trace.surface);+ const placement = item.trace.module === undefined ? undefined+ : built.source.observations.placements.find((candidate) =>+ candidate.id === item.trace.authoredId+ && sameModule(candidate.module, item.trace.module!)+ && candidate.surface === item.trace.surface);const generic = (): readonly StudioEntityDraft[] => projectedSpans.map((span) => {const identity = span.subjectId ?? span.id;const where = located.find((candidate) => candidate.id === identity);return {id: `${item.outputRef}:${span.id}`,- ...(item.type === "VisualTrack" ? { presentId: span.id } : {}),+ ...(sameType(item.typeRef, compositionTypes.visualTrack) ? { presentId: span.id } : {}),authoredId: identity,display: { title: identity, layers: [] },startFrame: span.startFrame,@@ -327,7 +342,10 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:files: input.sourceFiles,placement,draft,- declarations: registry.bindingDeclarations(item, placement, draft.lane),+ declarations: [+ ...registry.bindingDeclarations(item, placement, draft.lane),+ ...temporalBindingDeclarations(draft.temporal),+ ],placements: built.source.observations.placements,});const inspector = inspectorFieldsForBindings(@@ -337,7 +355,6 @@ export function snapshot(registry: StudioAdapterRegistry, built: Preview, input:);const editHandles = resolveTimelineEditHandles(bindings,- draft.timelineEdits ?? registry.timelineEdits(item, placement, draft.lane),draft.temporal,semantic,);diff --git a/packages/studio/src/source-transaction.ts b/packages/studio/src/source-transaction.tsnew file mode 100644index 00000000..212259fb--- /dev/null+++ b/packages/studio/src/source-transaction.ts@@ -0,0 +1,57 @@+import { readFile, rename, unlink, writeFile } from "node:fs/promises";+import { basename, dirname, join } from "node:path";++export type SourceFileOperations = {+ readonly read: (path: string) => Promise<string>;+ readonly write: (path: string, text: string) => Promise<void>;+ readonly move: (from: string, to: string) => Promise<void>;+ readonly remove: (path: string) => Promise<void>;+};++const nodeSourceFileOperations: SourceFileOperations = {+ read: async (path) => await readFile(path, "utf8"),+ write: async (path, text) => { await writeFile(path, text, "utf8"); },+ move: async (from, to) => { await rename(from, to); },+ remove: async (path) => { await unlink(path); },+};++/** Publish a set of complete Source texts, restoring already-published files on write failure. */+export async function replaceSourceFiles(+ files: ReadonlyMap<string, string>,+ operations: SourceFileOperations = nodeSourceFileOperations,+): Promise<void> {+ const temporaries: { readonly path: string; readonly temporary: string }[] = [];+ const previous = new Map<string, string>();+ const applied: string[] = [];+ try {+ for (const [absolute, text] of files) {+ previous.set(absolute, await operations.read(absolute));+ const temporary = join(dirname(absolute), `.${basename(absolute)}.hypit-studio.tmp`);+ await operations.write(temporary, text);+ temporaries.push({ path: absolute, temporary });+ }+ for (const item of temporaries) {+ await operations.move(item.temporary, item.path);+ applied.push(item.path);+ }+ } catch (error) {+ for (const absolute of [...applied].reverse()) {+ const text = previous.get(absolute);+ if (text === undefined) continue;+ const recovery = join(dirname(absolute), `.${basename(absolute)}.hypit-studio.recover.tmp`);+ try {+ await operations.write(recovery, text);+ await operations.move(recovery, absolute);+ } catch {+ // Preserve the original publish error; this path is best-effort restoration.+ } finally {+ try { await operations.remove(recovery); } catch { /* already moved */ }+ }+ }+ throw error;+ } finally {+ for (const item of temporaries) {+ try { await operations.remove(item.temporary); } catch { /* already moved */ }+ }+ }+}diff --git a/packages/studio/src/studio-preflight.ts b/packages/studio/src/studio-preflight.tsindex 14cf1cf5..db4b8a7e 100644--- a/packages/studio/src/studio-preflight.ts+++ b/packages/studio/src/studio-preflight.ts@@ -1,12 +1,14 @@import { plannedNeeds } from "@hypit/core";import type { Candidate } from "@hypit/protocol";+import { sameType } from "@hypit/protocol";+import type { StudioFilmCompanion } from "@hypit/studio-adapter";+import { semanticTrackTypes } from "@hypit/semantic-track";import type { CompiledSource } from "./compile.js";import type { Placement } from "./observe.js";import type { RunPlan } from "./run.js";-import type { StudioAdapterRegistry } from "./studio-registry.js";+import type { StudioCompanionRegistry } from "./studio-registry.js";import {- lastPlacementTag,outputFor,placementFor,roleFor,@@ -14,13 +16,13 @@ import {tracedStudioValues,unique,} from "./studio-trace.js";-import type { StudioProjectionRole, StudioTrace } from "./studio-trace.js";+import type { StudioViewRole, StudioTrace } from "./studio-trace.js";-export type StudioProjection = {+export type StudioViewRequirement = {readonly name: string;readonly ref: string;readonly type: string;- readonly role: StudioProjectionRole;+ readonly role: StudioViewRole;readonly candidateId?: string;readonly trace: StudioTrace;readonly candidatePolicy: "materialized-inline" | "deterministic-derived";@@ -29,7 +31,7 @@ export type StudioProjection = {export type StudioInspection = {readonly renderTargets: readonly string[];readonly filmComposition: string;- readonly projections: readonly StudioProjection[];+ readonly projections: readonly StudioViewRequirement[];};export class StudioPreflightError extends Error {@@ -54,27 +56,33 @@ function plannedExternalNeeds(base: RunPlan, refs: readonly string[]): readonly));}-function filmForTarget(source: CompiledSource, targetRef: string): {+function localName(value: string): string {+ return value.includes(":") ? value.slice(value.lastIndexOf(":") + 1) : value;+}++function filmForTarget(registry: StudioCompanionRegistry, source: CompiledSource, targetRef: string): {readonly renderTarget: boolean;readonly compositionRef?: string;readonly placement?: Placement;+ readonly companion?: StudioFilmCompanion;} {const targetPlacement = placementFor(source, targetRef);if (targetPlacement === undefined) return { renderTarget: false };- if (lastPlacementTag(source, targetRef) === "Film") {- return { renderTarget: true, compositionRef: targetRef, placement: targetPlacement };- }- if (lastPlacementTag(source, targetRef) !== "Video") return { renderTarget: false };- const composition = targetPlacement.references- .map((ref) => outputFor(source, ref))- .find((item) => item?.type === "Composition");- const compositionRef = composition?.ref;- const placement = compositionRef === undefined ? undefined : placementFor(source, compositionRef);- return {- renderTarget: true,- ...(compositionRef === undefined ? {} : { compositionRef }),- ...(placement === undefined ? {} : { placement }),- };+ const candidates = unique([+ targetRef,+ ...Object.values(targetPlacement.resolvedReferenceAttributes ?? {}),+ ...targetPlacement.children.flatMap((child) => Object.values(child.resolvedReferenceAttributes ?? {})),+ ]).flatMap((ref) => {+ const output = outputFor(source, ref);+ const placement = placementFor(source, ref);+ const companion = output === undefined ? undefined : registry.filmCompanionFor(output.typeRef, placement);+ return output === undefined || placement === undefined || companion === undefined+ ? []+ : [{ compositionRef: output.ref, placement, companion }];+ });+ if (candidates.length > 1) throw new Error(`Run target ${targetRef} reaches more than one Studio Film.`);+ const found = candidates[0];+ return found === undefined ? { renderTarget: false } : { renderTarget: true, ...found };}/**@@ -82,7 +90,7 @@ function filmForTarget(source: CompiledSource, targetRef: string): {* supplies the compiled graph and its exact BuildPlan/Need closure.*/export function inspectStudioRun(- registry: StudioAdapterRegistry,+ registry: StudioCompanionRegistry,source: CompiledSource,base: RunPlan,): StudioInspection {@@ -90,17 +98,23 @@ export function inspectStudioRun(if (base.targets.length === 0) issues.push("the Run Source has no target; Studio requires Film or Render");const targets = base.targets.flatMap((ref) => {- const found = filmForTarget(source, ref);+ const found = filmForTarget(registry, source, ref);return found.renderTarget ? [{ ref, ...found }] : [];});if (targets.length === 0 && base.targets.length > 0) {issues.push("the Run target is not a Film or Render output from the current SVML");}+ const filmCompositions = unique(targets.flatMap((target) =>+ target.compositionRef === undefined ? [] : [target.compositionRef]));+ if (filmCompositions.length > 1) {+ issues.push(`the Run reaches multiple Film compositions (${filmCompositions.join(", ")}); Studio requires one explicit Film`);+ }const chosen = targets.find((item) => item.compositionRef !== undefined && item.placement !== undefined);- if (chosen?.compositionRef === undefined || chosen.placement === undefined) {+ if (chosen?.compositionRef === undefined || chosen.placement === undefined || chosen.companion === undefined) {issues.push("Film/Render target has no traceable Film composition");throw new StudioPreflightError(issues);}+ const film = chosen.companion;const candidates = new Map(base.run.graph.candidates.map((item) => [item.id, item] as const));const satisfactions = new Map(base.run.graph.satisfactions.map((item) => [item.output, item.candidate] as const));@@ -112,52 +126,41 @@ export function inspectStudioRun(}}- // Only authored <film:Track source={...}/> children define Film membership- // and Studio lane order. Film's canvas, semantic and appearance references- // are not Tracks, and sibling outputs of those references are not implied.+ // The selected Film companion alone declares membership and semantic-axis vocabulary.const filmTrackRefs = unique(chosen.placement.children.flatMap((child) => {- const source = child.referenceAttributes.source;+ if (localName(child.tag) !== film.tracks.childSurface) return [];+ const source = child.resolvedReferenceAttributes?.[film.tracks.sourceAttribute];return source === undefined ? [] : [source];})).flatMap((ref) => {const output = outputFor(source, ref);- return output !== undefined && (output.type === "VisualTrack" || output.type === "AudioTrack")+ return output !== undefined && film.tracks.types.some((type) => sameType(type, output.typeRef))? [output.ref]: [];});- const semanticOutput = outputFor(source, chosen.placement.referenceAttributes.semantic ?? "");- if (semanticOutput?.type !== "SemanticTrack") {+ const semanticOutput = outputFor(source,+ chosen.placement.resolvedReferenceAttributes?.[film.semantic.attribute] ?? "");+ if (semanticOutput === undefined || !sameType(semanticOutput.typeRef, film.semantic.type)) {issues.push("Film has no traceable SemanticTrack reference");}- const semanticPlacement = semanticOutput === undefined- ? undefined- : placementFor(source, semanticOutput.ref);- const semanticTakeRefs = unique(semanticPlacement === undefined ? [] : [- ...semanticPlacement.references,- ...semanticPlacement.children.flatMap((child) => child.references),- ]).flatMap((ref) => outputFor(source, ref)?.type === "SemanticTake"- ? [outputFor(source, ref)!.ref] : []);- if (semanticTakeRefs.length === 0) issues.push("Film has no traceable SemanticTake chain");-- let adapterValueRefs: readonly string[] = [];+ let companionValueRefs: readonly string[] = [];try {- adapterValueRefs = unique(filmTrackRefs.flatMap((ref) =>+ companionValueRefs = unique(filmTrackRefs.flatMap((ref) =>tracedStudioValues(registry, source, ref)));} catch (error) {issues.push(error instanceof Error ? error.message : String(error));}- const adapterValueSet = new Set(adapterValueRefs);+ const companionValueSet = new Set(companionValueRefs);const projectionRefs = unique([...filmTrackRefs,- ...(semanticOutput?.type === "SemanticTrack" ? [semanticOutput.ref] : []),- ...semanticTakeRefs,- ...adapterValueRefs,+ ...(semanticOutput !== undefined && sameType(semanticOutput.typeRef, semanticTrackTypes.track) ? [semanticOutput.ref] : []),+ ...companionValueRefs,]);- const projections: StudioProjection[] = [];- const derived: Omit<StudioProjection, "candidatePolicy">[] = [];+ const projections: StudioViewRequirement[] = [];+ const derived: Omit<StudioViewRequirement, "candidatePolicy">[] = [];for (const ref of projectionRefs) {const output = outputFor(source, ref);- const role = roleFor(registry, source, ref) ?? (adapterValueSet.has(ref) ? "realization" : undefined);+ const role = roleFor(registry, source, ref) ?? (companionValueSet.has(ref) ? "supporting-value" : undefined);if (output === undefined || role === undefined) continue;const candidateId = satisfactions.get(ref);const candidate = candidateId === undefined ? undefined : candidates.get(candidateId);diff --git a/packages/studio/src/studio-registry.ts b/packages/studio/src/studio-registry.tsindex d3b8b45a..bce3b0f5 100644--- a/packages/studio/src/studio-registry.ts+++ b/packages/studio/src/studio-registry.ts@@ -1,20 +1,28 @@import type {- StudioAdapter,- StudioAdapterContext,+ StudioTrackCompanion,+ StudioTrackCompanionContext,StudioEditHandle,StudioEntityDraft,+ StudioFilmCompanion,StudioLaneAttachment,- StudioProjectionRole,+ StudioViewRole,StudioResolvedTrack,+ StudioScriptAdjustment,+ StudioScriptCompanion,+ StudioScriptSourceMap,StudioSourceBindingDeclaration,StudioSpan,- StudioTimelineEditDeclaration,} from "@hypit/studio-adapter";+import { studioParameterControls } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import { sameModule, sameType } from "@hypit/protocol";+import type { ModuleRef, TypeRef } from "@hypit/protocol";+import { semanticTrackTypes } from "@hypit/semantic-track";import type { Placement } from "./observe.js";import type { Clip, StudioTrackBinding } from "./shared.js";-export type { StudioEntityDraft, StudioProjectionRole, StudioSpan } from "@hypit/studio-adapter";+export type { StudioEntityDraft, StudioViewRole, StudioSpan } from "@hypit/studio-adapter";const flatLane = {heightPx: 52,@@ -25,7 +33,7 @@ const icons = new Set(["brand", "captions", "component", "layers", "ranking", "tconst chromes = new Set(["standard", "group", "point"]);const layouts = new Set(["repeat-x", "cover", "contain", "storyboard", "waveform"]);const inspectorDomains = new Set(["where", "how", "when"]);-const inspectorControls = new Set(["text", "number", "boolean", "select", "color"]);+const inspectorControls = new Set<string>(studioParameterControls);function bindingPaths(declarations: readonly StudioSourceBindingDeclaration[], prefix = ""): Set<string> {const paths = new Set<string>();@@ -41,7 +49,7 @@ function bindingPaths(declarations: readonly StudioSourceBindingDeclaration[], pfunction validateInspector(subject: string,bindings: readonly StudioSourceBindingDeclaration[] | undefined,- fields: StudioAdapter["inspector"],+ fields: StudioTrackCompanion["inspector"],): void {const paths = bindingPaths(bindings ?? []);const seen = new Set<string>();@@ -62,159 +70,206 @@ function validateInspector(}}-function validateTimelineEdits(subject: string, edits: readonly StudioTimelineEditDeclaration[] | undefined): void {- const gestures = new Set<string>();- for (const edit of edits ?? []) {- if (gestures.has(edit.gesture)) throw new Error(`${subject} repeats timeline gesture ${edit.gesture}`);- gestures.add(edit.gesture);- if (edit.targets.length === 0) throw new Error(`${subject} timeline gesture ${edit.gesture} has no inverse target`);- for (const target of edit.targets) {- if (target.kind !== "source-parameters") continue;- if (target.parameters.length === 0) {- throw new Error(`${subject} timeline gesture ${edit.gesture} has no source parameters`);- }- const roles = new Set<string>();- for (const parameter of target.parameters) {- if (parameter.parameter.length === 0 || roles.has(parameter.role)) {- throw new Error(`${subject} timeline gesture ${edit.gesture} has an invalid source parameter binding`);- }- roles.add(parameter.role);- }- }- }-}--function validateAdapterVocabulary(adapter: StudioAdapter): void {- if (adapter.tone !== undefined && !tones.has(adapter.tone)) {- throw new Error(`Studio adapter ${adapter.id} selects unsupported tone ${adapter.tone}`);+function validateCompanionVocabulary(companion: StudioTrackCompanion): void {+ if (companion.tone !== undefined && !tones.has(companion.tone)) {+ throw new Error(`Studio Track Companion ${companion.id} selects unsupported tone ${companion.tone}`);}- if (adapter.icon !== undefined && !icons.has(adapter.icon)) {- throw new Error(`Studio adapter ${adapter.id} selects unsupported icon ${adapter.icon}`);+ if (companion.icon !== undefined && !icons.has(companion.icon)) {+ throw new Error(`Studio Track Companion ${companion.id} selects unsupported icon ${companion.icon}`);}- validateInspector(`Studio adapter ${adapter.id}`, adapter.bindings, adapter.inspector);- validateTimelineEdits(`Studio adapter ${adapter.id}`, adapter.timelineEdits);- for (const attachment of adapter.attachments ?? []) {+ validateInspector(`Studio Track Companion ${companion.id}`, companion.bindings, companion.inspector);+ for (const attachment of companion.attachments ?? []) {if (attachment.tone !== undefined && !tones.has(attachment.tone)) {- throw new Error(`Studio adapter ${adapter.id} attachment ${attachment.id} selects unsupported tone ${attachment.tone}`);+ throw new Error(`Studio Track Companion ${companion.id} attachment ${attachment.id} selects unsupported tone ${attachment.tone}`);}if (!icons.has(attachment.icon)) {- throw new Error(`Studio adapter ${adapter.id} attachment ${attachment.id} selects unsupported icon ${attachment.icon}`);+ throw new Error(`Studio Track Companion ${companion.id} attachment ${attachment.id} selects unsupported icon ${attachment.icon}`);}- validateInspector(`Studio adapter ${adapter.id} attachment ${attachment.id}`, attachment.bindings, attachment.inspector);- validateTimelineEdits(`Studio adapter ${adapter.id} attachment ${attachment.id}`, attachment.timelineEdits);+ validateInspector(`Studio Track Companion ${companion.id} attachment ${attachment.id}`, attachment.bindings, attachment.inspector);}}-function validateDraftVocabulary(adapter: StudioAdapter, draft: StudioEntityDraft): void {- validateTimelineEdits(`Studio adapter ${adapter.id} entity ${draft.id}`, draft.timelineEdits);+function validateDraftVocabulary(companion: StudioTrackCompanion, draft: StudioEntityDraft): void {if (draft.display === undefined || typeof draft.display.title !== "string" || draft.display.title.trim().length === 0) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has no display title`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has no display title`);}if (!Array.isArray(draft.display.layers)) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has invalid display layers`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has invalid display layers`);}if (draft.presentation !== undefined && !chromes.has(draft.presentation.chrome)) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} selects unsupported chrome ${draft.presentation.chrome}`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} selects unsupported chrome ${draft.presentation.chrome}`);}for (const [index, layer] of draft.display.layers.entries()) {if (layer.kind === "text") {if (layer.role !== "content" || typeof layer.text !== "string") {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has invalid text layer ${index}`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has invalid text layer ${index}`);}continue;}if (layer.kind !== "preview" || (layer.role !== "content" && layer.role !== "decoration")|| !layouts.has(layer.layout)|| !(["image", "video", "audio"] as const).includes(layer.preview.kind)) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has invalid preview layer ${index}`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has invalid preview layer ${index}`);}const source = layer.preview.source;if (source.kind === "artifact") {if (typeof source.digest !== "string" || source.digest.length === 0) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has invalid Artifact source`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has invalid Artifact source`);}} else if (source.kind !== "surface-preview"|| source.module.length === 0 || source.version.length === 0 || source.surface.length === 0) {- throw new Error(`Studio adapter ${adapter.id} entity ${draft.id} has invalid Surface preview source`);+ throw new Error(`Studio Track Companion ${companion.id} entity ${draft.id} has invalid Surface preview source`);}}}function matches(- adapter: StudioAdapter,- type: string,+ companion: StudioTrackCompanion,+ type: TypeRef,placement: Pick<Placement, "surface" | "module"> | undefined,- siblingTypes: readonly string[],+ siblingTypes: readonly TypeRef[],): boolean {- const rule = adapter.output;- return rule.type === type+ const rule = companion.output;+ return sameType(rule.type, type)&& (rule.surface === undefined || rule.surface === placement?.surface)- && (rule.modules === undefined || (placement !== undefined && rule.modules.includes(placement.module.name)))- && (rule.siblingType === undefined || siblingTypes.includes(rule.siblingType));+ && (rule.modules === undefined || (placement !== undefined+ && rule.modules.some((module) => sameModule(module, placement.module))))+ && (rule.siblingType === undefined || siblingTypes.some((candidate) => sameType(candidate, rule.siblingType!)));}-function specificity(adapter: StudioAdapter): number {- const rule = adapter.output;+function specificity(companion: StudioTrackCompanion): number {+ const rule = companion.output;return (rule.surface === undefined ? 0 : 8)+ (rule.siblingType === undefined ? 0 : 4)+ (rule.modules === undefined ? 0 : 2);}/** Immutable interpretation assembled for one project session. */-export class StudioAdapterRegistry {- readonly #adapters: readonly StudioAdapter[];+export class StudioCompanionRegistry {+ readonly #tracks: readonly StudioTrackCompanion[];+ readonly #films: readonly StudioFilmCompanion[];+ readonly #scripts: readonly StudioScriptCompanion[];constructor(- adapters: readonly StudioAdapter[],- options: { readonly replace?: Readonly<Record<string, string>> } = {},+ tracks: readonly StudioTrackCompanion[],+ options: {+ readonly replace?: Readonly<Record<string, string>>;+ readonly films?: readonly StudioFilmCompanion[];+ readonly scripts?: readonly StudioScriptCompanion[];+ } = {},) {const ids = new Set<string>();- for (const adapter of adapters) {- if (ids.has(adapter.id)) throw new Error(`Studio adapter id is repeated: ${adapter.id}`);- ids.add(adapter.id);- validateAdapterVocabulary(adapter);+ for (const companion of tracks) {+ if (ids.has(companion.id)) throw new Error(`Studio Track Companion id is repeated: ${companion.id}`);+ ids.add(companion.id);+ validateCompanionVocabulary(companion);}+ const films = [...(options.films ?? [])];+ const scripts = [...(options.scripts ?? [])];+ for (const [label, companions] of [["Film", films], ["Script", scripts]] as const) {+ const companionIds = new Set<string>();+ for (const companion of companions) {+ if (companionIds.has(companion.id) || ids.has(companion.id)) {+ throw new Error(`Studio ${label} companion id is repeated: ${companion.id}`);+ }+ companionIds.add(companion.id);+ ids.add(companion.id);+ }+ }+ const kind = new Map<string, "track" | "film" | "script">([+ ...tracks.map((item) => [item.id, "track"] as const),+ ...films.map((item) => [item.id, "film"] as const),+ ...scripts.map((item) => [item.id, "script"] as const),+ ]);const replacements = options.replace ?? {};for (const [target, replacement] of Object.entries(replacements)) {- if (!ids.has(target)) throw new Error(`Studio adapter replacement target does not exist: ${target}`);- if (!ids.has(replacement)) throw new Error(`Studio adapter replacement does not exist: ${replacement}`);- if (target === replacement) throw new Error(`Studio adapter cannot replace itself: ${target}`);+ if (!ids.has(target)) throw new Error(`Studio companion replacement target does not exist: ${target}`);+ if (!ids.has(replacement)) throw new Error(`Studio companion replacement does not exist: ${replacement}`);+ if (target === replacement) throw new Error(`Studio companion cannot replace itself: ${target}`);+ if (kind.get(target) !== kind.get(replacement)) {+ throw new Error(`Studio companion replacement must keep its kind: ${target} -> ${replacement}`);+ }}- this.#adapters = Object.freeze(adapters.filter((adapter) => !(adapter.id in replacements)));+ this.#tracks = Object.freeze(tracks.filter((companion) => !(companion.id in replacements)));+ this.#films = Object.freeze(films.filter((film) => !(film.id in replacements)));+ this.#scripts = Object.freeze(scripts.filter((script) => !(script.id in replacements)));}- adapterFor(- type: string,+ filmCompanionFor(+ type: TypeRef,placement: Pick<Placement, "surface" | "module"> | undefined,- siblingTypes: readonly string[],- ): StudioAdapter | undefined {- const candidates = this.#adapters- .filter((adapter) => matches(adapter, type, placement, siblingTypes))- .map((adapter) => ({ adapter, score: specificity(adapter) }))- .sort((left, right) => right.score - left.score || left.adapter.id.localeCompare(right.adapter.id));+ ): StudioFilmCompanion | undefined {+ if (placement === undefined) return undefined;+ const found = this.#films.filter((companion) =>+ sameType(companion.match.outputType, type)+ && companion.match.surface === placement.surface+ && sameModule(companion.match.module, placement.module));+ if (found.length > 1) throw new Error(`Studio Film companions are ambiguous for ${placement.module.name}#${placement.surface}.`);+ return found[0];+ }++ scriptCompanionFor(module: ModuleRef, surface: string): StudioScriptCompanion | undefined {+ const found = this.#scripts.filter((companion) =>+ sameModule(companion.match.module, module) && companion.match.surface === surface);+ if (found.length > 1) throw new Error(`Studio Script companions are ambiguous for ${module.name}@${module.version}#${surface}.`);+ return found[0];+ }++ observeScript(+ module: ModuleRef,+ surface: string,+ input: Parameters<StudioScriptCompanion["observe"]>[0],+ ): StudioScriptSourceMap | undefined {+ const companion = this.scriptCompanionFor(module, surface);+ const found = companion?.observe(input);+ return companion === undefined || found === undefined+ ? undefined+ : { ...found, companion: companion.id };+ }++ adjustScript(input: {+ readonly companion: string;+ readonly sourceName: string;+ readonly source: string;+ readonly adjustment: StudioScriptAdjustment;+ }): string {+ const companion = this.#scripts.find((candidate) => candidate.id === input.companion);+ if (companion === undefined) throw new Error(`Studio Script companion ${input.companion} is unavailable.`);+ return companion.adjust({ sourceName: input.sourceName, source: input.source, adjustment: input.adjustment });+ }++ trackCompanionFor(+ type: TypeRef,+ placement: Pick<Placement, "surface" | "module"> | undefined,+ siblingTypes: readonly TypeRef[],+ ): StudioTrackCompanion | undefined {+ const candidates = this.#tracks+ .filter((companion) => matches(companion, type, placement, siblingTypes))+ .map((companion) => ({ companion, score: specificity(companion) }))+ .sort((left, right) => right.score - left.score || left.companion.id.localeCompare(right.companion.id));const best = candidates[0];if (best === undefined) return undefined;const tied = candidates.filter((candidate) => candidate.score === best.score);if (tied.length > 1) {- throw new Error(`Studio adapters are ambiguous for ${type}: ${tied.map((candidate) => candidate.adapter.id).join(", ")}`);+ throw new Error(`Studio Track Companions are ambiguous for ${type.module.name}@${type.module.version}#${type.name}: ${tied.map((candidate) => candidate.companion.id).join(", ")}`);}- return best.adapter;+ return best.companion;}classifyOutput(- type: string,+ type: TypeRef,placement: Placement | undefined,- siblingTypes: readonly string[],- ): StudioProjectionRole | undefined {- return this.adapterFor(type, placement, siblingTypes)?.role;+ siblingTypes: readonly TypeRef[],+ ): StudioViewRole | undefined {+ return this.trackCompanionFor(type, placement, siblingTypes)?.role;}requiredValuePorts(- type: string,+ type: TypeRef,placement: Placement | undefined,- siblingTypes: readonly string[],+ siblingTypes: readonly TypeRef[],): readonly string[] {- return this.adapterFor(type, placement, siblingTypes)?.requiredValues ?? [];+ return this.trackCompanionFor(type, placement, siblingTypes)?.requiredValues ?? [];}semanticTimelinePresentation(authoredLabel?: string): {@@ -224,42 +279,42 @@ export class StudioAdapterRegistry {readonly icon: StudioTrackBinding["icon"];readonly lane: StudioTrackBinding["lane"];} {- const adapter = this.adapterFor("SemanticTrack", undefined, []);+ const companion = this.trackCompanionFor(semanticTrackTypes.track, undefined, []);return {- family: adapter?.family ?? "semantic",- tone: adapter?.tone ?? "teal",+ family: companion?.family ?? "semantic",+ tone: companion?.tone ?? "teal",...(authoredLabel === undefined- ? (adapter?.label === undefined ? {} : { label: adapter.label })+ ? (companion?.label === undefined ? {} : { label: companion.label }): { label: authoredLabel }),- icon: adapter?.icon ?? "brand",- lane: adapter?.lane ?? flatLane,+ icon: companion?.icon ?? "brand",+ lane: companion?.lane ?? flatLane,};}- #trackAdapter(track: StudioResolvedTrack): StudioAdapter & { readonly family: StudioTrackBinding["family"] } {+ #trackCompanion(track: StudioResolvedTrack): StudioTrackCompanion & { readonly family: StudioTrackBinding["family"] } {const placement = track.trace.surface === undefined || track.trace.module === undefined? undefined- : { surface: track.trace.surface, module: { name: track.trace.module, version: "" } };- const siblingTypes = track.trace.outputPorts.flatMap((item) => item.type === undefined ? [] : [item.type]);- const adapter = this.adapterFor(track.type, placement, siblingTypes);- const family = adapter?.family;- if (adapter === undefined || family === undefined) {- throw new Error(`Studio has no timeline adapter for ${track.type} (${track.name}).`);+ : { surface: track.trace.surface, module: track.trace.module };+ const siblingTypes = track.trace.outputPorts.flatMap((item) => item.typeRef === undefined ? [] : [item.typeRef]);+ const companion = this.trackCompanionFor(track.typeRef, placement, siblingTypes);+ const family = companion?.family;+ if (companion === undefined || family === undefined) {+ throw new Error(`Studio has no Track Companion for ${track.type} (${track.name}).`);}- return { ...adapter, family };+ return { ...companion, family };}trackAttachments(track: StudioResolvedTrack): readonly StudioTrackBinding[] {const root = this.bindTrack(track);- const adapter = this.#trackAdapter(track);- return (adapter.attachments ?? []).map((attachment: StudioLaneAttachment) => ({+ const companion = this.#trackCompanion(track);+ return (companion.attachments ?? []).map((attachment: StudioLaneAttachment) => ({family: attachment.family,- tone: attachment.tone ?? adapter.tone ?? "neutral",+ tone: attachment.tone ?? companion.tone ?? "neutral",...(attachment.label === undefined ? {} : { label: attachment.label }),facet: attachment.facet,groupId: root.groupId,icon: attachment.icon,- adapter: `${adapter.id}:${attachment.id}`,+ companion: `${companion.id}:${attachment.id}`,attachmentId: attachment.id,lane: {...attachment.lane,@@ -270,33 +325,33 @@ export class StudioAdapterRegistry {}bindTrack(track: StudioResolvedTrack): StudioTrackBinding {- const adapter = this.#trackAdapter(track);- // An adapter may provide a deliberate presentation label for a facet+ const companion = this.#trackCompanion(track);+ // A Companion may provide a deliberate presentation label for a facet// (e.g. Speech Visual / Speech Audio). Authored ids remain the fallback// for ordinary user-named tracks.- const label = adapter.label ?? track.trace.authoredId;+ const label = companion.label ?? track.trace.authoredId;return {- family: adapter.family,- tone: adapter.tone ?? "neutral",+ family: companion.family,+ tone: companion.tone ?? "neutral",...(label === undefined ? {} : { label }),- facet: track.type === "AudioTrack" ? "audio" : "visual",+ facet: sameType(track.typeRef, compositionTypes.audioTrack) ? "audio" : "visual",groupId: track.trace.authoredId ?? track.outputRef,- icon: adapter.icon ?? (track.type === "AudioTrack" ? "waveform" : "layers"),- adapter: adapter.id,- lane: adapter.lane ?? flatLane,+ icon: companion.icon ?? (sameType(track.typeRef, compositionTypes.audioTrack) ? "waveform" : "layers"),+ companion: companion.id,+ lane: companion.lane ?? flatLane,...(track.trace.placement === undefined ? {} : { authoredTag: track.trace.placement }),references: track.trace.references.map(({ name, type }) => ({ name, type })),};}- projectTrack(input: StudioAdapterContext): readonly StudioEntityDraft[] {- const adapter = this.#trackAdapter(input.track);- const drafts = adapter.project?.(input) ?? input.generic();+ projectTrack(input: StudioTrackCompanionContext): readonly StudioEntityDraft[] {+ const companion = this.#trackCompanion(input.track);+ const drafts = companion.project?.(input) ?? input.generic();const preview = input.surfacePreview;const surfaceLayer: StudioEntityDraft["display"]["layers"][number] | undefined = preview === undefined? undefined: { kind: "preview", role: "decoration", preview, layout: "repeat-x" };- const projected: readonly StudioEntityDraft[] = adapter.poster?.source !== "surface-preview" || surfaceLayer === undefined+ const projected: readonly StudioEntityDraft[] = companion.poster?.source !== "surface-preview" || surfaceLayer === undefined? drafts: drafts.map((draft) => draft.lane !== undefined? draft@@ -307,7 +362,7 @@ export class StudioAdapterRegistry {layers: [surfaceLayer, ...draft.display.layers],},});- for (const draft of projected) validateDraftVocabulary(adapter, draft);+ for (const draft of projected) validateDraftVocabulary(companion, draft);return projected;}@@ -316,11 +371,11 @@ export class StudioAdapterRegistry {placement: Placement | undefined,lane?: string,) {- const adapter = this.#trackAdapter(track);+ const companion = this.#trackCompanion(track);if (lane !== undefined) {- return adapter.attachments?.find((attachment) => attachment.id === lane)?.bindings ?? [];+ return companion.attachments?.find((attachment) => attachment.id === lane)?.bindings ?? [];}- return adapter.bindings ?? [];+ return companion.bindings ?? [];}inspectorDeclarations(@@ -328,24 +383,13 @@ export class StudioAdapterRegistry {placement: Placement | undefined,lane?: string,) {- const adapter = this.#trackAdapter(track);+ const companion = this.#trackCompanion(track);if (lane !== undefined) {- return adapter.attachments?.find((attachment) => attachment.id === lane)?.inspector ?? [];+ return companion.attachments?.find((attachment) => attachment.id === lane)?.inspector ?? [];}- return adapter.inspector ?? [];+ return companion.inspector ?? [];}- timelineEdits(- track: StudioResolvedTrack,- placement: Placement | undefined,- lane?: string,- ): readonly StudioTimelineEditDeclaration[] {- const adapter = this.#trackAdapter(track);- if (lane !== undefined) {- return adapter.attachments?.find((attachment) => attachment.id === lane)?.timelineEdits ?? [];- }- return adapter.timelineEdits ?? [];- }}export function sealStudioClip(diff --git a/packages/studio/src/studio-trace.ts b/packages/studio/src/studio-trace.tsindex 738f68a1..3b877238 100644--- a/packages/studio/src/studio-trace.ts+++ b/packages/studio/src/studio-trace.ts@@ -1,14 +1,16 @@import type { CompiledSource } from "./compile.js";import type { Placement } from "./observe.js";-import type { StudioAdapterRegistry } from "./studio-registry.js";-import type { StudioProjectionRole, StudioTrackTrace } from "@hypit/studio-adapter";+import type { StudioCompanionRegistry } from "./studio-registry.js";+import type { StudioViewRole, StudioTrackTrace } from "@hypit/studio-adapter";+import type { TypeRef } from "@hypit/protocol";-export type { StudioProjectionRole } from "@hypit/studio-adapter";+export type { StudioViewRole } from "@hypit/studio-adapter";export type StudioTraceDependency = {readonly name: string;readonly ref: string;readonly type: string;+ readonly typeRef: TypeRef;};export type StudioTrace = StudioTrackTrace;@@ -16,6 +18,7 @@ export type StudioTrace = StudioTrackTrace;export type StudioOutput = {readonly name: string;readonly type: string;+ readonly typeRef: TypeRef;readonly ref: string;};@@ -24,14 +27,11 @@ function lastTag(placement: Placement | undefined): string {}export function outputFor(source: CompiledSource, ref: string): StudioOutput | undefined {- return source.exports.find((item) => item.ref === ref || item.name === ref);+ return source.exports.find((item) => item.ref === ref);}export function placementFor(source: CompiledSource, ref: string): Placement | undefined {- const output = outputFor(source, ref);- return source.observations.placements.find((item) =>- item.outputs.includes(ref) || (output !== undefined && item.outputs.includes(output.name))- );+ return source.observations.placements.find((item) => item.outputs.includes(ref));}export function unique(values: readonly string[]): string[] {@@ -43,34 +43,42 @@ export function lastPlacementTag(source: CompiledSource, ref: string): string {}export function roleFor(- registry: StudioAdapterRegistry,+ registry: StudioCompanionRegistry,source: CompiledSource,ref: string,-): StudioProjectionRole | undefined {+): StudioViewRole | undefined {const output = outputFor(source, ref);if (output === undefined) return undefined;const placement = placementFor(source, ref);const placementTypes = placement?.outputs.flatMap((candidate) => {const found = outputFor(source, candidate);- return found === undefined ? [] : [found.type];+ return found === undefined ? [] : [found.typeRef];}) ?? [];- return registry.classifyOutput(output.type, placement, placementTypes);+ return registry.classifyOutput(output.typeRef, placement, placementTypes);}export function traceFor(source: CompiledSource, ref: string): StudioTrace {const placement = placementFor(source, ref);if (placement === undefined) return { outputPorts: [], references: [] };- const refs = unique([- ...placement.references,- ...placement.children.flatMap((child) => child.references),- ]).flatMap((dependency) => {+ const direct: Array<{ readonly input?: string; readonly dependency: string }> =+ Object.entries(placement.resolvedReferenceAttributes ?? {}).map(([input, dependency]) => ({ input, dependency }));+ const nested: Array<{ readonly input?: string; readonly dependency: string }> =+ placement.children.flatMap((child) => Object.values(child.resolvedReferenceAttributes ?? {})+ .map((dependency) => ({ dependency })));+ const dependencies = [...direct, ...nested].filter((candidate, index, all) =>+ all.findIndex((other) => other.dependency === candidate.dependency+ && other.input === candidate.input) === index);+ const refs = dependencies.flatMap(({ input, dependency }) => {const output = outputFor(source, dependency);- return output === undefined ? [] : [{ name: output.name, ref: output.ref, type: output.type }];+ return output === undefined ? [] : [{+ ...(input === undefined ? {} : { input }),+ name: output.name, ref: output.ref, type: output.type, typeRef: output.typeRef,+ }];});return {placement: placement.tag,surface: placement.surface,- module: placement.module.name,+ module: { ...placement.module },...(placement.id === undefined ? {} : { authoredId: placement.id }),outputPorts: placement.outputPorts.map((port) => {const output = outputFor(source, port.ref);@@ -78,6 +86,7 @@ export function traceFor(source: CompiledSource, ref: string): StudioTrace {name: port.name,ref: output?.ref ?? port.ref,...(output?.type === undefined ? {} : { type: output.type }),+ ...(output?.typeRef === undefined ? {} : { typeRef: output.typeRef }),};}),references: refs,@@ -86,7 +95,7 @@ export function traceFor(source: CompiledSource, ref: string): StudioTrace {/** Additional same-Surface values a Companion requires beyond the terminal Track. */export function tracedStudioValues(- registry: StudioAdapterRegistry,+ registry: StudioCompanionRegistry,source: CompiledSource,ref: string,): readonly string[] {@@ -95,9 +104,9 @@ export function tracedStudioValues(if (output === undefined || placement === undefined) return [];const siblingTypes = placement.outputPorts.flatMap((port) => {const found = outputFor(source, port.ref);- return found === undefined ? [] : [found.type];+ return found === undefined ? [] : [found.typeRef];});- const ports = registry.requiredValuePorts(output.type, placement, siblingTypes);+ const ports = registry.requiredValuePorts(output.typeRef, placement, siblingTypes);return ports.map((name) => {const port = placement.outputPorts.find((candidate) => candidate.name === name);if (port === undefined) {diff --git a/packages/studio/src/surface-preview.ts b/packages/studio/src/surface-preview.tsindex 11a771aa..d69bb241 100644--- a/packages/studio/src/surface-preview.ts+++ b/packages/studio/src/surface-preview.ts@@ -21,11 +21,9 @@ export function findSurfacePreview(/** A selected package resource descriptor; transport remains Studio-owned. */export function studioSurfacePreview(domain: StudioDomain,- moduleName: string,+ module: { readonly name: string; readonly version: string },surface: string,): StudioMaterialPreview | undefined {- const module = domain.resolveModule(moduleName);- if (module === undefined) return undefined;const preview = findSurfacePreview(domain, module, surface);if (preview === undefined) return undefined;const kind = kindOf(preview.mediaType);diff --git a/packages/studio/src/temporal-graph.ts b/packages/studio/src/temporal-graph.tsindex d4889d18..a4c938f2 100644--- a/packages/studio/src/temporal-graph.ts+++ b/packages/studio/src/temporal-graph.ts@@ -1,13 +1,14 @@+import { sameType } from "@hypit/protocol";import type { BuildState, ProducerStep, StoredValue, TypedRecord } from "@hypit/protocol";+import { temporalModuleRef, temporalTypes } from "@hypit/temporal";import type {StudioTemporalBinding,+ StudioTemporalAuthority,+ StudioTemporalInstantProjection,StudioTemporalProjection,StudioTemporalSource,} from "@hypit/studio-adapter";-const TEMPORAL_MODULE = "@hypit/temporal";-const TEMPORAL_TYPES = new Set(["TemporalPoint", "TemporalWindow"]);-type PointExpression = {readonly ref?: string;readonly offset?: unknown;@@ -51,50 +52,96 @@ function expression(value: unknown): string {}function source(value: unknown): StudioTemporalSource | undefined {- const held = value as { readonly kind?: unknown; readonly id?: unknown } | undefined;+ const held = value as {+ readonly spaceId?: unknown;+ readonly narrativeId?: unknown;+ readonly kind?: unknown;+ readonly id?: unknown;+ } | undefined;if (held?.kind !== "program" && held?.kind !== "selection"&& held?.kind !== "segment" && held?.kind !== "moment") return undefined;+ if (typeof held.spaceId !== "string" || typeof held.narrativeId !== "string" || typeof held.id !== "string") {+ return undefined;+ }return {+ spaceId: held.spaceId,+ narrativeId: held.narrativeId,kind: held.kind,- ...(typeof held.id === "string" ? { id: held.id } : {}),+ id: held.id,+ };+}++function instant(value: unknown): StudioTemporalInstantProjection | undefined {+ const held = value as {+ readonly source?: unknown;+ readonly projection?: unknown;+ readonly authority?: {+ readonly kind?: unknown;+ readonly boundary?: unknown;+ readonly binding?: unknown;+ readonly relation?: unknown;+ };+ readonly frame?: unknown;+ } | undefined;+ if (held === undefined) return undefined;+ const temporalSource = source(held.source);+ if (temporalSource === undefined || !Number.isSafeInteger(held.frame)) return undefined;+ const point = held.projection as PointExpression | undefined;+ const reference = point?.ref;+ if (reference !== "program.start" && reference !== "program.end"+ && reference !== "selection.start" && reference !== "selection.end"+ && reference !== "segment.start" && reference !== "segment.end"+ && reference !== "moment.cue" && reference !== "absolute") return undefined;+ const authority = held?.authority;+ let resolvedAuthority: StudioTemporalAuthority | undefined;+ if (authority?.kind === "semantic"+ && (authority.boundary === "start" || authority.boundary === "end" || authority.boundary === "cue")) {+ resolvedAuthority = { kind: "semantic", source: temporalSource, boundary: authority.boundary };+ } else if (authority?.kind === "parameter" && typeof authority.binding === "string"+ && (authority.relation === "direct" || authority.relation === "after-start" || authority.relation === "before-end")) {+ resolvedAuthority = { kind: "parameter", binding: authority.binding, relation: authority.relation };+ } else if (authority?.kind === "fixed") {+ resolvedAuthority = { kind: "fixed" };+ }+ if (resolvedAuthority === undefined) return undefined;+ return {+ kind: "instant",+ expression: expression(held.projection),+ reference,+ frame: held.frame as number,+ source: temporalSource,+ authority: resolvedAuthority,};}function projection(record: TypedRecord): {readonly id: string;- readonly source: StudioTemporalSource;+ readonly subjectId: string;readonly projection: StudioTemporalProjection;} | undefined {const held = inline(record.value) as {readonly id?: unknown;- readonly source?: unknown;- readonly projection?: unknown;- readonly frame?: unknown;+ readonly subjectId?: unknown;+ readonly start?: unknown;+ readonly end?: unknown;readonly span?: { readonly startFrame?: unknown; readonly endFrameExclusive?: unknown };} | undefined;- const temporalSource = source(held?.source);- if (typeof held?.id !== "string" || temporalSource === undefined) return undefined;- if (record.type.name === "TemporalPoint") {- if (!Number.isSafeInteger(held.frame)) return undefined;- return {- id: held.id,- source: temporalSource,- projection: {- kind: "point",- expression: expression(held.projection),- frame: held.frame as number,- },- };+ if (typeof held?.id !== "string" || typeof held.subjectId !== "string") return undefined;+ if (sameType(record.type, temporalTypes.instant)) {+ const projected = instant(inline(record.value));+ return projected === undefined ? undefined : { id: held.id, subjectId: held.subjectId, projection: projected };}- const window = held.projection as { readonly start?: unknown; readonly end?: unknown } | undefined;+ const start = instant(held.start);+ const end = instant(held.end);+ if (start === undefined || end === undefined) return undefined;if (!Number.isSafeInteger(held.span?.startFrame) || !Number.isSafeInteger(held.span?.endFrameExclusive)) return undefined;return {id: held.id,- source: temporalSource,+ subjectId: held.subjectId,projection: {kind: "window",- startExpression: expression(window?.start),- endExpression: expression(window?.end),+ start,+ end,startFrame: held.span!.startFrame as number,endFrameExclusive: held.span!.endFrameExclusive as number,},@@ -128,17 +175,6 @@ function closure(state: BuildState, output: string): ReadonlySet<string> {return steps;}-function specOf(step: ProducerStep | undefined, records: ReadonlyMap<string, TypedRecord>): {- readonly record: string;- readonly id: string;-} | undefined {- const id = step?.inputs.spec;- if (id === undefined) return undefined;- const value = records.get(id);- const spec = value === undefined ? undefined : inline(value.value) as { readonly id?: unknown } | undefined;- return typeof spec?.id === "string" ? { record: id, id: spec.id } : undefined;-}-/*** Read Temporal lineage from the exact executed dependency closure of one* logical output. Projection and consumption are graph facts; source markup is@@ -153,17 +189,20 @@ export function executedTemporalBindings(const stepIds = closure(state, output);const steps = state.plan.steps.filter((step) => stepIds.has(step.id));return [...records.values()]- .filter((record) => record.type.module.name === TEMPORAL_MODULE && TEMPORAL_TYPES.has(record.type.name))+ .filter((record) => sameType(record.type, temporalTypes.instant) || sameType(record.type, temporalTypes.window)).flatMap((record): readonly StudioTemporalBinding[] => {const projected = projection(record);if (projected === undefined) return [];- const spec = specOf(producers.get(record.id), records);const consumers = steps.flatMap((step) => Object.entries(step.inputs).filter(([, input]) => input === record.id).map(([input]) => ({step: step.id,producer: { module: { ...step.producer.module }, name: step.producer.name },input,+ role: step.producer.module.name === temporalModuleRef.name+ && step.producer.module.version === temporalModuleRef.version+ ? "projection" as const+ : "domain" as const,inputs: Object.entries(step.inputs).flatMap(([name, id]) => {const found = records.get(id);if (found === undefined) return [];@@ -179,7 +218,6 @@ export function executedTemporalBindings(if (consumers.length === 0) return [];return [{record: record.id,- ...(spec === undefined ? {} : { specRecord: spec.record, specId: spec.id }),...projected,consumers: consumers.sort((left, right) => left.step.localeCompare(right.step)|| left.input.localeCompare(right.input)),diff --git a/packages/studio/src/ui/code.ts b/packages/studio/src/ui/code.tsindex 3bce4a63..f932e069 100644--- a/packages/studio/src/ui/code.ts+++ b/packages/studio/src/ui/code.ts@@ -142,6 +142,7 @@ export function createCodePane(): CodePane {if (savingPath === undefined) return;saveInFlight = true;let accepted = false;+ let acceptedRevision = savingRevision;saveState.textContent = "Saving";saveState.className = "code-save-state saving";try {@@ -154,7 +155,10 @@ export function createCodePane(): CodePane {const reason = await response.text();throw new Error(reason || `Save failed (${response.status})`);}+ const result = await response.json() as { readonly revision?: unknown };+ if (typeof result.revision === "number") acceptedRevision = result.revision;accepted = true;+ if (activeSource?.path === savingPath) editingRevision = acceptedRevision;if (activeSource?.path === savingPath && editor.value === savingText) {sourceText = savingText;dirty = false;diff --git a/packages/studio/src/ui/timeline.ts b/packages/studio/src/ui/timeline.tsindex 62b72982..db253a9c 100644--- a/packages/studio/src/ui/timeline.ts+++ b/packages/studio/src/ui/timeline.ts@@ -256,7 +256,6 @@ export function createTimeline(store: Store): Timeline {const semantic = edit.handle.semantic;const anchors = state.snapshot.semantic.anchors;if (semantic.kind === "moment") {- if (edit.handle.gesture !== "move") return undefined;const currentIndex = anchors.findIndex((anchor) => anchor.id === semantic.anchorId);const anchorIndex = nearestAnchorIndex(nextFrame,@@ -279,6 +278,23 @@ export function createTimeline(store: Store): Timeline {index > startIndex && anchor.frame > anchors[startIndex]!.frame ? [index] : []);nextEnd = nearestAnchorIndex(nextFrame, allowed, endIndex) ?? endIndex;} else if (edit.handle.gesture === "move") {+ const instantBoundary = edit.handle.temporal?.kind === "instant"+ && edit.handle.temporal.authority.kind === "semantic"+ && edit.handle.temporal.authority.source.kind === "selection"+ ? edit.handle.temporal.authority.boundary+ : undefined;+ if (instantBoundary === "start") {+ const allowed = anchors.flatMap((anchor, index) =>+ index < endIndex && anchor.frame < anchors[endIndex]!.frame ? [index] : []);+ nextStart = nearestAnchorIndex(nextFrame, allowed, startIndex) ?? startIndex;+ return { kind: "selection", startAnchorId: anchors[nextStart]!.id, endAnchorId: anchors[nextEnd]!.id };+ }+ if (instantBoundary === "end") {+ const allowed = anchors.flatMap((anchor, index) =>+ index > startIndex && anchor.frame > anchors[startIndex]!.frame ? [index] : []);+ nextEnd = nearestAnchorIndex(nextFrame, allowed, endIndex) ?? endIndex;+ return { kind: "selection", startAnchorId: anchors[nextStart]!.id, endAnchorId: anchors[nextEnd]!.id };+ }const pointerIndex = edit.pointerAnchorIndex ?? startIndex;const deltas = anchors.flatMap((_, index) => {const delta = index - pointerIndex;@@ -343,6 +359,15 @@ export function createTimeline(store: Store): Timeline {const nextStart = state.snapshot.semantic.anchors.find((anchor) => anchor.id === target.startAnchorId)?.frame;const nextEnd = state.snapshot.semantic.anchors.find((anchor) => anchor.id === target.endAnchorId)?.frame;if (current === undefined || nextStart === undefined || nextEnd === undefined) return undefined;+ const instantBoundary = edit.handle.temporal?.kind === "instant"+ && edit.handle.temporal.authority.kind === "semantic"+ && edit.handle.temporal.authority.source.kind === "selection"+ ? edit.handle.temporal.authority.boundary+ : undefined;+ if (instantBoundary === "start" || instantBoundary === "end") {+ const frame = instantBoundary === "start" ? nextStart : nextEnd;+ return { startFrame: frame, endFrameExclusive: frame + 1 };+ }return {startFrame: nextStart + edit.clip.startFrame - current.startFrame,endFrameExclusive: nextEnd + edit.clip.endFrameExclusive - current.endFrameExclusive,@@ -353,11 +378,17 @@ export function createTimeline(store: Store): Timeline {const next = state.snapshot.semantic.anchors.find((anchor) => anchor.id === target.anchorId)?.frame;if (current === undefined || next === undefined) return undefined;const delta = next - current.frame;+ if (edit.handle.gesture === "trim-start") {+ return { startFrame: next, endFrameExclusive: edit.clip.endFrameExclusive };+ }+ if (edit.handle.gesture === "trim-end") {+ return { startFrame: edit.clip.startFrame, endFrameExclusive: next };+ }return edit.handle.moveEffect === "move-start"? { startFrame: edit.clip.startFrame + delta, endFrameExclusive: edit.clip.endFrameExclusive }: { startFrame: edit.clip.startFrame + delta, endFrameExclusive: edit.clip.endFrameExclusive + delta };}- return edit.handle.sources === undefined ? undefined : absoluteWindowTarget(edit, nextFrame);+ return edit.handle.temporal === undefined ? undefined : absoluteWindowTarget(edit, nextFrame);};lanes.addEventListener("pointerdown", (event) => {pointerDownOnItem = (event.target as HTMLElement).closest(@@ -415,19 +446,36 @@ export function createTimeline(store: Store): Timeline {? rawFrameAt(event.clientX): frameAt(event.clientX);const resolvedSemanticTarget = semanticTarget(edit, nextFrame);- const windowTarget = { kind: "window" as const, ...absoluteWindowTarget(edit, nextFrame) };- const target = resolvedSemanticTarget ?? (edit.handle.sources === undefined ? undefined : windowTarget);- if (target === undefined) return;- if (target.kind === "selection"+ const resolvedWindow = previewWindow(edit, nextFrame);+ if (resolvedWindow === undefined || edit.handle.temporal === undefined) return;+ const target = edit.handle.temporal.kind === "instant"+ ? {+ kind: "instant" as const,+ frame: resolvedWindow.startFrame,+ ...(resolvedSemanticTarget === undefined ? {} : { semantic: resolvedSemanticTarget }),+ }+ : {+ kind: "window" as const,+ ...resolvedWindow,+ ...(resolvedSemanticTarget === undefined ? {} : { semantic: resolvedSemanticTarget }),+ };+ if (resolvedSemanticTarget?.kind === "selection"&& edit.handle.semantic?.kind === "selection"- && target.startAnchorId === edit.handle.semantic.startAnchorId- && target.endAnchorId === edit.handle.semantic.endAnchorId) return;- if (target.kind === "moment"+ && resolvedSemanticTarget.startAnchorId === edit.handle.semantic.startAnchorId+ && resolvedSemanticTarget.endAnchorId === edit.handle.semantic.endAnchorId+ && (target.kind === "instant"+ ? target.frame === edit.clip.startFrame+ : target.startFrame === edit.clip.startFrame && target.endFrameExclusive === edit.clip.endFrameExclusive)) return;+ if (resolvedSemanticTarget?.kind === "moment"&& edit.handle.semantic?.kind === "moment"- && target.anchorId === edit.handle.semantic.anchorId) return;- if (target.kind === "window"- && target.startFrame === edit.clip.startFrame- && target.endFrameExclusive === edit.clip.endFrameExclusive) return;+ && resolvedSemanticTarget.anchorId === edit.handle.semantic.anchorId+ && (target.kind === "instant"+ ? target.frame === edit.clip.startFrame+ : target.startFrame === edit.clip.startFrame && target.endFrameExclusive === edit.clip.endFrameExclusive)) return;+ if (resolvedSemanticTarget === undefined+ && (target.kind === "instant"+ ? target.frame === edit.clip.startFrame+ : target.startFrame === edit.clip.startFrame && target.endFrameExclusive === edit.clip.endFrameExclusive)) return;element.dispatchEvent(new CustomEvent("studio:write", { detail: { state: "saving" } }));void applyStudioMutation({type: "timeline.adjust",diff --git a/packages/studio/start.ts b/packages/studio/start.tsindex b4d23e74..f42376f2 100644--- a/packages/studio/start.ts+++ b/packages/studio/start.ts@@ -6,7 +6,7 @@ import { findRuntimeProfile } from "@hypit/cli";import { videoCliDistribution } from "@hypit/video-cli";import { openStudioArchive } from "./src/archive.js";-import { loadStudioAdapterRegistry } from "./src/adapter-profile.js";+import { loadStudioCompanionRegistry } from "./src/companion-profile.js";import { loadStudioDomain } from "./src/domain.js";import { loadStudioRun } from "./src/run.js";import { studioPlugin } from "./src/server.js";@@ -69,7 +69,7 @@ const port = Number(values.get("port") ?? "5179");if (!Number.isSafeInteger(port) || port <= 0) usage("--port must be a positive integer");const distributionPackageRoot = videoCliDistribution.packageRoot ?? resolve(here, "../..");-const registry = await loadStudioAdapterRegistry({+const registry = await loadStudioCompanionRegistry({workspaceRoot,packageRoot,distributionPackageRoot,@@ -82,6 +82,7 @@ try {run = await loadStudioRun({run: runPath,domain,+ registry,...(archive === undefined ? {} : { archive }),});} catch (error) {diff --git a/packages/studio/test/parameters.test.ts b/packages/studio/test/parameters.test.tsindex 5fe2d5e5..f2cbba2d 100644--- a/packages/studio/test/parameters.test.ts+++ b/packages/studio/test/parameters.test.ts@@ -6,13 +6,15 @@ import type {StudioSemanticTimeline,StudioTemporalLineage,} from "@hypit/studio-adapter";-import { projectedWindowTimelineEdits } from "@hypit/studio-adapter";import type { MarkupSurfaceRegistryLike, RegisteredSurface } from "@hypit/markup";import { inspectorFieldsForBindings, resolveTimelineEditHandles, sourceBindingsForDraft } from "../src/parameters.js";import { serializeParameterValue, validateParameterValue } from "../src/parameter-values.js";+const temporalIdentity = { spaceId: "speech", narrativeId: "story" } as const;+const semantic: StudioSemanticTimeline = {+ ...temporalIdentity,presentation: {family: "speech",tone: "teal",@@ -47,19 +49,24 @@ test("structured parameter values validate and serialize through the generic SVStest("timeline gestures resolve through the shared Selection identity", () => {const temporal: StudioTemporalLineage = {- source: { kind: "selection", id: "claim" },projection: {kind: "window",- startExpression: "selection.claim.start",- endExpression: "selection.claim.end",+ start: {+ kind: "instant", expression: "selection.start", reference: "selection.start", frame: 0,+ source: { ...temporalIdentity, kind: "selection", id: "claim" },+ authority: { kind: "semantic", source: { ...temporalIdentity, kind: "selection", id: "claim" }, boundary: "start" },+ },+ end: {+ kind: "instant", expression: "selection.end", reference: "selection.end", frame: 12,+ source: { ...temporalIdentity, kind: "selection", id: "claim" },+ authority: { kind: "semantic", source: { ...temporalIdentity, kind: "selection", id: "claim" }, boundary: "end" },+ },startFrame: 0,endFrameExclusive: 12,},phases: [],};- const handles = resolveTimelineEditHandles(- [], projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }), temporal, semantic,- );+ const handles = resolveTimelineEditHandles([], temporal, semantic);assert.deepEqual(handles.map((handle) => [handle.operation, handle.gesture, handle.coordinate, handle.enabled]), [["timeline.adjust", "move", "semantic-anchor", true],@@ -68,6 +75,7 @@ test("timeline gestures resolve through the shared Selection identity", () => {]);assert.deepEqual(handles.map((handle) => handle.semantic), Array.from({ length: 3 }, () => ({kind: "selection",+ narrativeId: "story",id: "claim",startAnchorId: "segment:a:token:1:start",endAnchorId: "segment:a:token:1:end",@@ -75,31 +83,73 @@ test("timeline gestures resolve through the shared Selection identity", () => {});test("moving a Moment projection resolves to the shared Moment identity", () => {- const handles = resolveTimelineEditHandles([], projectedWindowTimelineEdits({- start: "start", end: "end", duration: "for",- }), {- source: { kind: "moment", id: "beat" },- projection: { kind: "point", expression: "moment.beat", frame: 12 },+ const handles = resolveTimelineEditHandles([], {+ projection: {+ kind: "instant", expression: "moment.cue", reference: "moment.cue", frame: 12,+ source: { ...temporalIdentity, kind: "moment", id: "beat" },+ authority: { kind: "semantic", source: { ...temporalIdentity, kind: "moment", id: "beat" }, boundary: "cue" },+ },phases: [],}, {...semantic,moments: [{ id: "beat", anchorId: "segment:a:token:1:end", frame: 12 }],});- assert.deepEqual(handles.map((handle) => [handle.gesture, handle.enabled]), [- ["move", true],- ["trim-start", false],- ["trim-end", false],- ]);+ assert.deepEqual(handles.map((handle) => [handle.gesture, handle.enabled]), [["move", true]]);assert.deepEqual(handles[0]!.semantic, {kind: "moment",+ narrativeId: "story",id: "beat",anchorId: "segment:a:token:1:end",});});+test("at/for and until/for derive complementary semantic and duration inverses", () => {+ const duration = {+ id: "for", binding: "for", name: "for", value: "8f", language: "svml" as const, writable: true,+ source: { endpoint: "main::for", path: "main.svml", range: { start: 4, end: 6 }, preimage: "8f" },+ };+ const withMoment = {+ ...semantic,+ moments: [{ id: "beat", anchorId: "segment:a:token:1:end", frame: 12 }],+ };+ const moment = {+ kind: "instant" as const, expression: "moment.cue", reference: "moment.cue" as const, frame: 12,+ source: { ...temporalIdentity, kind: "moment" as const, id: "beat" },+ authority: { kind: "semantic" as const, source: { ...temporalIdentity, kind: "moment" as const, id: "beat" }, boundary: "cue" as const },+ };+ const after = {+ kind: "instant" as const, expression: "moment.cue+8f", reference: "moment.cue" as const, frame: 20,+ source: { ...temporalIdentity, kind: "moment" as const, id: "beat" },+ authority: { kind: "parameter" as const, binding: "for", relation: "after-start" as const },+ };+ const before = {+ kind: "instant" as const, expression: "moment.cue-8f", reference: "moment.cue" as const, frame: 4,+ source: { ...temporalIdentity, kind: "moment" as const, id: "beat" },+ authority: { kind: "parameter" as const, binding: "for", relation: "before-end" as const },+ };+ const atFor = resolveTimelineEditHandles([duration], {+ projection: { kind: "window", start: moment, end: after, startFrame: 12, endFrameExclusive: 20 }, phases: [],+ }, withMoment);+ assert.deepEqual(atFor.map((handle) => [handle.gesture, handle.semantic?.kind, handle.sources?.map((source) => source.role)]), [+ ["move", "moment", undefined],+ ["trim-start", "moment", ["duration"]],+ ["trim-end", undefined, ["duration"]],+ ]);++ const untilFor = resolveTimelineEditHandles([duration], {+ projection: { kind: "window", start: before, end: moment, startFrame: 4, endFrameExclusive: 12 }, phases: [],+ }, withMoment);+ assert.deepEqual(untilFor.map((handle) => [handle.gesture, handle.semantic?.kind, handle.sources?.map((source) => source.role)]), [+ ["move", "moment", undefined],+ ["trim-start", undefined, ["duration"]],+ ["trim-end", "moment", ["duration"]],+ ]);+});+test("absolute Window edits use only the Companion's exact parameter vocabulary", () => {const source = (start: number, end: number) => ({+ endpoint: `main::${start}`,path: "main.svml",range: { start, end },preimage: "1f",@@ -116,11 +166,17 @@ test("absolute Window edits use only the Companion's exact parameter vocabulary"];const handles = resolveTimelineEditHandles(parameters,- projectedWindowTimelineEdits({ start: "from", end: "until", duration: "length" }),{- source: { kind: "program" },projection: {- kind: "window", startExpression: "1f", endExpression: "20f",+ kind: "window",+ start: {+ kind: "instant", expression: "1f", reference: "absolute", frame: 1, source: { ...temporalIdentity, kind: "program", id: "program" },+ authority: { kind: "parameter", binding: "from", relation: "direct" },+ },+ end: {+ kind: "instant", expression: "20f", reference: "absolute", frame: 20, source: { ...temporalIdentity, kind: "program", id: "program" },+ authority: { kind: "parameter", binding: "until", relation: "direct" },+ },startFrame: 1, endFrameExclusive: 20,},phases: [],diff --git a/packages/studio/test/preflight.test.ts b/packages/studio/test/preflight.test.tsnew file mode 100644index 00000000..a8f53306--- /dev/null+++ b/packages/studio/test/preflight.test.ts@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import test from "node:test";++import { compositionTypes } from "@hypit/composition";+import { semanticTrackTypes } from "@hypit/semantic-track";+import type { StudioFilmCompanion, StudioPlacement } from "@hypit/studio-adapter";++import type { CompiledSource } from "../src/compile.js";+import type { RunPlan } from "../src/run.js";+import { inspectStudioRun, StudioPreflightError } from "../src/studio-preflight.js";+import { StudioCompanionRegistry } from "../src/studio-registry.js";++const filmModule = { name: "@example/film", version: "1" } as const;+const companion: StudioFilmCompanion = {+ id: "film",+ match: { module: filmModule, surface: "film", outputType: compositionTypes.composition },+ semantic: { attribute: "semantic", type: semanticTrackTypes.track },+ tracks: { childSurface: "Track", sourceAttribute: "source", types: [compositionTypes.visualTrack] },+};++function placement(id: string): StudioPlacement {+ return {+ sourcePath: "main.svml", tag: "Film", module: filmModule, surface: "film", id,+ range: { start: 0, end: 1 }, records: [], values: [], outputs: [`${id}.composition`], outputPorts: [],+ children: [], attributes: {}, attributeValueRanges: {}, referenceAttributes: {}, referenceTypes: {}, references: [],+ };+}++test("Studio rejects a Run that reaches two distinct Film compositions", () => {+ const source = {+ observations: { placements: [placement("one"), placement("two")], sourceMaps: [] },+ served: new Map(),+ exports: ["one", "two"].map((id) => ({+ name: `${id}.composition`, ref: `${id}.composition`, type: "Composition", typeRef: compositionTypes.composition,+ })),+ compiled: { program: { records: [] } },+ } as unknown as CompiledSource;+ const run = {+ source, targets: ["one.composition", "two.composition"], attachments: [],+ runPath: "build.svrun", authorSource: "main.svml",+ run: { graph: { candidates: [], operations: [], satisfactions: [], targets: [] } },+ plan: () => { throw new Error("multi-Film rejection must happen before planning projections"); },+ } as unknown as RunPlan;+ const registry = new StudioCompanionRegistry([], { films: [companion] });+ assert.throws(+ () => inspectStudioRun(registry, source, run),+ (error: unknown) => error instanceof StudioPreflightError+ && error.issues.some((issue) => issue.includes("multiple Film compositions")),+ );+});diff --git a/packages/studio/test/provenance.test.ts b/packages/studio/test/provenance.test.tsnew file mode 100644index 00000000..d4396889--- /dev/null+++ b/packages/studio/test/provenance.test.ts@@ -0,0 +1,64 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { NodeCompiledSourceClosure } from "@hypit/compiler-node";+import type { StudioPlacement } from "@hypit/studio-adapter";++import { observedCompiledSource } from "../src/compile.js";+import { outputFor, placementFor } from "../src/studio-trace.js";++const type = { module: { name: "example.track", version: "1" }, name: "VisualTrack" } as const;++function placement(sourcePath: string): StudioPlacement {+ return {+ sourcePath,+ tag: "example:Track",+ module: { name: "example.track", version: "1" },+ surface: "track",+ id: "track",+ range: { start: 10, end: 20 },+ records: [],+ values: [],+ outputs: ["visual"],+ outputPorts: [{ name: "visual", ref: "visual" }],+ children: [],+ attributes: { id: "track" },+ attributeValueRanges: { id: { start: 14, end: 19 } },+ referenceAttributes: {},+ referenceTypes: {},+ references: [],+ };+}++test("Studio joins repeated local names through compiler-owned provenance", async () => {+ const element = (source: string, output: string) => ({+ id: `${source}::element::10:20`, source, sourceName: source, frontend: "@hypit/markup@1",+ range: { start: 10, end: 20 }, records: [], components: [{ local: "track", id: `${source}::component::track` }],+ outputs: [{ component: `${source}::component::track`, name: "visual", local: "visual", id: output }],+ inputs: [{ id: `${source}::endpoint::10:id`, name: "id", range: { start: 14, end: 19 }, kind: "literal" as const }],+ });+ const compiled = {+ closure: { entry: "a.svml", units: [] },+ program: { closure: { modules: [] }, records: [] },+ graph: {+ format: "hypit.graph@1", candidates: [], operations: [],+ outputs: [+ { id: "a::output::visual", type, primary: "a-candidate" },+ { id: "b::output::visual", type, primary: "b-candidate" },+ ],+ },+ exports: [{ name: "visual", type, ref: { kind: "logical-output", id: "a::output::visual" } }],+ provenance: { format: "hypit.author-provenance@1", elements: [+ element("a.svml", "a::output::visual"),+ element("b.svml", "b::output::visual"),+ ] },+ attachments: [],+ } as unknown as NodeCompiledSourceClosure;+ const source = await observedCompiledSource(compiled, {+ placements: [placement("a.svml"), placement("b.svml")],+ sourceMaps: [],+ });+ assert.equal(outputFor(source, "b::output::visual")?.ref, "b::output::visual");+ assert.equal(placementFor(source, "b::output::visual")?.sourcePath, "b.svml");+ assert.equal(placementFor(source, "b::output::visual")?.authorEndpoints?.id, "b.svml::endpoint::10:id");+});diff --git a/packages/studio/test/registry.test.ts b/packages/studio/test/registry.test.tsnew file mode 100644index 00000000..e0e15cb3--- /dev/null+++ b/packages/studio/test/registry.test.ts@@ -0,0 +1,22 @@+import assert from "node:assert/strict";+import test from "node:test";++import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion } from "@hypit/studio-adapter";++import { StudioCompanionRegistry } from "../src/studio-registry.js";++test("Companion origin matching includes the exact module version", () => {+ const moduleV1 = { name: "@example/track", version: "1" } as const;+ const companion: StudioTrackCompanion = {+ id: "example", role: "track", family: "example",+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [moduleV1] },+ };+ const registry = new StudioCompanionRegistry([companion]);+ assert.equal(registry.trackCompanionFor(compositionTypes.visualTrack, { surface: "track", module: moduleV1 }, []), companion);+ assert.equal(registry.trackCompanionFor(+ compositionTypes.visualTrack,+ { surface: "track", module: { ...moduleV1, version: "2" } },+ [],+ ), undefined);+});diff --git a/packages/studio/test/source-transaction.test.ts b/packages/studio/test/source-transaction.test.tsnew file mode 100644index 00000000..62c57388--- /dev/null+++ b/packages/studio/test/source-transaction.test.ts@@ -0,0 +1,27 @@+import assert from "node:assert/strict";+import test from "node:test";++import { replaceSourceFiles } from "../src/source-transaction.js";++test("a failed multi-file publish restores every file already replaced", async () => {+ const files = new Map<string, string>([["/work/a.svml", "old-a"], ["/work/b.svml", "old-b"]]);+ let failed = false;+ await assert.rejects(replaceSourceFiles(new Map([+ ["/work/a.svml", "new-a"],+ ["/work/b.svml", "new-b"],+ ]), {+ read: async (path) => files.get(path)!,+ write: async (path, text) => { files.set(path, text); },+ move: async (from, to) => {+ if (to === "/work/b.svml" && !failed) {+ failed = true;+ throw new Error("publish failed");+ }+ files.set(to, files.get(from)!);+ files.delete(from);+ },+ remove: async (path) => { files.delete(path); },+ }), /publish failed/u);+ assert.equal(files.get("/work/a.svml"), "old-a");+ assert.equal(files.get("/work/b.svml"), "old-b");+});diff --git a/packages/studio/test/temporal-graph.test.ts b/packages/studio/test/temporal-graph.test.tsindex 8eaaccc6..53ab17a5 100644--- a/packages/studio/test/temporal-graph.test.ts+++ b/packages/studio/test/temporal-graph.test.ts@@ -15,25 +15,29 @@ const step = (id: string, owner: string, name: string, inputs: ProducerStep["inpid, producer: producer(owner, name), inputs, outputs, needs: {},});-test("Studio reads Point lineage from the executed projection and consumption edges", () => {+test("Studio reads Instant lineage and author authority from executed graph edges", () => {const program = [record("semantic", "@hypit/semantic-track", "SemanticTrack", { id: "speech" }),record("moment", "@hypit/narrative", "NarrativeMoment", { id: "cue", anchorId: "cue-anchor" }),- record("point-spec", "@hypit/temporal", "TemporalPointSpec", { id: "deck.card", projection: { ref: "moment.cue" } }),+ record("point-spec", "@hypit/temporal", "TemporalInstantSpec", {+ id: "deck.card", subjectId: "card", projection: { ref: "moment.cue" }, authority: { kind: "semantic", boundary: "cue" },+ }),record("card-spec", "@hypit/deck-track", "DepthStackCardSpec", { id: "card" }),];const executed = [- record("point", "@hypit/temporal", "TemporalPoint", {- id: "deck.card::cue", source: { kind: "moment", id: "cue" }, projection: { ref: "moment.cue" }, frame: 42,+ record("point", "@hypit/temporal", "TemporalInstant", {+ id: "deck.card::cue", subjectId: "card", source: { spaceId: "speech", narrativeId: "story", kind: "moment", id: "cue" }, projection: { ref: "moment.cue" },+ authority: { kind: "semantic", boundary: "cue" }, frame: 42,}),record("cards", "@hypit/deck-track", "DepthStackCardSet", { cards: [{ id: "card", activationFrame: 42 }] }),record("track", "@hypit/composition", "VisualTrack", { presents: [] }),- record("unused-point", "@hypit/temporal", "TemporalPoint", {- id: "unused::cue", source: { kind: "moment", id: "cue" }, projection: { ref: "moment.cue" }, frame: 7,+ record("unused-point", "@hypit/temporal", "TemporalInstant", {+ id: "unused::cue", subjectId: "unused", source: { spaceId: "speech", narrativeId: "story", kind: "moment", id: "cue" }, projection: { ref: "moment.cue" },+ authority: { kind: "semantic", boundary: "cue" }, frame: 7,}),];const steps = [- step("project", "@hypit/temporal", "project-moment-point", { semantic: "semantic", moment: "moment", spec: "point-spec" }, { point: "point" }),+ step("project", "@hypit/temporal", "project-moment-instant", { semantic: "semantic", moment: "moment", spec: "point-spec" }, { instant: "point" }),step("append", "@hypit/deck-track", "append-depth-stack-card", { set: "empty", spec: "card-spec", activation: "point" }, { set: "cards" }),step("render", "@hypit/deck-track", "render-depth-stack", { program: "cards" }, { track: "track" }),];@@ -54,17 +58,20 @@ test("Studio reads Point lineage from the executed projection and consumption edassert.equal(bindings.length, 1);assert.deepEqual(bindings[0], {record: "point",- specRecord: "point-spec",- specId: "deck.card",+ subjectId: "card",id: "deck.card::cue",- source: { kind: "moment", id: "cue" },- projection: { kind: "point", expression: "moment.cue", frame: 42 },+ projection: {+ kind: "instant", expression: "moment.cue", reference: "moment.cue", frame: 42,+ source: { spaceId: "speech", narrativeId: "story", kind: "moment", id: "cue" },+ authority: { kind: "semantic", source: { spaceId: "speech", narrativeId: "story", kind: "moment", id: "cue" }, boundary: "cue" },+ },consumers: [{step: "append",producer: producer("@hypit/deck-track", "append-depth-stack-card"),input: "activation",+ role: "domain",inputs: [- { name: "activation", record: "point", type: type("@hypit/temporal", "TemporalPoint"), value: executed[0]!.value.kind === "inline" ? executed[0]!.value.value : undefined },+ { name: "activation", record: "point", type: type("@hypit/temporal", "TemporalInstant"), value: executed[0]!.value.kind === "inline" ? executed[0]!.value.value : undefined },{ name: "spec", record: "card-spec", type: type("@hypit/deck-track", "DepthStackCardSpec"), value: { id: "card" } },],}],diff --git a/packages/typography-track-studio/package.json b/packages/typography-track-studio/package.jsonindex 40c31600..cdaf9b16 100644--- a/packages/typography-track-studio/package.json+++ b/packages/typography-track-studio/package.json@@ -7,6 +7,7 @@"exports": { ".": "./src/index.ts" },"hypit": { "activation": "./src/activation.ts" },"dependencies": {+ "@hypit/composition": "workspace:*","@hypit/studio-adapter": "workspace:*","@hypit/typography-track": "workspace:*"}diff --git a/packages/typography-track-studio/src/activation.ts b/packages/typography-track-studio/src/activation.tsindex 32773d1f..befae114 100644--- a/packages/typography-track-studio/src/activation.ts+++ b/packages/typography-track-studio/src/activation.ts@@ -1,7 +1,7 @@-import { createStudioAdapterHostFacet } from "@hypit/studio-adapter";-import { typographyTrackStudioAdapters } from "./index.js";+import { createStudioTrackCompanionHostFacet } from "@hypit/studio-adapter";+import { typographyTrackStudioTrackCompanions } from "./index.js";export default {format: "hypit.node-package@1" as const,- hostFacets: [createStudioAdapterHostFacet(typographyTrackStudioAdapters)],+ hostFacets: [createStudioTrackCompanionHostFacet(typographyTrackStudioTrackCompanions)],};diff --git a/packages/typography-track-studio/src/index.ts b/packages/typography-track-studio/src/index.tsindex bd914728..20f15907 100644--- a/packages/typography-track-studio/src/index.ts+++ b/packages/typography-track-studio/src/index.ts@@ -1,7 +1,8 @@-import { typographyTrackMarkupSurfaces } from "@hypit/typography-track";+import { typographyTrackMarkupSurfaces, typographyTrackModuleRef, typographyTrackTypes } from "@hypit/typography-track";import type { TypographyTrackProgram } from "@hypit/typography-track";-import type { StudioAdapter, StudioAdapterContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";-import { childEntities, projectedWindowTimelineEdits, requiredSurfaceValue, temporalLineageFor, textLayer } from "@hypit/studio-adapter";+import { compositionTypes } from "@hypit/composition";+import type { StudioTrackCompanion, StudioTrackCompanionContext, StudioEntityDraft, StudioInspectorFieldDeclaration } from "@hypit/studio-adapter";+import { childEntities, requiredSurfaceValue, temporalLineageFor, temporalSemanticSource, textLayer } from "@hypit/studio-adapter";const typographyProperties = (typographyTrackMarkupSurfaces.find((surface) => surface.name === "style")?.vocabulary.attributes@@ -68,42 +69,40 @@ function textOf(item: TypographyTrackProgram["items"][number]): string {.trim();}-function projectTypography(context: StudioAdapterContext): readonly StudioEntityDraft[] {+function projectTypography(context: StudioTrackCompanionContext): readonly StudioEntityDraft[] {const program = requiredSurfaceValue(context, "program") as TypographyTrackProgram;const items = program.items.map((item) => ({id: item.id,startFrame: item.span.startFrame,endFrameExclusive: item.span.endFrameExclusive,stackOrder: item.style.stackingOrder,+ sourceTypes: [typographyTrackTypes.itemSpec, typographyTrackTypes.plainItemSpec],}));return childEntities(context, items, "typography-item", "standard").map((entity, index) => {const item = program.items[index];if (item === undefined) return entity;const label = textOf(item);const temporal = temporalLineageFor(context, item.id, "window");+ const semanticSource = temporalSemanticSource(temporal);return {...entity,display: { ...entity.display, layers: label.length === 0 ? [] : [textLayer(label)] },- ...(temporal?.source.kind === "program" || temporal?.source.id === undefined+ ...(semanticSource?.id === undefined? {}- : { markerId: temporal.source.id }),+ : { markerId: semanticSource.id }),...(temporal === undefined ? {} : { temporal }),};});}-export const typographyTrackStudioAdapters: readonly StudioAdapter[] = [+export const typographyTrackStudioTrackCompanions: readonly StudioTrackCompanion[] = [{id: "track", role: "track",- output: { type: "VisualTrack", surface: "track", modules: ["@hypit/typography-track"] },+ output: { type: compositionTypes.visualTrack, surface: "track", modules: [typographyTrackModuleRef] },family: "text", tone: "violet", icon: "text",- timelineEdits: projectedWindowTimelineEdits({ start: "start", end: "end", duration: "for" }),bindings: [{ name: "placement" },{ name: "content" },- { name: "start", writable: true },- { name: "end", writable: true },- { name: "for", writable: true },{name: "style",recipe: { through: ["recipe"], bindings: typographyProperties.map(({ name }) => ({ name })) },diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 149bc35c..3a9adb7d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -66,6 +66,9 @@ importers:'@hypit/film':specifier: workspace:*version: link:packages/film+ '@hypit/film-studio':+ specifier: workspace:*+ version: link:packages/film-studio'@hypit/fonts-open':specifier: workspace:*version: link:packages/fonts-open@@ -174,6 +177,9 @@ importers:'@hypit/script':specifier: workspace:*version: link:packages/script+ '@hypit/script-studio':+ specifier: workspace:*+ version: link:packages/script-studio'@hypit/seedance':specifier: workspace:*version: link:packages/seedance@@ -183,6 +189,9 @@ importers:'@hypit/seedream':specifier: workspace:*version: link:packages/seedream+ '@hypit/semantic-take-estimate':+ specifier: workspace:*+ version: link:packages/semantic-take-estimate'@hypit/semantic-track':specifier: workspace:*version: link:packages/semantic-track@@ -216,6 +225,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:packages/temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:packages/temporal-markup'@hypit/text':specifier: workspace:*version: link:packages/text@@ -306,6 +318,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markupdevDependencies:'@hypit/artifact':specifier: workspace:*@@ -337,6 +352,9 @@ importers:'@hypit/audio-track':specifier: workspace:*version: link:../audio-track+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/studio-adapter':specifier: workspace:*version: link:../studio-adapter@@ -441,6 +459,9 @@ importers:'@hypit/caption-fine':specifier: workspace:*version: link:../caption-fine+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/narrative':specifier: workspace:*version: link:../narrative@@ -519,6 +540,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markup'@hypit/text':specifier: workspace:*version: link:../text@@ -532,6 +556,9 @@ importers:'@hypit/comment-sticker':specifier: workspace:*version: link:../comment-sticker+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/studio-adapter':specifier: workspace:*version: link:../studio-adapter@@ -712,6 +739,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markup'@hypit/text':specifier: workspace:*version: link:../text@@ -725,6 +755,9 @@ importers:packages/deck-track-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/deck-track':specifier: workspace:*version: link:../deck-track@@ -856,6 +889,21 @@ importers:specifier: workspace:*version: link:../validation+ packages/film-studio:+ dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition+ '@hypit/film':+ specifier: workspace:*+ version: link:../film+ '@hypit/semantic-track':+ specifier: workspace:*+ version: link:../semantic-track+ '@hypit/studio-adapter':+ specifier: workspace:*+ version: link:../studio-adapter+packages/fonts-open:dependencies:'@hypit/markup':@@ -864,6 +912,9 @@ importers:'@hypit/media':specifier: workspace:*version: link:../media+ '@hypit/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -1524,12 +1575,21 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markuppackages/media-track-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/media-track':specifier: workspace:*version: link:../media-track+ '@hypit/protocol':+ specifier: workspace:*+ version: link:../protocol'@hypit/studio-adapter':specifier: workspace:*version: link:../studio-adapter@@ -1623,6 +1683,9 @@ importers:packages/narrative:dependencies:+ '@hypit/component-kit':+ specifier: workspace:*+ version: link:../component-kit'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -1707,6 +1770,9 @@ importers:'@hypit/media-execution':specifier: workspace:*version: link:../media-execution+ '@hypit/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -1747,6 +1813,9 @@ importers:'@hypit/image-opencv-runtime':specifier: workspace:*version: link:../../services/image-opencv+ '@hypit/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -1922,6 +1991,9 @@ importers:'@hypit/endpoint-kit':specifier: workspace:*version: link:../endpoint-kit+ '@hypit/package-loader-node':+ specifier: workspace:*+ version: link:../package-loader-node'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -2014,6 +2086,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markup'@hypit/text':specifier: workspace:*version: link:../text@@ -2024,6 +2099,9 @@ importers:packages/ranking-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/ranking':specifier: workspace:*version: link:../ranking@@ -2280,6 +2358,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markupdevDependencies:'@hypit/artifact':specifier: workspace:*@@ -2305,6 +2386,9 @@ importers:packages/screen-overlay-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/screen-overlay':specifier: workspace:*version: link:../screen-overlay@@ -2331,6 +2415,15 @@ importers:specifier: workspace:*version: link:../core+ packages/script-studio:+ dependencies:+ '@hypit/script':+ specifier: workspace:*+ version: link:../script+ '@hypit/studio-adapter':+ specifier: workspace:*+ version: link:../studio-adapter+packages/seedance:dependencies:'@hypit/artifact':@@ -2388,6 +2481,37 @@ importers:specifier: workspace:*version: link:../text+ packages/semantic-take-estimate:+ dependencies:+ '@hypit/component-kit':+ specifier: workspace:*+ version: link:../component-kit+ '@hypit/elaborator':+ specifier: workspace:*+ version: link:../elaborator+ '@hypit/estimate':+ specifier: workspace:*+ version: link:../estimate+ '@hypit/markup':+ specifier: workspace:*+ version: link:../markup+ '@hypit/media':+ specifier: workspace:*+ version: link:../media+ '@hypit/narrative':+ specifier: workspace:*+ version: link:../narrative+ '@hypit/protocol':+ specifier: workspace:*+ version: link:../protocol+ '@hypit/speech':+ specifier: workspace:*+ version: link:../speech+ devDependencies:+ '@hypit/script':+ specifier: workspace:*+ version: link:../script+packages/semantic-track:dependencies:'@hypit/component-kit':@@ -2442,9 +2566,15 @@ importers:packages/speech:dependencies:+ '@hypit/component-kit':+ specifier: workspace:*+ version: link:../component-kit'@hypit/media':specifier: workspace:*version: link:../media+ '@hypit/narrative':+ specifier: workspace:*+ version: link:../narrative'@hypit/protocol':specifier: workspace:*version: link:../protocol@@ -2531,6 +2661,9 @@ importers:packages/speech-track-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/speech-track':specifier: workspace:*version: link:../speech-track@@ -2585,6 +2718,9 @@ importers:'@hypit/elaborator':specifier: workspace:*version: link:../elaborator+ '@hypit/film-studio':+ specifier: workspace:*+ version: link:../film-studio'@hypit/hyperframes':specifier: workspace:*version: link:../hyperframes@@ -2594,6 +2730,9 @@ importers:'@hypit/media-track-studio':specifier: workspace:*version: link:../media-track-studio+ '@hypit/narrative':+ specifier: workspace:*+ version: link:../narrative'@hypit/package-loader-node':specifier: workspace:*version: link:../package-loader-node@@ -2618,12 +2757,15 @@ importers:'@hypit/screen-overlay-studio':specifier: workspace:*version: link:../screen-overlay-studio- '@hypit/script':+ '@hypit/script-studio':specifier: workspace:*- version: link:../script+ version: link:../script-studio'@hypit/semantic-track':specifier: workspace:*version: link:../semantic-track+ '@hypit/speech':+ specifier: workspace:*+ version: link:../speech'@hypit/speech-track-studio':specifier: workspace:*version: link:../speech-track-studio@@ -2633,6 +2775,9 @@ importers:'@hypit/svs':specifier: workspace:*version: link:../svs+ '@hypit/temporal':+ specifier: workspace:*+ version: link:../temporal'@hypit/typography-track-studio':specifier: workspace:*version: link:../typography-track-studio@@ -2695,6 +2840,24 @@ importers:specifier: workspace:*version: link:../semantic-track+ packages/temporal-markup:+ dependencies:+ '@hypit/elaborator':+ specifier: workspace:*+ version: link:../elaborator+ '@hypit/markup':+ specifier: workspace:*+ version: link:../markup+ '@hypit/narrative':+ specifier: workspace:*+ version: link:../narrative+ '@hypit/semantic-track':+ specifier: workspace:*+ version: link:../semantic-track+ '@hypit/temporal':+ specifier: workspace:*+ version: link:../temporal+packages/text:dependencies:'@hypit/component-kit':@@ -2763,6 +2926,9 @@ importers:'@hypit/temporal':specifier: workspace:*version: link:../temporal+ '@hypit/temporal-markup':+ specifier: workspace:*+ version: link:../temporal-markup'@hypit/text':specifier: workspace:*version: link:../text@@ -2779,6 +2945,9 @@ importers:packages/typography-track-studio:dependencies:+ '@hypit/composition':+ specifier: workspace:*+ version: link:../composition'@hypit/studio-adapter':specifier: workspace:*version: link:../studio-adapter