{"version":3,"file":"worker.mjs","names":["relationId"],"sources":["../src/sandbox/script-bridge.ts","../src/dsl/edit.ts","../src/dsl/plan.ts","../src/sandbox/session.ts","../src/sandbox/worker.ts"],"sourcesContent":["/// <reference types=\"node\" />\nimport vm from 'node:vm';\n\nimport type { ScriptEntities, ScriptRelations } from '../api/types.ts';\nimport type { ConsoleShim } from './types.ts';\n\n/** The three bindings a script is invoked with, as objects of the script's own realm. */\nexport interface ScriptBindings {\n  entities: unknown;\n  relations: unknown;\n  console: unknown;\n}\n\n/** What the session offers; the script never receives these objects themselves. */\nexport interface HostScriptSurface {\n  entities: ScriptEntities;\n  relations: ScriptRelations;\n  console: ConsoleShim;\n}\n\n/**\n * The script's side of the boundary, built inside its own context.\n *\n * A function handed across realms carries its realm with it: from any host\n * object or function a script can read `constructor` and reach the host's\n * `Function`, and compile whatever it likes with the worker's privileges. So\n * nothing of the host's crosses. Every call travels as JSON text — a primitive,\n * which belongs to no realm — and the objects a script sees are parsed on its\n * own side. The context refuses code generation from strings, so its own\n * `Function` compiles nothing either.\n *\n * `call` and `start` are the one exception a bridge cannot avoid: they are host\n * functions the script can reach. Re-pointing them at the context's\n * `Function.prototype` puts their `constructor` under that same refusal.\n */\nconst BRIDGE_SOURCE = `(call, start) => {\n  const encode = (value) =>\n    JSON.stringify(value, (key, item) => {\n      const kind = typeof item;\n      if (kind === 'function' || kind === 'undefined' || kind === 'symbol' || kind === 'bigint')\n        throw new TypeError('A script passes only JSON values to the document');\n      return item;\n    });\n  const decode = (answer) => {\n    const result = JSON.parse(answer);\n    if (result.failed) throw new Error(result.message);\n    return result.value;\n  };\n  const method = (name) => (...args) => decode(call(name, encode(args)));\n  const awaited = (name) => (...args) =>\n    new Promise((resolve, reject) => {\n      let answer;\n      try {\n        answer = encode(args);\n      } catch (error) {\n        reject(error);\n        return;\n      }\n      start(name, answer, (result) => {\n        try {\n          resolve(decode(result));\n        } catch (error) {\n          reject(error);\n        }\n      });\n    });\n  // Logging takes whatever a script hands it, so each argument becomes text\n  // here rather than travelling as a value the boundary would refuse.\n  const printable = (value) => {\n    if (typeof value === 'string') return value;\n    if (value === null || typeof value !== 'object') return String(value);\n    try {\n      return JSON.stringify(value) ?? String(value);\n    } catch {\n      return '[unstringifiable]';\n    }\n  };\n  const logger = (name) => (...args) => {\n    call(name, JSON.stringify([args.map(printable).join(' ')]));\n  };\n  return {\n    entities: {\n      list: method('entities.list'),\n      get: method('entities.get'),\n      create: method('entities.create'),\n      update: method('entities.update'),\n      declareFields: method('entities.declareFields'),\n      delete: method('entities.delete'),\n      materialize: awaited('entities.materialize'),\n    },\n    relations: {\n      list: method('relations.list'),\n      of: method('relations.of'),\n      link: method('relations.link'),\n      move: method('relations.move'),\n      unlink: method('relations.unlink'),\n    },\n    console: {\n      log: logger('console.log'),\n      info: logger('console.info'),\n      warn: logger('console.warn'),\n      error: logger('console.error'),\n    },\n  };\n}`;\n\nfunction failure(error: unknown): string {\n  return JSON.stringify({ failed: true, message: error instanceof Error ? error.message : String(error) });\n}\n\n/** `undefined` survives as an absent field, which is what the script reads back. */\nfunction answer(value: unknown): string {\n  return JSON.stringify({ value });\n}\n\nfunction syncMethods(surface: HostScriptSurface): Record<string, (args: readonly unknown[]) => unknown> {\n  const { entities, relations, console: shim } = surface;\n  return {\n    'entities.list': () => entities.list(),\n    'entities.get': ([entityId]) => entities.get(entityId as string),\n    'entities.create': ([entityKind, payload]) =>\n      entities.create(\n        entityKind as Parameters<ScriptEntities['create']>[0],\n        payload as Parameters<ScriptEntities['create']>[1],\n      ),\n    'entities.update': ([entityId, changes]) =>\n      entities.update(entityId as string, changes as Parameters<ScriptEntities['update']>[1]),\n    'entities.declareFields': ([entityId, payload]) =>\n      entities.declareFields(entityId as string, payload as Parameters<ScriptEntities['declareFields']>[1]),\n    'entities.delete': ([entityId]) => entities.delete(entityId as string),\n    'relations.list': () => relations.list(),\n    'relations.of': (args) =>\n      args.length > 1\n        ? relations.of(args[0] as string, args[1] as Parameters<ScriptRelations['of']>[1])\n        : relations.of(args[0] as string),\n    'relations.link': ([relationKind, endpoint0, endpoint1]) =>\n      relations.link(relationKind as Parameters<ScriptRelations['link']>[0], endpoint0 as string, endpoint1 as string),\n    'relations.move': ([relationId, beforeRelationId]) =>\n      relations.move(relationId as string, beforeRelationId as string | null),\n    'relations.unlink': ([relationId]) => relations.unlink(relationId as string),\n    'console.log': (args) => shim.log(...args),\n    'console.info': (args) => shim.info(...args),\n    'console.warn': (args) => shim.warn(...args),\n    'console.error': (args) => shim.error(...args),\n  };\n}\n\n/**\n * Give the script its bindings inside `context`.\n *\n * `context` must refuse code generation from strings; see BRIDGE_SOURCE for\n * what that refusal is holding shut.\n */\nexport function bindScriptSurface(context: vm.Context, surface: HostScriptSurface): ScriptBindings {\n  const methods = syncMethods(surface);\n  const call = (name: string, argsJson: string): string => {\n    try {\n      const method = methods[name];\n      if (method === undefined) throw new Error(`Unknown sandbox call ${name}`);\n      return answer(method(JSON.parse(argsJson) as readonly unknown[]));\n    } catch (error) {\n      return failure(error);\n    }\n  };\n  const start = (name: string, argsJson: string, done: (result: string) => void): void => {\n    void (async () => {\n      try {\n        if (name !== 'entities.materialize') throw new Error(`Unknown sandbox call ${name}`);\n        const [entityId] = JSON.parse(argsJson) as readonly unknown[];\n        done(answer(await surface.entities.materialize(entityId as string)));\n      } catch (error) {\n        done(failure(error));\n      }\n    })();\n  };\n\n  const functionPrototype = vm.runInContext('Function.prototype', context) as object;\n  Object.setPrototypeOf(call, functionPrototype);\n  Object.setPrototypeOf(start, functionPrototype);\n  const build = vm.runInContext(BRIDGE_SOURCE, context, { filename: 'sandbox-bridge.js' }) as (\n    call: unknown,\n    start: unknown,\n  ) => ScriptBindings;\n  return build(call, start);\n}\n","import {\n  assertEntity,\n  isRecord,\n  relationId,\n  resourceId,\n  validLanguage,\n  type CaptionStyle,\n  type DslMutation,\n  type Media,\n  type MedeoDslSnapshot,\n  type SandboxContract,\n  type StoredFile,\n  type TextEdit,\n} from '@mengine/medeo-dsl';\n\nimport { anchorId, contentId, markerRelationId, placementId } from './ids.ts';\nimport { interpret, selectionOf } from './interpret.ts';\nimport {\n  cloneState,\n  loadState,\n  type MarkerFields,\n  type SelectionState,\n  type TranscriptFile,\n  type WorkingState,\n} from './state.ts';\nimport { applyEdit, codePointOffset, replacement, shiftOffset } from './text.ts';\n\ntype EntityKind = SandboxContract.EntityKind;\ntype RelationKind = SandboxContract.RelationKind;\ntype FieldChange = SandboxContract.FieldChange;\ntype Entity = SandboxContract.Entity;\ntype Relation = SandboxContract.Relation;\ntype Selection = { segment: number; textRange?: { start: number; end: number } };\n\n/** Mints ids for entities a script creates; resources take ids derived from their locator instead. */\nexport type SandboxIdFactory = (\n  kind: 'track' | 'clip' | 'sequence-marker' | 'audio-script' | 'segment' | 'phonetic-script' | 'caption',\n) => string;\n\n/** A text-sensitive document edit, kept in the order the script made it. */\nexport interface JournalEntry {\n  /** The script, PhoneticScript or Caption the edit belongs to; dropped when the plan deletes it. */\n  owner: string;\n  mutation: DslMutation;\n}\n\nconst trackRoles = ['video_clip', 'speech', 'caption', 'bgm'];\nconst mediaKinds = ['video', 'audio', 'voiceover-recording', 'image'] as const;\nconst styleKeys: readonly string[] = [\n  'font',\n  'fontSize',\n  'fontColor',\n  'fontWeight',\n  'entranceAnimation',\n  'entranceAnimationDurationMs',\n  'strokeColor',\n  'strokeWidth',\n  'positionX',\n  'positionY',\n];\n\n/**\n * Compilation (RFC 04 §8), one script write at a time. Each write is applied to\n * the working state or refused whole, checked against the contract and the\n * DSL's constraints as it lands, so a script sees its own writes and its\n * failures at the call that made them. Text edits and selections are journaled\n * in order, because a range is only meaningful against the text it was made on.\n */\nexport class DocumentEdit {\n  readonly base: WorkingState;\n  /** The voice each take read in this plan was synthesized with, by take. */\n  private readonly synthesized = new Map<string, string>();\n  private current: WorkingState;\n  private entries: JournalEntry[] = [];\n\n  constructor(\n    snapshot: MedeoDslSnapshot,\n    private readonly mint: SandboxIdFactory,\n  ) {\n    this.base = loadState(snapshot);\n    this.current = cloneState(this.base);\n  }\n\n  get state(): WorkingState {\n    return this.current;\n  }\n  get journal(): readonly JournalEntry[] {\n    return this.entries;\n  }\n\n  list(): Entity[] {\n    return interpret(this.current).entities;\n  }\n  get(entityId: string): Entity | null {\n    return this.list().find((entity) => entity.entityId === entityId) ?? null;\n  }\n  relations(): Relation[] {\n    return interpret(this.current).relations;\n  }\n  /** Ordered kinds come back in container order, which the relation list already follows. */\n  relationsOf(entityId: string, relationKind?: RelationKind): Relation[] {\n    return this.relations().filter(\n      (relation) =>\n        (relation.endpoint0EntityId === entityId || relation.endpoint1EntityId === entityId) &&\n        (relationKind === undefined || relation.relationKind === relationKind),\n    );\n  }\n\n  create<K extends EntityKind>(entityKind: K, payload: unknown): string {\n    return this.atomically(() => this.createEntity(entityKind, payload));\n  }\n  update(entityId: string, changes: readonly FieldChange[]): void {\n    if (!Array.isArray(changes)) throw new Error('entities.update takes a list of changes');\n    this.atomically(() => this.updateEntity(entityId, changes));\n  }\n  declareFields(entityId: string, payload: unknown): void {\n    if (!isRecord(payload)) throw new Error('declareFields takes an object of fields');\n    this.update(\n      entityId,\n      Object.entries(payload).map(([field, value]) => ({ op: 'set', path: [field], value })),\n    );\n  }\n  delete(entityId: string): void {\n    this.atomically(() => this.deleteEntity(entityId));\n  }\n  link(relationKind: RelationKind, from: string, to: string): string {\n    return this.atomically(() => this.linkRelation(relationKind, from, to));\n  }\n  move(relationId: string, beforeRelationId: string | null): void {\n    this.atomically(() => this.moveRelation(relationId, beforeRelationId));\n  }\n  unlink(relationId: string): void {\n    this.atomically(() => this.unlinkRelation(relationId));\n  }\n  /** PhoneticScripts whose text has no file yet: new or rewritten, to be stored before the plan. */\n  unstoredTexts(): { id: string; text: string }[] {\n    const s = this.current;\n    return [...s.phonetics].flatMap(([id, phoneme]) =>\n      phoneme.phonemeScript !== undefined && !s.phoneticFiles.has(id) ? [{ id, text: phoneme.phonemeScript }] : [],\n    );\n  }\n  /** The file a PhoneticScript's text was stored in, recorded while the text is still the one stored. */\n  recordStoredText(id: string, text: string, file: StoredFile): void {\n    if (this.current.phonetics.get(id)?.phonemeScript === text) this.current.phoneticFiles.set(id, { ...file });\n  }\n  /**\n   * Facts a read of a file reports — a medium's own, or the transcription file a transcript names —\n   * recorded only where the entity states none. A take's read also reports the voice it was\n   * synthesized with, which its voice-timbre is checked against (D193).\n   */\n  recordFile(entityId: string, facts: { storageKey?: string; digest?: string; voice?: { key: string } }): void {\n    const file = this.current.media.get(entityId) ?? this.current.scripts.get(entityId)?.file;\n    if (!file) return;\n    if (file.storageKey === undefined && typeof facts.storageKey === 'string' && facts.storageKey.length)\n      file.storageKey = facts.storageKey;\n    if (file.digest === undefined && typeof facts.digest === 'string' && facts.digest.length)\n      file.digest = facts.digest;\n    if (this.current.media.get(entityId)?.kind === 'voiceover-recording' && typeof facts.voice?.key === 'string')\n      this.synthesized.set(entityId, facts.voice.key);\n  }\n  /** Takes whose voice-timbre this plan links, each to be checked against the voice it was synthesized with. */\n  timbredTakes(): string[] {\n    const linked = [...this.current.timbres].filter(([id]) => !this.base.timbres.has(id));\n    return [...new Set(linked.map(([, timbre]) => timbre.recordingId))];\n  }\n  /** A take's voice-timbre names the Voice of the voice it was synthesized with (D193). */\n  assertTimbres(): void {\n    for (const [id, { recordingId, voiceId }] of this.current.timbres) {\n      const synthesized = this.synthesized.get(recordingId);\n      if (this.base.timbres.has(id) || synthesized === undefined) continue;\n      const key = this.current.voices.get(voiceId)?.key;\n      if (key !== synthesized)\n        throw new Error(\n          `voice-timbre(${recordingId}, ${voiceId}) names voice ${key}, but the take was synthesized with ${synthesized}: link the Voice of the voice it was synthesized with`,\n        );\n    }\n  }\n\n  /** A write lands whole or not at all. */\n  private atomically<T>(write: () => T): T {\n    const state = cloneState(this.current),\n      length = this.entries.length;\n    try {\n      return write();\n    } catch (error) {\n      this.current = state;\n      this.entries.length = length;\n      throw error;\n    }\n  }\n\n  // --- entities -----------------------------------------------------------------------------\n\n  private createEntity(entityKind: EntityKind, payload: unknown): string {\n    if (!isRecord(payload)) throw new Error('An entity payload is an object');\n    const s = this.current;\n    switch (entityKind) {\n      case 'timeline':\n        throw new Error('A document has exactly one Timeline');\n      case 'track': {\n        only(payload, ['role', 'hidden']);\n        const id = this.mint('track');\n        s.tracks.set(id, track(payload));\n        return id;\n      }\n      case 'clip': {\n        only(payload, ['volume']);\n        const id = this.mint('clip');\n        s.clips.set(id, clipFields(payload));\n        return id;\n      }\n      case 'sequence-marker': {\n        const id = this.mint('sequence-marker');\n        s.markers.set(id, marker(payload));\n        return id;\n      }\n      case 'video':\n      case 'audio':\n      case 'voiceover-recording':\n      case 'image': {\n        const media = mediaOf(entityKind, payload);\n        const id = resourceId('media', media.system, media.key);\n        // One medium per stored file: creating it again returns the one the document has.\n        const existing = s.media.get(id);\n        if (existing && existing.kind !== media.kind) throw new Error(`${id} is already a ${existing.kind}`);\n        if (!existing) s.media.set(id, media);\n        return id;\n      }\n      case 'voice': {\n        only(payload, ['voice']);\n        const voice = payload.voice;\n        if (!isRecord(voice)) throw new Error('A voice payload is { voice: { system, key, name? } }');\n        only(voice, ['system', 'key', 'name']);\n        if (voice.system !== 'voice-library' || typeof voice.key !== 'string' || !voice.key.length)\n          throw new Error('A voice names a voice-library key');\n        if (voice.name !== undefined && typeof voice.name !== 'string') throw new Error('A voice name is a string');\n        const id = resourceId('voice', voice.system, voice.key);\n        if (!s.voices.has(id))\n          s.voices.set(id, {\n            system: 'voice-library',\n            key: voice.key,\n            ...(voice.name === undefined ? {} : { name: voice.name }),\n          });\n        return id;\n      }\n      case 'audio-script': {\n        only(payload, ['segments', 'system', 'key', 'storageKey', 'digest']);\n        const file = transcriptFile(payload);\n        const parts = segmentList(payload.segments);\n        const id = this.mint('audio-script');\n        const segments = parts.map(({ language: _, ...part }) => ({ id: this.mint('segment'), ...part }));\n        s.scripts.set(id, {\n          segments: segments.map((segment) => ({ ...segment, langs: unmarked(segment.text) })),\n          ...(file ? { file } : {}),\n        });\n        this.entries.push({\n          owner: id,\n          mutation: {\n            type: 'create-entity',\n            table: 'audio-script-entities',\n            id,\n            value: { segments, ...file },\n          },\n        });\n        parts.forEach((part, index) => this.setLanguage(id, index, part.language));\n        return id;\n      }\n      case 'phonetic-script': {\n        only(payload, ['bases', 'selection', 'phonemeScript']);\n        const audioScriptId = this.base1(payload.bases, 'A PhoneticScript');\n        const selection = this.rangeOf(audioScriptId, requiredSelection(payload.selection));\n        const text = phonemeScript(payload.phonemeScript);\n        const id = this.mint('phonetic-script');\n        s.phonetics.set(id, { audioScriptId });\n        this.entries.push({\n          owner: id,\n          mutation: { type: 'create-entity', table: 'phonetic-script-entities', id, value: {} },\n        });\n        this.writePhoneme(id, selection, text);\n        return id;\n      }\n      case 'caption': {\n        only(payload, ['durationMs', 'bases', 'selection', 'text', 'style']);\n        const id = this.mint('caption');\n        s.captions.set(id, {});\n        this.entries.push({\n          owner: id,\n          mutation: { type: 'create-entity', table: 'caption-entities', id, value: {} },\n        });\n        this.writeCaption(id, {}, captionDraft(payload));\n        return id;\n      }\n      default:\n        throw new Error(`Unknown entity kind: ${String(entityKind)}`);\n    }\n  }\n\n  private updateEntity(entityId: string, changes: readonly FieldChange[]): void {\n    const s = this.current;\n    const entity = this.get(entityId);\n    if (!entity) throw new Error(`Missing entity: ${entityId}`);\n    for (const change of changes) {\n      if (!isRecord(change) || !Array.isArray(change.path) || !change.path.length || typeof change.path[0] !== 'string')\n        throw new Error('A change names an op and a path starting at a field');\n    }\n    switch (entity.entityKind) {\n      case 'timeline':\n        throw new Error('A Timeline has no fields');\n      case 'track': {\n        const next = applyChanges({ ...s.tracks.get(entityId)! }, changes);\n        s.tracks.set(entityId, track(next));\n        return;\n      }\n      case 'clip':\n        s.clips.set(entityId, clipFields(applyChanges({ ...s.clips.get(entityId)! }, changes)));\n        return;\n      case 'sequence-marker':\n        s.markers.set(entityId, marker(applyChanges({ ...s.markers.get(entityId)! }, changes)));\n        return;\n      case 'video':\n      case 'audio':\n      case 'voiceover-recording':\n      case 'image': {\n        const old = s.media.get(entityId)!;\n        for (const change of changes) {\n          const field = change.path[0] as string;\n          if (field === 'storageKey' || field === 'digest') throw new Error(`Field ${field} is the host's to write`);\n          if (field === 'system' || field === 'key') throw new Error(`A medium's ${field} is its identity`);\n        }\n        const { kind, ...file } = old;\n        const next = applyChanges({ ...file, durationMs: 'durationMs' in old ? old.durationMs : null }, changes);\n        const media = mediaOf(kind, { ...next, storageKey: undefined, digest: undefined });\n        s.media.set(entityId, {\n          ...media,\n          ...(old.storageKey === undefined ? {} : { storageKey: old.storageKey }),\n          ...(old.digest === undefined ? {} : { digest: old.digest }),\n        } as Media);\n        return;\n      }\n      case 'voice': {\n        const old = s.voices.get(entityId)!;\n        const next = applyChanges({ voice: { ...old } }, changes);\n        const voice = next.voice;\n        if (!isRecord(voice) || voice.system !== old.system || voice.key !== old.key)\n          throw new Error(\"A voice's system and key are its identity\");\n        only(voice, ['system', 'key', 'name']);\n        if (voice.name !== undefined && typeof voice.name !== 'string') throw new Error('A voice name is a string');\n        s.voices.set(entityId, {\n          system: old.system,\n          key: old.key,\n          ...(voice.name === undefined ? {} : { name: voice.name as string }),\n        });\n        return;\n      }\n      case 'audio-script':\n        for (const change of changes) this.changeSegments(entityId, change);\n        return;\n      case 'phonetic-script': {\n        const phonetic = s.phonetics.get(entityId)!;\n        // A base's field is edited on the base (RFC 04 §7.3).\n        for (const change of changes)\n          if (change.path[0] === 'segments') this.changeSegments(phonetic.audioScriptId, change);\n        const own = changes.filter((change) => change.path[0] !== 'segments');\n        if (!own.length) return;\n        const selection = phonetic.selection && selectionOf(s, phonetic.selection);\n        const before = {\n          bases: [phonetic.audioScriptId],\n          ...(selection ? { selection } : {}),\n          ...(phonetic.phonemeScript === undefined ? {} : { phonemeScript: phonetic.phonemeScript }),\n        };\n        const next = applyChanges(structuredClone(before), own);\n        only(next, ['bases', 'selection', 'phonemeScript']);\n        const audioScriptId = this.base1(next.bases, 'A PhoneticScript');\n        const range = this.rangeOf(audioScriptId, requiredSelection(next.selection));\n        const text = phonemeScript(next.phonemeScript);\n        if (JSON.stringify(next) === JSON.stringify(before)) return;\n        const old = phonetic.phonemeScript;\n        this.writePhoneme(entityId, range, text);\n        // New text is not in the old file; the plan stores it before it is written.\n        if (text !== old) s.phoneticFiles.delete(entityId);\n        return;\n      }\n      case 'caption': {\n        const caption = s.captions.get(entityId)!;\n        const base = caption.selection?.audioScriptId ?? caption.unresolved?.audioScriptId;\n        for (const change of changes)\n          if (change.path[0] === 'segments') {\n            if (base === undefined) throw new Error('A Caption with its own text has no script segments');\n            this.changeSegments(base, change);\n          }\n        const before = this.captionDraftOf(entityId);\n        const next = applyChanges(\n          structuredClone(before),\n          changes.filter((change) => change.path[0] !== 'segments'),\n        );\n        this.writeCaption(entityId, before, captionDraft(next));\n        return;\n      }\n    }\n  }\n\n  private deleteEntity(entityId: string): void {\n    const entity = this.get(entityId);\n    if (!entity) throw new Error(`Missing entity: ${entityId}`);\n    // A Clip's own marker goes with it (D188); every other Relation is unlinked first.\n    const own = entity.entityKind === 'clip' ? markerRelationId(entityId) : undefined;\n    const incident = this.relationsOf(entityId).filter((relation) => relation.relationId !== own);\n    if (incident.length)\n      throw new Error(\n        `Unlink ${entityId}'s relations first (delete never cascades): ${incident.map((r) => r.relationId).join(', ')}`,\n      );\n    const s = this.current;\n    switch (entity.entityKind) {\n      case 'timeline':\n        throw new Error('A document has exactly one Timeline');\n      case 'track':\n        s.tracks.delete(entityId);\n        s.trackClips.delete(entityId);\n        break;\n      case 'clip': {\n        s.clips.delete(entityId);\n        s.clipMarker.delete(entityId);\n        const marking = new Set(s.clipMarker.values());\n        for (const [markerId, owner] of s.markerOwner)\n          if (owner === entityId && !marking.has(markerId)) {\n            s.markers.delete(markerId);\n            s.markerOwner.delete(markerId);\n          }\n        break;\n      }\n      case 'sequence-marker':\n        s.markers.delete(entityId);\n        s.markerOwner.delete(entityId);\n        break;\n      case 'voice':\n        s.voices.delete(entityId);\n        break;\n      case 'audio-script':\n        s.scripts.delete(entityId);\n        break;\n      case 'phonetic-script':\n        s.phonetics.delete(entityId);\n        s.phoneticFiles.delete(entityId);\n        break;\n      case 'caption':\n        s.captions.delete(entityId);\n        break;\n      default:\n        s.media.delete(entityId);\n    }\n  }\n\n  // --- relations ----------------------------------------------------------------------------\n\n  private linkRelation(relationKind: RelationKind, from: string, to: string): string {\n    const s = this.current;\n    const kindOf = (id: string) => this.get(id)?.entityKind;\n    switch (relationKind) {\n      case 'contain': {\n        if (from === s.timelineId) {\n          if (kindOf(to) !== 'track') throw new Error('The Timeline contains Tracks');\n          if (s.trackOrder.includes(to)) throw new Error(`${to} is already contained by the Timeline`);\n          s.trackOrder.push(to);\n          s.trackClips.set(to, s.trackClips.get(to) ?? []);\n          return placementId(to);\n        }\n        if (kindOf(from) === 'track') {\n          if (kindOf(to) !== 'clip') throw new Error('A Track contains Clips');\n          if (this.trackOf(to) !== undefined) throw new Error(`${to} is already contained by a Track`);\n          s.trackClips.set(from, [...(s.trackClips.get(from) ?? []), to]);\n          return placementId(to);\n        }\n        if (kindOf(from) === 'clip') {\n          const content = kindOf(to);\n          if (!content || !['video', 'audio', 'voiceover-recording', 'image', 'caption'].includes(content))\n            throw new Error('A Clip contains media or a Caption');\n          if (s.clipContent.has(from)) throw new Error(`${from} already contains its content; unlink it first`);\n          s.clipContent.set(from, to);\n          return contentId(from);\n        }\n        throw new Error('contain(container, contained): Timeline → Track, Track → Clip, Clip → content');\n      }\n      case 'marker': {\n        if (kindOf(from) !== 'clip' || kindOf(to) !== 'sequence-marker')\n          throw new Error('marker(clip, sequence-marker)');\n        if (s.clipMarker.has(from)) throw new Error(`${from} already has a marker; unlink it first`);\n        if ([...s.clipMarker.values()].includes(to)) throw new Error(`${to} already marks a Clip`);\n        s.clipMarker.set(from, to);\n        s.markerOwner.set(to, from);\n        return markerRelationId(from);\n      }\n      case 'clip-anchor': {\n        if (kindOf(from) !== 'clip' || kindOf(to) !== 'clip') throw new Error('clip-anchor(child clip, host clip)');\n        if (s.clipHost.has(from)) throw new Error(`${from} already follows a host; unlink it first`);\n        // Anchors may not form a cycle, counting the one being made.\n        for (let host: string | undefined = to; host !== undefined; host = s.clipHost.get(host))\n          if (host === from) throw new Error('Time anchor cycle');\n        s.clipHost.set(from, to);\n        return anchorId(from);\n      }\n      case 'voice-timbre': {\n        if (kindOf(from) !== 'voiceover-recording' || kindOf(to) !== 'voice')\n          throw new Error('voice-timbre(voiceover-recording, voice)');\n        const value = { recordingId: from, voiceId: to };\n        const id = relationId('voice-timbre-relations', value);\n        s.timbres.set(id, value);\n        return id;\n      }\n      case 'derived-from': {\n        for (const end of [from, to]) {\n          const kind = kindOf(end);\n          if (!kind || kind === 'sequence-marker') throw new Error(`derived-from needs two stored entities: ${end}`);\n        }\n        const value = { entityId: from, sourceId: to };\n        const id = relationId('derived-from-relations', value);\n        // Linking an existing pair again keeps what it recorded when the product was made.\n        if (!s.derived.has(id)) s.derived.set(id, value);\n        return id;\n      }\n      default:\n        throw new Error(`Unknown relation kind: ${String(relationKind)}`);\n    }\n  }\n\n  private moveRelation(relationId: string, beforeRelationId: string | null): void {\n    const relation = this.relation(relationId);\n    if (relation.relationKind !== 'contain' || relationId === contentId(relation.endpoint0EntityId))\n      throw new Error('Only a Timeline’s Tracks and a Track’s Clips are ordered');\n    const container = relation.endpoint0EntityId;\n    const order =\n      container === this.current.timelineId ? this.current.trackOrder : this.current.trackClips.get(container);\n    if (!order || !order.includes(relation.endpoint1EntityId)) throw new Error(`${relationId} is not ordered`);\n    order.splice(order.indexOf(relation.endpoint1EntityId), 1);\n    if (beforeRelationId === null) {\n      order.push(relation.endpoint1EntityId);\n      return;\n    }\n    const before = this.relation(beforeRelationId);\n    if (before.relationKind !== 'contain' || before.endpoint0EntityId !== container || before.relationId === relationId)\n      throw new Error('Move a Relation in front of another in the same container');\n    order.splice(order.indexOf(before.endpoint1EntityId), 0, relation.endpoint1EntityId);\n  }\n\n  private unlinkRelation(relationId: string): void {\n    const relation = this.relation(relationId);\n    const s = this.current;\n    const [from, to] = [relation.endpoint0EntityId, relation.endpoint1EntityId];\n    switch (relation.relationKind) {\n      case 'contain':\n        if (from === s.timelineId) s.trackOrder.splice(s.trackOrder.indexOf(to), 1);\n        else if (relationId === contentId(from)) s.clipContent.delete(from);\n        else {\n          const clips = s.trackClips.get(from)!;\n          clips.splice(clips.indexOf(to), 1);\n        }\n        return;\n      case 'marker':\n        s.clipMarker.delete(from);\n        return;\n      case 'clip-anchor':\n        s.clipHost.delete(from);\n        return;\n      case 'voice-timbre':\n        s.timbres.delete(relationId);\n        return;\n      case 'derived-from':\n        s.derived.delete(relationId);\n        return;\n    }\n  }\n\n  private relation(relationId: string): Relation {\n    const relation = this.relations().find((row) => row.relationId === relationId);\n    if (!relation) throw new Error(`Missing relation: ${relationId}`);\n    return relation;\n  }\n  trackOf(clipId: string): string | undefined {\n    for (const [trackId, clips] of this.current.trackClips) if (clips.includes(clipId)) return trackId;\n  }\n\n  // --- variants -----------------------------------------------------------------------------\n\n  /** The single base a variant names. */\n  private base1(bases: unknown, variant: string): string {\n    if (!Array.isArray(bases) || bases.length !== 1 || typeof bases[0] !== 'string')\n      throw new Error(`${variant} has exactly one AudioScript base`);\n    if (!this.current.scripts.has(bases[0])) throw new Error(`Missing AudioScript base: ${bases[0]}`);\n    return bases[0];\n  }\n\n  private captionDraftOf(captionId: string): CaptionDraft {\n    const caption = this.current.captions.get(captionId)!;\n    const base = caption.selection?.audioScriptId ?? caption.unresolved?.audioScriptId;\n    const selection = caption.selection && selectionOf(this.current, caption.selection);\n    return {\n      durationMs: null,\n      bases: base === undefined ? [] : [base],\n      ...(selection ? { selection } : {}),\n      ...(caption.text === undefined ? {} : { text: caption.text }),\n      ...(caption.style === undefined ? {} : { style: structuredClone(caption.style) }),\n    };\n  }\n\n  /**\n   * A PhoneticScript's phoneme is one value — the segment it is written for and what to synthesize\n   * for it — journaled in order with the text edits its run follows (D181).\n   */\n  private writePhoneme(id: string, selection: SelectionState, text: string | undefined): void {\n    const phonetic = this.current.phonetics.get(id)!;\n    phonetic.audioScriptId = selection.audioScriptId;\n    phonetic.selection = selection;\n    if (text === undefined) delete phonetic.phonemeScript;\n    else phonetic.phonemeScript = text;\n    this.entries.push({\n      owner: id,\n      mutation: {\n        type: 'set-phoneme',\n        phoneticScriptId: id,\n        ...selection,\n        ...(text === undefined ? {} : { phonemeScript: text }),\n      },\n    });\n  }\n\n  /**\n   * A Caption reads its words from one base script or states its own (D168): stating text drops\n   * the selection and the base, and a selection needs a base. Text and selection writes are\n   * journaled in order; style is a plain field compared when the plan is built.\n   */\n  private writeCaption(id: string, before: CaptionDraft, next: CaptionDraft): void {\n    only(next, ['durationMs', 'bases', 'selection', 'text', 'style']);\n    if (next.durationMs !== undefined && next.durationMs !== null)\n      throw new Error(\"A Caption has no length of its own; set its Clip's marker instead (durationMs stays null)\");\n    const caption = this.current.captions.get(id)!;\n    if (next.style !== undefined) {\n      if (!isRecord(next.style)) throw new Error('Caption style is an object');\n      only(next.style, styleKeys);\n      assertEntity('caption-entities', { style: next.style });\n    }\n    const textChanged = next.text !== before.text;\n    if (next.text !== undefined) {\n      if (typeof next.text !== 'string') throw new Error('Caption text is a string');\n      if (textChanged || before.selection) {\n        // Stating its own words drops the script it read from.\n        if (caption.selection || caption.unresolved)\n          this.entries.push({ owner: id, mutation: patchCaption(id, { selection: undefined }) });\n        delete caption.selection;\n        delete caption.unresolved;\n        this.writeCaptionText(id, caption.text, next.text);\n        caption.text = next.text;\n      }\n    } else {\n      const bases = next.bases ?? [];\n      if (!Array.isArray(bases) || bases.length > 1) throw new Error('A Caption has at most one AudioScript base');\n      const base = bases[0] as string | undefined;\n      if (base !== undefined && !this.current.scripts.has(base)) throw new Error(`Missing AudioScript base: ${base}`);\n      if (next.selection !== undefined && base === undefined)\n        throw new Error('A Caption selection needs a base script');\n      const sameSelection =\n        base === (before.bases as string[] | undefined)?.[0] &&\n        JSON.stringify(next.selection) === JSON.stringify(before.selection);\n      if (caption.text !== undefined && (next.selection !== undefined || textChanged)) {\n        this.entries.push({ owner: id, mutation: patchCaption(id, { text: undefined }) });\n        delete caption.text;\n      }\n      if (next.selection !== undefined && (!sameSelection || textChanged)) {\n        const range = this.rangeOf(base!, next.selection as Selection);\n        this.entries.push({ owner: id, mutation: { type: 'set-caption-content', captionId: id, ...range } });\n        caption.selection = range;\n        delete caption.unresolved;\n      } else if (next.selection === undefined && (caption.selection || caption.unresolved)) {\n        this.entries.push({ owner: id, mutation: patchCaption(id, { selection: undefined }) });\n        delete caption.selection;\n        delete caption.unresolved;\n      }\n    }\n    if (next.style === undefined) delete caption.style;\n    else caption.style = structuredClone(next.style) as CaptionStyle;\n  }\n\n  private writeCaptionText(id: string, old: string | undefined, text: string): void {\n    if (old === undefined) this.entries.push({ owner: id, mutation: patchCaption(id, { text }) });\n    else {\n      const edits = replacement(old, text);\n      if (edits.length) this.entries.push({ owner: id, mutation: { type: 'edit-caption-text', captionId: id, edits } });\n    }\n  }\n\n  /** A selection as its segment of the base script, and a UTF-16 run of that segment's text when it states one. */\n  private rangeOf(scriptId: string, selection: Selection): SelectionState {\n    if (!isRecord(selection)) throw new Error('A selection is { segment, textRange? }');\n    only(selection, ['segment', 'textRange']);\n    const segment = this.current.scripts.get(scriptId)!.segments[selection.segment as number];\n    if (!Number.isSafeInteger(selection.segment) || !segment)\n      throw new Error(`Missing segment ${String(selection.segment)}`);\n    if (selection.textRange === undefined) {\n      if (!segment.text.length) throw new Error('An empty segment cannot be selected');\n      return { audioScriptId: scriptId, segmentId: segment.id };\n    }\n    if (!isRecord(selection.textRange)) throw new Error('A textRange is { start, end }');\n    only(selection.textRange, ['start', 'end']);\n    const start = codePointOffset(segment.text, selection.textRange.start as number);\n    const end = codePointOffset(segment.text, selection.textRange.end as number);\n    if (start >= end) throw new Error('A selection is a nonempty range');\n    return { audioScriptId: scriptId, segmentId: segment.id, start, end };\n  }\n\n  // --- script text --------------------------------------------------------------------------\n\n  private changeSegments(scriptId: string, change: FieldChange): void {\n    const script = this.current.scripts.get(scriptId);\n    if (!script) throw new Error(`Missing AudioScript: ${scriptId}`);\n    const path = change.path;\n    if (['system', 'key', 'storageKey', 'digest'].includes(path[0] as string))\n      throw new Error('A transcript names its transcription file when it is created, and keeps it');\n    if (path[0] !== 'segments') throw new Error(`An AudioScript has only segments, not ${String(path[0])}`);\n    const at = (index: unknown) => {\n      if (!Number.isSafeInteger(index) || !script.segments[index as number])\n        throw new Error(`Missing segment ${String(index)}`);\n      return index as number;\n    };\n    if (path.length === 1) {\n      switch (change.op) {\n        case 'set': {\n          // Segments keep their places: each takes the text at its index; extra ones are added or removed.\n          const parts = segmentList(change.value);\n          parts.forEach((part, index) =>\n            index < script.segments.length\n              ? this.setSegment(scriptId, index, part)\n              : this.insertSegment(scriptId, index, part),\n          );\n          while (script.segments.length > parts.length) this.removeSegment(scriptId, script.segments.length - 1);\n          return;\n        }\n        case 'list.insert': {\n          const [part] = segmentList([change.value]);\n          const index = change.index;\n          if (!Number.isSafeInteger(index) || index < 0 || index > script.segments.length)\n            throw new Error('Invalid segment index');\n          this.insertSegment(scriptId, index, part);\n          return;\n        }\n        case 'list.remove':\n          this.removeSegment(scriptId, at(change.index));\n          return;\n        case 'list.move': {\n          const from = at(change.from);\n          if (!Number.isSafeInteger(change.to) || change.to < 0 || change.to >= script.segments.length)\n            throw new Error('Invalid segment index');\n          // A segment keeps its id where it moves, and with it every selection of it.\n          const [segment] = script.segments.splice(from, 1);\n          script.segments.splice(change.to, 0, segment);\n          this.entries.push({\n            owner: scriptId,\n            mutation: { type: 'move-segment', audioScriptId: scriptId, segmentId: segment.id, index: change.to },\n          });\n          return;\n        }\n        default:\n          throw new Error(`${change.op} does not apply to segments`);\n      }\n    }\n    const index = at(path[1]);\n    const segment = script.segments[index];\n    if (path.length === 2) {\n      if (change.op !== 'set') throw new Error('Replace a segment with set, or edit its text or language');\n      const [part] = segmentList([change.value]);\n      this.setSegment(scriptId, index, part);\n      return;\n    }\n    if (path.length !== 3) throw new Error('A segment has only text and language');\n    if (path[2] === 'startMs' || path[2] === 'endMs')\n      throw new Error(\"A segment's time is the transcription's, given when the segment is added\");\n    if (path[2] === 'text') {\n      if (change.op === 'set') {\n        if (typeof change.value !== 'string') throw new Error('Segment text is a string');\n        this.editText(scriptId, segment.id, replacement(segment.text, change.value));\n      } else if (change.op === 'text.splice') {\n        if (typeof change.text !== 'string') throw new Error('Segment text is a string');\n        const start = codePointOffset(segment.text, change.index);\n        const end = codePointOffset(segment.text, change.index + change.deleteCount);\n        const edits: TextEdit[] = [];\n        if (end > start) edits.push({ type: 'delete', at: start, length: end - start });\n        if (change.text.length) edits.push({ type: 'insert', at: start, text: change.text });\n        this.editText(scriptId, segment.id, edits);\n      } else throw new Error(`${change.op} does not apply to segment text`);\n      return;\n    }\n    if (path[2] === 'language') {\n      if (change.op === 'set') this.setLanguage(scriptId, index, change.value as string);\n      else if (change.op === 'unset') this.setLanguage(scriptId, index, undefined);\n      else throw new Error(`${change.op} does not apply to a segment's language`);\n      return;\n    }\n    throw new Error(`A segment has no field ${String(path[2])}`);\n  }\n\n  /**\n   * The segment at `index` takes this text and language, keeping its id and so its selections, and\n   * its time: a part that states one states the segment's own.\n   */\n  private setSegment(scriptId: string, index: number, part: SegmentPart): void {\n    const segment = this.current.scripts.get(scriptId)!.segments[index];\n    if (part.startMs !== undefined && (part.startMs !== segment.startMs || part.endMs !== segment.endMs))\n      throw new Error(\"A segment's time is the transcription's, given when the segment is added\");\n    this.editText(scriptId, segment.id, replacement(segment.text, part.text));\n    this.setLanguage(scriptId, index, part.language);\n  }\n\n  private insertSegment(scriptId: string, index: number, part: SegmentPart): void {\n    const id = this.mint('segment');\n    const { language, ...stored } = part;\n    this.current.scripts.get(scriptId)!.segments.splice(index, 0, { id, ...stored, langs: unmarked(part.text) });\n    this.entries.push({\n      owner: scriptId,\n      mutation: { type: 'insert-segment', audioScriptId: scriptId, segmentId: id, index, ...stored },\n    });\n    this.setLanguage(scriptId, index, language);\n  }\n\n  /** What selected a removed segment keeps its base and shows nothing until a script selects again (D72). */\n  private removeSegment(scriptId: string, index: number): void {\n    const [segment] = this.current.scripts.get(scriptId)!.segments.splice(index, 1);\n    this.entries.push({\n      owner: scriptId,\n      mutation: { type: 'delete-segment', audioScriptId: scriptId, segmentId: segment.id },\n    });\n    for (const caption of this.current.captions.values())\n      if (caption.selection?.segmentId === segment.id) {\n        caption.unresolved = { audioScriptId: scriptId };\n        delete caption.selection;\n      }\n    for (const phonetic of this.current.phonetics.values())\n      if (phonetic.selection?.segmentId === segment.id) delete phonetic.selection;\n  }\n\n  /** Mark a whole segment with a language, or clear marks from it. */\n  private setLanguage(scriptId: string, index: number, language: string | undefined): void {\n    if (language !== undefined && !validLanguage(language)) throw new Error(`Invalid language: ${String(language)}`);\n    const segment = this.current.scripts.get(scriptId)!.segments[index];\n    if (!segment || !segment.text.length) return;\n    if (segment.langs.every((unit) => unit === language)) return;\n    this.editText(scriptId, segment.id, [\n      language === undefined\n        ? { type: 'unmark', start: 0, end: segment.text.length, key: 'language' }\n        : { type: 'mark', start: 0, end: segment.text.length, key: 'language', value: language },\n    ]);\n  }\n\n  /** Journal edits to a segment and move every run selected in it the way its Cursors will move. */\n  private editText(scriptId: string, segmentId: string, edits: readonly TextEdit[]): void {\n    if (!edits.length) return;\n    const segment = this.current.scripts.get(scriptId)!.segments.find((s) => s.id === segmentId)!;\n    const selections = [\n      ...[...this.current.captions.values()].map((caption) => caption.selection),\n      ...[...this.current.phonetics.values()].map((phonetic) => phonetic.selection),\n    ].filter((selection) => selection?.segmentId === segmentId && selection.start !== undefined);\n    for (const edit of edits) {\n      applyEdit(segment, edit);\n      for (const selection of selections) {\n        selection!.start = shiftOffset(selection!.start!, edit);\n        selection!.end = shiftOffset(selection!.end!, edit);\n      }\n    }\n    this.entries.push({\n      owner: scriptId,\n      mutation: { type: 'edit-text', audioScriptId: scriptId, segmentId, edits: [...edits] },\n    });\n  }\n}\n\n/** A Caption's payload while a write is applied to it: its own fields and its base, unchecked. */\ntype CaptionDraft = { [field: string]: unknown };\n\nfunction captionDraft(value: Record<string, unknown>): CaptionDraft {\n  // Stating its own words drops the selection and the base (contract).\n  if (value.text !== undefined) {\n    const { selection: _selection, bases: _bases, ...rest } = value;\n    return { ...rest };\n  }\n  return value;\n}\n\nfunction patchCaption(id: string, patch: { selection?: undefined; text?: string | undefined }): DslMutation {\n  return { type: 'patch-entity', table: 'caption-entities', id, patch };\n}\n\n/** Refuse fields a kind does not state. */\nfunction only(value: Record<string, unknown>, keys: readonly string[]): void {\n  for (const key of Object.keys(value)) if (!keys.includes(key)) throw new Error(`Unknown field: ${key}`);\n}\n\nfunction track(payload: Record<string, unknown>) {\n  only(payload, ['role', 'hidden']);\n  if (!trackRoles.includes(payload.role as string))\n    throw new Error(`A Track's role is one of ${trackRoles.join(', ')}`);\n  if (payload.hidden !== undefined && typeof payload.hidden !== 'boolean') throw new Error('hidden is a boolean');\n  return {\n    role: payload.role as 'video_clip' | 'speech' | 'caption' | 'bgm',\n    ...(payload.hidden === undefined ? {} : { hidden: payload.hidden }),\n  };\n}\n\nfunction clipFields(payload: Record<string, unknown>): { volume?: number } {\n  only(payload, ['volume']);\n  if (payload.volume === undefined) return {};\n  if (typeof payload.volume !== 'number' || !Number.isFinite(payload.volume)) throw new Error('volume is a number');\n  return { volume: payload.volume };\n}\n\nfunction marker(payload: Record<string, unknown>): MarkerFields {\n  only(payload, ['inMs', 'outMs', 'startMs', 'rate', 'fillTimeline']);\n  const whole = (value: unknown, field: string, signed = false) => {\n    if (typeof value !== 'number' || !Number.isSafeInteger(value) || (!signed && value < 0))\n      throw new Error(`${field} is a whole number of milliseconds`);\n    return value;\n  };\n  const result: MarkerFields = { inMs: whole(payload.inMs, 'inMs'), outMs: whole(payload.outMs, 'outMs') };\n  if (result.outMs <= result.inMs) throw new Error('A marker’s outMs is after its inMs');\n  if (payload.startMs !== undefined) result.startMs = whole(payload.startMs, 'startMs', true);\n  if (payload.rate !== undefined) {\n    if (typeof payload.rate !== 'number' || !Number.isFinite(payload.rate) || payload.rate <= 0)\n      throw new Error('rate is a positive number');\n    result.rate = payload.rate;\n  }\n  if (payload.fillTimeline !== undefined) {\n    if (payload.fillTimeline !== true) throw new Error('fillTimeline is only ever true');\n    result.fillTimeline = true;\n  }\n  return result;\n}\n\nfunction mediaOf(kind: (typeof mediaKinds)[number], payload: Record<string, unknown>): Media {\n  only(payload, ['system', 'key', 'storageKey', 'digest', 'durationMs']);\n  for (const field of ['storageKey', 'digest'])\n    if (payload[field] !== undefined) throw new Error(`Field ${field} is the host's to write`);\n  if (payload.system !== 'memota' && payload.system !== 'memota-speech')\n    throw new Error('A medium is stored in memota or memota-speech');\n  if (typeof payload.key !== 'string' || !payload.key.length) throw new Error('A medium names its file key');\n  if (kind === 'image') {\n    if (payload.durationMs !== undefined && payload.durationMs !== null)\n      throw new Error('An image has no length of its own (durationMs is null)');\n    return { kind, system: payload.system, key: payload.key };\n  }\n  if (typeof payload.durationMs !== 'number' || !Number.isSafeInteger(payload.durationMs) || payload.durationMs <= 0)\n    throw new Error('A video or sound states its length in whole milliseconds');\n  return { kind, system: payload.system, key: payload.key, durationMs: payload.durationMs } as Media;\n}\n\n/** A segment as a script states it; only a transcript's segment states its time. */\ntype SegmentPart = { text: string; language?: string; startMs?: number; endMs?: number };\n\nfunction segmentList(value: unknown): SegmentPart[] {\n  if (!Array.isArray(value)) throw new Error('segments is a list of { text, language?, startMs?, endMs? }');\n  return value.map((part) => {\n    if (!isRecord(part)) throw new Error('A segment is { text, language?, startMs?, endMs? }');\n    only(part, ['text', 'language', 'startMs', 'endMs']);\n    if (typeof part.text !== 'string') throw new Error('Segment text is a string');\n    if (part.language !== undefined && !validLanguage(part.language))\n      throw new Error(`Invalid language: ${JSON.stringify(part.language)}`);\n    const result: SegmentPart = { text: part.text };\n    if (part.language !== undefined) result.language = part.language as string;\n    if (part.startMs !== undefined || part.endMs !== undefined) {\n      const whole = (v: unknown) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;\n      if (!whole(part.startMs) || !whole(part.endMs) || (part.endMs as number) < (part.startMs as number))\n        throw new Error('A segment states its time as whole milliseconds startMs and endMs, endMs not before startMs');\n      result.startMs = part.startMs as number;\n      result.endMs = part.endMs as number;\n    }\n    return result;\n  });\n}\n\n/** The transcription file a transcript names: a Memota file by key, its facts the host's to read. */\nfunction transcriptFile(payload: Record<string, unknown>): TranscriptFile | undefined {\n  for (const field of ['storageKey', 'digest'])\n    if (payload[field] !== undefined) throw new Error(`Field ${field} is the host's to write`);\n  if (payload.system === undefined && payload.key === undefined) return;\n  if (payload.system !== 'memota') throw new Error('A transcription file is stored in memota');\n  if (typeof payload.key !== 'string' || !payload.key.length) throw new Error('A transcript names its file key');\n  return { system: 'memota', key: payload.key };\n}\n\n/** Phoneme content, stated only where the voice takes markup; without it TTS reads the selection's words (D190). */\nfunction phonemeScript(value: unknown): string | undefined {\n  if (value !== undefined && (typeof value !== 'string' || !value.length))\n    throw new Error('phonemeScript is phoneme content, a nonempty string; leave it unstated when there is none');\n  return value;\n}\n\n/** A PhoneticScript always states the segment it is written for. */\nfunction requiredSelection(value: unknown): Selection {\n  if (value === undefined)\n    throw new Error('A PhoneticScript selects the segment it is written for: selection { segment, textRange? }');\n  return value as Selection;\n}\n\nfunction unmarked(text: string): undefined[] {\n  return Array.from({ length: text.length }, () => undefined);\n}\n\n/** Apply changes to a plain payload. Lists are addressed by index; text splices count code points. */\nfunction applyChanges<T extends Record<string, unknown>>(target: T, changes: readonly FieldChange[]): T {\n  for (const change of changes) {\n    const path = change.path;\n    let parent: Record<string, unknown> | unknown[] = target;\n    for (const key of path.slice(0, -1)) {\n      const next = (parent as Record<string | number, unknown>)[key];\n      if (next === undefined && change.op === 'set' && typeof key === 'string' && !Array.isArray(parent)) {\n        (parent as Record<string, unknown>)[key] = {};\n      } else if (next === null || typeof next !== 'object') throw new Error(`Missing field: ${path.join('.')}`);\n      parent = (parent as Record<string | number, unknown>)[key] as Record<string, unknown> | unknown[];\n    }\n    const last = path[path.length - 1];\n    const holder = parent as Record<string | number, unknown>;\n    switch (change.op) {\n      case 'set':\n        holder[last] = structuredClone(change.value);\n        break;\n      case 'unset':\n        if (Array.isArray(holder)) throw new Error('Remove a list member with list.remove');\n        delete holder[last];\n        break;\n      case 'text.splice': {\n        const text = holder[last];\n        if (typeof text !== 'string') throw new Error(`${path.join('.')} is not text`);\n        const start = codePointOffset(text, change.index);\n        const end = codePointOffset(text, change.index + change.deleteCount);\n        holder[last] = text.slice(0, start) + change.text + text.slice(end);\n        break;\n      }\n      case 'list.insert':\n      case 'list.move':\n      case 'list.remove': {\n        const list = holder[last];\n        if (!Array.isArray(list)) throw new Error(`${path.join('.')} is not a list`);\n        if (change.op === 'list.insert') {\n          if (!Number.isSafeInteger(change.index) || change.index < 0 || change.index > list.length)\n            throw new Error('Invalid list index');\n          list.splice(change.index, 0, structuredClone(change.value));\n        } else if (change.op === 'list.remove') {\n          if (!Number.isSafeInteger(change.index) || !(change.index in list)) throw new Error('Invalid list index');\n          list.splice(change.index, 1);\n        } else {\n          if (!(change.from in list) || !Number.isSafeInteger(change.to) || change.to < 0 || change.to >= list.length)\n            throw new Error('Invalid list index');\n          const [item] = list.splice(change.from, 1);\n          list.splice(change.to, 0, item);\n        }\n        break;\n      }\n      default:\n        throw new Error(`Unknown change op: ${String((change as { op: unknown }).op)}`);\n    }\n  }\n  return target;\n}\n","import { resolveDslLayout } from '@mengine/medeo-client';\nimport type {\n  Clip,\n  CaptionStyle,\n  DslMutation,\n  FieldPatch,\n  MedeoDslSnapshot,\n  PhoneticScript,\n  StoredFile,\n  TimeAnchor,\n} from '@mengine/medeo-dsl';\n\nimport type { DocumentEdit } from './edit.ts';\nimport { interpret } from './interpret.ts';\nimport type { WorkingState } from './state.ts';\n\n/** What may play on each Track role. */\nconst contentByRole: Record<string, readonly string[]> = {\n  video_clip: ['video', 'image'],\n  speech: ['audio', 'voiceover-recording'],\n  bgm: ['audio'],\n  caption: ['caption'],\n};\n\n/**\n * The plan as document mutations, in an order one transaction accepts: the\n * journaled text edits first (creating the scripts and Captions they touch),\n * then other creations, field changes, relation rows, Tree placement, and the\n * deletions last. Anything a plan leaves inconsistent is refused here, before a\n * write; the client transaction then checks the whole result again.\n */\nexport function planMutations(edit: DocumentEdit): DslMutation[] {\n  const base = edit.base,\n    s = edit.state;\n  const rows = clipRows(s, true);\n  const baseRows = clipRows(base, false);\n  validate(edit, rows, baseRows);\n  fillFallbacks(s, rows, baseRows);\n\n  const out: DslMutation[] = [];\n  for (const entry of edit.journal) {\n    if (!s.scripts.has(entry.owner) && !s.captions.has(entry.owner) && !s.phonetics.has(entry.owner)) continue;\n    const m = entry.mutation;\n    // A new PhoneticScript is created with the file its final text was stored in.\n    if (m.type === 'create-entity' && m.table === 'phonetic-script-entities')\n      out.push({ ...m, value: storedFile(s, m.id) });\n    // A new transcript is created with what a read of its transcription file reported.\n    else if (m.type === 'create-entity' && m.table === 'audio-script-entities')\n      out.push({ ...m, value: { ...m.value, ...s.scripts.get(m.id)?.file } });\n    else out.push(m);\n  }\n\n  for (const [id, media] of s.media)\n    if (!base.media.has(id)) out.push({ type: 'create-entity', table: 'media-entities', id, value: media });\n  for (const [id, voice] of s.voices)\n    if (!base.voices.has(id)) out.push({ type: 'create-entity', table: 'voice-entities', id, value: voice });\n  for (const [id, track] of s.tracks)\n    if (!base.tracks.has(id)) out.push({ type: 'create-entity', table: 'track-entities', id, value: track });\n  for (const [id, row] of rows)\n    if (!baseRows.has(id)) out.push({ type: 'create-entity', table: 'clip-entities', id, value: row });\n\n  for (const [id, media] of s.media) {\n    const old = base.media.get(id);\n    if (!old) continue;\n    const patch = changed(old, media, ['storageKey', 'digest', 'durationMs']);\n    if (patch) out.push({ type: 'patch-entity', table: 'media-entities', id, patch });\n  }\n  for (const [id, voice] of s.voices) {\n    const old = base.voices.get(id);\n    const patch = old && changed(old, voice, ['name']);\n    if (patch) out.push({ type: 'patch-entity', table: 'voice-entities', id, patch });\n  }\n  for (const [id, track] of s.tracks) {\n    const old = base.tracks.get(id);\n    const patch = old && changed(old, track, ['role', 'hidden']);\n    if (patch) out.push({ type: 'patch-entity', table: 'track-entities', id, patch });\n  }\n  // Its phoneme is journaled; the file holding its text is written in the same write, so a merge\n  // never pairs one text with another's file.\n  for (const id of s.phonetics.keys()) {\n    if (!base.phonetics.has(id) || JSON.stringify(storedFile(base, id)) === JSON.stringify(storedFile(s, id))) continue;\n    const patch: FieldPatch<PhoneticScript> = {\n      system: undefined,\n      key: undefined,\n      storageKey: undefined,\n      digest: undefined,\n      ...storedFile(s, id),\n    };\n    out.push({ type: 'patch-entity', table: 'phonetic-script-entities', id, patch });\n  }\n  for (const [id, script] of s.scripts) {\n    const old = base.scripts.get(id)?.file;\n    const patch = old && script.file && changed(old, script.file, ['storageKey', 'digest']);\n    if (patch) out.push({ type: 'patch-entity', table: 'audio-script-entities', id, patch });\n  }\n  for (const [id, caption] of s.captions) {\n    const style = styleChanges(base.captions.get(id)?.style, caption.style);\n    if (style) out.push({ type: 'patch-entity', table: 'caption-entities', id, patch: { style } });\n  }\n  for (const [id, row] of rows) {\n    const old = baseRows.get(id);\n    if (!old) continue;\n    const patch: Record<string, unknown> = {};\n    if (JSON.stringify(old.seqMarker) !== JSON.stringify(row.seqMarker))\n      patch.seqMarker = {\n        inMs: row.seqMarker.inMs,\n        outMs: row.seqMarker.outMs,\n        rate: row.seqMarker.rate,\n        fillTimeline: row.seqMarker.fillTimeline,\n      };\n    if (old.volume !== row.volume) patch.volume = row.volume;\n    if (old.source !== row.source) patch.source = row.source;\n    if (!sameAnchor(old.anchor, row.anchor)) patch.anchor = row.anchor;\n    if (Object.keys(patch).length) out.push({ type: 'patch-entity', table: 'clip-entities', id, patch });\n  }\n\n  for (const [table, now, then] of [\n    ['voice-timbre-relations', s.timbres, base.timbres],\n    ['derived-from-relations', s.derived, base.derived],\n  ] as const) {\n    for (const [id, value] of now) if (!then.has(id)) out.push({ type: 'set-relation', table, value } as DslMutation);\n    for (const id of then.keys()) if (!now.has(id)) out.push({ type: 'delete-relation', table, id });\n  }\n\n  out.push(...treeMutations(base, s));\n\n  for (const [table, now, then] of [\n    ['clip-entities', s.clips, base.clips],\n    ['track-entities', s.tracks, base.tracks],\n    ['caption-entities', s.captions, base.captions],\n    ['phonetic-script-entities', s.phonetics, base.phonetics],\n    ['audio-script-entities', s.scripts, base.scripts],\n    ['media-entities', s.media, base.media],\n    ['voice-entities', s.voices, base.voices],\n  ] as const)\n    for (const id of then.keys()) if (!now.has(id)) out.push({ type: 'delete-entity', table, id });\n  return out;\n}\n\n/** A PhoneticScript's file facts as a row states them: only those it has. */\nfunction storedFile(s: WorkingState, id: string): Partial<StoredFile> {\n  const file = s.phoneticFiles.get(id) ?? {};\n  return Object.fromEntries(Object.entries(file).filter(([, value]) => value !== undefined));\n}\n\n/**\n * The Clip rows a state stores. A Clip becomes a row only once it has content\n * and a marker; while a script assembles it, it lives in the working state only.\n */\nfunction clipRows(s: WorkingState, strict: boolean): Map<string, Clip> {\n  const rows = new Map<string, Clip>();\n  for (const [id, clip] of s.clips) {\n    const markerId = s.clipMarker.get(id);\n    const marker = markerId === undefined ? undefined : s.markers.get(markerId);\n    const source = s.clipContent.get(id);\n    if (!marker || source === undefined) {\n      if (strict)\n        throw new Error(`Clip ${id} needs a marker and content: marker(clip, marker), contain(clip, content)`);\n      continue;\n    }\n    const host = s.clipHost.get(id);\n    if (strict && host !== undefined && marker.startMs === undefined)\n      throw new Error(`Clip ${id} follows ${host}, which needs its marker's startMs`);\n    const anchor: TimeAnchor | undefined =\n      marker.startMs === undefined\n        ? undefined\n        : { to: host ?? s.timelineId, offsetMs: marker.startMs, fallback_abs_ms: s.fallbacks.get(id) ?? 0 };\n    rows.set(id, {\n      seqMarker: {\n        inMs: marker.inMs,\n        outMs: marker.outMs,\n        ...(marker.rate === undefined ? {} : { rate: marker.rate }),\n        ...(marker.fillTimeline ? { fillTimeline: true as const } : {}),\n      },\n      source,\n      ...(clip.volume === undefined ? {} : { volume: clip.volume }),\n      ...(anchor ? { anchor } : {}),\n    });\n  }\n  return rows;\n}\n\nfunction validate(edit: DocumentEdit, rows: Map<string, Clip>, baseRows: Map<string, Clip>): void {\n  const base = edit.base,\n    s = edit.state;\n  for (const [markerId] of s.markers)\n    if (![...s.clipMarker.values()].includes(markerId))\n      throw new Error(`sequence-marker ${markerId} marks no Clip; link it with marker(clip, marker) or delete it`);\n  for (const id of s.tracks.keys())\n    if (!s.trackOrder.includes(id) && (base.trackOrder.includes(id) || !base.tracks.has(id)))\n      throw new Error(`Track ${id} is not contained by the Timeline: contain(timeline, track)`);\n  const touchedPlacement = (id: string) =>\n    edit.trackOf(id) !== trackOfState(base, id) ||\n    JSON.stringify(base.trackClips.get(trackOfState(base, id) ?? '')) !==\n      JSON.stringify(s.trackClips.get(edit.trackOf(id) ?? ''));\n  for (const [id, row] of rows) {\n    const old = baseRows.get(id);\n    if (\n      old &&\n      JSON.stringify({ ...old, anchor: anchorKey(old.anchor) }) ===\n        JSON.stringify({ ...row, anchor: anchorKey(row.anchor) }) &&\n      !touchedPlacement(id)\n    )\n      continue;\n    const trackId = edit.trackOf(id);\n    if (trackId === undefined) throw new Error(`Clip ${id} is not contained by a Track: contain(track, clip)`);\n    const role = s.tracks.get(trackId)?.role ?? '';\n    const media = s.media.get(row.source);\n    const kind = media?.kind ?? (s.captions.has(row.source) ? 'caption' : undefined);\n    if (!kind) throw new Error(`Clip ${id} contains ${row.source}, which is neither media nor a Caption`);\n    if (!contentByRole[role]?.includes(kind)) throw new Error(`A ${role} Track does not play ${kind} (Clip ${id})`);\n    const duration = media && 'durationMs' in media ? media.durationMs : undefined;\n    if (duration !== undefined && row.seqMarker.outMs > duration)\n      throw new Error(`Clip ${id}'s marker reaches ${row.seqMarker.outMs}ms, past its content's ${duration}ms`);\n    if (row.seqMarker.rate !== undefined && kind !== 'video' && kind !== 'audio' && kind !== 'voiceover-recording')\n      throw new Error(`Only video and sound change speed (Clip ${id})`);\n    if (row.seqMarker.fillTimeline && kind !== 'audio')\n      throw new Error(`Only BGM audio fills the Timeline (Clip ${id})`);\n    if (row.anchor && row.anchor.to === s.timelineId && row.anchor.offsetMs < 0)\n      throw new Error(`Clip ${id}'s startMs on the Track cannot be negative`);\n  }\n  for (const [id, caption] of s.captions) {\n    const touched = !base.captions.has(id) || edit.journal.some((entry) => entry.owner === id);\n    if (touched && caption.text === undefined && !caption.selection)\n      throw new Error(`Caption ${id} needs its own text or a selection of its base script`);\n    // Deleting a base is not refused; only a selection this plan writes must have its script.\n    if (touched && caption.selection && !s.scripts.has(caption.selection.audioScriptId))\n      throw new Error(`Caption ${id} selects ${caption.selection.audioScriptId}, which this plan deletes`);\n  }\n  for (const [id, phonetic] of s.phonetics) {\n    if (!edit.journal.some((entry) => entry.owner === id)) continue;\n    if (!s.scripts.has(phonetic.audioScriptId))\n      throw new Error(`PhoneticScript ${id} reads ${phonetic.audioScriptId}, which this plan deletes`);\n    if (!phonetic.selection) throw new Error(`PhoneticScript ${id} needs a selection of the segment it is written for`);\n  }\n  for (const [id, media] of s.media) {\n    const old = base.media.get(id);\n    if (\n      (media.kind === 'audio' || media.kind === 'voiceover-recording') &&\n      !media.storageKey &&\n      JSON.stringify(old) !== JSON.stringify(media)\n    )\n      throw new Error(`${id} plays from storage, and reading its file reported no storageKey`);\n  }\n}\n\nfunction trackOfState(s: WorkingState, clipId: string): string | undefined {\n  for (const [trackId, clips] of s.trackClips) if (clips.includes(clipId)) return trackId;\n}\n\n/** A changed placement records where it put the Clip, taken from the plan's own layout (D31). */\nfunction fillFallbacks(s: WorkingState, rows: Map<string, Clip>, baseRows: Map<string, Clip>): void {\n  const moved = [...rows].filter(([id, row]) => row.anchor && !sameAnchor(baseRows.get(id)?.anchor, row.anchor));\n  if (!moved.length) return;\n  const layout = resolveDslLayout(layoutInput(s, rows));\n  for (const [id, row] of moved) {\n    const start = layout.clips[id]?.startMs;\n    row.anchor!.fallback_abs_ms = start ?? Math.max(0, row.anchor!.offsetMs);\n  }\n}\n\nfunction layoutInput(s: WorkingState, rows: Map<string, Clip>): MedeoDslSnapshot {\n  return {\n    'timeline-entities': { [s.timelineId]: {} },\n    'track-entities': Object.fromEntries(s.tracks),\n    'clip-entities': Object.fromEntries(rows),\n    'media-entities': Object.fromEntries(s.media),\n    'audio-script-entities': {},\n    'phonetic-script-entities': {},\n    'caption-entities': Object.fromEntries([...s.captions.keys()].map((id) => [id, {}])),\n    'voice-entities': {},\n    'voice-timbre-relations': {},\n    'derived-from-relations': {},\n    'contain-relations': s.trackOrder.map((trackId) => ({\n      treeId: '0@0',\n      entityId: trackId,\n      children: (s.trackClips.get(trackId) ?? [])\n        .filter((clipId) => rows.has(clipId))\n        .map((clipId) => ({ treeId: '0@0', entityId: clipId, children: [] })),\n    })),\n    richText: {},\n    captionText: {},\n    phoneticText: {},\n    diagnostics: [],\n  } as unknown as MedeoDslSnapshot;\n}\n\nfunction anchorKey(anchor: TimeAnchor | undefined): string | undefined {\n  return anchor && `${anchor.to}@${anchor.offsetMs}`;\n}\nfunction sameAnchor(a: TimeAnchor | undefined, b: TimeAnchor | undefined): boolean {\n  return anchorKey(a) === anchorKey(b);\n}\n\nfunction changed<T extends object>(old: T, now: T, keys: readonly string[]): Record<string, unknown> | undefined {\n  const patch: Record<string, unknown> = {};\n  for (const key of keys) {\n    const before = (old as Record<string, unknown>)[key],\n      after = (now as Record<string, unknown>)[key];\n    if (JSON.stringify(before) !== JSON.stringify(after)) patch[key] = after;\n  }\n  return Object.keys(patch).length ? patch : undefined;\n}\n\n/** Style fields merge one by one; a field the Caption no longer states is cleared. */\nfunction styleChanges(\n  old: CaptionStyle | undefined,\n  now: CaptionStyle | undefined,\n): Record<string, unknown> | undefined {\n  const before = (old ?? {}) as Record<string, unknown>,\n    after = (now ?? {}) as Record<string, unknown>;\n  const patch: Record<string, unknown> = {};\n  for (const key of new Set([...Object.keys(before), ...Object.keys(after)]))\n    if (JSON.stringify(before[key]) !== JSON.stringify(after[key])) patch[key] = after[key];\n  return Object.keys(patch).length ? patch : undefined;\n}\n\n/**\n * Placement as Tree edits. Existing nodes move, keeping their identity; a run\n * that changed is rewritten in its final order, so indices never depend on\n * where a node started.\n */\nfunction treeMutations(base: WorkingState, s: WorkingState): DslMutation[] {\n  const out: DslMutation[] = [];\n  const placed = (state: WorkingState) => {\n    const parents = new Map<string, string | undefined>();\n    for (const trackId of state.trackOrder) {\n      parents.set(trackId, undefined);\n      for (const clipId of state.trackClips.get(trackId) ?? []) parents.set(clipId, trackId);\n    }\n    return parents;\n  };\n  const before = placed(base),\n    after = placed(s);\n  for (const id of before.keys()) if (!after.has(id)) out.push({ type: 'delete-node', entityId: id });\n  if (JSON.stringify(base.trackOrder) !== JSON.stringify(s.trackOrder))\n    s.trackOrder.forEach((trackId, index) =>\n      out.push({ type: before.has(trackId) ? 'move-node' : 'insert-node', entityId: trackId, index }),\n    );\n  for (const trackId of s.trackOrder) {\n    const children = s.trackClips.get(trackId) ?? [];\n    if (\n      base.trackOrder.includes(trackId) &&\n      JSON.stringify(base.trackClips.get(trackId) ?? []) === JSON.stringify(children)\n    )\n      continue;\n    children.forEach((clipId, index) =>\n      out.push({\n        type: before.has(clipId) ? 'move-node' : 'insert-node',\n        entityId: clipId,\n        parentId: trackId,\n        index,\n      }),\n    );\n  }\n  return out;\n}\n\n/** What the plan changes, in the contract's terms: one line per entity or relation. */\nexport function planPreview(edit: DocumentEdit): string {\n  const before = interpret(edit.base),\n    after = interpret(edit.state);\n  const lines: string[] = [];\n  const entitiesBefore = new Map(before.entities.map((entity) => [entity.entityId, entity]));\n  const entitiesAfter = new Map(after.entities.map((entity) => [entity.entityId, entity]));\n  for (const [id, entity] of entitiesAfter) {\n    const old = entitiesBefore.get(id);\n    if (!old) lines.push(`+ ${entity.entityKind} ${id} ${JSON.stringify(entity.payload)}`);\n    else if (JSON.stringify(old.payload) !== JSON.stringify(entity.payload))\n      lines.push(`~ ${entity.entityKind} ${id} ${JSON.stringify(entity.payload)}`);\n  }\n  for (const [id, entity] of entitiesBefore) if (!entitiesAfter.has(id)) lines.push(`- ${entity.entityKind} ${id}`);\n  const relation = (r: (typeof after.relations)[number]) =>\n    `${r.relationKind}(${r.endpoint0EntityId}, ${r.endpoint1EntityId}) ${r.relationId}`;\n  const relationsBefore = new Map(before.relations.map((r) => [r.relationId, r]));\n  const relationsAfter = new Map(after.relations.map((r) => [r.relationId, r]));\n  for (const [id, r] of relationsAfter) {\n    const old = relationsBefore.get(id);\n    if (!old || old.endpoint1EntityId !== r.endpoint1EntityId || old.endpoint0EntityId !== r.endpoint0EntityId)\n      lines.push(`+ ${relation(r)}`);\n  }\n  for (const [id, r] of relationsBefore) {\n    const now = relationsAfter.get(id);\n    if (!now || now.endpoint1EntityId !== r.endpoint1EntityId || now.endpoint0EntityId !== r.endpoint0EntityId)\n      lines.push(`- ${relation(r)}`);\n  }\n  const orderBefore = before.relations.filter((r) => r.relationKind === 'contain').map((r) => r.relationId);\n  const orderAfter = after.relations.filter((r) => r.relationKind === 'contain').map((r) => r.relationId);\n  if (\n    JSON.stringify(orderBefore.filter((id) => orderAfter.includes(id))) !==\n    JSON.stringify(orderAfter.filter((id) => orderBefore.includes(id)))\n  )\n    lines.push('~ contain order changed');\n  if (!lines.length) return 'No changes';\n  const shown = lines.slice(0, 200);\n  return [...shown, ...(shown.length < lines.length ? [`[${lines.length - shown.length} more changes]`] : [])].join(\n    '\\n',\n  );\n}\n","import { LoroDoc } from 'loro-crdt';\n\nimport { MedeoDsl, type DslAudit, type StoredFile } from '@mengine/medeo-client';\n\nimport type { EntityAssetContent, SandboxEntity, ScriptEntities, ScriptRelations } from '../api/types.ts';\nimport { DocumentEdit, type SandboxIdFactory } from '../dsl/edit.ts';\nimport { planMutations, planPreview } from '../dsl/plan.ts';\nimport type { ConsoleShim } from './types.ts';\n\nexport interface EditSessionOptions {\n  /** The document as the run reads it: a native Loro snapshot. */\n  snapshot: Uint8Array;\n  mint: SandboxIdFactory;\n  /** Reads a medium's or a transcript's file through the host; absent, file facts stay unknown. */\n  readFile?: (entity: SandboxEntity) => Promise<EntityAssetContent>;\n  /** Stores raw text in Memota through the host, for a PhoneticScript's phonemeScript. */\n  uploadText?: (text: string) => Promise<StoredFile>;\n  onLog?: (line: string) => void;\n  /** Called after each write a script made that landed. */\n  onWrite?: () => void;\n}\n\nexport interface SessionPlan {\n  /** Native operations on the snapshot the run read, base64; absent when nothing changed. */\n  loroUpdate?: string;\n  preview: string;\n  /** Media the plan created, by id and file key, for lineage after a commit. */\n  createdMedia: { id: string; key: string }[];\n}\n\nconst soundKinds = new Set(['audio', 'voiceover-recording']);\n\n/**\n * One script run against a private fork of the document. Writes compile into\n * the working state as they land; the plan is applied to the fork in one\n * audited transaction, and the native update it produced is what gets published.\n */\nexport class EditSession {\n  readonly edit: DocumentEdit;\n  private readonly doc = new LoroDoc();\n  private readonly dsl: MedeoDsl;\n  private readonly reads = new Set<Promise<unknown>>();\n  /** Entities whose file this run has read, so settling never reads one twice. */\n  private readonly filesRead = new Set<string>();\n  private unhandled?: { error: unknown };\n\n  constructor(private readonly options: EditSessionOptions) {\n    this.doc.import(options.snapshot);\n    this.dsl = new MedeoDsl(this.doc);\n    this.edit = new DocumentEdit(this.dsl.getSnapshot(), options.mint);\n  }\n\n  surface(): { entities: ScriptEntities; relations: ScriptRelations; console: ConsoleShim } {\n    const edit = this.edit;\n    const write = <T>(run: () => T): T => {\n      const result = run();\n      this.options.onWrite?.();\n      return result;\n    };\n    const log = (level: string) => (line: unknown) =>\n      this.options.onLog?.(level ? `[${level}] ${String(line)}` : String(line));\n    return {\n      entities: {\n        list: () => edit.list(),\n        get: (entityId) => edit.get(entityId),\n        create: (entityKind, payload) => write(() => edit.create(entityKind, payload)),\n        update: (entityId, changes) => write(() => edit.update(entityId, changes)),\n        declareFields: (entityId, payload) => write(() => edit.declareFields(entityId, payload)),\n        delete: (entityId) => write(() => edit.delete(entityId)),\n        materialize: (entityId) => this.track(this.materialize(entityId)),\n      },\n      relations: {\n        list: () => edit.relations(),\n        of: (entityId, relationKind) => edit.relationsOf(entityId, relationKind),\n        link: (relationKind, from, to) => write(() => edit.link(relationKind, from, to)),\n        move: (relationId, beforeRelationId) => write(() => edit.move(relationId, beforeRelationId)),\n        unlink: (relationId) => write(() => edit.unlink(relationId)),\n      },\n      console: { log: log(''), info: log('info'), warn: log('warn'), error: log('error') },\n    };\n  }\n\n  /**\n   * Before the plan is built: every read the script started completes; a file the plan names anew —\n   * a medium, or the transcription file a transcript names — is read once from the store, which\n   * alone knows where its bytes live and their digest (D187); and text written for a PhoneticScript\n   * is stored as a Memota file, because the document keeps raw content with its file.\n   */\n  async settle(): Promise<void> {\n    while (this.reads.size) await Promise.allSettled(this.reads);\n    // A rejection the script never handled is reported once the current turn ends.\n    await new Promise((resolve) => setImmediate(resolve));\n    if (this.unhandled) throw this.unhandled.error;\n    for (const id of this.namedFiles()) {\n      if (this.filesRead.has(id)) continue;\n      // Without a host that reads files the facts stay unknown; a sound still needs its storage to play.\n      if (!this.options.readFile && !soundKinds.has(this.edit.state.media.get(id)?.kind ?? '')) continue;\n      await this.materialize(id);\n    }\n    // Each voice-timbre the plan links is checked against the voice its take was synthesized with,\n    // read once like the take's file (D193).\n    if (this.options.readFile)\n      for (const id of this.edit.timbredTakes()) if (!this.filesRead.has(id)) await this.materialize(id);\n    this.edit.assertTimbres();\n    for (const { id, text } of this.edit.unstoredTexts()) {\n      const upload = this.options.uploadText;\n      if (!upload) throw new Error('This host stores no files');\n      this.edit.recordStoredText(id, text, await upload(text));\n    }\n  }\n\n  buildPlan(audit: DslAudit): SessionPlan {\n    const mutations = planMutations(this.edit);\n    const createdMedia = [...this.edit.state.media]\n      .filter(([id]) => !this.edit.base.media.has(id))\n      .map(([id, media]) => ({ id, key: media.key }));\n    const preview = planPreview(this.edit);\n    if (!mutations.length) return { preview, createdMedia };\n    const before = this.doc.oplogVersion();\n    this.dsl.applyMutations(mutations, audit);\n    const update = this.doc.export({ mode: 'update', from: before });\n    return { loroUpdate: Buffer.from(update).toString('base64'), preview, createdMedia };\n  }\n\n  dispose(): void {\n    this.dsl.dispose();\n    this.doc.free();\n  }\n\n  /** Files the plan names that the document did not name as they are now: new or changed media and transcripts. */\n  private namedFiles(): string[] {\n    const { state, base } = this.edit;\n    const changed = (now: unknown, then: unknown) => JSON.stringify(now) !== JSON.stringify(then);\n    return [\n      ...[...state.media].filter(([id, media]) => changed(media, base.media.get(id))).map(([id]) => id),\n      ...[...state.scripts]\n        .filter(([id, script]) => script.file && changed(script.file, base.scripts.get(id)?.file))\n        .map(([id]) => id),\n    ];\n  }\n\n  private async materialize(entityId: string): Promise<{ assetId: string; content: unknown }> {\n    const entity = this.edit.get(entityId);\n    if (!entity) throw new Error(`Missing entity: ${entityId}`);\n    const transcript = entity.entityKind === 'audio-script' && (entity.payload as { key?: string }).key !== undefined;\n    if (!transcript && !['video', 'audio', 'voiceover-recording', 'image'].includes(entity.entityKind))\n      throw new Error(\n        `Only a medium or a transcript naming its transcription file has a stored file to read; ${entityId} is a ${entity.entityKind}`,\n      );\n    const read = this.options.readFile;\n    if (!read) throw new Error('This host reads no files');\n    const result = await read(entity);\n    this.edit.recordFile(entityId, result);\n    this.filesRead.add(entityId);\n    return { assetId: (entity.payload as { key: string }).key, content: result.content };\n  }\n\n  /**\n   * A rejection the script left unhandled — a failed read it never awaited — stops the plan.\n   * One it caught is the script's business.\n   */\n  reportUnhandled(error: unknown): void {\n    this.unhandled ??= { error };\n  }\n\n  /** An unawaited read still completes before the plan is built. */\n  private track<T>(promise: Promise<T>): Promise<T> {\n    this.reads.add(promise);\n    const done = () => this.reads.delete(promise);\n    promise.then(done, done);\n    return promise;\n  }\n}\n","/// <reference types=\"node\" />\nimport { randomUUID } from 'node:crypto';\nimport vm from 'node:vm';\nimport { parentPort, workerData } from 'node:worker_threads';\n\nimport type { DslAudit, StoredFile } from '@mengine/medeo-client';\n\nimport type { EntityAssetContent, SandboxEntity } from '../api/types.ts';\nimport type { SandboxIdFactory } from '../dsl/edit.ts';\nimport { bindScriptSurface } from './script-bridge.ts';\nimport { EditSession } from './session.ts';\n\n/**\n * Node worker entry for agent edit scripts: open the document fork, run the\n * script in a bare `vm` context holding only the bindings `script-bridge.ts`\n * builds there, and report the plan. Writes and logs stream to the host, so a\n * timeout or out-of-memory termination still leaves the partial count.\n */\n\nexport interface WorkerData {\n  snapshot: Uint8Array;\n  script: string;\n  audit: Omit<DslAudit, 'payload'>;\n  /** Deterministic id label for tests; omitted, ids are random. */\n  idLabel?: string;\n  /** Whether the host reads files; without it a plan leaves the facts of the files it names unknown. */\n  readsFiles: boolean;\n}\n\nexport type WorkerMessage =\n  | { t: 'read-file'; requestId: number; entity: SandboxEntity }\n  | { t: 'upload-text'; requestId: number; text: string }\n  | { t: 'ready' }\n  | { t: 'write' }\n  | { t: 'log'; line: string }\n  | { t: 'done'; preview: string; loroUpdate?: string; createdMedia: { id: string; key: string }[] }\n  | {\n      t: 'fail';\n      phase: 'parse' | 'runtime';\n      error: { message: string; line?: number; column?: number; stack?: string };\n    };\n\nconst data = workerData as WorkerData;\nif (parentPort == null) throw new Error('sandbox worker must run inside a worker_threads Worker');\nconst port = parentPort;\nlet requestId = 0;\nconst pending = new Map<number, { resolve: (result: unknown) => void; reject: (error: Error) => void }>();\nport.on('message', (message: { t: string; requestId: number; result: unknown; error?: string }) => {\n  if (message.t !== 'host-result') return;\n  const waiter = pending.get(message.requestId);\n  pending.delete(message.requestId);\n  if (message.error) waiter?.reject(new Error(message.error));\n  else waiter?.resolve(message.result);\n});\n/** Ask the host for resource I/O, which the worker has none of. */\nfunction ask<T>(message: DistributiveOmit<Extract<WorkerMessage, { requestId: number }>, 'requestId'>): Promise<T> {\n  return new Promise((resolve, reject) => {\n    const id = ++requestId;\n    pending.set(id, { resolve: resolve as (result: unknown) => void, reject });\n    post({ ...message, requestId: id } as WorkerMessage);\n  });\n}\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\nconst readFile = (entity: SandboxEntity) => ask<EntityAssetContent>({ t: 'read-file', entity });\nconst uploadText = (text: string) => ask<StoredFile>({ t: 'upload-text', text });\nfunction post(message: WorkerMessage): void {\n  port.postMessage(message);\n}\n\nfunction idFactory(label?: string): SandboxIdFactory {\n  let n = 0;\n  return (kind) => `${kind}_${label == null ? randomUUID() : `${label}${++n}`}`;\n}\n\n/** Extract script line/column from the first `agent-script.js` stack frame. */\nfunction positionFromError(\n  error: unknown,\n  script?: string,\n  phase?: 'parse' | 'runtime',\n): { line?: number; column?: number; stack?: string; message: string } {\n  // Duck-type: vm SyntaxError in a worker may fail `instanceof Error` across realms.\n  const obj = error != null && typeof error === 'object' ? (error as Record<string, unknown>) : null;\n  const message =\n    obj != null && typeof obj.message === 'string'\n      ? obj.message\n      : error instanceof Error\n        ? error.message\n        : String(error);\n  const stack = obj != null && typeof obj.stack === 'string' ? obj.stack : undefined;\n  let line = typeof obj?.lineNumber === 'number' ? obj.lineNumber : undefined;\n  let column = typeof obj?.columnNumber === 'number' ? obj.columnNumber : undefined;\n  if (stack != null) {\n    // Prefer the header form `agent-script.js:N` (SyntaxError) or `agent-script.js:N:M`.\n    const match = /agent-script\\.js:(\\d+)(?::(\\d+))?/.exec(stack);\n    if (match != null) {\n      line = Number(match[1]);\n      if (match[2] != null) column = Number(match[2]);\n    }\n  }\n  // V8 often points a parse error at the token after an unclosed `{`/`(`/`[`; report the\n  // line the script left open instead.\n  if (phase === 'parse' && script != null && line != null && line >= 2) {\n    const lines = script.split('\\n');\n    const prev = lines[line - 2];\n    if (prev != null && /[{([]\\s*$/.test(prev)) {\n      line = line - 1;\n      column = prev.length;\n    }\n  }\n  return { message, line, column, stack };\n}\n\nasync function main(): Promise<void> {\n  const session = new EditSession({\n    snapshot: data.snapshot,\n    mint: idFactory(data.idLabel),\n    ...(data.readsFiles ? { readFile } : {}),\n    uploadText,\n    onLog: (line) => post({ t: 'log', line }),\n    onWrite: () => post({ t: 'write' }),\n  });\n  process.on('unhandledRejection', (reason) => session.reportUnhandled(reason));\n  // The prelude stays on the script's first line so stack line numbers map 1:1 onto it.\n  const wrapped = `(async (entities, relations, console) => {${data.script}\\n})`;\n  // The script's own realm: its `Function` compiles nothing, and every binding it is given was\n  // made inside it. See `script-bridge.ts`.\n  const ctx = vm.createContext(Object.create(null) as Record<string, unknown>, {\n    codeGeneration: { strings: false, wasm: false },\n  });\n  const bindings = bindScriptSurface(ctx, session.surface());\n\n  let run: unknown;\n  try {\n    run = vm.runInContext(wrapped, ctx, { filename: 'agent-script.js' });\n  } catch (error) {\n    post({ t: 'fail', phase: 'parse', error: positionFromError(error, data.script, 'parse') });\n    return;\n  }\n  if (typeof run !== 'function') {\n    post({ t: 'fail', phase: 'runtime', error: { message: 'agent script wrapper did not evaluate to a function' } });\n    return;\n  }\n  try {\n    const invoke = run as (entities: unknown, relations: unknown, console: unknown) => Promise<unknown>;\n    // Cold start is done; the host starts the timeout here.\n    post({ t: 'ready' });\n    await invoke(bindings.entities, bindings.relations, bindings.console);\n    await session.settle();\n    const plan = session.buildPlan({ ...data.audit, payload: { script: data.script } });\n    post({\n      t: 'done',\n      preview: plan.preview,\n      createdMedia: plan.createdMedia,\n      ...(plan.loroUpdate ? { loroUpdate: plan.loroUpdate } : {}),\n    });\n  } catch (error) {\n    post({ t: 'fail', phase: 'runtime', error: positionFromError(error, data.script, 'runtime') });\n  } finally {\n    session.dispose();\n  }\n}\n\nmain().catch((error: unknown) => {\n  post({ t: 'fail', phase: 'runtime', error: positionFromError(error) });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEtB,SAAS,QAAQ,OAAwB;CACvC,OAAO,KAAK,UAAU;EAAE,QAAQ;EAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAAE,CAAC;AACzG;;AAGA,SAAS,OAAO,OAAwB;CACtC,OAAO,KAAK,UAAU,EAAE,M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