@mengine/medeo-tool 1.2.1-alpha.9 → 1.3.1-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as collectAffectedPartIds, o as renderPreview, s as renderCompactProjection, t as EditSandboxSession } from "./script-session-CHyIUBkO.mjs";
1
+ import { c as renderPreview, l as renderCompactProjection, n as EntitySandbox, o as isMediaAssetVariantKind, r as toDslRows, s as collectAffectedPartIds, t as EditSandboxSession } from "./script-session-1eqBGegp.mjs";
2
2
  import { EntityGraphHttpClient, ManualSyncDoc, MengineHttpClient, MengineHttpRequestError, ValidationError, createMirrorVideoDocument, createPlainMemoryAdapter, decodeDocVersionMark, encodeDocVersionMark, migrateLegacyTimelineToEntities, replayJournal, toVideoDocument } from "@mengine/medeo-client";
3
3
  import { Worker } from "node:worker_threads";
4
4
  import { randomUUID } from "node:crypto";
@@ -205,11 +205,11 @@ const KNOWN_RELATION_KINDS = [
205
205
  "marker-timeline",
206
206
  "physical-asset",
207
207
  "generated",
208
- "phonetic-script-provenance",
209
- "caption-provenance",
210
208
  "caption-alignment",
211
209
  "clip-anchor",
212
- "audio-script-render"
210
+ "phonetic-script-render",
211
+ "audio-script-source",
212
+ "audio-script-marker"
213
213
  ];
214
214
  //#endregion
215
215
  //#region src/entity/entity-http-client.ts
@@ -333,13 +333,6 @@ async function safeReadJson(response) {
333
333
  * Voice results use the speech system; every other medium uses `memota`.
334
334
  */
335
335
  const ASSET_SYSTEMS = new Set(["memota", "memota-speech"]);
336
- /** Entity kinds that may carry a generated Relation endpoint (DSL `GeneratedMedia`). */
337
- const GENERATED_MEDIA_KINDS = new Set([
338
- "video",
339
- "image",
340
- "audio",
341
- "voice"
342
- ]);
343
336
  /** Bounded CAS retry budget for the sync commit after a concurrent winner. */
344
337
  const MAX_COMMIT_ATTEMPTS = 3;
345
338
  /** Validate host-supplied facts; a malformed record fails the whole query. */
@@ -359,42 +352,18 @@ function parseGenerationFacts(value) {
359
352
  });
360
353
  }
361
354
  function planGenerationScope(base, commands, state) {
362
- const createdMediaIds = /* @__PURE__ */ new Set();
363
- const keyChangedAssetIds = /* @__PURE__ */ new Set();
364
- const bindingTouchedMediaIds = /* @__PURE__ */ new Set();
365
- for (const command of commands) if (command.kind === "create-entity") {
366
- if (command.entity.entity_kind === "asset") keyChangedAssetIds.add(command.entity.entity_id);
367
- else if (GENERATED_MEDIA_KINDS.has(command.entity.entity_kind)) createdMediaIds.add(command.entity.entity_id);
368
- } else if (command.kind === "update-entity") {
369
- const baseEntity = base.entities.find((entity) => entity.entity_id === command.entity_id);
370
- if (baseEntity?.entity_kind !== "asset") continue;
371
- const before = assetKeyOf(baseEntity);
372
- const after = assetKeyOf({
373
- entity_id: command.entity_id,
374
- entity_kind: "asset",
375
- payload: command.payload
376
- });
377
- if (after !== void 0 && before !== after) keyChangedAssetIds.add(command.entity_id);
378
- } else if (command.kind === "link-relation") {
379
- if (command.relation.relation_kind === "physical-asset") bindingTouchedMediaIds.add(command.relation.endpoint_0_entity_id);
380
- } else if (command.kind === "unlink-relation") {
381
- const removed = base.relations.find((relation) => relation.relation_id === command.relation_id);
382
- if (removed?.relation_kind === "physical-asset") bindingTouchedMediaIds.add(removed.endpoint_0_entity_id);
383
- }
384
- const scoped = new Set([...createdMediaIds, ...bindingTouchedMediaIds]);
385
- const assetsById = new Map(state.entities.filter((entity) => entity.entity_kind === "asset").map((entity) => [entity.entity_id, entity]));
386
- for (const relation of state.relations) {
387
- if (relation.relation_kind !== "physical-asset") continue;
388
- if (!keyChangedAssetIds.has(relation.endpoint_1_entity_id)) continue;
389
- scoped.add(relation.endpoint_0_entity_id);
390
- }
355
+ const touchedIds = /* @__PURE__ */ new Set();
356
+ for (const command of commands) if (command.kind === "create-entity" && isMediaAssetVariantKind(command.entity.entity_kind)) touchedIds.add(command.entity.entity_id);
357
+ const beforeByKey = resolveMediaByAssetKey(base);
358
+ const scoped = /* @__PURE__ */ new Set();
391
359
  const queryKeys = /* @__PURE__ */ new Set();
392
- for (const relation of state.relations) {
393
- if (relation.relation_kind !== "physical-asset") continue;
394
- if (!scoped.has(relation.endpoint_0_entity_id)) continue;
395
- const asset = assetsById.get(relation.endpoint_1_entity_id);
396
- const key = asset === void 0 ? void 0 : assetKeyOf(asset);
397
- if (key !== void 0) queryKeys.add(key);
360
+ for (const [key, mediaIds] of resolveMediaByAssetKey(state)) {
361
+ const previousIds = new Set(beforeByKey.get(key) ?? []);
362
+ for (const id of mediaIds) {
363
+ if (!touchedIds.has(id) || previousIds.has(id)) continue;
364
+ scoped.add(id);
365
+ queryKeys.add(key);
366
+ }
398
367
  }
399
368
  return {
400
369
  scopedMediaIds: scoped,
@@ -403,8 +372,8 @@ function planGenerationScope(base, commands, state) {
403
372
  }
404
373
  /**
405
374
  * Ordered generated(output,input) Relations missing from `state` for the given
406
- * factual records. Both endpoints must already exist and fact-match through
407
- * physical-asset bindings, and the pair must involve a media Entity the plan
375
+ * factual records. Both endpoints must already exist and match their own Asset
376
+ * identities, and the pair must involve a media Entity the plan
408
377
  * newly fact-exposed (`scopedMediaIds`): lineage scopes to the commit's diff,
409
378
  * so a pair the user deleted between untouched entities stays deleted. A pair
410
379
  * the facts already resolved against the plan's base state is likewise skipped.
@@ -414,8 +383,9 @@ function planGenerationScope(base, commands, state) {
414
383
  function planGeneratedRelations(input) {
415
384
  const { state, facts } = input;
416
385
  const scoped = input.scopedMediaIds;
417
- const mediaByAssetKey = resolveMediaByAssetKey(state);
418
- const baseResolvable = new Set(resolvablePairs(resolveMediaByAssetKey(input.baseState), facts));
386
+ const factKeys = new Set(facts.flatMap((fact) => [fact.outputAssetId, ...fact.inputAssetIds]));
387
+ const mediaByAssetKey = resolveMediaByAssetKey(state, factKeys);
388
+ const baseResolvable = new Set(resolvablePairs(resolveMediaByAssetKey(input.baseState, factKeys), facts));
419
389
  const linkedPairs = new Set(state.relations.filter((relation) => relation.relation_kind === "generated").map((relation) => pairKey(relation.endpoint_0_entity_id, relation.endpoint_1_entity_id)));
420
390
  const relations = [];
421
391
  for (const fact of facts) for (const outputId of mediaByAssetKey.get(fact.outputAssetId) ?? []) for (const inputAssetId of fact.inputAssetIds) for (const inputId of mediaByAssetKey.get(inputAssetId) ?? []) {
@@ -439,23 +409,18 @@ function planGeneratedRelations(input) {
439
409
  * Sync generation lineage after a confirmed entity commit. Any failure is
440
410
  * returned as a `failed` outcome instead of thrown, so the already-durable
441
411
  * commit result is never masked; a successful query that finds nothing is
442
- * `current`. A revision conflict re-reads, re-derives the trigger keys from
443
- * the fresh bindings, queries any newly scoped facts, re-plans, and retries
444
- * within `MAX_COMMIT_ATTEMPTS` before reporting failure a stale asset query
445
- * must never let a backfillable edge be reported as `current`.
412
+ * `current`. Asset identities are immutable, so facts are queried once. A
413
+ * revision conflict re-reads current entities and relations, re-plans, and
414
+ * retries within `MAX_COMMIT_ATTEMPTS`; deleted endpoints are never recreated.
446
415
  */
447
416
  async function syncGeneratedRelations(input) {
448
417
  const { client, docId, baseState, entityCommands, loadFacts } = input;
449
- let state;
450
- let facts = [];
451
- const queriedKeys = /* @__PURE__ */ new Set();
452
418
  try {
453
- state = await client.fetchState();
419
+ let state = await client.fetchState();
454
420
  let scope = planGenerationScope(baseState, entityCommands, state);
421
+ if (scope.queryAssetKeys.length === 0) return { status: "current" };
422
+ const facts = parseGenerationFacts(await loadFacts(docId, scope.queryAssetKeys));
455
423
  for (let attempt = 1; attempt <= MAX_COMMIT_ATTEMPTS; attempt++) {
456
- const unseenKeys = scope.queryAssetKeys.filter((key) => !queriedKeys.has(key));
457
- for (const key of unseenKeys) queriedKeys.add(key);
458
- if (unseenKeys.length > 0) facts = [...facts, ...parseGenerationFacts(await loadFacts(docId, unseenKeys))];
459
424
  if (scope.queryAssetKeys.length === 0) return { status: "current" };
460
425
  const relations = planGeneratedRelations({
461
426
  baseState,
@@ -495,7 +460,7 @@ async function syncGeneratedRelations(input) {
495
460
  }
496
461
  }
497
462
  function assetKeyOf(entity) {
498
- if (entity.entity_kind !== "asset") return void 0;
463
+ if (!isMediaAssetVariantKind(entity.entity_kind)) return void 0;
499
464
  const external = entity.payload?.external;
500
465
  if (external == null || typeof external !== "object" || Array.isArray(external)) return void 0;
501
466
  const { system, key } = external;
@@ -503,25 +468,24 @@ function assetKeyOf(entity) {
503
468
  if (typeof key !== "string" || key.length === 0 || key.trim() !== key) return void 0;
504
469
  return key;
505
470
  }
506
- /**
507
- * Media Entity ids fact-matched to each external asset key. Bindings follow
508
- * the canonical physical-asset direction (endpoint 0 = sequence media,
509
- * endpoint 1 = Asset) that the DSL spec enforces.
510
- */
511
- function resolveMediaByAssetKey(state) {
512
- const assetsById = new Map(state.entities.filter((entity) => entity.entity_kind === "asset").map((entity) => [entity.entity_id, entity]));
513
- const mediaKinds = new Set([...GENERATED_MEDIA_KINDS]);
514
- const mediaIds = new Set(state.entities.filter((entity) => mediaKinds.has(entity.entity_kind)).map((entity) => entity.entity_id));
471
+ /** Media variants own their Asset locator; generation lookup never follows Relations. */
472
+ function resolveMediaByAssetKey(state, factKeys) {
473
+ const systemByKey = /* @__PURE__ */ new Map();
474
+ for (const entity of state.entities) {
475
+ const key = assetKeyOf(entity);
476
+ if (key === void 0 || !factKeys?.has(key)) continue;
477
+ const system = entity.payload.external.system;
478
+ if (systemByKey.has(key) && systemByKey.get(key) !== system) throw new Error(`Ambiguous generation asset id ${key} across media and speech namespaces`);
479
+ systemByKey.set(key, system);
480
+ }
515
481
  const resolved = /* @__PURE__ */ new Map();
516
- for (const relation of state.relations) {
517
- if (relation.relation_kind !== "physical-asset") continue;
518
- if (!mediaIds.has(relation.endpoint_0_entity_id)) continue;
519
- const asset = assetsById.get(relation.endpoint_1_entity_id);
520
- const key = asset === void 0 ? void 0 : assetKeyOf(asset);
482
+ for (const entity of state.entities) {
483
+ if (!isMediaAssetVariantKind(entity.entity_kind)) continue;
484
+ const key = assetKeyOf(entity);
521
485
  if (key === void 0) continue;
522
- const media = resolved.get(key);
523
- if (media === void 0) resolved.set(key, [relation.endpoint_0_entity_id]);
524
- else if (!media.includes(relation.endpoint_0_entity_id)) media.push(relation.endpoint_0_entity_id);
486
+ const matches = resolved.get(key) ?? [];
487
+ matches.push(entity.entity_id);
488
+ resolved.set(key, matches);
525
489
  }
526
490
  return resolved;
527
491
  }
@@ -647,6 +611,18 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
647
611
  " readonly system: 'font-library';",
648
612
  " readonly key: string;",
649
613
  "}",
614
+ "/**",
615
+ " * One ordered entry of the Caption's segment selection. `segmentId` quotes the",
616
+ " * composed AudioScript's own stable segment identity — a local id quoted by the",
617
+ " * variant, never a peer Entity reference. Text itself is never copied here;",
618
+ " * complete Caption content is assembled through its direct baseEntityIds.",
619
+ " * The optional `textRange` narrows one Segment to an intra-Segment sub-span",
620
+ " * (intra-segment re-segmentation); without it the whole Segment text is selected.",
621
+ " */",
622
+ "export type CaptionSegmentSelection = JsonObject & {",
623
+ " readonly segmentId: string;",
624
+ " readonly textRange?: CaptionTextRange;",
625
+ "};",
650
626
  "export interface CaptionStyleFields {",
651
627
  " readonly font?: CaptionFontDescriptor;",
652
628
  " readonly fontSize?: number;",
@@ -659,6 +635,24 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
659
635
  " readonly positionX?: number;",
660
636
  " readonly positionY?: number;",
661
637
  "}",
638
+ "/**",
639
+ " * Half-open `[start, end)` position window inside one Segment's text, counted",
640
+ " * in Unicode code points (not UTF-16 code units), so a boundary never splits a",
641
+ " * surrogate pair. Positions are non-negative safe integers with `start < end`;",
642
+ " * `end` must not exceed the Segment's code-point length.",
643
+ " */",
644
+ "export interface CaptionTextRange extends JsonObject {",
645
+ " readonly start: number;",
646
+ " readonly end: number;",
647
+ "}",
648
+ "export type CaptionTextSelection = JsonObject & {",
649
+ " segmentId: string;",
650
+ " /** Half-open Unicode code-point range within the selected source segment. */",
651
+ " textRange?: {",
652
+ " start: number;",
653
+ " end: number;",
654
+ " };",
655
+ "};",
662
656
  "export type ClipEntityId = EntityId;",
663
657
  "export type ClipPlacement =",
664
658
  " | {",
@@ -674,11 +668,21 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
674
668
  " readonly hostClipEntityId: string;",
675
669
  " readonly anchorOffset: number;",
676
670
  " };",
671
+ "export interface ComposedPhoneticContent extends ComposedScriptContent {",
672
+ " phonemeScript?: string;",
673
+ " prosody?: JsonObject;",
674
+ "}",
675
+ "/** Read result only: base text is assembled from the real AudioScript row. */",
676
+ "export interface ComposedScriptContent {",
677
+ " audio_script_entity_id: string;",
678
+ " text: string;",
679
+ " segments: ScriptTextSegment[];",
680
+ "}",
677
681
  "export type CreateEntityInput = {",
678
682
  " [K in KnownEntityKind]: {",
679
683
  " entity_id?: string;",
680
684
  " entity_kind: K;",
681
- " payload: EntityPayloadByKind[K];",
685
+ " payload: StoredEntityPayload<K>;",
682
686
  " };",
683
687
  "}[KnownEntityKind];",
684
688
  "export interface DeleteBgmInput {",
@@ -703,19 +707,29 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
703
707
  " | 'clip-marker'",
704
708
  " | 'marker-content'",
705
709
  " | 'axvideo-marker'",
706
- " | 'marker-timeline';",
710
+ " | 'marker-timeline'",
711
+ " | 'audio-script-marker';",
707
712
  "export interface EntityFacade {",
713
+ " /** Read complete assembled fields; returned objects are snapshots. Use update to persist edits. */",
708
714
  " list(): SandboxEntity[];",
709
715
  " get(entityId: string): SandboxEntity | null;",
710
- " /** Return every explicitly imported Asset entity for a Memota asset id. */",
711
- " findByAssetId(assetId: string): SandboxEntity<'asset'>[];",
716
+ " /** Find document resources by external Memota asset id, including directly composed media variants. */",
717
+ " findByAssetId(assetId: string): SandboxEntity<ResourceEntityKind>[];",
718
+ " /** Assemble selected Caption text; missing composition is an error. */",
719
+ " readCaptionContent(entityId: string): ComposedScriptContent;",
720
+ " /** Assemble base text and pronunciation fields before generating Voice. */",
721
+ " readPhoneticScriptContent(entityId: string): ComposedPhoneticContent;",
712
722
  " create(input: CreateEntityInput): string;",
713
- " /** Replace one Entity's owned payload without changing its identity or kind. */",
723
+ " /** Patch assembled fields, routing inherited fields to their declaring entity. */",
714
724
  " update(input: UpdateEntityInput): void;",
725
+ " /** Explicitly declare own fields, overriding unambiguous bases without modifying them. Ordinary edits use update. */",
726
+ " declareFields(input: UpdateEntityInput): void;",
715
727
  " /** Delete an Entity only after all of its incident Relations have been explicitly unlinked. */",
716
728
  " delete(input: DeleteEntityInput): void;",
717
- " /** Import one physical asset without implying a one-to-one media Entity mapping. */",
718
- " importAsset(input: ImportAssetInput): string;",
729
+ " /** Get or create one typed Asset by factual external id and return its single content identity. Never creates a Clip. */",
730
+ " ensureMedia(fact: MediaAssetFact): {",
731
+ " contentEntityId: string;",
732
+ " };",
719
733
  "}",
720
734
  "export type EntityId = string;",
721
735
  "export interface EntityPayloadByKind {",
@@ -726,12 +740,12 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
726
740
  " role?: string;",
727
741
  " };",
728
742
  " clip: JsonObject;",
729
- " /** Asset-owned metadata. Peer media associations belong in physical-asset Relations. */",
743
+ " /** Physical resource fields; never a copy of Caption content. */",
730
744
  " asset: JsonObject;",
731
- " video: BoundedNativeSequencePayload;",
732
- " audio: BoundedNativeSequencePayload;",
733
- " voice: BoundedNativeSequencePayload;",
734
- " image: UnboundedConstantSequencePayload;",
745
+ " video: BoundedNativeSequencePayload & MediaAssetPayload;",
746
+ " audio: BoundedNativeSequencePayload & MediaAssetPayload;",
747
+ " voice: BoundedNativeSequencePayload & MediaAssetPayload;",
748
+ " image: UnboundedConstantSequencePayload & MediaAssetPayload;",
735
749
  " 'sequence-marker': JsonObject & {",
736
750
  " sourceRange: {",
737
751
  " start: number;",
@@ -752,15 +766,27 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
752
766
  " timeRemapping?: JsonValue;",
753
767
  " anchorOffset?: number;",
754
768
  " durationPolicy?: 'timeline';",
769
+ " /** Directly assigned AudioScript annotation times; annotation Markers only. */",
770
+ " segmentRanges?: {",
771
+ " segmentId: string;",
772
+ " startMs: number;",
773
+ " endMs: number;",
774
+ " }[];",
755
775
  " };",
756
776
  " viewport: JsonObject;",
757
777
  " 'audio-script': JsonObject & {",
758
778
  " segments: ScriptTextSegment[];",
759
779
  " };",
760
780
  " 'phonetic-script': JsonObject & {",
761
- " segments: ScriptTextSegment[];",
781
+ " baseEntityIds: string[];",
782
+ " phonemeScript?: string;",
783
+ " prosody?: JsonObject;",
784
+ " };",
785
+ " caption: BoundedNativeSequencePayload & {",
786
+ " baseEntityIds: string[];",
787
+ " selections: CaptionTextSelection[];",
788
+ " style?: JsonObject;",
762
789
  " };",
763
- " caption: BoundedNativeSequencePayload;",
764
790
  "}",
765
791
  "export interface EntityStoreSnapshot {",
766
792
  " revision: number;",
@@ -772,10 +798,18 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
772
798
  " readonly kind: 'image';",
773
799
  " readonly storageKey?: string;",
774
800
  "}",
775
- "export interface ImportAssetInput {",
776
- " asset_id: string;",
777
- " entity_id?: string;",
778
- " payload?: JsonObject;",
801
+ "export interface InsertCaptionClipInput {",
802
+ " readonly timelineEntityId: string;",
803
+ " /** Stable placed caption identity, distinct from the Caption content identity. */",
804
+ " readonly captionClipEntityId?: string;",
805
+ " /** Existing bases composed by this variant; includes an AudioScript text owner. */",
806
+ " readonly baseEntityIds: readonly string[];",
807
+ " /** Ordered selection of the AudioScript segments this Caption displays. */",
808
+ " readonly selections: readonly CaptionSegmentSelection[];",
809
+ " /** Intrinsic cue length of the Caption entity itself; display comes from the placement. */",
810
+ " readonly durationMs: number;",
811
+ " readonly style?: CaptionStyleFields;",
812
+ " readonly placement: ClipPlacement;",
779
813
  "}",
780
814
  "export interface InsertClipInput {",
781
815
  " readonly trackEntityId: string;",
@@ -840,20 +874,21 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
840
874
  " | 'marker-timeline'",
841
875
  " | 'physical-asset'",
842
876
  " | 'generated'",
843
- " | 'phonetic-script-provenance'",
844
- " | 'caption-provenance'",
845
877
  " | 'caption-alignment'",
846
878
  " | 'clip-anchor'",
847
- " | 'audio-script-render';",
879
+ " | 'phonetic-script-render'",
880
+ " | 'audio-script-source'",
881
+ " | 'audio-script-marker';",
848
882
  "export interface LinearClipSpeed {",
849
883
  " readonly kind: 'linear';",
850
884
  " readonly rate: number;",
851
885
  " readonly mode?: string;",
852
886
  "}",
853
- "export interface LinkAudioScriptRenderRelationInput {",
887
+ "/** `audio-script-source(script, source)`; the script was transcribed from the source media. */",
888
+ "export interface LinkAudioScriptSourceRelationInput {",
854
889
  " relation_id?: string;",
855
- " output_entity_id: string;",
856
890
  " script_entity_id: string;",
891
+ " source_entity_id: string;",
857
892
  " trace?: JsonObject;",
858
893
  "}",
859
894
  "export interface LinkClipAnchorRelationInput {",
@@ -868,6 +903,12 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
868
903
  " input_entity_id: string;",
869
904
  " trace?: JsonObject;",
870
905
  "}",
906
+ "export interface LinkPhoneticScriptRenderRelationInput {",
907
+ " relation_id?: string;",
908
+ " output_entity_id: string;",
909
+ " phonetic_script_entity_id: string;",
910
+ " trace?: JsonObject;",
911
+ "}",
871
912
  "interface LinkRelationBase {",
872
913
  " relation_id?: string;",
873
914
  " endpoint_0_entity_id: string;",
@@ -886,17 +927,20 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
886
927
  " metadata?: JsonObject;",
887
928
  " })",
888
929
  " | (LinkRelationBase & {",
889
- " relation_kind: 'phonetic-script-provenance' | 'caption-provenance';",
890
- " metadata: JsonObject & {",
891
- " segmentAlignment: JsonValue;",
892
- " };",
893
- " })",
894
- " | (LinkRelationBase & {",
895
930
  " relation_kind: 'caption-alignment';",
896
931
  " metadata: JsonObject & {",
897
932
  " alignment: JsonValue;",
898
933
  " };",
899
934
  " });",
935
+ "/** Facts resolved from media storage. A trim window never substitutes for intrinsic duration. */",
936
+ "export type MediaAssetFact = ImageMediaAssetFact | VideoMediaAssetFact | AudioMediaAssetFact | VoiceMediaAssetFact;",
937
+ "export type MediaAssetPayload = JsonObject & {",
938
+ " external: {",
939
+ " system: 'memota' | 'memota-speech';",
940
+ " key: string;",
941
+ " };",
942
+ " storageKey?: string;",
943
+ "};",
900
944
  "export type MediaClipInsertion =",
901
945
  " | {",
902
946
  " readonly kind: 'before';",
@@ -940,14 +984,16 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
940
984
  " list(): SandboxRelation[];",
941
985
  " /** Incident lookup is endpoint-agnostic; persisted endpoint positions stay unchanged. */",
942
986
  " of(entityId: string, relationKind?: KnownRelationKind): SandboxRelation[];",
943
- " /** For physical-asset use sequence media as endpoint 0 and Asset as endpoint 1. */",
987
+ " /** Link existing entities through ordinary associations; variant bases are stored directly on the variant. */",
944
988
  " link(input: LinkRelationInput): string;",
945
989
  " /** Author ordered generated(output,input); generic link() deliberately rejects this kind. */",
946
990
  " linkGenerated(input: LinkGeneratedRelationInput): string;",
947
991
  " /** Author ordered clip-anchor(child,host) without positional endpoint ambiguity. */",
948
992
  " linkClipAnchor(input: LinkClipAnchorRelationInput): string;",
949
- " /** Author ordered audio-script-render(output,script) without positional endpoint ambiguity. */",
950
- " linkAudioScriptRender(input: LinkAudioScriptRenderRelationInput): string;",
993
+ " /** Author ordered phonetic-script-render(output,script) without positional endpoint ambiguity. */",
994
+ " linkPhoneticScriptRender(input: LinkPhoneticScriptRenderRelationInput): string;",
995
+ " /** Author ordered audio-script-source(script,source) without positional endpoint ambiguity. */",
996
+ " linkAudioScriptSource(input: LinkAudioScriptSourceRelationInput): string;",
951
997
  " /** Remove a Relation by identity; endpoint replacement is an explicit unlink plus link. */",
952
998
  " unlink(input: UnlinkRelationInput): void;",
953
999
  "}",
@@ -977,10 +1023,12 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
977
1023
  " readonly sourceRange: SequenceRange<number>;",
978
1024
  " readonly volume?: number;",
979
1025
  "}",
1026
+ "/** Asset identity, either an old physical-only row or a directly composed media variant. */",
1027
+ "export type ResourceEntityKind = 'image' | 'video' | 'audio' | 'voice';",
980
1028
  "export interface SandboxEntity<K extends KnownEntityKind = KnownEntityKind> {",
981
1029
  " entity_id: string;",
982
1030
  " entity_kind: K;",
983
- " payload: EntityPayloadByKind[K];",
1031
+ " payload: StoredEntityPayload<K>;",
984
1032
  "}",
985
1033
  "export interface SandboxRelation {",
986
1034
  " relation_id: string;",
@@ -1038,6 +1086,13 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
1038
1086
  " /** Playback gain in decibels. */",
1039
1087
  " readonly volume: number;",
1040
1088
  "}",
1089
+ "/** Stored own fields; a variant may obtain required content fields from its declared bases. */",
1090
+ "export type StoredEntityPayload<K extends KnownEntityKind> =",
1091
+ " | EntityPayloadByKind[K]",
1092
+ " | (JsonObject &",
1093
+ " Partial<EntityPayloadByKind[K]> & {",
1094
+ " baseEntityIds: string[];",
1095
+ " });",
1041
1096
  "export interface TrimClipInput {",
1042
1097
  " readonly clipEntityId: string;",
1043
1098
  " readonly sourceRange: SequenceRange<number>;",
@@ -1067,6 +1122,7 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
1067
1122
  " /** Passing `undefined` explicitly removes the optional remapping value. */",
1068
1123
  " readonly timeRemapping?: JsonValue | undefined;",
1069
1124
  "}",
1125
+ "/** Patch supplied fields on the assembled entity; omitted fields remain unchanged. */",
1070
1126
  "export interface UpdateEntityInput {",
1071
1127
  " entity_id: string;",
1072
1128
  " payload: JsonObject;",
@@ -1089,31 +1145,47 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
1089
1145
  " readonly kind: 'voice';",
1090
1146
  " readonly durationMs: number;",
1091
1147
  " readonly storageKey: string;",
1092
- " readonly voice: VoiceDescriptor;",
1148
+ " /** Present for synthesized voice, absent for original recorded audio. */",
1149
+ " readonly voice?: VoiceDescriptor;",
1093
1150
  "}",
1094
1151
  "export interface VoiceoverCaptionFact {",
1095
1152
  " /** Stable placed caption identity supplied by the materialized side effect. */",
1096
1153
  " readonly captionClipEntityId: string;",
1097
- " readonly text: string;",
1154
+ " /** Directly held bases; includes the AudioScript used by the Voice. */",
1155
+ " readonly baseEntityIds: readonly string[];",
1156
+ " /** Ordered selection of AudioScript segments; caption text is never passed inline. */",
1157
+ " readonly selections: readonly CaptionSegmentSelection[];",
1098
1158
  " readonly startMs: number;",
1099
1159
  " readonly durationMs: number;",
1100
1160
  " readonly style?: CaptionStyleFields;",
1101
1161
  "}",
1102
- "export interface VoiceoverTakeInput {",
1162
+ "export type VoiceoverTakeInput = {",
1103
1163
  " readonly timelineEntityId: string;",
1104
1164
  " /** Stable placed speech identity, distinct from media.assetId. */",
1105
1165
  " readonly voiceoverClipEntityId: string;",
1106
- " readonly hostClipEntityId: string;",
1107
- " readonly anchorOffset: number;",
1108
1166
  " readonly media: VoiceMediaAssetFact;",
1109
- " /** Complete spoken text; the editor owns the deterministic local script segment identity. */",
1110
- " readonly scriptText: string;",
1167
+ " /** Existing pronunciation variant; its composed AudioScript stays the text owner. */",
1168
+ " readonly phoneticScriptEntityId: string;",
1111
1169
  " readonly volume: number;",
1112
1170
  " readonly captions: readonly VoiceoverCaptionFact[];",
1113
- "}",
1171
+ "} & (",
1172
+ " | {",
1173
+ " readonly placement: ClipPlacement;",
1174
+ " readonly hostClipEntityId?: never;",
1175
+ " readonly anchorOffset?: never;",
1176
+ " }",
1177
+ " | {",
1178
+ " readonly placement?: never;",
1179
+ " readonly hostClipEntityId: string;",
1180
+ " readonly anchorOffset: number;",
1181
+ " }",
1182
+ ");",
1114
1183
  "export interface VoiceoverTakeResult {",
1115
1184
  " readonly voiceoverClipEntityId: string;",
1116
1185
  " readonly voiceEntityId: string;",
1186
+ " /** The pronunciation variant the Voice was rendered from. */",
1187
+ " readonly phoneticScriptEntityId: string;",
1188
+ " /** The base-text owner resolved from the PhoneticScript baseEntityIds. */",
1117
1189
  " readonly audioScriptEntityId: string;",
1118
1190
  " readonly captionClipEntityIds: readonly string[];",
1119
1191
  "}",
@@ -1144,6 +1216,7 @@ const ENTITY_EDIT_SANDBOX_API_DTS = [
1144
1216
  " deleteBgm(input: DeleteBgmInput): void;",
1145
1217
  " setCaptionVisibility(input: SetCaptionVisibilityInput): void;",
1146
1218
  " patchCaptionStyle(input: PatchCaptionStyleInput): void;",
1219
+ " insertCaptionClip(input: InsertCaptionClipInput): ClipEntityId;",
1147
1220
  "}",
1148
1221
  "export interface TimelineApi {",
1149
1222
  " snapshot(): EntityStoreSnapshot;",
@@ -1166,25 +1239,27 @@ const MEDEO_TOOL_DESCRIPTION = `
1166
1239
  Edit the authoritative Medeo Entity/Relation graph through a deterministic, side-effect-free JavaScript sandbox. Timeline objects and edit targets are Entities, not Memota assets or legacy parts.
1167
1240
 
1168
1241
  Operations:
1169
- - snapshot: return the Entity/Relation state summary and opaque base version.
1242
+ - snapshot: initialize missing fixed editor structure, then return the Entity/Relation state summary and opaque base version. Initialization is idempotent and may advance the entity revision once; unchanged snapshots do not write.
1170
1243
  - migrate-legacy: explicitly migrate an existing legacy timeline using recalled asset_facts. MEngine reads the canonical document and version, verifies that editing facts are preserved, and commits migration alone. Then take a fresh snapshot before any edit; never pass a caller-created legacy snapshot or version.
1171
1244
  - run-edit-script: inspect timeline.snapshot(), entities.*, and relations.*; edit.* operates existing Entity ids and creates the required Clip/SequenceMarker structural graph. Asset import, media Entity creation and timeline edits belong in ONE plan. The sandbox has no network, storage or generation access. Pass recalled asset facts through inputs; generation history is not a script input — the host program queries it itself after each commit. A successful run returns preview, logs, base revision and plan_id.
1172
1245
  - commit-plan: commit the complete Entity/Relation plan through revision CAS. The server derives the read-only timeline projection in the same transaction. There is no separate writable timeline plan and no preflight replay into a legacy editor. A failed transport is unconfirmed, never committed; retry the same plan_id.
1173
1246
 
1174
1247
  Default flow: snapshot → run-edit-script with auto_commit=false → inspect preview → commit-plan. Use auto_commit=true only for low-risk edits when the host does not need user confirmation. On version mismatch, rerun snapshot and the script; never try to patch a rejected journal by hand.
1175
1248
 
1176
- Generating an Asset alone does not require an Entity. Using that resource in the editor DOES: recall the Asset facts, reuse or create the appropriate media Entity and physical-asset Relation, then pass the media Entity id to edit.insertClip. A raw asset id or URL is not valid contentEntityId. Asset and media Entity identity are not one-to-one. Generation lineage is program-synced: after each successful commit the tool connects existing media Entities from host-recalled generation facts (endpoint 0 output, endpoint 1 input) that the host queries itself — do not pass generation history through inputs. Do not author generated Relations yourself, and never create an Entity merely to backfill or represent lineage; media Entities the edit itself legitimately needs (for example placing a recalled input asset) are still created normally. Text-only generation has no input and no lineage edge. relations.of(entityId) is endpoint-agnostic.
1249
+ Generating an Asset alone does not require an Entity. Using that resource in the editor DOES: recall the Asset facts, call entities.ensureMedia(fact), then pass its contentEntityId to edit.insertClip. A raw external asset id or URL is not valid contentEntityId. Image/Video/Audio/Voice are logical variants of Asset: a resource has ONE identity and ONE typed row owning both media fields and external {system,key}/storageKey, with no separate Asset row or physical-asset relation. ensureMedia returns contentEntityId and reuses that single identity by external asset id. Each placement still gets its own Clip and SequenceMarker. Generation lineage is program-synced: after each successful commit the tool connects existing typed Assets from host-recalled generation facts (endpoint 0 output, endpoint 1 input) that the host queries itself — do not pass generation history through inputs. Do not author generated Relations yourself, and never create an Entity merely to backfill or represent lineage; media variants the edit itself legitimately needs are still created normally. Text-only generation has no input and no lineage edge. relations.of(entityId) is endpoint-agnostic.
1177
1250
  `.trim();
1178
1251
  const MEDEO_TOOL_EXECUTION_RULES = `
1179
1252
  The host supplies the current document. Do not ask for, invent, or pass a document id.
1180
1253
  timeline.snapshot() returns the Entity/Relation graph with its revision, not a legacy VideoDraft. Inspect Timeline, Track, Clip, SequenceMarker and their relations to plan edits.
1181
1254
  Generation lineage is not a model input: the host program queries it via loadGenerationFacts and syncs generated Relations after each successful commit. Memota asset facts are host-provided through inputs. Never invent an asset id, Entity kind, or peer Entity id.
1182
- Before importing an Asset, call entities.findByAssetId(assetId), inspect every match, and decide whether an existing Entity represents the intended logical asset. Multiple matches are valid; do not assume Asset↔media is one-to-one.
1255
+ Use entities.ensureMedia(fact) to get or create the canonical typed Asset. Native media placement helpers use the same resolver. findByAssetId includes directly composed media variants, including Voice. Every Image/Video/Audio/Voice must own its external identity; separate Asset+media graphs are invalid. A typed Asset's external identity cannot be removed or rewritten: to replace its source, ensureMedia for the new Asset and replace the Clip's content. Conflicting facts fail closed. Asset generation itself still creates no editor Entities.
1183
1256
  For recalled video/audio/voice, create a bounded/native payload whose extent end comes from factual media duration/coordinates in inputs; never fabricate a duration. Image uses unbounded/constant semantics and has no invented end. If required facts are absent, do not create the media Entity yet.
1184
- For physical-asset authoring, use sequence media as endpoint_0_entity_id and Asset as endpoint_1_entity_id. Generated lineage Relations are not model-authored: the tool derives them from host generation facts after a successful commit, so do not call relations.linkGenerated to record provenance. relations.of remains endpoint-agnostic for lookup.
1257
+ Caption content is assembled from AudioScript; never create an inline text Asset for it. Generated media lineage is host-owned; do not author generated Relations yourself. relations.of remains endpoint-agnostic for lookup.
1185
1258
  The compatibility reader supports the existing four Track roles: video_clip (Image/Video), speech (Voice), caption (Caption), and bgm (Audio), one of each. Clip.volume is decibels (-60 to 20, 0 = original). Marker.sourceRange is the selected source interval; Marker.duration is effective display/playback duration. Coordinates and duration are whole milliseconds for this reader, not a global DSL restriction. Placement is exactly one of Clip.order, Marker.targetRange, or clip-anchor(child,host) plus Marker.anchorOffset. Use the native move/delete/voiceover helpers so placement and cascade decisions are in the same entity plan. Reading the graph never rebinds anchors or invents empty clips. Linear timeRemapping is {kind:'linear',rate:2,mode:'constant'} and agrees with rounded source span divided by rate. Image remains unbounded/constant; an explicit linear rate scales its display window, not an invented media extent. Nonlinear speed and multiple visual overlay tracks are unsupported.
1186
- Voice links to AudioScript through audio-script-render(output,script). Caption owns text/style and is placed through a Clip anchored to the Voice Clip; caption alignment/provenance agree with that Voice/AudioScript. BGM Audio keeps factual source duration and its Marker declares durationPolicy:'timeline'. External Asset identity and storageKey are distinct from the placed Clip identity. Never introduce a speech entity kind.
1187
- Create only the known entity kinds. On an empty document, explicitly create Timeline and Track(role='video_clip') and connect timeline-track before inserting a Clip. If snapshot reports legacy migration is required, recall the listed asset facts and call migrate-legacy first. Missing facts, unsupported layouts, and version conflicts fail closed; never fall back to an old timeline method or raw update endpoint.
1259
+ Entities own fields; ordinary Relations express associations; variants directly hold baseEntityIds and assemble the referenced entities. These foundations are fixed: implementation must follow them, never redefine them. Any entity may compose multiple bases. Equal field names from multiple bases (even equal values) are errors, even when the variant declares that field itself. After validating all base fields are unambiguous, explicitly declared own fields may override base fields without mutating the bases. Base ordering never resolves conflicts. AudioScript owns segmented text. Caption and PhoneticScript persist baseEntityIds including their AudioScript, plus their own fields; no composition Relation exists. Create the real bases before reading or committing a variant. Inside the DSL sandbox, entities.get/list expose complete assembled fields. Consumers read fields without inspecting base IDs or merging bases. entities.update patches supplied fields and routes inherited fields to their declaring entity; omitted fields remain unchanged. entities.declareFields explicitly declares own overrides and is distinct from an ordinary field edit. Persistence keeps owned fields only. entities.readCaptionContent(id) and entities.readPhoneticScriptContent(id) return assembled text. Missing/cyclic bases and field conflicts fail before persistence.
1260
+ Use edit.insertCaptionClip with baseEntityIds and selections; each voiceover caption also supplies baseEntityIds. A selection names segmentId and may use a half-open Unicode code-point textRange to split a segment for the screen without rewriting AudioScript. Generate Voice from an existing PhoneticScript, then use phoneticScriptEntityId in the voiceover helper or relations.linkPhoneticScriptRender({output_entity_id,phonetic_script_entity_id}) for its render relation. Caption and Voice have their own Clips; display anchoring is explicit and independent of composition/alignment.
1261
+ Move or stretch only the Clip's display Marker; preserve Caption intrinsic Sequence, AudioScript text and its annotation Markers. AudioScript cannot enter a Clip and has no intrinsic time. audio-script-source links its ASR source Audio/Video/Voice; audio-script-marker attaches annotation Markers with directly assigned segmentRanges:{segmentId,startMs,endMs} in whole milliseconds. Annotation Markers have no Clip/AXVideo/content/Timeline relations and never refer to other Markers for time. BGM keeps factual source duration with durationPolicy:'timeline'. Never introduce a speech entity kind.
1262
+ Create only the known entity kinds. The host initializes one Timeline and four fixed Tracks before editing; inspect and reuse their IDs from timeline.snapshot(), never create another Timeline or Track for each operation. If snapshot reports legacy migration is required, recall the listed asset facts and call migrate-legacy first. Missing facts, unsupported layouts, and version conflicts fail closed; never fall back to an old timeline method or raw update endpoint.
1188
1263
  Use only the globals and methods declared by the following TypeScript interface. Values not declared here are unavailable.
1189
1264
  `.trim();
1190
1265
  /** Render the complete MEngine-owned context injected before one model call. */
@@ -1824,8 +1899,56 @@ function createMedeoTool(options) {
1824
1899
  pendingPushes.delete(docId);
1825
1900
  if (plan.plan_kind === "timeline" && result.kind === "rejected" && result.reason === "push_rejected") documents.delete(docId);
1826
1901
  }
1827
- async function fetchEntityStateForSandbox(docId) {
1828
- return await getEntityClient(docId).fetchState();
1902
+ async function fetchEntityStateForSandbox(docId, doc, pull) {
1903
+ const client = getEntityClient(docId);
1904
+ for (let attempt = 0; attempt < 4; attempt += 1) {
1905
+ const state = await client.fetchState();
1906
+ if (pendingPushes.has(docId)) return state;
1907
+ const document = doc.snapshot();
1908
+ const hasTimeline = state.entities.some((row) => row.entity_kind === "timeline");
1909
+ const hasLegacyContent = Object.keys(document.part_library ?? {}).length > 0 || (document.tracks ?? []).some((track) => (track.items ?? []).length > 0);
1910
+ if (!hasTimeline && hasLegacyContent) return state;
1911
+ if (!hasTimeline) {
1912
+ if (pull.warnings !== void 0) throw new Error("Editor initialization requires a fresh canonical snapshot; retry snapshot");
1913
+ const baseRows = toDslRows(state);
1914
+ const migrated = migrateLegacyTimelineToEntities(document, [], baseRows);
1915
+ try {
1916
+ await getGraphClient(docId).commit({
1917
+ revision: state.revision,
1918
+ rows: baseRows
1919
+ }, migrated, { migrationBaseVv: encodeDocVersionMark(doc.versionMark()) });
1920
+ } catch (error) {
1921
+ if (!(error instanceof MengineHttpRequestError) || error.status !== 409) throw new Error(`Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`);
1922
+ }
1923
+ pull = await observePull(doc);
1924
+ continue;
1925
+ }
1926
+ const sandbox = new EntitySandbox({
1927
+ state,
1928
+ idFactory: (prefix) => `${prefix}_${randomUUID()}`
1929
+ });
1930
+ sandbox.ensureFoundation();
1931
+ if (sandbox.commandCount === 0) return state;
1932
+ if (pull.warnings !== void 0) throw new Error("Editor initialization requires a fresh canonical snapshot; retry snapshot");
1933
+ try {
1934
+ const committed = await client.commit(state.revision, sandbox.buildPlan().rows);
1935
+ await doc.pull();
1936
+ return committed;
1937
+ } catch (error) {
1938
+ if (!(error instanceof MengineEntityHttpRequestError) || error.status !== 409) throw new Error(`Editor initialization was not confirmed; retry snapshot to reconcile state: ${error instanceof Error ? error.message : String(error)}`);
1939
+ pull = await observePull(doc);
1940
+ }
1941
+ }
1942
+ throw new Error("Editor initialization conflicted repeatedly; take a fresh snapshot");
1943
+ }
1944
+ function getGraphClient(docId) {
1945
+ return new EntityGraphHttpClient({
1946
+ docId,
1947
+ httpOrigin: requiredContext(options.httpOrigin, docId, "httpOrigin"),
1948
+ ...options.authToken === void 0 ? {} : { authToken: () => optionalContext(options.authToken, docId) },
1949
+ ...options.userId === void 0 ? {} : { userId: () => optionalContext(options.userId, docId) },
1950
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
1951
+ });
1829
1952
  }
1830
1953
  async function commitCachedPlan(docId, _doc, plan, validation, baseState) {
1831
1954
  if (plan.plan_kind === "timeline") throw new Error("Legacy timeline plans are not editable; use an Entity/Relation plan");
@@ -1840,8 +1963,7 @@ function createMedeoTool(options) {
1840
1963
  * from host-recalled lineage. The commit is already durable, so a sync
1841
1964
  * failure never fails the op; it is attached to the result and surfaced as a
1842
1965
  * warning instead. The plan's diff against `baseState` scopes the sync:
1843
- * created media Entities, edits that re-point an existing physical-asset
1844
- * binding or Asset external key, and creations — not untouched pairs.
1966
+ * newly created media Asset identities not untouched pairs or placement-only edits.
1845
1967
  * One-sided facts are skipped silently inside the sync.
1846
1968
  */
1847
1969
  async function attachGenerationSync(docId, plan, result, baseState) {
@@ -1892,7 +2014,7 @@ function createMedeoTool(options) {
1892
2014
  if (docId.length === 0) throw new Error("doc_id must be a non-empty string");
1893
2015
  if (contextId.length === 0) throw new Error("context_id must be a non-empty string");
1894
2016
  return await runExclusive(docId, async (doc) => {
1895
- const [, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(docId)]);
2017
+ const entityState = await fetchEntityStateForSandbox(docId, doc, await observePull(doc));
1896
2018
  const documentVersion = `${encodeDocVersionMark(doc.versionMark())}:entities:${entityState.revision}`;
1897
2019
  const baselineKey = `${contextId}\u0000${docId}`;
1898
2020
  const previousVersion = modelContextVersions.get(baselineKey);
@@ -1917,7 +2039,8 @@ function createMedeoTool(options) {
1917
2039
  async function snapshot(input) {
1918
2040
  return runExclusive(input.doc_id, async (doc) => {
1919
2041
  assertNoPendingPush(input.doc_id);
1920
- const [pull, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(input.doc_id)]);
2042
+ const pull = await observePull(doc);
2043
+ const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);
1921
2044
  return {
1922
2045
  ok: true,
1923
2046
  op: "snapshot",
@@ -1932,13 +2055,7 @@ function createMedeoTool(options) {
1932
2055
  async function migrate(input) {
1933
2056
  return runExclusive(input.doc_id, async (doc) => {
1934
2057
  assertNoPendingPush(input.doc_id);
1935
- const client = new EntityGraphHttpClient({
1936
- docId: input.doc_id,
1937
- httpOrigin: requiredContext(options.httpOrigin, input.doc_id, "httpOrigin"),
1938
- ...options.authToken === void 0 ? {} : { authToken: () => optionalContext(options.authToken, input.doc_id) },
1939
- ...options.userId === void 0 ? {} : { userId: () => optionalContext(options.userId, input.doc_id) },
1940
- ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
1941
- });
2058
+ const client = getGraphClient(input.doc_id);
1942
2059
  const base = await client.fetchState();
1943
2060
  if (base.rows.entities.some((row) => row.entityKind === "timeline")) return {
1944
2061
  ok: true,
@@ -1974,7 +2091,8 @@ function createMedeoTool(options) {
1974
2091
  async function run(input) {
1975
2092
  return runExclusive(input.doc_id, async (doc) => {
1976
2093
  assertNoPendingPush(input.doc_id);
1977
- const [pull, entityState] = await Promise.all([observePull(doc), fetchEntityStateForSandbox(input.doc_id)]);
2094
+ const pull = await observePull(doc);
2095
+ const entityState = await fetchEntityStateForSandbox(input.doc_id, doc, pull);
1978
2096
  const document = doc.snapshot();
1979
2097
  const baseVersion = encodeDocVersionMark(doc.versionMark());
1980
2098
  const result = await runEditScript({