{"version":3,"sources":["../src/assets/scene-decoder.ts","../src/instances/legacy.ts","../src/components/children.ts","../src/components/transform.ts","../src/collect-subtree.ts","../src/components/mobility.ts","../src/components/morph-weights.ts","../src/components/name.ts","../src/errors.ts","../src/instances/binding.ts","../src/instances/collect-profile.ts","../src/instances/externalization.ts","../src/instances/keyed.ts","../src/instances/state.ts","../src/instances/scene-instances.ts","../src/instances/source-references.ts","../src/instances/entity-ref.ts","../src/mobility-diagnostics.ts","../src/systems/mobility-static-moved.ts","../src/systems/propagate-transforms.ts","../src/plugin.ts","../src/systems/hierarchy-projection.ts"],"sourcesContent":["import {\n  type AssetDecoder,\n  type AssetDecoderContribution,\n  type AssetKind,\n  type AssetLoadError,\n  err,\n  ok,\n  type Result,\n  type SceneAsset,\n  type SceneEntity,\n  type SceneInstanceOverride,\n} from '@forgeax/engine-types';\nimport { normalizeLegacySceneAsset } from '../instances/legacy.js';\n\nexport const sceneAssetKind: AssetKind<SceneAsset, 'scene'> = {\n  kind: 'scene',\n} as AssetKind<SceneAsset, 'scene'>;\n\nfunction invalidScene(guid: string, reason: string): Result<SceneAsset, AssetLoadError> {\n  return err({\n    code: 'asset-package-invalid',\n    expected: 'a scene payload with keyed entities',\n    hint: 'recook the SceneAsset and publish its complete envelope',\n    detail: { guid, reason },\n  });\n}\n\ntype SceneWireRefResult =\n  | { readonly ok: true; readonly value: SceneAsset }\n  | { readonly ok: false; readonly reason: string };\n\nfunction resolveWireRef(\n  refs: readonly string[],\n  value: number,\n  location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n  const guid = refs[value];\n  if (!Number.isInteger(value) || value < 0 || guid === undefined) {\n    return {\n      ok: false,\n      reason: `${location} references refs[${value}], but refs contains ${refs.length} entries`,\n    };\n  }\n  return { ok: true, value: guid };\n}\n\nfunction resolveInstanceSource(\n  source: unknown,\n  refs: readonly string[],\n  location: string,\n): { readonly ok: true; readonly value: string } | { readonly ok: false; readonly reason: string } {\n  if (typeof source === 'string' && source.length > 0) return { ok: true, value: source };\n  if (typeof source !== 'number' || !Number.isInteger(source)) {\n    return { ok: false, reason: `${location} must be a GUID or refs index` };\n  }\n  return resolveWireRef(refs, source, location);\n}\n\nfunction resolveSkinGuids(\n  skinGuids: readonly (number | string)[] | undefined,\n  refs: readonly string[],\n):\n  | { readonly ok: true; readonly value: readonly string[] | undefined }\n  | { readonly ok: false; readonly reason: string } {\n  if (skinGuids === undefined) return { ok: true, value: undefined };\n  const resolved: string[] = [];\n  for (let index = 0; index < skinGuids.length; index += 1) {\n    const value = skinGuids[index];\n    if (typeof value === 'string') {\n      resolved.push(value);\n      continue;\n    }\n    if (typeof value !== 'number' || !Number.isInteger(value)) {\n      return { ok: false, reason: `skinGuids[${index}] is not a GUID or refs index` };\n    }\n    const ref = resolveWireRef(refs, value, `skinGuids[${index}]`);\n    if (!ref.ok) return ref;\n    resolved.push(ref.value);\n  }\n  return { ok: true, value: resolved };\n}\n\nfunction resolveSceneWireRefs(\n  payload: { readonly entities: unknown; readonly skinGuids?: unknown },\n  refs: readonly string[],\n): SceneWireRefResult {\n  const normalized = normalizeLegacySceneAsset({ kind: 'scene', entities: payload.entities });\n  const rawEntities = normalized.entities;\n  if (rawEntities === null || typeof rawEntities !== 'object' || Array.isArray(rawEntities)) {\n    return { ok: false, reason: 'entities must be a keyed object' };\n  }\n  const entities: Record<string, SceneEntity> = {};\n  for (const [key, rawEntity] of Object.entries(rawEntities as Record<string, unknown>)) {\n    const entity = rawEntity as\n      | {\n          readonly components?: unknown;\n          readonly instance?: {\n            readonly source?: unknown;\n            readonly overrides?: unknown;\n          };\n        }\n      | undefined;\n    if (key.length === 0 || entity === undefined || typeof entity !== 'object') {\n      return { ok: false, reason: `entities[${JSON.stringify(key)}] is malformed` };\n    }\n    if (\n      entity.components === null ||\n      typeof entity.components !== 'object' ||\n      Array.isArray(entity.components)\n    ) {\n      return { ok: false, reason: `entities.${key}.components must be an object` };\n    }\n    const components: Record<string, Record<string, unknown>> = {};\n    for (const [componentName, rawFields] of Object.entries(\n      entity.components as Record<string, unknown>,\n    )) {\n      if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields)) {\n        return {\n          ok: false,\n          reason: `entities.${key}.components.${componentName} must be an object`,\n        };\n      }\n      // Component schema lookup is World-local after the ECS core reduction.\n      // The runtime projection owns the World-local schema and converts\n      // authored GUID fields into World.sharedRefs handles. Keep this loader\n      // boundary POD-only instead of consulting a removed process-global ECS\n      // component registry.\n      components[componentName] = { ...(rawFields as Record<string, unknown>) };\n    }\n    const instance = entity.instance;\n    let resolvedInstance: SceneEntity['instance'];\n    if (instance !== undefined) {\n      if (instance === null || typeof instance !== 'object') {\n        return { ok: false, reason: `entities.${key}.instance must be an object` };\n      }\n      const source = resolveInstanceSource(\n        instance.source,\n        refs,\n        `entities.${key}.instance.source`,\n      );\n      if (!source.ok) return source;\n      if (instance.overrides !== undefined && !Array.isArray(instance.overrides)) {\n        return { ok: false, reason: `entities.${key}.instance.overrides must be an array` };\n      }\n      let overrides: NonNullable<SceneEntity['instance']>['overrides'] | undefined;\n      if (instance.overrides === undefined) {\n        overrides = undefined;\n      } else {\n        const resolvedOverrides: SceneInstanceOverride[] = [];\n        for (const [index, rawOverride] of (instance.overrides as readonly unknown[]).entries()) {\n          if (\n            rawOverride === null ||\n            typeof rawOverride !== 'object' ||\n            Array.isArray(rawOverride) ||\n            !Array.isArray((rawOverride as { readonly target?: unknown }).target) ||\n            (rawOverride as { readonly target?: unknown[] }).target?.some(\n              (part) => typeof part !== 'string' || part.length === 0,\n            )\n          ) {\n            return {\n              ok: false,\n              reason: `entities.${key}.instance.overrides[${index}] is malformed`,\n            };\n          }\n          const target = (rawOverride as { readonly target: readonly string[] }).target;\n          const rawComponents = (rawOverride as { readonly components?: unknown }).components;\n          if (\n            rawComponents === null ||\n            typeof rawComponents !== 'object' ||\n            Array.isArray(rawComponents)\n          ) {\n            return {\n              ok: false,\n              reason: `entities.${key}.instance.overrides[${index}].components is malformed`,\n            };\n          }\n          resolvedOverrides.push({\n            target: [...target] as [string, ...string[]],\n            components: rawComponents as SceneEntity['components'],\n          });\n        }\n        overrides = resolvedOverrides;\n      }\n      resolvedInstance = {\n        source: source.value,\n        ...(overrides === undefined ? {} : { overrides }),\n      };\n    }\n    entities[key] = {\n      components,\n      ...(resolvedInstance === undefined ? {} : { instance: resolvedInstance }),\n    };\n  }\n\n  const skinGuids = resolveSkinGuids(\n    Array.isArray(payload.skinGuids)\n      ? (payload.skinGuids as readonly (number | string)[])\n      : payload.skinGuids === undefined\n        ? undefined\n        : ([] as readonly (number | string)[]),\n    refs,\n  );\n  if (!skinGuids.ok) return skinGuids;\n\n  return {\n    ok: true,\n    value: {\n      kind: 'scene',\n      entities,\n      ...(skinGuids.value === undefined ? {} : { skinGuids: skinGuids.value }),\n    },\n  };\n}\n\n/** Scene owns structural validation; World-local projection resolves shared refs. */\nexport const sceneAssetDecoder: AssetDecoder<SceneAsset> = {\n  async decode({ envelope }): Promise<Result<SceneAsset, AssetLoadError>> {\n    const payload = envelope.payload;\n    if (\n      payload.kind !== 'scene' ||\n      payload.entities === null ||\n      typeof payload.entities !== 'object'\n    ) {\n      return invalidScene(envelope.guid, 'scene payload is missing keyed entities');\n    }\n    const resolved = resolveSceneWireRefs(payload, envelope.refs);\n    if (!resolved.ok) return invalidScene(envelope.guid, resolved.reason);\n    return ok(resolved.value);\n  },\n};\n\nexport const sceneAssetContribution: AssetDecoderContribution<SceneAsset, 'scene'> = {\n  kind: sceneAssetKind,\n  decoder: sceneAssetDecoder,\n  consumer: 'Scene',\n};\n","/**\n * Normalize the small set of SceneAsset fields emitted by the 0.1.27\n * ScriptablePack template before the current keyed runtime validates them.\n *\n * This is deliberately a boundary migration. Current authoring and runtime\n * types stay keyed and use `shadowFilter`; only old payloads carry numeric\n * ChildOf addresses or `pcfKernelSize`.\n */\nexport function migrateLegacySceneComponentFields(\n  componentName: string,\n  source: Record<string, unknown>,\n  addressByLocalId?: ReadonlyMap<number, string>,\n): Record<string, unknown> {\n  const fields = { ...source };\n  const address = (value: unknown): unknown =>\n    Number.isSafeInteger(value) ? (addressByLocalId?.get(value as number) ?? String(value)) : value;\n  if (componentName === 'DirectionalLight' && Object.hasOwn(fields, 'pcfKernelSize')) {\n    const kernel = fields.pcfKernelSize;\n    const shadowFilter = kernel === 1 ? 1 : kernel === 3 ? 2 : kernel === 5 ? 3 : undefined;\n    if (shadowFilter !== undefined && !Object.hasOwn(fields, 'shadowFilter')) {\n      delete fields.pcfKernelSize;\n      fields.shadowFilter = shadowFilter;\n    }\n  }\n  if (componentName === 'ChildOf' && Number.isSafeInteger(fields.parent)) {\n    fields.parent = address(fields.parent);\n  }\n  if (componentName === 'Children' && Array.isArray(fields.entities)) {\n    fields.entities = fields.entities.map(address);\n  }\n  return fields;\n}\n\ninterface LegacySceneEntity {\n  readonly localId?: unknown;\n  readonly bindingKey?: unknown;\n  readonly components?: unknown;\n  readonly instance?: unknown;\n}\n\n/**\n * Lift the pre-keyed SceneAsset array into the current keyed shape.\n *\n * The 0.1.27 template used `localId` for storage and `bindingKey` for the\n * gameplay-facing names. Keeping the binding key is essential: the runtime\n * resolves `player`, `camera`, and joints by that name, not by the old number.\n * This function is intentionally structural and accepts `unknown` only at the\n * compatibility boundary; current authoring types remain keyed.\n */\nexport function normalizeLegacySceneAsset(\n  scene: unknown,\n): import('@forgeax/engine-types').SceneAsset {\n  if (scene === null || typeof scene !== 'object') return scene as never;\n  const candidate = scene as { readonly entities?: unknown };\n  if (!Array.isArray(candidate.entities))\n    return scene as import('@forgeax/engine-types').SceneAsset;\n\n  const rows = candidate.entities as readonly LegacySceneEntity[];\n  const addressByLocalId = new Map<number, string>();\n  const rowKeys: string[] = [];\n  const used = new Set<string>();\n  for (const [index, row] of rows.entries()) {\n    const localId = Number.isSafeInteger(row?.localId) ? (row.localId as number) : index;\n    const bindingKey =\n      typeof row?.bindingKey === 'string' && row.bindingKey.length > 0\n        ? row.bindingKey\n        : String(localId);\n    const key = used.has(bindingKey) ? String(localId) : bindingKey;\n    used.add(key);\n    addressByLocalId.set(localId, key);\n    rowKeys.push(key);\n  }\n\n  const entities: Record<\n    string,\n    { readonly components: Record<string, Record<string, unknown>>; readonly instance?: unknown }\n  > = {};\n  for (const [index, row] of rows.entries()) {\n    const key = rowKeys[index] as string;\n    const rawComponents = row?.components;\n    const components: Record<string, Record<string, unknown>> = {};\n    if (\n      rawComponents !== null &&\n      typeof rawComponents === 'object' &&\n      !Array.isArray(rawComponents)\n    ) {\n      for (const [componentName, rawFields] of Object.entries(\n        rawComponents as Record<string, unknown>,\n      )) {\n        if (rawFields === null || typeof rawFields !== 'object' || Array.isArray(rawFields))\n          continue;\n        components[componentName] = migrateLegacySceneComponentFields(\n          componentName,\n          rawFields as Record<string, unknown>,\n          addressByLocalId,\n        );\n      }\n    }\n    entities[key] = {\n      components,\n      ...(row?.instance === undefined ? {} : { instance: row.instance }),\n    };\n  }\n  return {\n    ...(scene as Record<string, unknown>),\n    entities,\n  } as import('@forgeax/engine-types').SceneAsset;\n}\n","// @forgeax/engine-runtime - Children (forward-list of child entities).\n//\n// Schema: 1 array<entity> field `entities` (variable-length, ECS-managed via\n// the BufferPool slot column + sidecar count column allocated by the ECS\n// relationship owner).\n//\n// feat-20260515-buffer-array-vocab-collapse M3 / w17:\n// the legacy `VarArrayView<Entity>` value-shape wrapper was retired in\n// favour of a direct `TypedArray` snapshot returned by `world.get`. AI users\n// read the engine-maintained list through the read-only `Uint32Array` snapshot:\n//\n//   const snap = world.get(parent, Children).unwrap().entities;\n//   const liveCount = snap.length;\n//   for (let i = 0; i < liveCount; i++) { const child = snap[i]; ... }\n//\n// Snapshot length equals the live element count (sidecar count column owned\n// by the ECS layer); the public snapshot is detached and rematerialised on\n// every `world.get` (D-4 no-cache), so `fill` or index writes cannot mutate the\n// target. Internal relationship maintenance and Scene traversal borrow the\n// live array through the package-internal zero-copy seams instead.\n//\n// feat-20260531-ecs-relationship-abstraction-bidirectional-sync M4 / t20:\n// Children is the MIRROR side of the ChildOf relationship. Its schema is\n// unchanged (the `entities: 'array<entity>'` shape is exactly what the\n// relationship mirror contract requires), but the engine now maintains this\n// list automatically whenever ChildOf is added / removed / reparented on a\n// child entity (M2 bidirectional-sync hook on ChildOf). The prior OOS-10\n// \"AI users keep the two sides consistent themselves\" contract is retired:\n// `world.addComponent(child, ChildOf{parent})` appends `child` to\n// `parent.Children.entities`, `world.removeComponent` / reparent prunes it.\n// For the ChildOf hierarchy the engine owns consistency; no public target\n// write can diverge from the source relationship.\n//\n// feat-20260514-ecs-children-instances-managed-buffer-array M3 / w13 (kept\n// for context): migrated from the legacy `{ count: 'u32' }` advisory marker\n// to the real variable-length entity-array storage path.\n//   - OOS-09 (prior loop): no `addChild` / `removeChild` / `removeChildren`\n//     Commands API. Retired this feat: `world.addChild` / `world.removeChild`\n//     / `world.reparent` ship in M3, plus the relationship hook above.\n//   - Normal ChildOf child despawn invokes the source onRemove hook and\n//     removes the child before the row is retired; parent despawn follows the\n//     linkedSpawn cascade. A dangling u32 is therefore an explicitly malformed\n//     internal fixture or a non-linked generic relationship, not a normal\n//     ChildOf lifecycle result. Consumers still probe liveness before using a\n//     handle and receive the structured ECS error for malformed state.\n//\n// charter mapping: proposition 2 (Bevy ChildOf+Children pair, holder\n// perspective) + proposition 3 (machine-readable schema:\n// `componentSchema(Children).entities === 'array<entity>'`) + proposition 4 (explicit\n// failure: dangling entries surface to the AI user via `world.get(parent, Entity)` liveness probe,\n// not silent drop) + proposition 5 (consistent abstraction: Children is the\n// generic relationship-mirror shape, not a ChildOf special case).\n\nimport { defineRelationship } from '@forgeax/engine-ecs';\nimport { Transform } from './transform';\n\n/**\n * Hierarchy forward-list of child entities.\n *\n * `entities` is a variable-length `array<entity>` field; each element is\n * an `Entity` u32 the ECS relationship owner materialized. The value returned\n * by `world.get(parent, Children).unwrap().entities` is a detached read-only\n * `Uint32Array` snapshot rematerialised fresh on every read (D-4 no-cache);\n * mutating the returned array cannot change ECS-owned storage, and the\n * snapshot's `length` equals the live element count. Internal Scene/ECS paths\n * use the package-internal zero-copy array seams instead of this snapshot.\n *\n * Invariants:\n *   - `propagateTransforms` consumes Children from the ECS-owned materialized\n *     buffer and expands each root parent-first. The forward list is also\n *     available for AI-user traversal / debug / inspection.\n *   - Children <-> ChildOf consistency is maintained by the engine via the\n *     ChildOf `relationship` mirror hook (see ./child-of.ts): adding /\n *     removing / reparenting ChildOf on a child auto-updates the parent's\n *     `entities` list. AI users do not hand-sync the two sides for the\n *     hierarchy.\n *   - ChildOf's linked lifecycle keeps ordinary Children entries aligned: a\n *     child despawn prunes its source slot and a parent despawn cascades. A\n *     deliberately malformed/non-linked edge remains observable as a dead\n *     handle and must be diagnosed through the structured error channel.\n *\n * @example Spawn a parent and two children via ChildOf (engine maintains Children):\n *   const parent = world.spawn({ component: Transform, data: identityXf() }).unwrap();\n *   const a = world.spawn(\n *     { component: Transform, data: identityXf() },\n *     { component: ChildOf, data: { parent } },\n *   ).unwrap();\n *   const b = world.spawn(\n *     { component: Transform, data: identityXf() },\n *     { component: ChildOf, data: { parent } },\n *   ).unwrap();\n *   // Read back via the read-only snapshot - engine appended a, b:\n *   const snap = world.get(parent, Children).unwrap().entities;\n *   for (let i = 0; i < snap.length; i++) {\n *     const child = snap[i];\n *     // ... consume; probe the handle before using it when reading a\n *     // deliberately malformed/non-linked relationship.\n *   }\n */\nexport const { source: ChildOf, target: Children } = defineRelationship({\n  sourceName: 'ChildOf',\n  sourceField: 'parent',\n  targetName: 'Children',\n  targetField: 'entities',\n  // Every scene hierarchy node is spatial.  Adding ChildOf therefore\n  // materializes the local/derived transform pair at the same structural\n  // boundary, so render- and scene-authored children cannot enter a frame\n  // with an incomplete hierarchy node.\n  sourceRequires: [Transform],\n  exclusive: true,\n  linkedSpawn: true,\n});\n","// @forgeax/engine-runtime - authored local transform and derived world output.\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nconst IDENTITY_MAT4 = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);\n\n/** Scene-owned derived world transform. Only TransformPropagation writes it. */\nexport const GlobalTransform = defineComponent(\n  'GlobalTransform',\n  {\n    world: { type: 'array<f32, 16>', default: IDENTITY_MAT4 },\n  },\n  { transient: true },\n);\n\n/**\n * Authored local position, rotation and scale columns.\n *\n * The ECS `requires` declaration is the generic structural invariant: callers\n * add `Transform`, while `GlobalTransform` is materialized once at spawn/add.\n */\nexport const Transform = defineComponent(\n  'Transform',\n  {\n    pos: { type: 'array<f32, 3>', default: new Float32Array([0, 0, 0]) },\n    // Component order [x, y, z, w] is shared with glTF.\n    quat: { type: 'array<f32, 4>', default: new Float32Array([0, 0, 0, 1]) },\n    scale: { type: 'array<f32, 3>', default: new Float32Array([1, 1, 1]) },\n  },\n  { requires: [GlobalTransform] },\n);\n","// Scene-owned hierarchy traversal shared by scene collection and render hooks.\n\nimport type { EntityHandle, World } from '@forgeax/engine-ecs';\n\nimport { Children } from './components/children';\n\n/** Walk a Children hierarchy breadth-first, reusing an optional visited set. */\nexport function collectSubtree(\n  world: World,\n  spawnRoot: EntityHandle,\n  visited?: Set<number>,\n): Set<number> {\n  if (visited === undefined) visited = new Set<number>();\n  if (visited.has(spawnRoot as number)) return visited;\n  const queue: number[] = [spawnRoot as number];\n  visited.add(spawnRoot as number);\n  for (let cursor = 0; cursor < queue.length; cursor += 1) {\n    const current = queue[cursor] as number;\n    const children = world.get(current as EntityHandle, Children);\n    if (!children.ok) continue;\n    const entities = children.value.entities as ArrayLike<number>;\n    for (let index = 0; index < entities.length; index += 1) {\n      const child = entities[index] as number;\n      if (visited.has(child)) continue;\n      visited.add(child);\n      queue.push(child);\n    }\n  }\n  return visited;\n}\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/**\n * Author commitment about whether an entity moves.\n *\n * `'static'` promises the Transform never changes after placement,\n * `'stationary'` is legal only on lights (fixed position, changing\n * parameters), and `'movable'` makes no promise. An entity without `Mobility`\n * is movable. `Mobility` is the rendering/baking authority; physics\n * `RigidBodyType` is the simulation authority and neither derives the other.\n */\nexport type MobilityKind = 'static' | 'stationary' | 'movable';\n\n/** Numeric enum values stored in the `Mobility.kind` column; also its schema labels. */\nexport const MobilityKindValue = {\n  static: 0,\n  stationary: 1,\n  movable: 2,\n} as const satisfies Record<MobilityKind, number>;\n\n/** Narrow a stored `Mobility.kind` column value back to its label. */\nexport function mobilityKindFromU32(value: number): MobilityKind {\n  if (value === MobilityKindValue.static) return 'static';\n  if (value === MobilityKindValue.stationary) return 'stationary';\n  return 'movable';\n}\n\n/**\n * Mobility declaration: `world.spawn({ component: Mobility, data: { kind: MobilityKindValue.static } })`.\n * Absence and the schema default both mean movable.\n */\nexport const Mobility = defineComponent('Mobility', {\n  kind: { type: 'enum', default: MobilityKindValue.movable, labels: MobilityKindValue },\n});\n","import { defineComponent } from '@forgeax/engine-ecs';\n\n/** Per-entity morph weights; length is validated against the mesh target count. */\nexport const MorphWeights = defineComponent('MorphWeights', {\n  weights: { type: 'array<f32>' },\n});\n","// @forgeax/engine-runtime --- Name component (built-in identifier).\n//\n// Single-field minimal skeleton: { value: 'string' }. Bare 'string' schema\n// vocab keyword routes through ECS UniqueRefStore (D-R3 single-arm managed\n// dispatch); the read shape is a native JS string.\n//\n// Lives in `runtime` rather than `ecs` because Name is a built-in *component*,\n// not part of the ECS framework itself (it does not participate in archetype /\n// query / world mechanics like the essential `Entity` component does). Mirrors\n// Bevy's split: `Entity` lives in `bevy_ecs`; `Name` lives in `bevy_core`.\n//\n// Migrated from packages/ecs/src/name.ts by tweak-20260612-ecs-concept-compression\n// (architecture-principles.md §1 SSOT: Name's authoritative location is the\n// runtime built-in components surface, not the ECS framework barrel).\n//\n// Naming follows the Bevy-aligned convention locked by feat-20260513:\n// single-semantic component drops the 'Component' suffix (Transform / Camera\n// / DirectionalLight / Name).\n\nimport { defineComponent } from '@forgeax/engine-ecs';\n\nexport const Name = defineComponent('Name', { value: { type: 'string' } });\n","import type { EcsError, EntityHandle } from '@forgeax/engine-ecs';\nimport type { SceneEntityRef } from '@forgeax/engine-types';\n\nexport type SceneErrorCode = 'hierarchy-broken' | 'hierarchy-cycle';\n\n/** Scene-instantiation failures owned by the scene package. */\nexport type SceneInstanceErrorCode = 'component-not-defined' | 'scene-override-type-mismatch';\n\nexport { ComponentNotDefinedError } from '@forgeax/engine-ecs/projection';\n\n/** The structured ECS failure retained by a Scene derived-write diagnostic. */\nexport interface SceneErrorCause {\n  readonly code: EcsError['code'];\n  readonly expected?: string;\n  readonly hint?: string;\n  readonly detail?: unknown;\n}\n\n/** Location detail shared by hierarchy diagnostics and derived-write errors. */\nexport interface SceneHierarchyErrorDetail {\n  readonly kind?: 'hierarchy';\n  readonly entity: EntityHandle;\n  readonly parent: EntityHandle;\n}\n\n/** A flat derived publication failure with its original ECS error intact. */\nexport interface SceneDerivedWriteErrorDetail {\n  readonly kind: 'derived-write';\n  readonly entity: EntityHandle;\n  readonly parent: EntityHandle;\n  readonly bindingIndex: number;\n  readonly base: number;\n  readonly start: number;\n  readonly count: number;\n  readonly cause: SceneErrorCause;\n}\n\nexport type SceneErrorDetail = SceneHierarchyErrorDetail | SceneDerivedWriteErrorDetail;\n\nexport class SceneError extends Error {\n  readonly code: SceneErrorCode;\n  readonly expected: string;\n  readonly hint: string;\n  readonly detail: SceneErrorDetail | undefined;\n\n  constructor(args: {\n    code: SceneErrorCode;\n    expected: string;\n    hint: string;\n    detail?: SceneErrorDetail;\n  }) {\n    super(`[SceneError ${args.code}] expected: ${args.expected}; hint: ${args.hint}`);\n    this.name = 'SceneError';\n    this.code = args.code;\n    this.expected = args.expected;\n    this.hint = args.hint;\n    this.detail = args.detail;\n  }\n}\n\n/**\n * Non-blocking `Mobility` contract violations. Detection belongs to the package\n * that can see both sides of the contract (scene: Transform, render: meshes,\n * physics: RigidBody); every producer reports through this one union.\n */\nexport type MobilityDiagnosticCode =\n  | 'mobility-invalid-kind'\n  | 'mobility-static-moved'\n  | 'mobility-physics-conflict';\n\n/** Entity location shared by every Mobility diagnostic. */\nexport interface MobilityDiagnosticSubject {\n  readonly entity: EntityHandle;\n  /** Persistent authored identity; absent for runtime-spawned entities. */\n  readonly sceneEntityRef?: SceneEntityRef;\n}\n\nexport type MobilityInvalidKindDetail = MobilityDiagnosticSubject;\n\nexport type MobilityStaticMovedDetail = MobilityDiagnosticSubject;\n\nexport interface MobilityPhysicsConflictDetail extends MobilityDiagnosticSubject {\n  readonly rigidBodyType: 'dynamic' | 'kinematic';\n}\n\n/** One reported Mobility violation; `detail` narrows per `code`. */\nexport type MobilityDiagnostic =\n  | {\n      readonly code: 'mobility-invalid-kind';\n      readonly expected: string;\n      readonly hint: string;\n      readonly detail: MobilityInvalidKindDetail;\n    }\n  | {\n      readonly code: 'mobility-static-moved';\n      readonly expected: string;\n      readonly hint: string;\n      readonly detail: MobilityStaticMovedDetail;\n    }\n  | {\n      readonly code: 'mobility-physics-conflict';\n      readonly expected: string;\n      readonly hint: string;\n      readonly detail: MobilityPhysicsConflictDetail;\n    };\n","import type { EntityHandle } from '@forgeax/engine-ecs';\nimport type { SceneEntityAddress, SceneEntityRef } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\n\nexport type { SceneEntityRef } from '@forgeax/engine-types';\n\nexport type SceneBindingError = {\n  readonly code: 'scene-binding-missing' | 'scene-binding-wrong-instance';\n  readonly expected: string;\n  readonly hint: string;\n  readonly detail: { readonly sceneSourceKey: string; readonly address: SceneEntityAddress };\n};\n\nexport type SceneBindingDeclarationError = {\n  readonly code: 'scene-binding-duplicate' | 'scene-binding-source-missing';\n  readonly expected: string;\n  readonly hint: string;\n  readonly detail: { readonly sceneSourceKey?: string; readonly address?: SceneEntityAddress };\n};\n\nexport function validateSceneEntityKeys(\n  sceneSourceKey: string,\n  entityKeys: readonly string[],\n): Result<readonly string[], SceneBindingDeclarationError> {\n  if (sceneSourceKey.length === 0) {\n    return err({\n      code: 'scene-binding-source-missing',\n      expected: 'a non-empty scene sourceKey',\n      hint: 'declare the scene sourceKey in the author inventory',\n      detail: {},\n    });\n  }\n  const seen = new Set<string>();\n  for (const entityKey of entityKeys) {\n    if (entityKey.length === 0 || seen.has(entityKey)) {\n      return err({\n        code: 'scene-binding-duplicate',\n        expected: 'unique non-empty entity keys within one scene',\n        hint: 'rename the duplicate entity key in the scene producer',\n        detail: { sceneSourceKey, address: entityKey },\n      });\n    }\n    seen.add(entityKey);\n  }\n  return ok([...entityKeys]);\n}\n\nexport function sceneEntity(sceneSourceKey: string, address: SceneEntityAddress): SceneEntityRef {\n  return { sceneSourceKey, address };\n}\n\n/** Stable map key shared by direct and nested SceneEntityRef addresses. */\nexport function sceneEntityAddressKey(address: SceneEntityAddress): string {\n  if (typeof address === 'string') return `s:${JSON.stringify(address)}`;\n  if (address.length === 1) return `s:${JSON.stringify(address[0] ?? '')}`;\n  return `a:${JSON.stringify(address)}`;\n}\n\n/** Inverse of {@link sceneEntityAddressKey}. */\nexport function sceneEntityAddressFromKey(key: string): SceneEntityAddress {\n  const value: unknown = JSON.parse(key.slice(2));\n  return value as SceneEntityAddress;\n}\n\nexport function resolveSceneEntity(\n  ref: SceneEntityRef,\n  instance: {\n    readonly sceneSourceKey: string;\n    readonly bindings: ReadonlyMap<string, EntityHandle | number>;\n  },\n): Result<EntityHandle | number, SceneBindingError> {\n  if (ref.sceneSourceKey !== instance.sceneSourceKey) {\n    return err({\n      code: 'scene-binding-wrong-instance',\n      expected: `scene instance ${ref.sceneSourceKey}`,\n      hint: 'resolve the SceneEntityRef against its owning SceneInstance',\n      detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n    });\n  }\n  const value = instance.bindings.get(sceneEntityAddressKey(ref.address));\n  if (value === undefined) {\n    return err({\n      code: 'scene-binding-missing',\n      expected: 'entity key declared by the scene producer',\n      hint: 'declare the entity key in the scene producer before consuming it',\n      detail: { sceneSourceKey: ref.sceneSourceKey, address: ref.address },\n    });\n  }\n  return ok(value);\n}\n","/** Immutable Scene collection policy shared by runtime collectors. */\nexport interface SceneCollectProfile {\n  readonly includeComponent: (componentName: string, transient: boolean) => boolean;\n  readonly includeField: (componentName: string, fieldName: string, transient: boolean) => boolean;\n}\n\nexport const SCENE_COLLECT_PROFILE: SceneCollectProfile = Object.freeze({\n  includeComponent: (_componentName: string, transient: boolean) => !transient,\n  includeField: (_componentName: string, _fieldName: string, transient: boolean) => !transient,\n});\n","import type { AssetRef, SceneAsset, SceneInstanceOverride } from '@forgeax/engine-types';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\n\nexport type SceneComponentSchemaResolver = (\n  componentName: string,\n) => Readonly<Record<string, string>> | undefined;\n\nexport interface SceneExternalizationError {\n  readonly field: string;\n  readonly value: unknown;\n}\n\nexport interface ExternalizedSceneAsset {\n  readonly payload: Record<string, unknown>;\n  readonly refs: readonly AssetRef[];\n}\n\nfunction sharedKind(type: string | undefined): 'one' | 'many' | undefined {\n  if (type?.startsWith('shared<')) return 'one';\n  if (type?.startsWith('array<shared<')) return 'many';\n  return undefined;\n}\n\ninterface RefContext {\n  readonly refs: AssetRef[];\n  readonly indexByGuid: Map<string, number>;\n}\n\nfunction addRef(\n  context: RefContext,\n  guid: string,\n  sourceField: NonNullable<AssetRef['sourceField']>,\n  sceneEntityKey?: string,\n): number {\n  const prior = context.indexByGuid.get(guid);\n  if (prior !== undefined) return prior;\n  const index = context.refs.length;\n  context.refs.push({\n    guid,\n    sourceField,\n    ...(sceneEntityKey === undefined ? {} : { sceneEntityKey }),\n  } as AssetRef);\n  context.indexByGuid.set(guid, index);\n  return index;\n}\n\nfunction externalizeFields(\n  componentName: string,\n  source: Record<string, unknown>,\n  resolveSchema: SceneComponentSchemaResolver,\n  context: RefContext,\n  sceneEntityKey: string | undefined,\n): Record<string, unknown> {\n  const schema = resolveSchema(componentName);\n  const fields: Record<string, unknown> = {};\n  for (const [fieldName, value] of Object.entries(\n    migrateLegacySceneComponentFields(componentName, source),\n  )) {\n    if (value === undefined) continue;\n    const kind = sharedKind(schema?.[fieldName]);\n    if (kind === 'one' && value === 0) {\n      // Null distinguishes an empty shared handle from refs[0] on the wire.\n      fields[fieldName] = null;\n    } else if (kind === 'one' && typeof value === 'string') {\n      fields[fieldName] = addRef(context, value, { componentName, fieldName }, sceneEntityKey);\n    } else if (kind === 'many' && Array.isArray(value)) {\n      fields[fieldName] = value.map((item, arrayIndex) =>\n        typeof item === 'string'\n          ? addRef(context, item, { componentName, fieldName, arrayIndex }, sceneEntityKey)\n          : item === 0\n            ? null\n            : item,\n      );\n    } else {\n      fields[fieldName] = value;\n    }\n  }\n  return fields;\n}\n\nfunction externalizeOverride(\n  override: SceneInstanceOverride,\n  resolveSchema: SceneComponentSchemaResolver,\n  context: RefContext,\n  sceneEntityKey: string,\n): SceneInstanceOverride {\n  const components: Record<string, Record<string, unknown>> = {};\n  for (const [componentName, rawFields] of Object.entries(override.components)) {\n    components[componentName] = externalizeFields(\n      componentName,\n      { ...(rawFields as Record<string, unknown>) },\n      resolveSchema,\n      context,\n      sceneEntityKey,\n    );\n  }\n  return {\n    target: [...override.target],\n    components,\n  };\n}\n\n/** Project a keyed SceneAsset's shared asset fields into a payload plus refs. */\nexport function externalizeSceneAsset(\n  scene: SceneAsset,\n  resolveSchema: SceneComponentSchemaResolver,\n): Result<ExternalizedSceneAsset, SceneExternalizationError> {\n  const normalized = normalizeLegacySceneAsset(scene);\n  const context: RefContext = { refs: [], indexByGuid: new Map() };\n  const entities: Record<string, Record<string, unknown>> = {};\n  for (const [key, entity] of Object.entries(normalized.entities)) {\n    const components: Record<string, Record<string, unknown>> = {};\n    for (const [componentName, raw] of Object.entries(entity.components)) {\n      const source = raw as Record<string, unknown> | undefined;\n      if (source === undefined) continue;\n      components[componentName] = externalizeFields(\n        componentName,\n        source,\n        resolveSchema,\n        context,\n        key,\n      );\n    }\n    const instance = entity.instance;\n    entities[key] = {\n      components,\n      ...(instance === undefined\n        ? {}\n        : {\n            instance: {\n              source: addRef(\n                context,\n                instance.source,\n                { componentName: 'SceneInstance', fieldName: 'source' },\n                key,\n              ),\n              ...(instance.overrides === undefined\n                ? {}\n                : {\n                    overrides: instance.overrides.map((override) =>\n                      externalizeOverride(override, resolveSchema, context, key),\n                    ),\n                  }),\n            },\n          }),\n    };\n  }\n\n  for (const [arrayIndex, guid] of (normalized.skinGuids ?? []).entries()) {\n    if (typeof guid !== 'string') return err({ field: 'skinGuids', value: guid });\n    addRef(context, guid, { componentName: '<scene>', fieldName: 'skinGuids', arrayIndex });\n  }\n  return ok({\n    payload: {\n      kind: 'scene',\n      entities,\n      ...(normalized.skinGuids === undefined\n        ? {}\n        : {\n            skinGuids: normalized.skinGuids.map((guid) => context.indexByGuid.get(guid) as number),\n          }),\n    },\n    refs: context.refs,\n  });\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentDefinition, componentSchema } from '@forgeax/engine-ecs/internal';\nimport type {\n  ComponentValuesMap,\n  LocalEntityId,\n  SceneAsset,\n  SceneEntityAddress,\n} from '@forgeax/engine-types';\nimport {\n  err,\n  type Handle,\n  ok,\n  PACK_ERROR_HINTS,\n  type Result,\n  type SceneEntity,\n} from '@forgeax/engine-types';\nimport { migrateLegacySceneComponentFields, normalizeLegacySceneAsset } from './legacy.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\nimport { isPrimitiveScalarFieldType, primitiveJsType } from './state.js';\n\n/** Numeric representation used only inside the Scene runtime. */\nexport interface CompiledSceneEntity {\n  readonly localId: LocalEntityId;\n  readonly components: Partial<ComponentValuesMap>;\n}\n\nexport interface CompiledSceneAsset {\n  readonly kind: 'scene';\n  readonly entities: readonly CompiledSceneEntity[];\n  readonly mounts?: readonly SceneInstanceMount[];\n  readonly skinGuids?: readonly string[];\n}\n\nexport interface CompiledSceneResult {\n  readonly asset: CompiledSceneAsset;\n  readonly keyByLocalId: ReadonlyMap<number, string>;\n  readonly mountKeyByLocalId: ReadonlyMap<number, string>;\n  /** Private slots that attach directly to this scene's synthetic root. */\n  readonly rootLocalIds: readonly number[];\n  /** Effective private ChildOf edges, including nested scene attachment. */\n  readonly hierarchyParentByLocalId: ReadonlyMap<number, number>;\n  readonly resolveAddress: (address: unknown, field?: string) => number | undefined;\n}\n\nexport interface KeyedSceneCompileContext {\n  readonly resolveSource: (\n    source: string,\n    parent: Handle<'SceneAsset', 'shared'>,\n  ) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n  readonly resolveAsset: (handle: Handle<'SceneAsset', 'shared'>) => Result<SceneAsset, unknown>;\n  readonly stack: ReadonlySet<number>;\n}\n\nfunction fail(reason: string, detail: Record<string, unknown> = {}): Result<never, unknown> {\n  return err({\n    code: 'asset-package-invalid',\n    expected: 'a keyed SceneAsset with schema-valid fields and entity/instance addresses',\n    hint: 'repair the SceneAsset source and recook the asset',\n    detail: { reason, ...detail },\n  });\n}\n\nfunction keyList(entities: Readonly<Record<string, SceneEntity>>): string[] {\n  return Object.keys(entities).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nfunction addressParts(value: unknown): readonly string[] | undefined {\n  if (typeof value === 'string' && value.length > 0) return [value];\n  // ScriptablePack 0.1.27 serialized ChildOf/Children addresses as numeric\n  // local IDs. Accept that legacy wire form only at this compiler boundary;\n  // the authoring contract remains string keyed.\n  if (Number.isSafeInteger(value)) return [String(value)];\n  if (!Array.isArray(value) || value.length === 0) return undefined;\n  if (!value.every((part) => typeof part === 'string' && part.length > 0)) return undefined;\n  return value as readonly string[];\n}\n\n/** Author values must survive storage conversion without coercion or wrap. */\nfunction validPrimitive(type: string, value: unknown): boolean {\n  if (typeof value !== primitiveJsType(type)) return false;\n  if (typeof value !== 'number') return true;\n  if (!Number.isFinite(value)) return false;\n  if (type === 'f32') return Number.isFinite(Math.fround(value));\n  if (type === 'f64') return true;\n  const signed = type.startsWith('i');\n  const bits = type.startsWith('enum') ? 32 : Number(type.slice(1));\n  const bound = 2 ** (bits - (signed ? 1 : 0));\n  return Number.isInteger(value) && value >= (signed ? -bound : 0) && value < bound;\n}\n\nfunction fieldRemap(\n  world: World,\n  componentName: string,\n  fields: Record<string, unknown>,\n  resolveAddress: (address: unknown, field: string) => number | undefined,\n  entityKey?: string,\n): Result<Record<string, unknown>, unknown> {\n  const token = world.components.resolve(componentName);\n  if (token === undefined) return fail('unknown component', { component: componentName });\n  const schema = componentSchema(token) as Record<string, string>;\n  const definition = componentDefinition(token);\n  const out: Record<string, unknown> = {};\n  for (const [fieldName, value] of Object.entries(\n    migrateLegacySceneComponentFields(componentName, fields),\n  )) {\n    const fieldType = schema[fieldName];\n    if (fieldType === undefined) {\n      return fail('unknown component field', {\n        component: componentName,\n        field: fieldName,\n        ...(entityKey === undefined ? {} : { entity: entityKey }),\n      });\n    }\n    const kind = classifyEntityField(token as Component, fieldName);\n    if (kind === null) {\n      const array = definition.fields[fieldName]?.arrayMeta;\n      const primitive = array?.elementType === 'bool' ? 'u8' : (array?.elementType ?? fieldType);\n      if (isPrimitiveScalarFieldType(primitive)) {\n        const values = array\n          ? Array.isArray(value)\n            ? value\n            : ArrayBuffer.isView(value) && 'length' in value\n              ? Array.from(value as unknown as ArrayLike<unknown>)\n              : undefined\n          : [value];\n        if (\n          values === undefined ||\n          (array?.length !== undefined && values.length !== array.length) ||\n          values.some((item) => !validPrimitive(primitive, item))\n        )\n          return fail('authored component value violates its declared schema', {\n            component: componentName,\n            field: fieldName,\n            type: fieldType,\n            ...(entityKey === undefined ? {} : { entity: entityKey }),\n          });\n        // Typed author arrays become numeric values before the ECS writer;\n        // copying a differently sized view's raw bytes would reinterpret them.\n        out[fieldName] = array ? values : value;\n        continue;\n      }\n      out[fieldName] = value;\n      continue;\n    }\n    const remap = (address: number): number =>\n      resolveAddress(address, `${componentName}.${fieldName}`) ?? address;\n    // The keyed authoring model uses string addresses for scalar entity fields\n    // and an address per element for array<entity>. The ECS kernel still gets\n    // numeric local slots, so conversion is complete before spawn.\n    if (kind.isArray) {\n      if (!Array.isArray(value))\n        return fail('array entity field is not an array', {\n          component: componentName,\n          field: fieldName,\n        });\n      const numeric: number[] = [];\n      for (const item of value) {\n        const parts = addressParts(item);\n        if (parts === undefined)\n          return fail('invalid entity address', {\n            component: componentName,\n            field: fieldName,\n            address: item,\n          });\n        const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n        if (slot === undefined)\n          return fail('missing entity address target', {\n            component: componentName,\n            field: fieldName,\n            address: parts,\n          });\n        numeric.push(slot);\n      }\n      out[fieldName] = remapEntityFieldValue(numeric, kind, remap);\n      continue;\n    }\n    if (value === null) {\n      out[fieldName] = null;\n      continue;\n    }\n    const parts = addressParts(value);\n    if (parts === undefined)\n      return fail('invalid entity address', {\n        component: componentName,\n        field: fieldName,\n        address: value,\n      });\n    const slot = resolveAddress(parts, `${componentName}.${fieldName}`);\n    if (slot === undefined)\n      return fail('missing entity address target', {\n        component: componentName,\n        field: fieldName,\n        address: parts,\n      });\n    out[fieldName] = remapEntityFieldValue(slot, kind, remap);\n  }\n  return ok(out);\n}\n\n/**\n * Compile keyed author data to the private numeric Scene representation. The\n * compiler establishes every local and nested address before the caller starts\n * spawning entities, so malformed references and recursive instances cannot\n * leave a partially usable World projection.\n */\nexport function compileKeyedSceneAsset(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  asset: SceneAsset,\n  context: KeyedSceneCompileContext,\n): Result<CompiledSceneResult, unknown> {\n  asset = normalizeLegacySceneAsset(asset);\n  if (\n    asset.kind !== 'scene' ||\n    asset.entities === null ||\n    typeof asset.entities !== 'object' ||\n    Array.isArray(asset.entities)\n  ) {\n    return fail('entities must be a keyed object');\n  }\n  const currentRaw = Number(handle);\n  const activeStack = context.stack.has(currentRaw)\n    ? context.stack\n    : new Set([...context.stack, currentRaw]);\n  const keys = keyList(asset.entities);\n  if (keys.some((key) => key.length === 0)) return fail('entity keys must be non-empty');\n\n  const ownKeys = keys.filter((key) => asset.entities[key]?.instance === undefined);\n  const instanceKeys = keys.filter((key) => asset.entities[key]?.instance !== undefined);\n  const slotByKey = new Map<string, number>();\n  const keyByLocalId = new Map<number, string>();\n  for (const [slot, key] of [...ownKeys, ...instanceKeys].entries()) {\n    slotByKey.set(key, slot);\n    keyByLocalId.set(slot, key);\n  }\n\n  const instances = new Map<\n    string,\n    {\n      readonly node: SceneEntity;\n      readonly compiled: CompiledSceneResult;\n      mount: SceneInstanceMount;\n    }\n  >();\n  const mountKeyByLocalId = new Map<number, string>();\n  let nextMemberFirst = ownKeys.length + instanceKeys.length;\n  for (const key of instanceKeys) {\n    const node = asset.entities[key] as SceneEntity;\n    const declaration = node.instance;\n    if (\n      declaration === undefined ||\n      typeof declaration.source !== 'string' ||\n      declaration.source.length === 0\n    ) {\n      return fail('instance source must be a non-empty GUID', { entity: key });\n    }\n    const childHandle = context.resolveSource(declaration.source, handle);\n    if (!childHandle.ok) return childHandle;\n    const childRaw = Number(childHandle.value);\n    if (activeStack.has(childRaw)) {\n      return err({\n        code: 'pack-cyclic-reference',\n        expected: 'acyclic SceneAsset instance graph',\n        hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n        detail: {\n          code: 'pack-cyclic-reference',\n          kind: 'mount-asset',\n          cycle: [...activeStack, childRaw].map(String),\n        },\n      });\n    }\n    const childAsset = context.resolveAsset(childHandle.value);\n    if (!childAsset.ok) return childAsset;\n    const childContext: KeyedSceneCompileContext = {\n      ...context,\n      stack: activeStack,\n    };\n    const compiled = compileKeyedSceneAsset(\n      world,\n      childHandle.value,\n      childAsset.value,\n      childContext,\n    );\n    if (!compiled.ok) return compiled;\n    const slot = ownKeys.length + instances.size;\n    const memberCount =\n      compiled.value.asset.entities.length +\n      (compiled.value.asset.mounts?.length ?? 0) +\n      (compiled.value.asset.mounts ?? []).reduce((sum, mount) => sum + mount.memberCount, 0);\n    instances.set(key, {\n      node,\n      compiled: compiled.value,\n      mount: {\n        localId: slot as LocalEntityId,\n        source: Number(childHandle.value),\n        memberFirst: nextMemberFirst as LocalEntityId,\n        memberCount,\n      },\n    });\n    mountKeyByLocalId.set(slot, key);\n    nextMemberFirst += memberCount;\n  }\n\n  const resolveAddress = (value: unknown): number | undefined => {\n    const parts = addressParts(value);\n    if (parts === undefined) return undefined;\n    const first = parts[0];\n    if (first === undefined) return undefined;\n    const own = slotByKey.get(first);\n    if (own !== undefined && parts.length === 1) return own;\n    const instance = instances.get(first);\n    if (instance === undefined) return undefined;\n    const childSlot = instance.compiled.resolveAddress(parts.slice(1));\n    return childSlot === undefined ? undefined : Number(instance.mount.memberFirst) + childSlot;\n  };\n\n  const convertComponents = (\n    key: string,\n  ): Result<Record<string, Record<string, unknown>>, unknown> => {\n    const node = asset.entities[key] as SceneEntity;\n    const components: Record<string, Record<string, unknown>> = {};\n    for (const [componentName, raw] of Object.entries(node.components)) {\n      const fields = fieldRemap(\n        world,\n        componentName,\n        { ...(raw as Record<string, unknown>) },\n        resolveAddress,\n        key,\n      );\n      if (!fields.ok) return fields;\n      components[componentName] = fields.value;\n    }\n    return ok(components);\n  };\n\n  // Schema conversion completes before spawn; instance ChildOf is deferred until\n  // its mount slot is live, while other components stay on that mount.\n  for (const [key, instance] of instances) {\n    const converted = convertComponents(key);\n    if (!converted.ok) return converted;\n    const components = converted.value;\n    const childOf = components.ChildOf?.parent;\n    if (typeof childOf === 'number') {\n      const { ChildOf: _ignored, ...mountComponents } = components;\n      instance.mount = {\n        ...instance.mount,\n        components: mountComponents,\n        parent: childOf as LocalEntityId,\n      };\n    } else {\n      instance.mount = { ...instance.mount, components };\n    }\n  }\n\n  const converted: CompiledSceneEntity[] = [];\n  for (const key of ownKeys) {\n    const components = convertComponents(key);\n    if (!components.ok) return components;\n    converted.push({ localId: slotByKey.get(key) as LocalEntityId, components: components.value });\n  }\n\n  // Convert ordered child-relative overrides into the private field patch\n  // representation. Values resolve in the declaring parent namespace.\n  // A component declaration that is absent on the target is represented as one\n  // component-add override; an existing component stays field-granular so an\n  // override cannot erase fields that were not mentioned by the author.\n  const childHasComponent = (\n    result: CompiledSceneResult,\n    target: number,\n    componentName: string,\n  ): boolean => {\n    const own = result.asset.entities.find((entity) => Number(entity.localId) === target);\n    if (own !== undefined && own.components[componentName] !== undefined) return true;\n    const mount = result.asset.mounts?.find((entry) => Number(entry.localId) === target);\n    return mount?.components?.[componentName] !== undefined;\n  };\n  for (const [key, instance] of instances) {\n    const declaration = instance.node.instance as NonNullable<SceneEntity['instance']>;\n    const { mount, compiled } = instance;\n    const childSlot = (target: SceneEntityAddress): number | undefined =>\n      compiled.resolveAddress(target);\n    const overrides: MountOverride[] = [];\n    for (const override of declaration.overrides ?? []) {\n      const target = childSlot(override.target);\n      if (target === undefined)\n        return fail('instance override target does not exist', {\n          entity: key,\n          target: override.target,\n        });\n      for (const [componentName, fields] of Object.entries(override.components)) {\n        const convertedFields = fieldRemap(\n          world,\n          componentName,\n          { ...(fields as Record<string, unknown>) },\n          resolveAddress,\n          `${key}.instance.${override.target.join('.')}`,\n        );\n        if (!convertedFields.ok) return convertedFields;\n        if (!childHasComponent(compiled, target, componentName)) {\n          overrides.push({\n            localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n            comp: componentName,\n            value: convertedFields.value,\n          });\n        } else {\n          overrides.push(\n            ...Object.entries(convertedFields.value).map(([field, value]) => ({\n              localId: ((mount.memberFirst as number) + target) as LocalEntityId,\n              comp: componentName,\n              field,\n              value,\n            })),\n          );\n        }\n      }\n    }\n    if (overrides.length > 0) instance.mount = { ...mount, overrides };\n  }\n\n  const mounts = [...instances.values()].map((instance) => instance.mount);\n\n  const rootLocalIds: number[] = [\n    ...convertedRootLocalIds(converted),\n    ...mounts.filter((mount) => mount.parent === undefined).map((mount) => Number(mount.localId)),\n  ];\n\n  // Validate the authored hierarchy using the same keyed address resolver that\n  // will be used for component fields. General component reference cycles are\n  // legal; only ChildOf cycles are rejected before any spawn.\n  const hierarchyParentByLocalId = new Map<number, number>();\n  for (const node of converted) {\n    const parent = node.components.ChildOf?.parent;\n    if (typeof parent === 'number' && parent >= 0) {\n      hierarchyParentByLocalId.set(Number(node.localId), parent);\n    }\n  }\n  for (const { mount, compiled } of instances.values()) {\n    if (mount.parent !== undefined) {\n      hierarchyParentByLocalId.set(Number(mount.localId), mount.parent);\n    }\n    for (const [childLocalId, childParent] of compiled.hierarchyParentByLocalId) {\n      hierarchyParentByLocalId.set(\n        Number(mount.memberFirst) + childLocalId,\n        Number(mount.memberFirst) + childParent,\n      );\n    }\n    for (const childRoot of compiled.rootLocalIds) {\n      hierarchyParentByLocalId.set(Number(mount.memberFirst) + childRoot, Number(mount.localId));\n    }\n    for (const override of mount.overrides ?? []) {\n      if (override.comp !== 'ChildOf') continue;\n      if (override.field === 'parent' && typeof override.value === 'number') {\n        hierarchyParentByLocalId.set(Number(override.localId), override.value);\n      } else if (\n        override.field === undefined &&\n        typeof override.value === 'object' &&\n        override.value !== null\n      ) {\n        const parentValue = (override.value as Record<string, unknown>).parent;\n        if (typeof parentValue === 'number') {\n          hierarchyParentByLocalId.set(Number(override.localId), parentValue);\n        }\n      }\n    }\n  }\n  for (const start of hierarchyParentByLocalId.keys()) {\n    const seen = new Set<number>();\n    let current: number | undefined = start;\n    while (current !== undefined && hierarchyParentByLocalId.has(current)) {\n      if (seen.has(current))\n        return fail('hierarchy cycle', { entity: keyByLocalId.get(start), address: [...seen] });\n      seen.add(current);\n      current = hierarchyParentByLocalId.get(current);\n    }\n  }\n\n  return ok({\n    asset: {\n      kind: 'scene',\n      entities: converted,\n      ...(mounts.length > 0 ? { mounts } : {}),\n      ...(asset.skinGuids === undefined ? {} : { skinGuids: asset.skinGuids }),\n    },\n    keyByLocalId,\n    mountKeyByLocalId,\n    rootLocalIds,\n    hierarchyParentByLocalId,\n    resolveAddress,\n  });\n}\n\nfunction convertedRootLocalIds(nodes: readonly CompiledSceneEntity[]): number[] {\n  return nodes\n    .filter((node) => node.components.ChildOf === undefined)\n    .map((node) => Number(node.localId));\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { Handle, LocalEntityId } from '@forgeax/engine-types';\nimport type { MountOverride } from './runtime-types.js';\n\n/**\n * Per-component, per-field override record carried in `SceneInstanceState`.\n *\n * Composite key `<componentName>:<fieldName>` keeps the override map flat\n * (single Map nesting level) so AI users walking `state.overrides` see one\n * iteration depth — D-2 prefers a single SSOT over multi-Map nesting that\n * would make iteration order ambiguous (charter F1: single mental model).\n *\n * The value is `unknown` because the per-component schema vocab lives in the\n * ECS layer; runtime fail-fast via `EcsErrorCode = 'scene-override-type-\n * mismatch'` (plan-strategy §D-9) catches type drift on the apply path.\n *\n * @internal Surface from `state.overrides` only; AI users never construct a\n *   record directly. Use `world.setSceneOverride(root, member, comp,\n *   field, value)` to write and `world.removeSceneOverride(root, member,\n *   comp, field)` to roll back to the source SceneAsset value.\n */\nexport interface SceneInstanceOverrideRecord {\n  readonly comp: string;\n  /**\n   * Component-granular add-or-patch discriminant (feat-20260713 M1 / w4):\n   * present -> this record patches a single field; absent -> it adds/upserts\n   * the whole `comp` (M2 apply semantics). Mirrors `MountOverride.field`.\n   */\n  readonly field?: string;\n  readonly value: unknown;\n}\n\n/**\n * Dynamic state payload for one SceneInstance — held in the World's\n * UniqueRefStore behind a `unique<SceneInstanceState>` slot on the synthetic\n * root entity. Mirrors the old class-based layout (plan-strategy §D-2 +\n * design doc §11.2 internal-state-table) but flattened into plain JS Maps/Sets so\n * AI users can iterate without indirection.\n *\n * Lifecycle:\n *   - allocated by `world.instantiateScene(handle, parent?)` — the W in\n *     `world.allocUniqueRef('SceneInstanceState', state)` returns the u32\n *     slot id stored in the SceneInstance.state column;\n *   - released by `world.despawn(root)` (the standard managed-handle release loop)\n *     or explicitly via `world.despawnScene(root)` / `world.despawnDescendants(root)`.\n *\n * Readers use `worldGetSceneInstanceState(world, root)`; the World resolves\n * the component's managed handle and rejects released generations. Scene\n * override operations own mutation of the maps.\n */\nexport interface SceneInstanceState {\n  readonly source: Handle<'SceneAsset', 'shared'>;\n  readonly sceneSourceKey?: string;\n  /** Authored key for each private numeric slot, retained for collection. */\n  readonly keyByLocalId: Map<number, string>;\n  /** Authored key of this instance when it is nested in a parent scene. */\n  readonly instanceKey?: string;\n  readonly bindings: Map<string, EntityHandle>;\n  readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n  readonly detachedLocalIds: Set<LocalEntityId>;\n  readonly overrides: Map<LocalEntityId, Map<string, SceneInstanceOverrideRecord>>;\n  readonly rootEntities: EntityHandle[];\n  readonly mountRoots: EntityHandle[];\n  readonly totalSlots: number;\n  readonly mountTimeOverrides: readonly MountOverride[];\n}\n\nexport interface SceneWorldState {\n  resolver: unknown;\n}\n\nconst sceneWorldStates = new WeakMap<World, SceneWorldState>();\n\nexport function sceneWorldState(world: World): SceneWorldState {\n  const current = sceneWorldStates.get(world);\n  if (current !== undefined) return current;\n  const created: SceneWorldState = { resolver: null };\n  sceneWorldStates.set(world, created);\n  return created;\n}\n\nexport function mountOverrideStateKey(ov: MountOverride): string {\n  return ov.field !== undefined ? `${ov.comp}:${ov.field}` : ov.comp;\n}\n\nexport function isPrimitiveScalarFieldType(fieldType: string): boolean {\n  if (\n    fieldType === 'f32' ||\n    fieldType === 'f64' ||\n    fieldType === 'u32' ||\n    fieldType === 'i32' ||\n    fieldType === 'u8' ||\n    fieldType === 'i8' ||\n    fieldType === 'u16' ||\n    fieldType === 'i16' ||\n    fieldType === 'bool' ||\n    fieldType === 'enum' ||\n    fieldType === 'string'\n  ) {\n    return true;\n  }\n  return fieldType.startsWith('enum<');\n}\n\nexport function primitiveJsType(fieldType: string): string {\n  if (fieldType === 'bool') return 'boolean';\n  if (fieldType === 'string') return 'string';\n  return 'number';\n}\n","// @forgeax/engine-scene — scene instantiation and instance-state subsystem.\n\nimport {\n  type Component,\n  type ComponentData,\n  type ComponentSchema,\n  type EcsError,\n  ENTITY_NULL_RAW,\n  type EntityHandle,\n  type InputShapeOf,\n  type ShapeOf,\n  type World,\n} from '@forgeax/engine-ecs';\nimport { classifyEntityField, remapEntityFieldValue } from '@forgeax/engine-ecs/externalization';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { fillComponentDefaults, StaleEntityError } from '@forgeax/engine-ecs/projection';\nimport type {\n  Handle,\n  LocalEntityId,\n  PackErrorCode,\n  PackErrorDetail,\n  SceneAsset,\n  SceneEntityAddress,\n  SceneEntityRef,\n} from '@forgeax/engine-types';\nimport {\n  err,\n  ok,\n  PACK_ERROR_HINTS,\n  type Result,\n  toUnique,\n  unwrapHandle,\n} from '@forgeax/engine-types';\nimport { ComponentNotDefinedError } from '../errors';\nimport { resolveSceneEntity, sceneEntityAddressKey } from './binding.js';\nimport {\n  type CompiledSceneAsset,\n  type CompiledSceneEntity,\n  compileKeyedSceneAsset,\n} from './keyed.js';\nimport type { MountOverride, SceneInstanceMount } from './runtime-types.js';\nimport { retainSceneSourceReferences } from './source-references.js';\nimport {\n  isPrimitiveScalarFieldType,\n  mountOverrideStateKey,\n  primitiveJsType,\n  type SceneInstanceState,\n  sceneWorldState,\n} from './state.js';\n\nexport type { SceneInstanceOverrideRecord, SceneInstanceState } from './state.js';\n\nconst entityIndex = (entity: EntityHandle): number => (entity as number) & 0x00ffffff;\nconst entityGeneration = (entity: EntityHandle): number => ((entity as number) >>> 24) & 0xff;\n\n/**\n * Legacy diagnostic shape retained on the scene-instantiation result for\n * non-blocking runtime observations. SceneAsset schema violations are\n * rejected by the keyed compiler before this result is produced; no authored\n * unknown-field record is emitted by the current path.\n *\n *   const r = worldInstantiateScene(world, handle);\n *   if (r.ok) for (const d of r.value.diagnostics)\n *     console.warn('scene diagnostic', d);\n *\n * Direct `world.spawn` / `world.addComponent` / `Commands.spawn` remain\n * fail-fast with `SpawnDataUnknownFieldError`.\n */\nexport type SceneInstantiateDiagnostic = {\n  /** Component name associated with the observation. */\n  readonly component: string;\n  /** Field associated with the observation. */\n  readonly field: string;\n  /** LocalEntityId within the owning SceneAsset, when applicable. */\n  readonly localId: number;\n};\n\n/**\n * Success value of `worldInstantiateScene`. `root` is the synthetic scene-root\n * EntityHandle (carries `SceneInstance`); `diagnostics` contains only\n * non-blocking runtime observations. Schema-invalid authored fields fail before\n * an entity is created.\n */\nexport type SceneInstantiateOk = {\n  readonly root: EntityHandle;\n  readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * Success value of `worldInstantiateSceneFlat` — the \"edit the scene itself\"\n * primitive. Unlike `instantiateScene`, NO synthetic SceneInstance root is\n * minted and NO `ChildOf` is forced onto top-level members: the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf` (an entity with no `ChildOf` stays a root). `roots`\n * is the set of those top-level handles (own rootless entities + top-level\n * mount carriers). Nested prefabs inside the scene STILL materialise as their\n * own SceneInstance anchors (charter P4: instance == entity-with-SceneInstance)\n * — only THIS scene is flat.\n */\nexport type SceneInstantiateFlatOk = {\n  readonly roots: EntityHandle[];\n  /**\n   * All mount carrier entities spawned while flattening this scene. These are\n   * separate from `roots`: carriers with an authored parent are not roots,\n   * but still delimit a nested prefab subtree for post-spawn hooks.\n   */\n  readonly mountEntities: EntityHandle[];\n  readonly diagnostics: readonly SceneInstantiateDiagnostic[];\n};\n\n/**\n * @internal Intermediate produced by `_spawnSceneMembers` and consumed by both\n * the anchor finisher (`_instantiateSceneAsset`) and the flat finisher\n * (`_instantiateSceneAssetFlat`). Holds everything the shared member-spawn\n * (mounts recursion + own-entity spawn + deferred owned-parent wiring) computes,\n * before either finisher decides whether to wrap the members in a synthetic\n * SceneInstance root.\n */\nexport interface SceneMembersSpawn {\n  /** LocalEntityId → live Entity u32 (ENTITY_NULL_RAW for unspawned slots). */\n  readonly mapping: Uint32Array;\n  /** Reverse map live Entity → LocalEntityId for override / detach bookkeeping. */\n  readonly entityToLocalId: Map<EntityHandle, LocalEntityId>;\n  /** Own entities that carried no `ChildOf` — the scene's authored top-level roots. */\n  readonly rootEntities: EntityHandle[];\n  /** Mount carriers whose `mount.parent === undefined` (default-parented). */\n  readonly mountEntitiesNeedingRootParent: EntityHandle[];\n  /** Every mount carrier spawned by this scene, including explicitly parented carriers. */\n  readonly mountEntities: EntityHandle[];\n  /**\n   * The child anchor and mapping for each mount. Flat scene opening has no\n   * outer SceneInstance state to own parent-namespace mount overrides, so it\n   * records those overrides on this child anchor after the shared spawn pass.\n   */\n  readonly mountInstances: readonly {\n    readonly mount: SceneInstanceMount;\n    readonly root: EntityHandle;\n    readonly mapping: Uint32Array;\n    readonly key?: string;\n  }[];\n  /** `entities.length + mounts + Σ memberCount`, captured at instantiate-time. */\n  readonly totalSlots: number;\n}\n\n/**\n * Populate the instance binding projection from the private numeric mapping.\n * The authored key remains the only lookup identity: nested instance paths are\n * represented as the same string/tuple key accepted by `SceneEntityRef`, while\n * the numeric mapping stays local to the Scene owner.\n */\nfunction collectSceneEntityBindings(\n  world: World,\n  root: EntityHandle,\n  prefix: readonly string[],\n  bindings: Map<string, EntityHandle>,\n  visited = new Set<number>(),\n): void {\n  const rootRaw = root as unknown as number;\n  if (visited.has(rootRaw)) return;\n  visited.add(rootRaw);\n  const state = worldGetSceneInstanceState(world, root);\n  if (!state.ok) return;\n  const sceneInstance = world.components.resolve('SceneInstance');\n  if (sceneInstance === undefined) return;\n  const component = world.get(root, sceneInstance);\n  if (!component.ok) return;\n  const mapping = (component.value as unknown as { mapping: ArrayLike<number> }).mapping;\n  for (const [slot, key] of state.value.keyByLocalId) {\n    const raw = mapping[slot];\n    if (raw === undefined || raw === ENTITY_NULL_RAW) continue;\n    const address: SceneEntityAddress =\n      prefix.length === 0 ? key : ([...prefix, key] as unknown as [string, ...string[]]);\n    bindings.set(sceneEntityAddressKey(address), raw as unknown as EntityHandle);\n  }\n  for (const childRoot of state.value.mountRoots) {\n    const childState = worldGetSceneInstanceState(world, childRoot);\n    const childKey = childState.ok ? childState.value.instanceKey : undefined;\n    if (childKey === undefined) continue;\n    collectSceneEntityBindings(world, childRoot, [...prefix, childKey], bindings, visited);\n  }\n}\n\nexport type SceneAssetResolver = (\n  source: number | string,\n  parentHandle: Handle<'SceneAsset', 'shared'>,\n) => Result<Handle<'SceneAsset', 'shared'>, unknown>;\n\n/** @internal */\nexport function worldSetSceneAssetResolver(world: World, resolver: SceneAssetResolver): void {\n  sceneWorldState(world).resolver = resolver;\n}\n\n/** @internal */\nexport function worldGetSceneAssetResolver(world: World): SceneAssetResolver | null {\n  return sceneWorldState(world).resolver as SceneAssetResolver | null;\n}\n\n/**\n * Materialise a SceneAsset (and any nested SceneAsset references via\n * `mounts[]`) into live entities. Returns the synthetic root Entity that\n * carries the `SceneInstance` ECS component (charter P4: instance ==\n * entity-with-SceneInstance).\n *\n * Recursion path is closed inside `_instantiateSceneRec(handle, parent,\n * stack)` (D-3); cycle detection is fail-fast `pack-cyclic-reference +\n * detail.kind:'mount-asset'` (D-1 mirror, plan-strategy §D-3). The\n * caller-supplied `parent` flows to the synthetic root's `ChildOf` so the\n * full sub-tree attaches under the AI user's host entity.\n *\n * @example\n *   const r = worldInstantiateScene(world, handle);\n *   if (!r.ok) return r;\n *   const { root, diagnostics } = r.value;\n *   for (const d of diagnostics) // non-blocking runtime observations\n *     console.warn('scene diagnostic', d);\n *   const inst = world.get(root, SceneInstance).value;\n *   const member = inst.mapping[0]; // first member entity\n */\nexport function worldInstantiateScene(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  parent?: EntityHandle,\n  sceneSourceKey?: string,\n): Result<SceneInstantiateOk, EcsError> {\n  const stack = new Set<number>();\n  // Keep the existing result shape for non-blocking runtime observations. The\n  // keyed compiler rejects schema-invalid authoring data before spawning.\n  const diagnostics: SceneInstantiateDiagnostic[] = [];\n  const r = worldInstantiateSceneRec(\n    world,\n    handle,\n    parent,\n    stack,\n    diagnostics,\n    undefined,\n    sceneSourceKey,\n  );\n  if (!r.ok) return r;\n  return ok({ root: r.value, diagnostics });\n}\n\n/**\n * Materialise a projected `SceneAsset` payload without exposing the temporary\n * shared-ref handle to the caller. The World remains the owner of both the\n * handle and the instantiated SceneInstance: the producer grant is released\n * after the SceneInstance retains its source, including when instantiation\n * fails. This is the payload-shaped counterpart to `worldInstantiateScene` for\n * hosts that load a SceneAsset directly from the Engine AssetRegistry.\n */\nexport function worldInstantiateScenePayload(\n  world: World,\n  asset: SceneAsset,\n  parent?: EntityHandle,\n): Result<SceneInstantiateOk, EcsError> {\n  const handle = world.allocSharedRef('SceneAsset', asset);\n  try {\n    return worldInstantiateScene(world, handle, parent);\n  } finally {\n    // The SceneInstance source column retains the handle on success. On a\n    // failed materialisation there should be no remaining holder; either way\n    // release the producer grant owned by this convenience entrypoint.\n    world.sharedRefs.release(handle);\n  }\n}\n\n/**\n * Materialise a SceneAsset FLAT — the \"edit the scene itself\" primitive.\n * Unlike `instantiateScene`, this mints NO synthetic SceneInstance root and\n * forces NO `ChildOf` onto top-level members: the scene's own entities become\n * plain top-level world entities whose hierarchy is exactly their authored\n * `ChildOf` (an entity with no `ChildOf` is a root). Use this to OPEN a scene\n * for editing; use `instantiateScene` (anchor) at runtime / for nested\n * prefabs where an instance boundary + override isolation is wanted.\n *\n * Nested prefabs referenced via `mounts[]` STILL materialise as their own\n * SceneInstance anchors (charter P4 preserved) — only THIS top scene is flat.\n *\n * @example\n *   const r = worldInstantiateSceneFlat(world, handle);\n *   if (!r.ok) return r;\n *   const { roots, diagnostics } = r.value; // roots = top-level handles\n */\nexport function worldInstantiateSceneFlat(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneInstantiateFlatOk, EcsError> {\n  const stack = new Set<number>();\n  const diagnostics: SceneInstantiateDiagnostic[] = [];\n  const handleKey = unwrapHandle(handle);\n  const resolved = worldResolveSceneAsset(world, handle);\n  if (!resolved.ok) return resolved;\n  stack.add(handleKey);\n  let r: Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError>;\n  try {\n    r = worldInstantiateSceneAssetFlat(world, handle, resolved.value, stack, diagnostics);\n  } finally {\n    stack.delete(handleKey);\n  }\n  if (!r.ok) return r;\n  return ok({ ...r.value, diagnostics });\n}\n/**\n * @internal Recursive helper carrying the cycle-detection stack. Sugar /\n * other public callers must not see this mechanic — use `instantiateScene`\n * (D-3 / charter P1).\n */\nexport function worldInstantiateSceneRec(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  parent: EntityHandle | undefined,\n  stack: Set<number>,\n  diagnostics: SceneInstantiateDiagnostic[],\n  instanceKey?: string,\n  sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n  const handleKey = unwrapHandle(handle);\n  if (stack.has(handleKey)) {\n    const cycleArr: string[] = [];\n    for (const k of stack) cycleArr.push(String(k));\n    cycleArr.push(String(handleKey));\n    const detail: PackErrorDetail = {\n      code: 'pack-cyclic-reference',\n      kind: 'mount-asset',\n      cycle: cycleArr,\n    };\n    return err({\n      code: 'pack-cyclic-reference' as PackErrorCode,\n      expected: 'acyclic SceneAsset mount graph',\n      hint: PACK_ERROR_HINTS['pack-cyclic-reference'],\n      detail,\n    } as unknown as EcsError);\n  }\n  const resolved = worldResolveSceneAsset(world, handle);\n  if (!resolved.ok) return resolved;\n  const asset = resolved.value;\n  stack.add(handleKey);\n  try {\n    return worldInstantiateSceneAsset(\n      world,\n      handle,\n      asset,\n      parent,\n      stack,\n      diagnostics,\n      instanceKey,\n      sceneSourceKey,\n    );\n  } finally {\n    stack.delete(handleKey);\n  }\n}\n/**\n * @internal Resolve a SceneAsset handle through the SharedRefStore.\n * The handle u32 is the SharedRefStore slot id (`world.allocSharedRef\n * ('SceneAsset', asset)` is the producer; rc starts at 1, the SceneInstance\n * spawn retains to rc=2 in M4 / w13). Errors propagate as EcsError so the\n * instantiateScene chain returns a single closed union.\n */\nexport function worldResolveSceneAsset(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n): Result<SceneAsset, EcsError> {\n  const r = world.sharedRefs.resolve(handle);\n  if (!r.ok) {\n    return err(r.error as unknown as EcsError);\n  }\n  return ok(r.value as SceneAsset);\n}\n/**\n * @internal Spawn one SceneAsset's members — the shared body of both scene\n * finishers. Recurses into `mounts[]` (each nested prefab becomes its own\n * SceneInstance anchor), spawns `entities[]` honouring their authored\n * `ChildOf`, and wires deferred owned-parent mount edges. Does NOT create a\n * synthetic root or force any `ChildOf` — that is the caller's (finisher's)\n * job. `_instantiateSceneRec` owns cycle bookkeeping.\n */\nexport function worldSpawnSceneMembers(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  asset: CompiledSceneAsset,\n  stack: Set<number>,\n  diagnostics: SceneInstantiateDiagnostic[],\n  mountKeys?: ReadonlyMap<number, string>,\n): Result<SceneMembersSpawn, EcsError> {\n  const sceneInstanceToken = world.components.resolve('SceneInstance');\n  if (sceneInstanceToken === undefined) {\n    return err(new ComponentNotDefinedError('SceneInstance'));\n  }\n  const childOfToken = world.components.resolve('ChildOf');\n  // ChildOf is optional — only needed if the asset declares ChildOf or a\n  // caller-supplied parent must be wired. If absent and we need it, we\n  // fail-fast at the wiring site below.\n\n  const ownEntities = asset.entities;\n  const ownMounts = asset.mounts ?? [];\n  const memberSum = ownMounts.reduce((s, m) => s + m.memberCount, 0);\n  const countBaseline = ownEntities.length + ownMounts.length + memberSum;\n  // C-R1 (studio-issues #6): mapping table must be sized to maxLocalId+1,\n  // not to the entity count. An editor scene may have non-contiguous\n  // localIds (deleted entities leave gaps); sizing to count means any\n  // localId >= count is a silent Uint32Array OOB no-op -> entity spawns\n  // but is unreachable by localId -> users report \"character can't move\".\n  // Take the max of count-baseline and id-range so both packed and\n  // sparse scenes work without over-allocation in the common case.\n  let maxLocalId = ownEntities.reduce((m, e) => Math.max(m, e.localId as unknown as number), -1);\n  for (const mount of ownMounts) {\n    maxLocalId = Math.max(maxLocalId, mount.localId as unknown as number);\n    const last = (mount.memberFirst as unknown as number) + mount.memberCount - 1;\n    maxLocalId = Math.max(maxLocalId, last);\n  }\n  const totalSlots = Math.max(countBaseline, maxLocalId + 1);\n\n  // R2/Bonus: namespace-overlap fail-fast (AC-05 /\n  // pack-mount-localid-overlap). Each LocalEntityId in\n  // [0, totalSlots) must be claimed by exactly one of:\n  //   - entities[i].localId\n  //   - mounts[i].localId\n  //   - mounts[i] window slot (memberFirst .. memberFirst+memberCount-1)\n  // Overlap or duplicate claim => fail-fast with the offending localIds\n  // and human-readable origin labels.\n  {\n    const claims = new Map<number, string>();\n    const overlapLids = new Set<number>();\n    const overlapSources: string[] = [];\n    const claim = (lid: number, src: string): void => {\n      const prior = claims.get(lid);\n      if (prior !== undefined) {\n        if (!overlapLids.has(lid)) {\n          overlapLids.add(lid);\n          overlapSources.push(prior);\n          overlapSources.push(src);\n        } else {\n          overlapSources.push(src);\n        }\n        return;\n      }\n      claims.set(lid, src);\n    };\n    for (const ent of ownEntities) {\n      claim(ent.localId as unknown as number, `entities[${ent.localId as unknown as number}]`);\n    }\n    for (const mount of ownMounts) {\n      const mLid = mount.localId as unknown as number;\n      claim(mLid, `mount[${mLid}]`);\n      const first = mount.memberFirst as unknown as number;\n      for (let k = 0; k < mount.memberCount; k += 1) {\n        claim(first + k, `mount[${mLid}].member[${k}]`);\n      }\n    }\n    if (overlapLids.size > 0) {\n      const overlapping = Array.from(overlapLids).sort((a, b) => a - b);\n      return err({\n        code: 'pack-mount-localid-overlap' as PackErrorCode,\n        expected: 'each LocalEntityId claimed by exactly one entity or mount slot',\n        hint: PACK_ERROR_HINTS['pack-mount-localid-overlap'],\n        detail: {\n          code: 'pack-mount-localid-overlap',\n          overlapping,\n          sources: overlapSources,\n        } as PackErrorDetail,\n      } as unknown as EcsError);\n    }\n  }\n\n  // Slot table: indexed by LocalEntityId; populated as entities / mounts /\n  // members are spawned. mapping[localId] = encoded Entity u32. Unspawned\n  // slots hold ENTITY_NULL_RAW (0xffffffff) — NOT 0, because a fresh World's\n  // first spawn encodes to gen=0+idx=0=raw 0, which is a valid Entity. The\n  // remap path in `_buildSceneEntityComponentDatas` distinguishes the two\n  // (live=ENTITY_NULL_RAW => parent unspawned at remap time => surface as\n  // null sentinel; live=any other u32 => valid live Entity, including 0).\n  const mapping = new Uint32Array(totalSlots).fill(ENTITY_NULL_RAW);\n  const entityToLocalId = new Map<EntityHandle, LocalEntityId>();\n  const rootEntities: EntityHandle[] = [];\n  const mountEntities: EntityHandle[] = [];\n  // R2/B-1: mount entities whose `mount.parent === undefined` need their\n  // ChildOf wired to the outer synthetic root (this scene's root). Step 5\n  // does the wiring once the synthetic root entity is materialised; we\n  // collect them here in step 1.\n  const mountEntitiesNeedingRootParent: EntityHandle[] = [];\n  // D-8 (feat-20260707): mount entities whose `mount.parent` points at an\n  // OWNED entity slot are wired AFTER step 2 spawns the owned entities —\n  // mounts are processed first (step 1), so the owned parent slot is still\n  // ENTITY_NULL_RAW at mount-processing time. Same deferred-wiring shape as\n  // mountEntitiesNeedingRootParent: register [mountEntity, parentSlot] here,\n  // wire ChildOf once the slot is live. Without this the edge was silently\n  // dropped, and the mount carrier stayed unreachable from its owned parent.\n  const mountEntitiesNeedingDeferredParent: Array<[EntityHandle, number]> = [];\n  const mountInstances: Array<{\n    readonly mount: SceneInstanceMount;\n    readonly root: EntityHandle;\n    readonly mapping: Uint32Array;\n  }> = [];\n\n  // 1. Recurse into mounts[] FIRST so the mount-window slots\n  //    (`mount.localId` + `[memberFirst, memberFirst+memberCount)`) are\n  //    populated before any owned entity tries to remap a LocalEntityId\n  //    pointing into the mount window (AC-24 cross-boundary reference).\n  for (const mount of ownMounts) {\n    // R2/B-3 + R2/B-4: validate overrides BEFORE child resolution so a\n    // malformed override fails fast without observable side-effects.\n    const overrideValidationRes = worldValidateMountOverrides(world, mount);\n    if (!overrideValidationRes.ok) {\n      return overrideValidationRes;\n    }\n\n    // Spawn the mount entity (carries mount.components).\n    const mountLid = mount.localId as unknown as number;\n    const mountSpawnRes = worldSpawnMountEntity(world, mount, mapping, diagnostics);\n    if (!mountSpawnRes.ok) return mountSpawnRes;\n    const mountEntity = mountSpawnRes.value;\n    mountEntities.push(mountEntity);\n    mapping[mountLid] = mountEntity as unknown as number;\n\n    // Resolve mount.source -> child SceneAsset handle.\n    const childHandleRes = worldResolveMountSource(world, mount.source, handle);\n    if (!childHandleRes.ok) return childHandleRes;\n    const childHandle = childHandleRes.value;\n\n    // Recursively instantiate the child. Its synthetic root attaches as a\n    // child of the mount entity; runtime observations share the same result\n    // accumulator and bubble to the top-level instance.\n    const childRes = worldInstantiateSceneRec(\n      world,\n      childHandle,\n      mountEntity,\n      stack,\n      diagnostics,\n      mountKeys?.get(mountLid),\n    );\n    if (!childRes.ok) return childRes;\n\n    // R2/B-2: cross-check mount.memberCount === child.totalSlots BEFORE\n    // copying the mount window. The child SceneInstance.mapping length is\n    // the authoritative `totalSlots` of the child. AC-04 / requirements\n    // S-5 mandate fail-fast at runtime for this disagreement.\n    const childInstRes = world.get(childRes.value, sceneInstanceToken);\n    if (!childInstRes.ok) return childInstRes;\n    const childMapping = (childInstRes.value as unknown as { mapping: Uint32Array }).mapping;\n    mountInstances.push({\n      mount,\n      root: childRes.value,\n      mapping: childMapping,\n      ...(mountKeys?.get(mountLid) === undefined ? {} : { key: mountKeys.get(mountLid) }),\n    });\n    if (childMapping.length !== mount.memberCount) {\n      return err({\n        code: 'pack-mount-count-mismatch' as PackErrorCode,\n        expected: 'mount.memberCount === child SceneAsset totalSlots',\n        hint: PACK_ERROR_HINTS['pack-mount-count-mismatch'],\n        detail: {\n          code: 'pack-mount-count-mismatch',\n          mountLocalId: mountLid,\n          declared: mount.memberCount,\n          actual: childMapping.length,\n        } as PackErrorDetail,\n      } as unknown as EcsError);\n    }\n\n    // Pull the child's mapping into our parent window. Default unset slots\n    // to ENTITY_NULL_RAW so downstream \"live\" checks distinguish them from\n    // the first Entity (gen=0+idx=0 encodes to raw u32 0).\n    const window = mount.memberCount;\n    for (let k = 0; k < window; k += 1) {\n      mapping[(mount.memberFirst as unknown as number) + k] = childMapping[k] ?? ENTITY_NULL_RAW;\n    }\n\n    // Apply mount.overrides at instantiate-time (AC-19).\n    // Each override.localId addresses a slot in *this* (parent) namespace\n    // (R2/F-8 cement: parent-namespace + memberFirst+offset addressing).\n    // The state map will be populated below with these overrides — but we\n    // must also write the value through to the live entity column so the\n    // readback invariant holds.\n    // Mount-entity itself never has children attached by the caller other\n    // than via the recursive child; nothing else to wire here.\n    if (childOfToken !== undefined) {\n      if (mount.parent !== undefined) {\n        // Reparent the mount-entity ChildOf to the caller-specified parent.\n        const parentSlot = mount.parent as unknown as number;\n        const parentEntity = mapping[parentSlot];\n        if (parentEntity !== undefined && parentEntity !== ENTITY_NULL_RAW) {\n          const r = world.addComponent(mountEntity, {\n            component: childOfToken,\n            data: { parent: parentEntity } as never,\n          });\n          if (!r.ok) {\n            // ChildOf may already be present from layer-1; reparent via set.\n            const set = world.set(mountEntity, childOfToken, {\n              parent: parentEntity,\n            } as never);\n            if (!set.ok) return set as Result<SceneMembersSpawn, EcsError>;\n          }\n        } else {\n          // D-8: the owned parent slot is not spawned yet (owned entities\n          // spawn in step 2, after this mount loop). Defer the ChildOf wire\n          // to step 2's tail once mapping[parentSlot] is live.\n          mountEntitiesNeedingDeferredParent.push([mountEntity, parentSlot]);\n        }\n      } else {\n        // R2/B-1: default semantic — mount.parent === undefined wires the\n        // mount entity ChildOf to *this* scene's synthetic root (created\n        // in step 3 below). Defer the actual wire to step 5 after the\n        // synthetic root spawn; record the mount entity here.\n        mountEntitiesNeedingRootParent.push(mountEntity);\n      }\n    }\n  }\n\n  // 2. Spawn entities[] entities. Topo-sort by ChildOf so parents are\n  //    spawned before children (so localId remap can read mapping live).\n  //    This runs AFTER mount processing (step 1) so cross-boundary\n  //    `ChildOf {parent: <mount-window-localId>}` references resolve\n  //    correctly (AC-24).\n  const order = sceneTopoSort(ownEntities);\n  for (const idx of order) {\n    const node = ownEntities[idx];\n    if (node === undefined) continue;\n    const lid = node.localId as unknown as number;\n    const compDataRes = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n    if (!compDataRes.ok) return compDataRes;\n    const sp = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n      ...compDataRes.value,\n    );\n    if (!sp.ok) return sp as Result<SceneMembersSpawn, EcsError>;\n    const e = sp.value;\n    mapping[lid] = e as unknown as number;\n    entityToLocalId.set(e, lid as unknown as LocalEntityId);\n    if (node.components.ChildOf === undefined) {\n      rootEntities.push(e);\n    }\n  }\n\n  // Hierarchy order cannot order arbitrary entity references (including\n  // cycles). Once every slot is live, rebind schema-declared entity fields\n  // through the same projection used at spawn. No asset-specific fixups.\n  for (const node of [\n    ...ownEntities,\n    ...ownMounts.map((mount) => ({ localId: mount.localId, components: mount.components ?? {} })),\n  ]) {\n    const entity = mapping[node.localId as unknown as number] as EntityHandle;\n    const componentDatas = worldBuildSceneEntityComponentDatas(world, node, mapping, diagnostics);\n    if (!componentDatas.ok) return componentDatas;\n    for (const { component, data } of componentDatas.value) {\n      const references = Object.fromEntries(\n        Object.entries(data).filter(\n          ([field]) =>\n            Object.hasOwn(node.components[component.name] ?? {}, field) &&\n            classifyEntityField(component, field) !== null,\n        ),\n      );\n      if (Object.keys(references).length === 0) continue;\n      const rebound = world.set(entity, component, references as never);\n      if (!rebound.ok) return rebound;\n    }\n  }\n\n  // 2b. D-8 (feat-20260707): wire deferred owned-parent mount ChildOf edges.\n  //     Owned entities are now live (step 2 above), so mapping[parentSlot]\n  //     resolves. Same shape as the mountEntitiesNeedingRootParent wiring in\n  //     step 5. The relationship mirror hook (relationshipOnInsert) pushes the\n  //     carrier into the owned parent's Children mirror automatically.\n  if (childOfToken !== undefined) {\n    for (const [mountEntity, parentSlot] of mountEntitiesNeedingDeferredParent) {\n      const parentEntity = mapping[parentSlot];\n      if (parentEntity === undefined || parentEntity === ENTITY_NULL_RAW) continue;\n      const set = world.set(mountEntity, childOfToken, { parent: parentEntity } as never);\n      if (!set.ok) {\n        const r = world.addComponent(mountEntity, {\n          component: childOfToken,\n          data: { parent: parentEntity } as never,\n        });\n        if (!r.ok) return r as Result<SceneMembersSpawn, EcsError>;\n      }\n    }\n  }\n\n  return ok({\n    mapping,\n    entityToLocalId,\n    rootEntities,\n    mountEntitiesNeedingRootParent,\n    mountEntities,\n    mountInstances,\n    totalSlots,\n  });\n}\n/**\n * @internal Spawn one SceneAsset's entities + apply mounts recursively, then\n * wrap them in a synthetic SceneInstance root (the anchor). This is the\n * runtime / Play / nested-mount finisher (charter P4: instance ==\n * entity-with-SceneInstance). Caller (`_instantiateSceneRec`) owns cycle\n * bookkeeping.\n */\nexport function worldInstantiateSceneAsset(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  asset: SceneAsset,\n  parent: EntityHandle | undefined,\n  stack: Set<number>,\n  diagnostics: SceneInstantiateDiagnostic[],\n  instanceKey?: string,\n  sceneSourceKey?: string,\n): Result<EntityHandle, EcsError> {\n  const sceneInstanceToken = world.components.resolve('SceneInstance');\n  if (sceneInstanceToken === undefined) {\n    return err(new ComponentNotDefinedError('SceneInstance'));\n  }\n  const childOfToken = world.components.resolve('ChildOf');\n\n  const compiled = compileKeyedSceneAsset(world, handle, asset, {\n    resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n    resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n    stack,\n  });\n  if (!compiled.ok) return err(compiled.error as EcsError);\n  const compiledAsset = compiled.value.asset;\n  // Validate and acquire source references before any child or member can spawn.\n  const sourceReferences = retainSceneSourceReferences(world, asset);\n  if (!sourceReferences.ok) return sourceReferences;\n  const releaseSourceReferences = sourceReferences.value;\n  const membersRes = worldSpawnSceneMembers(\n    world,\n    handle,\n    compiledAsset,\n    stack,\n    diagnostics,\n    compiled.value.mountKeyByLocalId,\n  );\n  if (!membersRes.ok) {\n    releaseSourceReferences();\n    return membersRes;\n  }\n  const { mapping, entityToLocalId, rootEntities, mountEntitiesNeedingRootParent, totalSlots } =\n    membersRes.value;\n  const { mountInstances } = membersRes.value;\n  const ownMounts = compiledAsset.mounts ?? [];\n\n  // Allocate the actual instance state once. The managed store owns payload\n  // identity and release; Scene holds no parallel handle-to-state registry.\n  const detached = new Set<LocalEntityId>();\n  const bindings = new Map<string, EntityHandle>();\n  const state: SceneInstanceState = {\n    source: handle,\n    ...(sceneSourceKey === undefined ? {} : { sceneSourceKey }),\n    keyByLocalId: new Map(compiled.value.keyByLocalId),\n    ...(instanceKey === undefined ? {} : { instanceKey }),\n    bindings,\n    entityToLocalId,\n    detachedLocalIds: detached,\n    overrides: new Map(),\n    rootEntities,\n    mountRoots: mountInstances.map(({ root }) => root),\n    totalSlots,\n    mountTimeOverrides: ownMounts.flatMap((m) => m.overrides ?? []),\n  };\n  const stateRef = world.allocUniqueRef('SceneInstanceState', state, releaseSourceReferences);\n  // Spawn the root with SceneInstance component, mapping snapshot, and\n  // state ref. The mapping is a Uint32Array (array<entity> field shape).\n  // Convert mapping Uint32Array to plain number[] for spawn write — the\n  // ECS array<entity> arm copies element-by-element and accepts both, but\n  // the plain-array form sidesteps a Uint32Array.length=0 corner case\n  // observed during M2 testing where a non-empty Uint32Array was written\n  // as if empty (suspect: archetype write-array dispatch on instanceof\n  // Array vs TypedArray).\n  const mappingPlain: number[] = Array.from(mapping);\n  // The synthetic root is the ChildOf parent of every owned root entity\n  // (step 5 below) and may itself become a ChildOf parent of a caller-\n  // supplied `parent` chain. propagateTransforms expands the ECS-maintained\n  // Children lists parent-first and treats a parent missing Transform\n  // as `hierarchy-broken`, so the synthetic root must carry Transform\n  // (identity TRS via layer-2 defaults) when Transform is defined.\n  const rootComponents: ComponentData[] = [\n    {\n      component: sceneInstanceToken,\n      data: {\n        source: handle,\n        mapping: mappingPlain,\n        state: stateRef,\n      } as never,\n    },\n  ];\n  const transformToken = world.components.resolve('Transform');\n  if (transformToken !== undefined) {\n    rootComponents.push({\n      component: transformToken,\n      data: {} as never,\n    });\n  }\n  const rootSpawn = (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(\n    ...rootComponents,\n  );\n  if (!rootSpawn.ok) {\n    releaseSourceReferences();\n    return rootSpawn;\n  }\n  const rootEntity = rootSpawn.value;\n\n  // Apply mount overrides after the synthetic root has been spawned.\n  for (const mount of ownMounts) {\n    for (const ov of mount.overrides ?? []) {\n      // feat-20260713 M2 / w8: `MountOverride.field` is optional (add-or-patch\n      // discriminant carried by the shape itself). Record the override into\n      // the SceneInstanceState map keyed by comp (no field) or comp:field\n      // (field-patch), then apply it to the live member column via the shared\n      // add-or-patch helper.\n      const lid = ov.localId as unknown as LocalEntityId;\n      let fieldMap = state.overrides.get(lid);\n      if (fieldMap === undefined) {\n        fieldMap = new Map();\n        state.overrides.set(lid, fieldMap);\n      }\n      const { localId: _localId, ...record } = ov;\n      fieldMap.set(mountOverrideStateKey(ov), record);\n      // Apply override to the live member entity column.\n      const memberEntityRaw = mapping[lid as unknown as number];\n      if (memberEntityRaw !== undefined && memberEntityRaw !== ENTITY_NULL_RAW) {\n        const memberEntity = memberEntityRaw as unknown as EntityHandle;\n        const applyRes = worldApplyMountOverride(\n          world,\n          memberEntity,\n          worldRemapMountOverride(world, ov, mapping),\n        );\n        if (!applyRes.ok) {\n          return applyRes as Result<EntityHandle, EcsError>;\n        }\n      }\n    }\n  }\n\n  // Populate direct and nested keyed addresses only after this root state is\n  // visible. Child SceneInstance states were published by the recursive spawn\n  // above, so the same walk can project the complete address closure.\n  collectSceneEntityBindings(world, rootEntity, [], bindings);\n\n  // 5. Wire ChildOf for every owned root entity (no ChildOf at layer-1)\n  //    to the synthetic root.\n  if (childOfToken !== undefined) {\n    for (const rootE of rootEntities) {\n      const has = world.get(rootE, childOfToken);\n      if (!has.ok) {\n        // No ChildOf yet — attach to synthetic root.\n        const r = world.addComponent(rootE, {\n          component: childOfToken,\n          data: { parent: rootEntity } as never,\n        });\n        if (!r.ok) return r as Result<EntityHandle, EcsError>;\n      }\n    }\n    // R2/B-1: wire mount entities with default `mount.parent === undefined`\n    // to this scene's synthetic root. _spawnMountEntity may have attached a\n    // placeholder ChildOf {parent: ENTITY_NULL_RAW} when mount.components\n    // was empty; overwrite via set so the ChildOf chain meshRenderer ->\n    // childSyntheticRoot -> mountEntity -> outerSyntheticRoot resolves\n    // through Transform-bearing parents (AC-16 / requirements S-7).\n    for (const mountE of mountEntitiesNeedingRootParent) {\n      const set = world.set(mountE, childOfToken, { parent: rootEntity } as never);\n      if (!set.ok) {\n        const r = world.addComponent(mountE, {\n          component: childOfToken,\n          data: { parent: rootEntity } as never,\n        });\n        if (!r.ok) return r as Result<EntityHandle, EcsError>;\n      }\n    }\n    // Caller-supplied parent: synthetic root's ChildOf -> parent.\n    if (parent !== undefined) {\n      const r = world.addComponent(rootEntity, {\n        component: childOfToken,\n        data: { parent } as never,\n      });\n      if (!r.ok) return r as Result<EntityHandle, EcsError>;\n    }\n  }\n\n  return ok(rootEntity);\n}\n/**\n * @internal Flat finisher — spawn one SceneAsset's members WITHOUT wrapping\n * them in a synthetic SceneInstance root and WITHOUT forcing `ChildOf` onto\n * top-level members. Used for \"opening a scene to edit\": the scene's own\n * entities become plain top-level world entities whose hierarchy is exactly\n * their authored `ChildOf`. Nested prefabs inside still materialise as their\n * own SceneInstance anchors (the mount recursion in `_spawnSceneMembers` is\n * always anchored). Returns the top-level handles (own rootless entities +\n * top-level mount carriers).\n */\nexport function worldInstantiateSceneAssetFlat(\n  world: World,\n  handle: Handle<'SceneAsset', 'shared'>,\n  asset: SceneAsset,\n  stack: Set<number>,\n  diagnostics: SceneInstantiateDiagnostic[],\n): Result<{ roots: EntityHandle[]; mountEntities: EntityHandle[] }, EcsError> {\n  const compiled = compileKeyedSceneAsset(world, handle, asset, {\n    resolveSource: (source, parentHandle) => worldResolveMountSource(world, source, parentHandle),\n    resolveAsset: (childHandle) => worldResolveSceneAsset(world, childHandle),\n    stack,\n  });\n  if (!compiled.ok) return err(compiled.error as EcsError);\n  // Flat roots have no persistent source owner, but authored overrides must be\n  // validated before any nested instance spawns and stay live during application.\n  const sourceReferences = retainSceneSourceReferences(world, asset);\n  if (!sourceReferences.ok) return sourceReferences;\n  try {\n    const membersRes = worldSpawnSceneMembers(\n      world,\n      handle,\n      compiled.value.asset,\n      stack,\n      diagnostics,\n      compiled.value.mountKeyByLocalId,\n    );\n    if (!membersRes.ok) return membersRes;\n    const { rootEntities, mountEntitiesNeedingRootParent, mountEntities, mountInstances } =\n      membersRes.value;\n    const childOfToken = world.components.resolve('ChildOf');\n\n    // Apply parent mount overrides to the live columns and record them on the\n    // nested child anchor. Flat mode has no outer SceneInstance state; without\n    // this hand-authored mounts[].overrides affect the live value but disappear\n    // from the child state, so Gateway re-open cannot discover or revert them.\n    for (const { mount, root, mapping: childMapping } of mountInstances) {\n      const childStateRes = worldGetSceneInstanceState(world, root);\n      if (!childStateRes.ok) return childStateRes;\n      for (const ov of mount.overrides ?? []) {\n        const childLocalId =\n          (ov.localId as unknown as number) - (mount.memberFirst as unknown as number);\n        const memberEntityRaw = childMapping[childLocalId];\n        if (memberEntityRaw === undefined || memberEntityRaw === ENTITY_NULL_RAW) continue;\n        const memberEntity = memberEntityRaw as unknown as EntityHandle;\n        const applyRes = worldApplyMountOverride(\n          world,\n          memberEntity,\n          worldRemapMountOverride(world, ov, childMapping),\n        );\n        if (!applyRes.ok) {\n          return applyRes as Result<\n            { roots: EntityHandle[]; mountEntities: EntityHandle[] },\n            EcsError\n          >;\n        }\n        let fieldMap = childStateRes.value.overrides.get(childLocalId as LocalEntityId);\n        if (fieldMap === undefined) {\n          fieldMap = new Map();\n          childStateRes.value.overrides.set(childLocalId as LocalEntityId, fieldMap);\n        }\n        fieldMap.set(mountOverrideStateKey(ov), {\n          comp: ov.comp,\n          ...(ov.field === undefined ? {} : { field: ov.field }),\n          value: ov.value,\n        });\n      }\n    }\n\n    // Default-parented mount carriers (`mount.parent === undefined`) would, in\n    // anchor mode, attach to the synthetic root. Flat mode has none, so they\n    // stay top-level. `_spawnMountEntity` may have left a placeholder\n    // `ChildOf {parent: ENTITY_NULL_RAW}` (rare: mount with no components AND\n    // Transform unregistered) — strip it so the carrier is a genuine root.\n    if (childOfToken !== undefined) {\n      for (const mountE of mountEntitiesNeedingRootParent) {\n        const co = world.get(mountE, childOfToken);\n        if (co.ok && (co.value as { parent: number }).parent === ENTITY_NULL_RAW) {\n          world.removeComponent(mountE, childOfToken);\n        }\n      }\n    }\n\n    return ok({ roots: [...rootEntities, ...mountEntitiesNeedingRootParent], mountEntities });\n  } finally {\n    sourceReferences.value();\n  }\n}\n/** @internal Build ComponentData[] for one SceneEntity, remapping localIds.\n *\n * SceneAsset payloads use the same schema contract as explicit ECS writes.\n * Unknown fields fail before the first entity is spawned, with the component\n * schema's structured error. The source object is never mutated.\n */\nexport function worldBuildSceneEntityComponentDatas(\n  world: World,\n  node: CompiledSceneEntity,\n  mapping: Uint32Array,\n  _diagnostics: SceneInstantiateDiagnostic[],\n): Result<ComponentData[], EcsError> {\n  const out: ComponentData[] = [];\n  const nodeLocalId = node.localId as unknown as number;\n  for (const compName of Object.keys(node.components)) {\n    const token = world.components.resolve(compName);\n    if (token === undefined) {\n      return err(new ComponentNotDefinedError(compName));\n    }\n    const raw = node.components[compName] ?? {};\n    const schema = componentSchema(token) as Record<string, string>;\n    const remappedRaw: Record<string, unknown> = {};\n    for (const fieldName of Object.keys(raw)) {\n      const fieldType = schema[fieldName];\n      // Do not mutate the source `raw`. SceneAsset compilation normally catches\n      // this earlier; this guard keeps the private numeric projection fail-fast\n      // for callers that provide a precompiled asset.\n      if (fieldType === undefined) {\n        return err({\n          code: 'spawn-data-unknown-field',\n          expected: `field name in {${Object.keys(schema).sort().join(', ')}}`,\n          hint: `unknown field '${fieldName}' on component '${compName}' at scene localId ${nodeLocalId}`,\n          detail: {\n            component: compName,\n            field: fieldName,\n            entity: nodeLocalId,\n            knownFields: Object.keys(schema).sort(),\n          },\n        } as unknown as EcsError);\n      }\n      const value = (raw as Record<string, unknown>)[fieldName];\n      const kind = classifyEntityField(token, fieldName);\n      if (kind !== null) {\n        // Entity / array<entity> field — remap through the shared kernel.\n        // localId -> live Entity. Slots not yet spawned hold ENTITY_NULL_RAW.\n        const sceneRemap = (localId: number): number => {\n          if (localId < 0 || localId >= mapping.length) return ENTITY_NULL_RAW;\n          const live = mapping[localId];\n          return live === undefined || live === ENTITY_NULL_RAW ? ENTITY_NULL_RAW : live;\n        };\n        remappedRaw[fieldName] = remapEntityFieldValue(value, kind, sceneRemap);\n      } else {\n        remappedRaw[fieldName] = value;\n      }\n    }\n    const filled = fillComponentDefaults(token, remappedRaw);\n    out.push({ component: token, data: filled as never });\n  }\n  return ok(out);\n}\n\n/**\n * Resolve the private local-slot values produced by keyed SceneAsset\n * compilation before an instance override is written to a live ECS row.\n * Override references are authored in the declaring parent namespace, while\n * `worldApplyMountOverride` deliberately accepts ordinary live component data.\n */\nfunction worldRemapMountOverride(\n  world: World,\n  override: MountOverride,\n  mapping: Uint32Array,\n): MountOverride {\n  const token = world.components.resolve(override.comp);\n  if (token === undefined) return override;\n  const remapField = (field: string, value: unknown): unknown => {\n    const kind = classifyEntityField(token as Component, field);\n    if (kind === null) return value;\n    const toLive = (slot: number): number => {\n      if (slot < 0 || slot >= mapping.length) return ENTITY_NULL_RAW;\n      return mapping[slot] ?? ENTITY_NULL_RAW;\n    };\n    return remapEntityFieldValue(value, kind, toLive);\n  };\n  if (override.field !== undefined) {\n    return { ...override, value: remapField(override.field, override.value) };\n  }\n  if (\n    typeof override.value !== 'object' ||\n    override.value === null ||\n    Array.isArray(override.value)\n  ) {\n    return override;\n  }\n  const value: Record<string, unknown> = {};\n  for (const [field, fieldValue] of Object.entries(override.value as Record<string, unknown>)) {\n    value[field] = remapField(field, fieldValue);\n  }\n  return { ...override, value };\n}\n\n/**\n * @internal feat-20260713 M2 / w8: apply one MountOverride to a live member\n * entity column. The `field?` shape is the add-or-patch discriminant:\n *\n *   - `field` present -> PATCH one field: `world.set(member, comp, {[field]:\n *     value})`. Omitted fields keep their authored / existing values.\n *   - `field` absent  -> ADD/UPSERT the whole component: `value` is the\n *     per-field value map for `comp`. When the member already carries `comp`\n *     it is upserted (set-over each supplied field + schema defaults for the\n *     omitted ones — the whole component is rewritten from the value map +\n *     defaults, never a `component-already-present` error). When absent it is\n *     added fresh via `addComponent` (fillComponentDefaults fills omitted\n *     fields). The value-map is fed through `fillComponentDefaults` so the\n *     add and upsert paths write byte-identical rows.\n *\n * Component registration + value-key validation happened at\n * `_validateMountOverrides` (fail-fast before any spawn); by this point the\n * comp resolves through the World-local catalog and the value keys are schema-valid.\n * still guards defensively (an unregistered comp is a no-op skip, matching\n * the prior field-patch behaviour). Returns the underlying set / addComponent\n * Result so a shared-field value gate (D-4) or any other write error\n * propagates unchanged.\n */\nexport function worldApplyMountOverride(\n  world: World,\n  member: EntityHandle,\n  ov: MountOverride,\n): Result<void, EcsError> {\n  const ovToken = world.components.resolve(ov.comp);\n  if (ovToken === undefined) return ok(undefined);\n  if (ov.field !== undefined) {\n    // PATCH one field.\n    return world.set(member, ovToken, { [ov.field]: ov.value } as never);\n  }\n  // ADD/UPSERT the whole component. Fill omitted fields from the schema so\n  // add and upsert produce identical rows (upsert = full rewrite from the\n  // value map + defaults).\n  const rawValue = (ov.value ?? {}) as Record<string, unknown>;\n  const filled = fillComponentDefaults(ovToken as Component, rawValue);\n  const has = world.get(member, ovToken);\n  if (has.ok) {\n    // Already present -> upsert (set every filled field, no duplicate error).\n    return world.set(member, ovToken, filled as never);\n  }\n  return world.addComponent(member, { component: ovToken, data: filled as never });\n}\n/**\n * @internal R2/B-3 + R2/B-4: validate `mount.overrides[]` BEFORE any\n * spawn so a malformed override fails fast with no observable side\n * effects (charter P3 explicit-failure). Two checks:\n *\n * 1. `override.localId` must address a slot inside the parent-namespace\n *    member window `[memberFirst, memberFirst + memberCount)` (AC-06).\n * 2. `override.field` must exist in the resolved component schema\n *    (AC-07). When the component is unregistered we cannot validate the\n *    field shape; let the existing fall-through path proceed (the\n *    catalog guard inside the override-application loop\n *    will skip the write).\n */\nexport function worldValidateMountOverrides(\n  world: World,\n  mount: SceneInstanceMount,\n): Result<void, EcsError> {\n  const overrides = mount.overrides;\n  if (overrides === undefined) return ok(undefined);\n  const memberFirst = mount.memberFirst as unknown as number;\n  const memberCount = mount.memberCount;\n  const memberLast = memberFirst + memberCount;\n  const mountLid = mount.localId as unknown as number;\n  for (const ov of overrides) {\n    const ovLid = ov.localId as unknown as number;\n    // R2/B-3: parent-namespace check — override.localId must lie in the\n    // member window [memberFirst, memberFirst + memberCount).\n    if (ovLid < memberFirst || ovLid >= memberLast) {\n      return err({\n        code: 'pack-mount-override-localid-out-of-range' as PackErrorCode,\n        expected: `override.localId in [${memberFirst}, ${memberLast})`,\n        hint: PACK_ERROR_HINTS['pack-mount-override-localid-out-of-range'],\n        detail: {\n          code: 'pack-mount-override-localid-out-of-range',\n          overrideLocalId: ovLid,\n          mountLocalId: mountLid,\n          memberCount,\n        } as PackErrorDetail,\n      } as unknown as EcsError);\n    }\n    // feat-20260713 M2 / w8: double-branch schema check.\n    //   - field-patch form (field present): the component (when registered)\n    //     must declare `override.field` in its schema (R2/B-4, unchanged).\n    //   - component-add form (field absent): the component MUST be registered\n    //     (component-not-defined otherwise) AND every key in the value map\n    //     must be a schema field (pack-mount-override-unknown-field).\n    const ovToken = world.components.resolve(ov.comp);\n    if (ov.field !== undefined) {\n      if (ovToken !== undefined) {\n        const schema = componentSchema(ovToken) as Record<string, unknown>;\n        if (!(ov.field in schema)) {\n          return err({\n            code: 'pack-mount-override-unknown-field' as PackErrorCode,\n            expected: `override.field defined on component '${ov.comp}'`,\n            hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n            detail: {\n              code: 'pack-mount-override-unknown-field',\n              comp: ov.comp,\n              field: ov.field,\n              mountLocalId: mountLid,\n            } as PackErrorDetail,\n          } as unknown as EcsError);\n        }\n      }\n    } else {\n      // component-add form: comp must be registered so we can validate + apply\n      // the whole component (add/upsert needs the schema).\n      if (ovToken === undefined) {\n        return err(new ComponentNotDefinedError(ov.comp));\n      }\n      const schema = componentSchema(ovToken) as Record<string, unknown>;\n      const valueMap = (ov.value ?? {}) as Record<string, unknown>;\n      for (const key of Object.keys(valueMap)) {\n        if (!(key in schema)) {\n          return err({\n            code: 'pack-mount-override-unknown-field' as PackErrorCode,\n            expected: `override.value keys defined on component '${ov.comp}'`,\n            hint: PACK_ERROR_HINTS['pack-mount-override-unknown-field'],\n            detail: {\n              code: 'pack-mount-override-unknown-field',\n              comp: ov.comp,\n              field: key,\n              mountLocalId: mountLid,\n            } as PackErrorDetail,\n          } as unknown as EcsError);\n        }\n      }\n    }\n  }\n  return ok(undefined);\n}\n/** @internal Spawn the mount-entity slot carrying mount.components (if any).\n *\n * R2/B-1: the mount entity is a structural intermediate in the ChildOf\n * chain `cube -> innerSyntheticRoot -> mountEntity -> outerSyntheticRoot`,\n * so it MUST carry Transform whenever Transform is registered (mirrors\n * the D-V-0 synthetic-root invariant). Otherwise propagateTransforms\n * expanding the chain hits a Transform-less parent and emits per-frame\n * `RhiError(hierarchy-broken)` (verify R1 root cause of the\n * hello-scene-nesting demo black frames).\n */\nexport function worldSpawnMountEntity(\n  world: World,\n  mount: SceneInstanceMount,\n  mapping: Uint32Array,\n  diagnostics: SceneInstantiateDiagnostic[],\n): Result<EntityHandle, EcsError> {\n  const fakeNode: CompiledSceneEntity = {\n    localId: mount.localId,\n    components: mount.components ?? {},\n  };\n  const cdRes = worldBuildSceneEntityComponentDatas(world, fakeNode, mapping, diagnostics);\n  if (!cdRes.ok) return cdRes;\n  // R2/B-1: ensure Transform is attached so propagateTransforms can expand\n  // through this entity. Layer-2 defaults supply identity TRS; the\n  // mount.components overlay (when present and including Transform) takes\n  // precedence and is already in cdRes.value.\n  const transformToken = world.components.resolve('Transform');\n  if (transformToken !== undefined) {\n    const hasTransform = cdRes.value.some((c) => c.component === transformToken);\n    if (!hasTransform) {\n      cdRes.value.push({ component: transformToken, data: {} as never });\n    }\n  }\n  if (cdRes.value.length === 0) {\n    // Mount has no components AND Transform is unregistered (rare unit-\n    // test path). Fall back to the placeholder ChildOf so the spawn has\n    // a real archetype. Step 5 overwrites this placeholder.\n    const childOfToken = world.components.resolve('ChildOf');\n    if (childOfToken === undefined) {\n      return err(new ComponentNotDefinedError('ChildOf'));\n    }\n    cdRes.value.push({\n      component: childOfToken,\n      data: { parent: ENTITY_NULL_RAW } as never,\n    });\n  }\n  return (world.spawn as (...c: ComponentData[]) => Result<EntityHandle, EcsError>)(...cdRes.value);\n}\n/** @internal Resolve mount.source through the wired SceneAssetResolver. */\nexport function worldResolveMountSource(\n  world: World,\n  source: number | string,\n  parentHandle: Handle<'SceneAsset', 'shared'>,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n  const resolver = worldGetSceneAssetResolver(world);\n  if (resolver === null) {\n    return err({\n      code: 'stale-entity' as const,\n      expected: 'wired SceneAssetResolver (auto-wired by engine.assets.instantiate)',\n      hint:\n        'engine.assets.instantiate sugar wires this for you; ' +\n        'call worldSetSceneAssetResolver before nested scene expansion.',\n      detail: { entity: 0, slot: 0, generation: 0 },\n    } as unknown as EcsError);\n  }\n  const r = resolver(source, parentHandle);\n  if (!r.ok) {\n    // Resolver carries `unknown` err (loose contract — engine-runtime may\n    // wire any shape); narrow back to EcsError here at the boundary.\n    return err(r.error as EcsError);\n  }\n  return ok(r.value);\n}\n/**\n * Public sugar — get the SceneInstanceState (Map / Set view) for\n * `root`. Equivalent to `world.get(root, SceneInstance)` followed by a\n * managed-ref resolution; provided so AI users do not have to learn the\n * `ref<T>` slot resolution mechanic for the common read path.\n *\n * Returns Err when `root` does not carry SceneInstance or the ref slot is dead.\n */\nexport function worldGetSceneInstanceState(\n  world: World,\n  root: EntityHandle,\n): Result<SceneInstanceState, EcsError> {\n  const sceneInstanceToken = world.components.resolve('SceneInstance');\n  if (sceneInstanceToken === undefined) {\n    return err(new ComponentNotDefinedError('SceneInstance'));\n  }\n  const r = world.get(root, sceneInstanceToken);\n  if (!r.ok) return r;\n  const stateRefRaw = (r.value as unknown as { state: number }).state;\n  const stateRefHandle = toUnique<'SceneInstanceState'>(stateRefRaw);\n  const payload = world.resolveUniqueRef<SceneInstanceState>(stateRefHandle);\n  if (!payload.ok) {\n    return err(\n      new StaleEntityError(root as unknown as number, entityIndex(root), entityGeneration(root), {\n        operation: 'resolveSceneInstanceState',\n        component: 'SceneInstance',\n        expectedGeneration: entityGeneration(root),\n        actualGeneration: entityGeneration(root),\n      }),\n    );\n  }\n  return payload;\n}\n\n/** Resolve a generated SceneEntityRef against one concrete SceneInstance. */\nexport function worldResolveSceneEntity(\n  world: World,\n  root: EntityHandle,\n  ref: SceneEntityRef,\n): Result<EntityHandle, EcsError> {\n  const state = worldGetSceneInstanceState(world, root);\n  if (!state.ok) return state;\n  // Anonymous POD scenes remain addressable with an explicit empty source key.\n  // Never let the caller supply the identity used for the comparison: that\n  // would make an anonymous instance accept a fabricated persistent ref.\n  const resolved = resolveSceneEntity(ref, {\n    sceneSourceKey: state.value.sceneSourceKey ?? '',\n    bindings: state.value.bindings,\n  });\n  if (!resolved.ok) return err(resolved.error as unknown as EcsError);\n  return ok(resolved.value as EntityHandle);\n}\n/**\n * Despawn a SceneInstance root + all its members. `opts.keepDetached`\n * preserves members marked via `worldDetachSceneMember` (plan-strategy\n * §D-5). Returns the count of entities actually despawned (root + each\n * non-detached member).\n *\n * For a plain entity (no SceneInstance), behaviour matches\n * `world.despawn(entity)` followed by `despawnDescendants(entity)` — i.e.\n * `keepDetached` is a no-op.\n */\nexport function worldDespawnScene(\n  world: World,\n  root: EntityHandle,\n  opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n  const dRes = worldDespawnDescendants(world, root, opts);\n  if (!dRes.ok) return dRes;\n  const drop = world.despawn(root);\n  if (!drop.ok) return drop;\n  return ok(dRes.value + 1);\n}\n/**\n * Despawn every descendant of `root` reachable through Children mirror /\n * SceneInstance.mapping. `opts.keepDetached` is honoured only when `root`\n * carries a SceneInstance (otherwise the option is ignored — there is no\n * detached set on a plain entity).\n *\n * Returns the count of entities despawned. The `root` itself is NOT\n * despawned (that is `despawnScene`'s extra step).\n */\nexport function worldDespawnDescendants(\n  world: World,\n  root: EntityHandle,\n  opts?: { keepDetached?: boolean },\n): Result<number, EcsError> {\n  let detached: Set<LocalEntityId> | null = null;\n  let entityToLocalId: Map<EntityHandle, LocalEntityId> | null = null;\n  if (opts?.keepDetached === true) {\n    const stateRes = worldGetSceneInstanceState(world, root);\n    if (stateRes.ok) {\n      detached = stateRes.value.detachedLocalIds;\n      entityToLocalId = stateRes.value.entityToLocalId;\n    }\n  }\n  let count = 0;\n  // Collect descendants first (DFS via iterDescendants) to avoid mutating\n  // while iterating. SceneInstance.mapping also owns members that may not be\n  // reachable through a Children mirror in a partially registered host. The\n  // nested anchor list closes that same ownership boundary for mounted scenes.\n  const list: EntityHandle[] = [];\n  const seen = new Set<number>();\n  const collect = (anchor: EntityHandle): void => {\n    for (const e of world.iterDescendants(anchor)) {\n      const raw = e as unknown as number;\n      if (!seen.has(raw)) {\n        seen.add(raw);\n        list.push(e);\n      }\n    }\n    const stateRes = worldGetSceneInstanceState(world, anchor);\n    if (!stateRes.ok) return;\n    for (const e of stateRes.value.entityToLocalId.keys()) {\n      const raw = e as unknown as number;\n      if (!seen.has(raw)) {\n        seen.add(raw);\n        list.push(e);\n      }\n    }\n    for (const nestedRoot of stateRes.value.mountRoots) {\n      const raw = nestedRoot as unknown as number;\n      if (seen.has(raw)) continue;\n      seen.add(raw);\n      list.push(nestedRoot);\n      collect(nestedRoot);\n    }\n  };\n  collect(root);\n  const childOfToken = world.components.resolve('ChildOf');\n  // ChildOf uses linkedSpawn, so a parent-first pass would recursively retire\n  // its children before this function can count them. Sort the ownership set\n  // by its live ChildOf depth instead of relying on mirror traversal order;\n  // nested SceneInstance roots are siblings of their mount carrier in the\n  // flattened traversal but parents of the mounted members.\n  const owned = new Set(list.map((entity) => Number(entity)));\n  const ownedDepth = (entity: EntityHandle): number => {\n    if (childOfToken === undefined) return 0;\n    let current = entity;\n    let depth = 0;\n    const visited = new Set<number>();\n    while (!visited.has(Number(current))) {\n      visited.add(Number(current));\n      const parentRes = world.get(current, childOfToken);\n      if (!parentRes.ok) break;\n      const parent = (parentRes.value as { parent: EntityHandle }).parent;\n      if (!owned.has(Number(parent))) break;\n      depth += 1;\n      current = parent;\n    }\n    return depth;\n  };\n  list.sort((a, b) => ownedDepth(b) - ownedDepth(a));\n  for (const e of list) {\n    if (detached !== null) {\n      const lid = entityToLocalId?.get(e);\n      if (lid !== undefined && detached.has(lid)) {\n        if (childOfToken !== undefined) {\n          world.removeComponent(e, childOfToken);\n        }\n        continue;\n      }\n    }\n    const r = world.despawn(e);\n    if (!r.ok) {\n      if (r.error.code === 'stale-entity') continue;\n      return r;\n    }\n    count += 1;\n  }\n  return ok(count);\n}\n/**\n * Write a runtime override to a member entity belonging to `root`. Routes\n * through `world.set(member, comp, { [field]: value })` after an entity-\n * scope guard so cross-instance writes fail-fast. Type-mismatch surfaces\n * `EcsErrorCode = 'scene-override-type-mismatch'` (D-9).\n */\nexport function worldSetSceneOverride<S extends ComponentSchema>(\n  world: World,\n  root: EntityHandle,\n  member: EntityHandle,\n  component: Component<string, S>,\n  field: keyof ShapeOf<S> & string,\n  value: unknown,\n): Result<void, EcsError> {\n  const stateRes = worldGetSceneInstanceState(world, root);\n  if (!stateRes.ok) return stateRes;\n  const state = stateRes.value;\n  const lid = state.entityToLocalId.get(member);\n  if (lid === undefined) {\n    return err(\n      new StaleEntityError(\n        member as unknown as number,\n        entityIndex(member),\n        entityGeneration(member),\n        {\n          operation: 'setSceneOverride',\n          component: component.name,\n          expectedGeneration: entityGeneration(member),\n          actualGeneration: entityGeneration(member),\n        },\n      ),\n    );\n  }\n  // Type guard: only check primitive scalar field types where we can\n  // narrow `typeof`; ref / handle / entity / array / buffer fields skip\n  // (write would surface a deeper error from set).\n  const schemaType = (componentSchema(component) as Record<string, string>)[field];\n  if (schemaType !== undefined && isPrimitiveScalarFieldType(schemaType)) {\n    const expectJsType = primitiveJsType(schemaType);\n    const actualJsType = typeof value;\n    if (expectJsType !== actualJsType) {\n      return err({\n        code: 'scene-override-type-mismatch' as const,\n        expected: `value typeof === ${expectJsType}`,\n        hint:\n          `setSceneOverride(${component.name}.${field}) expected ${expectJsType}, ` +\n          `got ${actualJsType}; coerce or pick a different override path.`,\n        detail: {\n          code: 'scene-override-type-mismatch' as const,\n          comp: component.name,\n          field: field as string,\n          expectedType: schemaType,\n          actualType: actualJsType,\n        },\n      } as unknown as EcsError);\n    }\n  }\n  const setRes = world.set(member, component, { [field]: value } as Partial<InputShapeOf<S>>);\n  if (!setRes.ok) return setRes;\n  // Record into state.overrides\n  let fieldMap = state.overrides.get(lid);\n  if (fieldMap === undefined) {\n    fieldMap = new Map();\n    state.overrides.set(lid, fieldMap);\n  }\n  fieldMap.set(`${component.name}:${field}`, {\n    comp: component.name,\n    field: field as string,\n    value,\n  });\n  return ok(undefined);\n}\n/**\n * Drop a runtime override (and any mount-time override for the same\n * (member, comp, field) triple); roll the live column value back to the\n * source SceneAsset's layer-1 explicit value (M2 v1 — M3+ widens to layer\n * 2/3 defaults via fillComponentDefaults).\n */\nexport function worldRemoveSceneOverride<S extends ComponentSchema>(\n  world: World,\n  root: EntityHandle,\n  member: EntityHandle,\n  component: Component<string, S>,\n  field: keyof ShapeOf<S> & string,\n): Result<void, EcsError> {\n  const stateRes = worldGetSceneInstanceState(world, root);\n  if (!stateRes.ok) return stateRes;\n  const state = stateRes.value;\n  const lid = state.entityToLocalId.get(member);\n  if (lid === undefined) return ok(undefined);\n  const fieldMap = state.overrides.get(lid);\n  if (fieldMap !== undefined) {\n    fieldMap.delete(`${component.name}:${field}`);\n    if (fieldMap.size === 0) state.overrides.delete(lid);\n  }\n  // Look up the source SceneAsset layer-1 value.\n  const assetRes = worldResolveSceneAsset(world, state.source);\n  if (!assetRes.ok) return assetRes;\n  const key = state.keyByLocalId.get(lid as unknown as number);\n  const node = key === undefined ? undefined : assetRes.value.entities[key];\n  const layer1 = node?.components[component.name] as Record<string, unknown> | undefined;\n  if (layer1 !== undefined && field in layer1) {\n    const r = world.set(member, component, { [field]: layer1[field] } as Partial<InputShapeOf<S>>);\n    if (!r.ok) return r;\n  }\n  return ok(undefined);\n}\n/** Mark a member entity detached. Idempotent (set semantics). */\nexport function worldDetachSceneMember(\n  world: World,\n  root: EntityHandle,\n  member: EntityHandle,\n): Result<void, EcsError> {\n  const sceneInstanceToken = world.components.resolve('SceneInstance');\n  if (sceneInstanceToken === undefined) {\n    return err(new ComponentNotDefinedError('SceneInstance'));\n  }\n  const stateRes = worldGetSceneInstanceState(world, root);\n  if (!stateRes.ok) return stateRes;\n  const state = stateRes.value;\n  const lid = state.entityToLocalId.get(member);\n  if (lid === undefined) return ok(undefined);\n  state.detachedLocalIds.add(lid);\n  return ok(undefined);\n}\n/** Clear a detached mark. Idempotent (set semantics). */\nexport function worldReattachSceneMember(\n  world: World,\n  root: EntityHandle,\n  member: EntityHandle,\n): Result<void, EcsError> {\n  const stateRes = worldGetSceneInstanceState(world, root);\n  if (!stateRes.ok) return stateRes;\n  const state = stateRes.value;\n  const lid = state.entityToLocalId.get(member);\n  if (lid === undefined) return ok(undefined);\n  state.detachedLocalIds.delete(lid);\n  return ok(undefined);\n}\n/**\n * Get the SceneAsset handle a SceneInstance root was instantiated from.\n * Returns Err on a plain entity (no SceneInstance component).\n */\nexport function worldGetSceneAssetForInstance(\n  world: World,\n  root: EntityHandle,\n): Result<Handle<'SceneAsset', 'shared'>, EcsError> {\n  const stateRes = worldGetSceneInstanceState(world, root);\n  if (!stateRes.ok) return stateRes;\n  return ok(stateRes.value.source);\n}\n\n/**\n * Topological sort over the implicit ChildOf graph (parents before children).\n * Cycle-free input always covers all n nodes; cyclic input emits whatever was\n * reachable from indegree-0 (the fallback caller handles cycle reporting via\n * `pack-cyclic-reference` at the upstream scanner / runtime path).\n */\nfunction sceneTopoSort(nodes: readonly CompiledSceneEntity[]): readonly number[] {\n  const n = nodes.length;\n  const childrenOf: number[][] = Array.from({ length: n }, () => []);\n  const indeg = new Uint32Array(n);\n  const localIdToIdx = new Map<number, number>();\n  for (let i = 0; i < n; i += 1) {\n    const node = nodes[i];\n    if (node === undefined) continue;\n    localIdToIdx.set(node.localId as unknown as number, i);\n  }\n  for (let i = 0; i < n; i += 1) {\n    const node = nodes[i];\n    if (node === undefined) continue;\n    const child = node.components.ChildOf;\n    if (child === undefined) continue;\n    const p = (child as Record<string, unknown>).parent;\n    if (typeof p === 'number') {\n      const parentIdx = localIdToIdx.get(p);\n      if (parentIdx !== undefined && parentIdx !== i) {\n        childrenOf[parentIdx]?.push(i);\n        indeg[i] = (indeg[i] ?? 0) + 1;\n      }\n    }\n  }\n  const order: number[] = [];\n  const queue: number[] = [];\n  for (let i = 0; i < n; i += 1) if ((indeg[i] ?? 0) === 0) queue.push(i);\n  while (queue.length > 0) {\n    const head = queue.shift();\n    if (head === undefined) break;\n    order.push(head);\n    for (const c of childrenOf[head] ?? []) {\n      indeg[c] = (indeg[c] ?? 0) - 1;\n      if ((indeg[c] ?? 0) === 0) queue.push(c);\n    }\n  }\n  // Append any nodes left unvisited (defensive — cycle would surface here).\n  for (let i = 0; i < n; i += 1) {\n    if (!order.includes(i) && nodes[i] !== undefined) order.push(i);\n  }\n  return order;\n}\n","import type { EcsError, World } from '@forgeax/engine-ecs';\nimport { componentSchema } from '@forgeax/engine-ecs/internal';\nimport { BUILTIN_BASE, err, ok, type Result, type SceneAsset } from '@forgeax/engine-types';\n\n/** The instance source remains readable when a live component is overridden. */\nexport function retainSceneSourceReferences(\n  world: World,\n  asset: SceneAsset,\n): Result<() => void, EcsError> {\n  const handles = new Set<number>();\n  const collect = (components: SceneAsset['entities'][string]['components']) => {\n    for (const [name, values] of Object.entries(components)) {\n      const token = world.components.resolve(name);\n      if (!token || !values) continue;\n      const schema = componentSchema(token);\n      for (const [field, value] of Object.entries(values)) {\n        const shape = schema[field];\n        const refs = shape?.startsWith('shared<')\n          ? [value]\n          : shape?.startsWith('array<shared<') &&\n              (Array.isArray(value) || ArrayBuffer.isView(value))\n            ? Array.from(value as ArrayLike<unknown>)\n            : [];\n        for (const ref of refs)\n          if (typeof ref === 'number' && ref >= BUILTIN_BASE) handles.add(ref);\n      }\n    }\n  };\n  for (const node of Object.values(asset.entities)) {\n    collect(node.components);\n    for (const override of node.instance?.overrides ?? []) collect(override.components);\n  }\n  const retained: number[] = [];\n  const release = () => {\n    for (const handle of retained.splice(0)) world.sharedRefs.release(handle as never);\n  };\n  for (const handle of handles) {\n    const result = world.sharedRefs.retain(handle as never);\n    if (!result.ok) {\n      release();\n      return err(result.error as unknown as EcsError);\n    }\n    retained.push(handle);\n  }\n  return ok(release);\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type { SceneEntityRef } from '@forgeax/engine-types';\nimport { sceneEntity, sceneEntityAddressFromKey } from './binding.js';\nimport { worldGetSceneInstanceState } from './scene-instances.js';\n\n/**\n * @internal Reverse keyed-binding lookup for diagnostics. Prefers the outermost\n * instance (no parent `instanceKey`), whose address spans nested instances.\n * Returns undefined for entities that no SceneInstance binds.\n */\nexport function worldSceneEntityRefOf(\n  world: World,\n  entity: EntityHandle,\n): SceneEntityRef | undefined {\n  const component = world.components.resolve('SceneInstance');\n  if (component === undefined) return undefined;\n  const query = world.query({ read: [component] });\n  if (!query.ok) return undefined;\n  let nested: SceneEntityRef | undefined;\n  for (const row of query.value) {\n    const resolved = worldGetSceneInstanceState(world, row.entity);\n    if (!resolved.ok) continue;\n    const state = resolved.value;\n    for (const [key, bound] of state.bindings) {\n      if (bound !== entity) continue;\n      const ref = sceneEntity(state.sceneSourceKey ?? '', sceneEntityAddressFromKey(key));\n      if (state.instanceKey === undefined) return ref;\n      nested ??= ref;\n    }\n  }\n  return nested;\n}\n","import type { EntityHandle, World } from '@forgeax/engine-ecs';\nimport type {\n  MobilityDiagnostic,\n  MobilityDiagnosticCode,\n  MobilityDiagnosticSubject,\n} from './errors';\nimport { worldSceneEntityRefOf } from './instances/entity-ref';\n\n/** Producer-supplied facts for one violation; scene derives entity location and text. */\nexport type MobilityViolation = MobilityDiagnostic extends infer D\n  ? D extends MobilityDiagnostic\n    ? { readonly code: D['code'] } & Omit<D['detail'], keyof MobilityDiagnosticSubject>\n    : never\n  : never;\n\nexport type MobilityDiagnosticListener = (\n  world: World,\n  diagnostic: Readonly<MobilityDiagnostic>,\n) => void;\n\nconst MOBILITY_TEXT: Readonly<\n  Record<MobilityDiagnosticCode, { readonly expected: string; readonly hint: string }>\n> = {\n  'mobility-invalid-kind': {\n    expected:\n      \"Mobility 'stationary' only on light entities; mesh entities are 'static' or 'movable'\",\n    hint: 'set Mobility.kind to MobilityKindValue.static (never moves) or MobilityKindValue.movable, or remove Mobility',\n  },\n  'mobility-static-moved': {\n    expected: \"an entity with Mobility 'static' keeps its Transform after placement\",\n    hint: 'declare MobilityKindValue.movable (or remove Mobility) on entities that move; rendering stays correct, but static caches and baked data for this entity become stale',\n  },\n  'mobility-physics-conflict': {\n    expected: \"Mobility 'static' only with no RigidBody or RigidBody type 'static'\",\n    hint: \"declare MobilityKindValue.movable for simulated or kinematic bodies, or set RigidBody.type to 'static'; neither component is derived from the other\",\n  },\n};\n\nconst reportedByWorld = new WeakMap<World, Set<string>>();\nconst listeners = new Set<MobilityDiagnosticListener>();\n\n/** Observe Mobility violations. Each `(World, code, entity)` is reported once. */\nexport function subscribeMobilityDiagnostics(listener: MobilityDiagnosticListener): () => void {\n  listeners.add(listener);\n  return () => listeners.delete(listener);\n}\n\n/**\n * Report one Mobility violation found by its detecting owner. Returns false when\n * the same `(code, entity)` was already reported for this World.\n */\nexport function emitMobilityDiagnostic(\n  world: World,\n  entity: EntityHandle,\n  violation: MobilityViolation,\n): boolean {\n  let reported = reportedByWorld.get(world);\n  if (reported === undefined) {\n    reported = new Set();\n    reportedByWorld.set(world, reported);\n  }\n  const key = `${violation.code}|${entity}`;\n  if (reported.has(key)) return false;\n  reported.add(key);\n\n  const sceneEntityRef = worldSceneEntityRefOf(world, entity);\n  const { code, ...facts } = violation;\n  const diagnostic = Object.freeze({\n    code,\n    ...MOBILITY_TEXT[code],\n    detail: Object.freeze({\n      ...facts,\n      entity,\n      ...(sceneEntityRef === undefined ? {} : { sceneEntityRef }),\n    }),\n  }) as MobilityDiagnostic;\n  for (const listener of listeners) {\n    try {\n      listener(world, diagnostic);\n    } catch {\n      // Diagnostics must never break the detecting system.\n    }\n  }\n  console.warn(diagnostic);\n  return true;\n}\n","import { type EntityHandle, type Query, Update, type World } from '@forgeax/engine-ecs';\nimport { Mobility, MobilityKindValue } from '../components/mobility';\nimport { Transform } from '../components/transform';\nimport { emitMobilityDiagnostic } from '../mobility-diagnostics';\n\nexport const MOBILITY_STATIC_MOVED_SYSTEM = 'mobilityStaticMoved' as const;\n\ninterface StaticMovedQueries {\n  readonly declared: Query;\n  readonly moved: Query;\n}\n\nconst QUERIES = new WeakMap<World, StaticMovedQueries>();\n\nfunction queriesFor(world: World): StaticMovedQueries {\n  let queries = QUERIES.get(world);\n  if (queries === undefined) {\n    queries = {\n      declared: world.query({ with: [Transform], added: [Mobility] }).unwrap(),\n      moved: world.query({ read: [Mobility], with: [Transform], changed: [Transform] }).unwrap(),\n    };\n    QUERIES.set(world, queries);\n  }\n  return queries;\n}\n\n/**\n * Report `mobility-static-moved` for static entities whose Transform changed\n * after the frame that declared them static. Initial placement (Transform\n * written in the same frame Mobility is added) is not a violation.\n */\nexport function detectMobilityStaticMoved(world: World): void {\n  const { declared, moved } = queriesFor(world);\n  const placed = new Set<number>();\n  for (const span of declared.spans().unwrap()) {\n    for (let row = 0; row < span.length; row += 1) placed.add(span.entities[row] as number);\n  }\n  const violations: EntityHandle[] = [];\n  for (const span of moved.spans().unwrap()) {\n    const kinds = span.get(Mobility).kind;\n    for (let row = 0; row < span.length; row += 1) {\n      if (kinds[row] !== MobilityKindValue.static) continue;\n      const entity = span.entities[row] as number;\n      if (!placed.has(entity)) violations.push(entity as EntityHandle);\n    }\n  }\n  for (const entity of violations) {\n    emitMobilityDiagnostic(world, entity, { code: 'mobility-static-moved' });\n  }\n}\n\nexport function registerMobilityStaticMoved(world: World): () => void {\n  world\n    .addSystem(Update, {\n      name: MOBILITY_STATIC_MOVED_SYSTEM,\n      queries: [],\n      fn: detectMobilityStaticMoved,\n    })\n    .unwrap();\n  return () => {\n    world.removeSystem(Update, MOBILITY_STATIC_MOVED_SYSTEM);\n    QUERIES.delete(world);\n  };\n}\n","import {\n  defineSystem,\n  defineSystemSet,\n  type EcsError,\n  ENTITY_NULL_RAW,\n  type EntityHandle,\n  FixedUpdate,\n  type Query,\n  type SystemHandle,\n  Update,\n  type World,\n} from '@forgeax/engine-ecs';\nimport {\n  type DerivedColumnBinding,\n  type DerivedRangeCursor,\n  type DerivedRangeWriter,\n  getDerivedWriter,\n} from '@forgeax/engine-ecs/internal';\nimport { createStateProjection, type StateProjection } from '@forgeax/engine-ecs/projection';\nimport { worldRead } from '@forgeax/engine-ecs/world-read';\nimport { type Mat4, mat4 } from '@forgeax/engine-math';\nimport { err, ok, type Result } from '@forgeax/engine-types';\nimport { ChildOf } from '../components/child-of';\nimport { Children } from '../components/children';\nimport { GlobalTransform, Transform } from '../components/transform';\nimport { SceneError } from '../errors';\n\nexport const PROPAGATE_TRANSFORMS_SYSTEM = 'propagateTransforms' as const;\nexport const PROPAGATE_TRANSFORMS_FIXED_SYSTEM = 'propagateTransformsFixed' as const;\nexport const TransformSet = defineSystemSet({ name: 'transform' });\nexport const TransformFixedSet = defineSystemSet({ name: 'transform-fixed' });\n\n/**\n * Optional, test-owned counters for the parent-first executor. The counters\n * are disabled unless a caller brackets a run with begin/end; production\n * propagation therefore pays only one predictable branch per instrumented\n * event. They are deliberately not a second execution state or a public\n * dirty/cache contract.\n */\nexport interface TransformPropagationTrace {\n  hierarchyRootInvocations: number;\n  hierarchyRootCursorReuses: number;\n  hierarchyRootCursorAllocations: number;\n  hierarchyEntityLookups: number;\n  hierarchyRowsEvaluated: number;\n  hierarchyEdgesVisited: number;\n  hierarchyPublishedRows: number;\n  hierarchyPublishedRuns: number;\n  hierarchyResidualParentProbes: number;\n  flatStructuralRootRows: number;\n}\n\nlet propagationTrace: TransformPropagationTrace | undefined;\nlet hierarchyRootCursorAllocationCount = 0;\nlet propagationTraceRootCursorAllocationStart = 0;\n\nfunction createHierarchyRootCursor(): DerivedRangeCursor {\n  hierarchyRootCursorAllocationCount += 1;\n  return { bindingIndex: -1, row: -1 };\n}\n\nexport function beginTransformPropagationTrace(): void {\n  propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n  propagationTrace = {\n    hierarchyRootInvocations: 0,\n    hierarchyRootCursorReuses: 0,\n    hierarchyRootCursorAllocations: 0,\n    hierarchyEntityLookups: 0,\n    hierarchyRowsEvaluated: 0,\n    hierarchyEdgesVisited: 0,\n    hierarchyPublishedRows: 0,\n    hierarchyPublishedRuns: 0,\n    hierarchyResidualParentProbes: 0,\n    flatStructuralRootRows: 0,\n  };\n}\n\nexport function endTransformPropagationTrace(): TransformPropagationTrace {\n  const trace = propagationTrace;\n  propagationTrace = undefined;\n  const rootCursorAllocations =\n    hierarchyRootCursorAllocationCount - propagationTraceRootCursorAllocationStart;\n  propagationTraceRootCursorAllocationStart = hierarchyRootCursorAllocationCount;\n  if (trace !== undefined) {\n    trace.hierarchyRootCursorAllocations = rootCursorAllocations;\n    return trace;\n  }\n  return {\n    hierarchyRootInvocations: 0,\n    hierarchyRootCursorReuses: 0,\n    hierarchyRootCursorAllocations: 0,\n    hierarchyEntityLookups: 0,\n    hierarchyRowsEvaluated: 0,\n    hierarchyEdgesVisited: 0,\n    hierarchyPublishedRows: 0,\n    hierarchyPublishedRuns: 0,\n    hierarchyResidualParentProbes: 0,\n    flatStructuralRootRows: 0,\n  };\n}\n\nfunction countPropagation(name: keyof TransformPropagationTrace): void {\n  const trace = propagationTrace;\n  if (trace !== undefined) trace[name] += 1;\n}\n\ninterface Scratch {\n  position: Float32Array;\n  rotation: Float32Array;\n  scale: Float32Array;\n  local: Mat4;\n  parent: Mat4;\n  candidate: Mat4;\n  hierarchyStackEntities: EntityHandle[];\n  hierarchyStackChildren: number[];\n  hierarchyProbeEntities: EntityHandle[];\n  hierarchyCurrentCursor: DerivedRangeCursor;\n  hierarchyParentCursor: DerivedRangeCursor;\n  hierarchyChildCursor: DerivedRangeCursor;\n  hierarchyResidualCursor: DerivedRangeCursor;\n  hierarchyResidualParentCursor: DerivedRangeCursor;\n  hierarchyRootCursor: DerivedRangeCursor;\n  hierarchyStates: Uint8Array[];\n  hierarchyChanged: Uint8Array[];\n  hierarchyBindingTables: number[];\n  hierarchyBindingRows: number[];\n  flatChanged: Uint8Array[];\n  flatBindingTables: number[];\n  flatBindingRows: number[];\n  flatCursor: DerivedRangeCursor;\n  flatTouched: number[];\n  flatPublished: Uint8Array;\n  /**\n   * False until one full hierarchy pass succeeds, and again after any error.\n   * While true, every hierarchy row's world matrix is proven against its\n   * parent, so later frames only re-walk subtrees reached by change evidence.\n   */\n  hierarchyValid: boolean;\n  structure?: StateProjection;\n  dirtyTransforms?: Query<readonly [typeof Transform]>;\n  dirtyParents?: Query<readonly [typeof ChildOf]>;\n  dirtyGlobals?: Query<readonly [typeof GlobalTransform]>;\n  flatQuery?: FlatQuery;\n  hierarchyQuery?: HierarchyQuery;\n  transformQuery?: TransformQuery;\n  hierarchyWriter?: HierarchyWriter;\n  transformWriter?: TransformWriter;\n  missingGlobalQuery?: MissingGlobalQuery;\n  missingTransformQuery?: MissingTransformQuery;\n}\n\ntype FlatQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyQuery = Query<\n  readonly [typeof Transform, typeof ChildOf],\n  readonly [typeof GlobalTransform]\n>;\ntype TransformQuery = Query<readonly [typeof Transform], readonly [typeof GlobalTransform]>;\ntype HierarchyWriter = DerivedRangeWriter<\n  typeof Transform | typeof ChildOf,\n  typeof GlobalTransform\n>;\ntype TransformWriter = DerivedRangeWriter<typeof Transform, typeof GlobalTransform>;\ntype HierarchyBinding = DerivedColumnBinding<\n  typeof Transform | typeof ChildOf,\n  typeof GlobalTransform\n>;\ntype TransformBinding = DerivedColumnBinding<typeof Transform, typeof GlobalTransform>;\ntype MissingGlobalQuery = Query<readonly [], readonly [], readonly []>;\ntype MissingTransformQuery = Query<readonly [], readonly [], readonly []>;\n\ninterface RegistrationLease {\n  refs: number;\n}\n\nconst SCRATCH = new WeakMap<World, Scratch>();\nconst REGISTRATION_LEASES = new WeakMap<World, RegistrationLease>();\n\nfunction pairError<T = void>(entity: EntityHandle, expected: string): Result<T, SceneError> {\n  return err(\n    new SceneError({\n      code: 'hierarchy-broken',\n      expected,\n      hint: 'attach both Transform and GlobalTransform at scene authoring or import time, then retry propagation',\n      detail: { entity, parent: entity },\n    }),\n  );\n}\n\nfunction ensureQueries(world: World, scratch: Scratch): Result<void, SceneError> {\n  if (\n    scratch.flatQuery !== undefined &&\n    scratch.hierarchyQuery !== undefined &&\n    scratch.transformQuery !== undefined &&\n    scratch.hierarchyWriter !== undefined &&\n    scratch.transformWriter !== undefined &&\n    scratch.missingGlobalQuery !== undefined &&\n    scratch.missingTransformQuery !== undefined\n  ) {\n    return ok(undefined);\n  }\n  const flatOutput = world.query({\n    read: [Transform],\n    write: [GlobalTransform],\n    without: [ChildOf],\n    changed: [Transform],\n  });\n  scratch.dirtyTransforms ??= world.query({ read: [Transform], changed: [Transform] }).unwrap();\n  scratch.dirtyParents ??= world.query({ read: [ChildOf], changed: [ChildOf] }).unwrap();\n  scratch.dirtyGlobals ??= world\n    .query({ read: [GlobalTransform], changed: [GlobalTransform] })\n    .unwrap();\n  const hierarchy = world.query({ read: [Transform, ChildOf], write: [GlobalTransform] });\n  const transform = world.query({ read: [Transform], write: [GlobalTransform] });\n  const missingGlobal = world.query({ with: [Transform], without: [GlobalTransform] });\n  const missingTransform = world.query({ with: [GlobalTransform], without: [Transform] });\n  if (\n    !flatOutput.ok ||\n    !hierarchy.ok ||\n    !transform.ok ||\n    !missingGlobal.ok ||\n    !missingTransform.ok\n  ) {\n    return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n  }\n  const hierarchyWriter = getDerivedWriter(hierarchy.value, GlobalTransform);\n  const transformWriter = getDerivedWriter(transform.value, GlobalTransform);\n  if (!hierarchyWriter.ok || !transformWriter.ok) {\n    return pairError(0 as EntityHandle, 'dense Transform and ChildOf derived bindings');\n  }\n  scratch.flatQuery = flatOutput.value as FlatQuery;\n  scratch.hierarchyQuery = hierarchy.value as HierarchyQuery;\n  scratch.transformQuery = transform.value as TransformQuery;\n  scratch.hierarchyWriter = hierarchyWriter.value as HierarchyWriter;\n  scratch.transformWriter = transformWriter.value as TransformWriter;\n  scratch.missingGlobalQuery = missingGlobal.value as MissingGlobalQuery;\n  scratch.missingTransformQuery = missingTransform.value as MissingTransformQuery;\n  return ok(undefined);\n}\n\nfunction validateTransformPairs(world: World, scratch: Scratch): Result<void, SceneError> {\n  const queryResult = ensureQueries(world, scratch);\n  if (!queryResult.ok) return queryResult;\n  const missingGlobal = scratch.missingGlobalQuery;\n  const missingTransform = scratch.missingTransformQuery;\n  if (missingGlobal === undefined || missingTransform === undefined) {\n    return pairError(0 as EntityHandle, 'valid Transform and GlobalTransform pair queries');\n  }\n  for (const row of missingGlobal) {\n    return pairError(row.entity, 'each Transform entity to carry a GlobalTransform pair');\n  }\n  for (const row of missingTransform) {\n    return pairError(row.entity, 'each GlobalTransform entity to carry a Transform pair');\n  }\n  return ok(undefined);\n}\n\nfunction scratchFor(world: World): Scratch {\n  const existing = SCRATCH.get(world);\n  if (existing !== undefined) return existing;\n  const created = {\n    position: new Float32Array(3),\n    rotation: new Float32Array(4),\n    scale: new Float32Array(3),\n    local: mat4.create(),\n    parent: mat4.create(),\n    candidate: mat4.create(),\n    hierarchyStackEntities: [] as EntityHandle[],\n    hierarchyStackChildren: [] as number[],\n    hierarchyProbeEntities: [] as EntityHandle[],\n    hierarchyCurrentCursor: { bindingIndex: -1, row: -1 },\n    hierarchyParentCursor: { bindingIndex: -1, row: -1 },\n    hierarchyChildCursor: { bindingIndex: -1, row: -1 },\n    hierarchyResidualCursor: { bindingIndex: -1, row: -1 },\n    hierarchyResidualParentCursor: { bindingIndex: -1, row: -1 },\n    hierarchyRootCursor: createHierarchyRootCursor(),\n    hierarchyStates: [],\n    hierarchyChanged: [],\n    hierarchyBindingTables: [],\n    hierarchyBindingRows: [],\n    flatChanged: [],\n    flatBindingTables: [],\n    flatBindingRows: [],\n    flatCursor: { bindingIndex: -1, row: -1 },\n    flatTouched: [] as number[],\n    flatPublished: new Uint8Array(0),\n    hierarchyValid: false,\n  };\n  SCRATCH.set(world, created);\n  return created;\n}\n\nfunction composeColumns(\n  position: ArrayLike<number>,\n  rotation: ArrayLike<number>,\n  scale: ArrayLike<number>,\n  out: Mat4,\n  scratch: Scratch,\n  positionStart = 0,\n  rotationStart = 0,\n): void {\n  scratch.position[0] = position[positionStart] ?? 0;\n  scratch.position[1] = position[positionStart + 1] ?? 0;\n  scratch.position[2] = position[positionStart + 2] ?? 0;\n  scratch.rotation[0] = rotation[rotationStart] ?? 0;\n  scratch.rotation[1] = rotation[rotationStart + 1] ?? 0;\n  scratch.rotation[2] = rotation[rotationStart + 2] ?? 0;\n  scratch.rotation[3] = rotation[rotationStart + 3] ?? 1;\n  scratch.scale[0] = scale[positionStart] ?? 1;\n  scratch.scale[1] = scale[positionStart + 1] ?? 1;\n  scratch.scale[2] = scale[positionStart + 2] ?? 1;\n  mat4.compose(out, scratch.position, scratch.rotation, scratch.scale);\n}\n\nfunction composeFlatColumns(\n  positions: ArrayLike<number>,\n  rotations: ArrayLike<number>,\n  scales: ArrayLike<number>,\n  worlds: Float32Array,\n  count: number,\n): void {\n  for (let row = 0; row < count; row += 1) {\n    const position = row * 3;\n    const rotation = row * 4;\n    const world = row * 16;\n    const x = rotations[rotation] ?? 0;\n    const y = rotations[rotation + 1] ?? 0;\n    const z = rotations[rotation + 2] ?? 0;\n    const w = rotations[rotation + 3] ?? 1;\n    const x2 = x + x;\n    const y2 = y + y;\n    const z2 = z + z;\n    const xx = x * x2;\n    const xy = x * y2;\n    const xz = x * z2;\n    const yy = y * y2;\n    const yz = y * z2;\n    const zz = z * z2;\n    const wx = w * x2;\n    const wy = w * y2;\n    const wz = w * z2;\n    const sx = scales[position] ?? 1;\n    const sy = scales[position + 1] ?? 1;\n    const sz = scales[position + 2] ?? 1;\n\n    worlds[world] = (1 - (yy + zz)) * sx;\n    worlds[world + 1] = (xy + wz) * sx;\n    worlds[world + 2] = (xz - wy) * sx;\n    worlds[world + 3] = 0;\n    worlds[world + 4] = (xy - wz) * sy;\n    worlds[world + 5] = (1 - (xx + zz)) * sy;\n    worlds[world + 6] = (yz + wx) * sy;\n    worlds[world + 7] = 0;\n    worlds[world + 8] = (xz + wy) * sz;\n    worlds[world + 9] = (yz - wx) * sz;\n    worlds[world + 10] = (1 - (xx + yy)) * sz;\n    worlds[world + 11] = 0;\n    worlds[world + 12] = positions[position] ?? 0;\n    worlds[world + 13] = positions[position + 1] ?? 0;\n    worlds[world + 14] = positions[position + 2] ?? 0;\n    worlds[world + 15] = 1;\n  }\n}\n\nfunction propagateFlat(\n  world: World,\n  scratch: Scratch,\n  candidates: readonly EntityHandle[],\n  globalEdited: readonly EntityHandle[],\n): Result<EntityHandle[], SceneError> {\n  const query = scratch.flatQuery;\n  if (query === undefined)\n    return err(\n      new SceneError({\n        code: 'hierarchy-broken',\n        expected: 'a valid changed Transform write query',\n        hint: 'register the scene components before running TransformPropagation',\n      }),\n    );\n  const spans = query.spans();\n  if (!spans.ok) return pairError(0 as EntityHandle, 'dense numeric Transform spans');\n  let bindingIndex = 0;\n  try {\n    for (const span of spans.value) {\n      const local = span.get(Transform);\n      const world = span.mut(GlobalTransform).world;\n      composeFlatColumns(local.pos, local.quat, local.scale, world, span.length);\n      bindingIndex += 1;\n    }\n  } catch (cause) {\n    const error = cause as EcsError;\n    return err(derivedWriteError(error, bindingIndex));\n  }\n\n  // A structural relation change can turn an unchanged Transform row into a\n  // flat root (most importantly ChildOf removal), and an external\n  // GlobalTransform write can corrupt a flat root. The changed Transform query\n  // above observes neither, so re-derive only those candidate roots and\n  // report the ones whose world matrix changed so their subtrees re-walk.\n  const transformWriter = scratch.transformWriter;\n  if (transformWriter === undefined) {\n    return pairError(0 as EntityHandle, 'dense Transform and GlobalTransform derived bindings');\n  }\n  const changedRoots: EntityHandle[] = [];\n  if (candidates.length === 0 && globalEdited.length === 0) return ok(changedRoots);\n  const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n  ensureFlatBuffers(scratch, transformBindings);\n  const cursor = scratch.flatCursor;\n  const touched = scratch.flatTouched;\n  touched.length = 0;\n  const visit = (entity: EntityHandle): void => {\n    if (!transformWriter.locateEntity(entity, cursor)) return;\n    const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n    if (parentRaw !== undefined && parentRaw !== ENTITY_NULL_RAW) return;\n    const binding = transformBindings[cursor.bindingIndex];\n    const changed = scratch.flatChanged[cursor.bindingIndex];\n    if (binding === undefined || changed === undefined || changed[cursor.row] !== 0) return;\n    countPropagation('flatStructuralRootRows');\n    composeBindingRow(binding, cursor.row, undefined, 0, scratch, changed);\n    if (changed[cursor.row] === 0) return;\n    touched.push(cursor.bindingIndex, cursor.row);\n    changedRoots.push(entity);\n  };\n  for (const entity of candidates) visit(entity);\n  for (const entity of globalEdited) visit(entity);\n  let result: Result<EntityHandle[], SceneError> = ok(changedRoots);\n  const published = scratch.flatPublished;\n  for (let index = 0; index < touched.length; index += 2) {\n    const touchedBinding = touched[index] as number;\n    const changed = scratch.flatChanged[touchedBinding];\n    if (changed === undefined || published[touchedBinding] !== 0) continue;\n    published[touchedBinding] = 1;\n    const publication = transformWriter.publishChangedRows(touchedBinding, changed);\n    if (!publication.ok && result.ok) {\n      result = err(derivedWriteError(publication.error, touchedBinding));\n    }\n  }\n  for (let index = 0; index < touched.length; index += 2) {\n    const changed = scratch.flatChanged[touched[index] as number];\n    if (changed !== undefined) changed[touched[index + 1] as number] = 0;\n  }\n  touched.length = 0;\n  published.fill(0);\n  return result;\n}\n\ninterface TransformColumnShape {\n  readonly pos: ArrayLike<number>;\n  readonly quat: ArrayLike<number>;\n  readonly scale: ArrayLike<number>;\n}\n\ninterface OutputColumnShape {\n  readonly world: Float32Array;\n}\n\ninterface HierarchyColumnShape extends TransformColumnShape {\n  readonly parent: ArrayLike<number>;\n}\n\nfunction transformColumns(binding: TransformBinding | HierarchyBinding): TransformColumnShape {\n  return binding.read as unknown as TransformColumnShape;\n}\n\nfunction hierarchyColumns(binding: HierarchyBinding): HierarchyColumnShape {\n  return binding.read as unknown as HierarchyColumnShape;\n}\n\nfunction worldColumn(binding: TransformBinding | HierarchyBinding): Float32Array {\n  return (binding.write as unknown as OutputColumnShape).world;\n}\n\nfunction hierarchyError(\n  code: 'hierarchy-broken' | 'hierarchy-cycle',\n  entity: EntityHandle,\n  parent: EntityHandle,\n  expected: string,\n  hint: string,\n): SceneError {\n  return new SceneError({ code, expected, hint, detail: { entity, parent } });\n}\n\nfunction writeCandidate(\n  binding: TransformBinding | HierarchyBinding,\n  row: number,\n  candidate: Mat4,\n  changed: Uint8Array,\n): void {\n  const worlds = worldColumn(binding);\n  const base = row * 16;\n  for (let index = 0; index < 16; index += 1) {\n    if (worlds[base + index] !== candidate[index]) {\n      worlds.set(candidate, base);\n      changed[row] = 1;\n      return;\n    }\n  }\n}\n\nfunction composeBindingRow(\n  binding: TransformBinding | HierarchyBinding,\n  row: number,\n  parentBinding: TransformBinding | undefined,\n  parentRow: number,\n  scratch: Scratch,\n  changed: Uint8Array,\n): void {\n  // Hierarchy bindings carry the parent column; flat structural-root repair\n  // uses the same numeric kernel but is intentionally counted separately.\n  if ('parent' in (binding.read as object)) countPropagation('hierarchyRowsEvaluated');\n  const local = transformColumns(binding);\n  const offset = row * 3;\n  composeColumns(local.pos, local.quat, local.scale, scratch.local, scratch, offset, row * 4);\n  if (parentBinding === undefined) {\n    scratch.candidate.set(scratch.local);\n  } else {\n    const parentWorld = worldColumn(parentBinding);\n    const parentOffset = parentRow * 16;\n    for (let index = 0; index < 16; index += 1) {\n      scratch.parent[index] = parentWorld[parentOffset + index] ?? 0;\n    }\n    // Column-major composition is intentionally identical to the previous\n    // matrix path: Global = Parent * Local, with no TRS decomposition.\n    mat4.multiply(scratch.candidate, scratch.parent, scratch.local);\n  }\n  writeCandidate(binding, row, scratch.candidate, changed);\n}\n\nfunction ensureHierarchyBuffers(scratch: Scratch, bindings: readonly HierarchyBinding[]): void {\n  let same = scratch.hierarchyBindingTables.length === bindings.length;\n  if (same) {\n    for (let index = 0; index < bindings.length; index += 1) {\n      const binding = bindings[index];\n      if (\n        binding === undefined ||\n        scratch.hierarchyBindingTables[index] !== binding.tableId ||\n        scratch.hierarchyBindingRows[index] !== binding.rowCapacity\n      ) {\n        same = false;\n        break;\n      }\n    }\n  }\n  if (same) return;\n  scratch.hierarchyBindingTables = bindings.map((binding) => binding.tableId);\n  scratch.hierarchyBindingRows = bindings.map((binding) => binding.rowCapacity);\n  scratch.hierarchyStates = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n  scratch.hierarchyChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n}\n\nfunction resetHierarchyBuffers(scratch: Scratch): void {\n  for (let index = 0; index < scratch.hierarchyStates.length; index += 1) {\n    scratch.hierarchyStates[index]?.fill(0);\n    scratch.hierarchyChanged[index]?.fill(0);\n  }\n}\n\nfunction ensureFlatBuffers(scratch: Scratch, bindings: readonly TransformBinding[]): void {\n  let same = scratch.flatBindingTables.length === bindings.length;\n  if (same) {\n    for (let index = 0; index < bindings.length; index += 1) {\n      const binding = bindings[index];\n      if (\n        binding === undefined ||\n        scratch.flatBindingTables[index] !== binding.tableId ||\n        scratch.flatBindingRows[index] !== binding.rowCapacity\n      ) {\n        same = false;\n        break;\n      }\n    }\n  }\n  if (same) return;\n  scratch.flatBindingTables = bindings.map((binding) => binding.tableId);\n  scratch.flatBindingRows = bindings.map((binding) => binding.rowCapacity);\n  scratch.flatChanged = bindings.map((binding) => new Uint8Array(binding.rowCapacity));\n  scratch.flatPublished = new Uint8Array(bindings.length);\n}\n\nfunction derivedWriteError(cause: EcsError, bindingIndex: number): SceneError {\n  return new SceneError({\n    code: 'hierarchy-broken',\n    expected: 'derived GlobalTransform range publication to succeed',\n    hint: cause.hint ?? 'retry propagation on a healthy World',\n    detail: {\n      kind: 'derived-write',\n      entity: 0 as EntityHandle,\n      parent: 0 as EntityHandle,\n      bindingIndex,\n      base: 0,\n      start: 0,\n      count: 0,\n      cause,\n    },\n  });\n}\n\nfunction findHierarchyLocation(\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  entity: EntityHandle,\n  cursor: DerivedRangeCursor,\n): HierarchyBinding | undefined {\n  countPropagation('hierarchyEntityLookups');\n  if (!writer.locateEntity(entity, cursor)) return undefined;\n  return bindings[cursor.bindingIndex];\n}\n\nfunction findTransformLocation(\n  writer: TransformWriter,\n  bindings: readonly TransformBinding[],\n  entity: EntityHandle,\n  cursor: DerivedRangeCursor,\n): TransformBinding | undefined {\n  countPropagation('hierarchyEntityLookups');\n  if (!writer.locateEntity(entity, cursor)) return undefined;\n  return bindings[cursor.bindingIndex];\n}\n\nfunction countPublishedRows(changed: Uint8Array): void {\n  const trace = propagationTrace;\n  if (trace === undefined) return;\n  let runOpen = false;\n  for (let row = 0; row < changed.length; row += 1) {\n    if ((changed[row] ?? 0) !== 0) {\n      trace.hierarchyPublishedRows += 1;\n      if (!runOpen) {\n        trace.hierarchyPublishedRuns += 1;\n        runOpen = true;\n      }\n    } else {\n      runOpen = false;\n    }\n  }\n}\n\nfunction noteHierarchyError(current: SceneError | undefined, next: SceneError): SceneError {\n  if (current === undefined) return next;\n  const currentEntity = Number(current.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n  const nextEntity = Number(next.detail?.entity ?? Number.MAX_SAFE_INTEGER);\n  return nextEntity < currentEntity ||\n    (nextEntity === currentEntity && next.code.localeCompare(current.code) < 0)\n    ? next\n    : current;\n}\n\nfunction composeLocalHierarchyEntity(\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  entity: EntityHandle,\n  scratch: Scratch,\n  changed: Uint8Array[],\n): boolean {\n  const cursor = scratch.hierarchyCurrentCursor;\n  const binding = findHierarchyLocation(writer, bindings, entity, cursor);\n  if (binding === undefined) return false;\n  composeBindingRow(\n    binding,\n    cursor.row,\n    undefined,\n    0,\n    scratch,\n    changed[cursor.bindingIndex] as Uint8Array,\n  );\n  const states = scratch.hierarchyStates[cursor.bindingIndex];\n  if (states !== undefined) states[cursor.row] = 3;\n  return true;\n}\n\nfunction handleActiveCycle(\n  repeated: EntityHandle,\n  stackEntities: EntityHandle[],\n  stackChildren: number[],\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  scratch: Scratch,\n  changed: Uint8Array[],\n  report: (error: SceneError) => void,\n): void {\n  let cycleStart = -1;\n  for (let index = 0; index < stackEntities.length; index += 1) {\n    if (stackEntities[index] === repeated) {\n      cycleStart = index;\n      break;\n    }\n  }\n  if (cycleStart < 0) return;\n  const repeatedCursor: DerivedRangeCursor = { bindingIndex: -1, row: -1 };\n  const repeatedBinding = findHierarchyLocation(writer, bindings, repeated, repeatedCursor);\n  const repeatedParent =\n    repeatedBinding === undefined\n      ? repeated\n      : ((hierarchyColumns(repeatedBinding).parent[repeatedCursor.row] ??\n          ENTITY_NULL_RAW) as number as EntityHandle);\n  report(\n    hierarchyError(\n      'hierarchy-cycle',\n      repeated,\n      repeatedParent,\n      'a parent-before-child Transform hierarchy',\n      'repair the ChildOf cycle and retry TransformPropagation',\n    ),\n  );\n  for (let index = cycleStart; index < stackEntities.length; index += 1) {\n    const cycleEntity = stackEntities[index];\n    if (cycleEntity === undefined) continue;\n    composeLocalHierarchyEntity(writer, bindings, cycleEntity, scratch, changed);\n    stackChildren[index] = 0;\n  }\n}\n\nfunction walkChildren(\n  world: World,\n  root: EntityHandle,\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  transformWriter: TransformWriter,\n  transformBindings: readonly TransformBinding[],\n  scratch: Scratch,\n  report: (error: SceneError) => void,\n  allowCompletedRoot: boolean,\n  refresh = false,\n): void {\n  countPropagation('hierarchyRootInvocations');\n  const stackEntities = scratch.hierarchyStackEntities;\n  const stackChildren = scratch.hierarchyStackChildren;\n  stackEntities.length = 0;\n  stackChildren.length = 0;\n\n  // The cursor is scratch-owned and reused for every root, so a hot root walk\n  // allocates nothing. Residual recovery may be entered once for each member\n  // of a malformed parent path; state 4 means a previous fallback walk already\n  // expanded this root and all reachable Children edges, so do not repeat it.\n  const rootCursor = scratch.hierarchyRootCursor;\n  if (!allowCompletedRoot) countPropagation('hierarchyRootCursorReuses');\n  if (findHierarchyLocation(writer, bindings, root, rootCursor) !== undefined) {\n    const state = scratch.hierarchyStates[rootCursor.bindingIndex]?.[rootCursor.row] ?? 0;\n    if (allowCompletedRoot ? state === 4 : state !== 0 && !refresh) return;\n  }\n  stackEntities.push(root);\n  stackChildren.push(-1);\n\n  const currentCursor = scratch.hierarchyCurrentCursor;\n  const parentCursor = scratch.hierarchyParentCursor;\n  const childCursor = scratch.hierarchyChildCursor;\n  while (stackEntities.length > 0) {\n    const top = stackEntities.length - 1;\n    const current = stackEntities[top];\n    if (current === undefined) {\n      stackEntities.pop();\n      stackChildren.pop();\n      continue;\n    }\n    const hierarchyBinding = findHierarchyLocation(writer, bindings, current, currentCursor);\n    const nextChild = stackChildren[top] ?? -1;\n    if (nextChild < 0) {\n      if (hierarchyBinding !== undefined) {\n        const states = scratch.hierarchyStates[currentCursor.bindingIndex];\n        if (refresh && states !== undefined) states[currentCursor.row] = 0;\n        if ((states?.[currentCursor.row] ?? 0) === 0) {\n          if (states !== undefined) states[currentCursor.row] = 1;\n          const parentRaw = (hierarchyColumns(hierarchyBinding).parent[currentCursor.row] ??\n            ENTITY_NULL_RAW) as number;\n          // Every non-cycle outcome composes this row exactly once: under its\n          // parent when the parent is complete, otherwise as a local root.\n          let parentSource: TransformBinding | undefined;\n          let cycle = false;\n          if (parentRaw !== ENTITY_NULL_RAW) {\n            const parent = parentRaw as EntityHandle;\n            const parentBinding = findTransformLocation(\n              transformWriter,\n              transformBindings,\n              parent,\n              parentCursor,\n            );\n            const parentHierarchy = findHierarchyLocation(writer, bindings, parent, childCursor);\n            // A parent outside the hierarchy bindings is a flat root, already complete (2).\n            const parentState =\n              parentHierarchy === undefined\n                ? 2\n                : (scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0);\n            if (parentBinding === undefined) {\n              report(\n                hierarchyError(\n                  'hierarchy-broken',\n                  current,\n                  parent,\n                  'each ChildOf parent to carry Transform and GlobalTransform',\n                  'repair the missing parent pair before retrying propagation',\n                ),\n              );\n            } else if (parentState === 1) {\n              handleActiveCycle(\n                parent,\n                stackEntities,\n                stackChildren,\n                writer,\n                bindings,\n                scratch,\n                scratch.hierarchyChanged,\n                report,\n              );\n              cycle = true;\n            } else if (parentState === 0) {\n              report(\n                hierarchyError(\n                  'hierarchy-broken',\n                  current,\n                  parent,\n                  'Children to enumerate every parent-before-child edge',\n                  'repair the Children mirror and retry TransformPropagation',\n                ),\n              );\n            } else {\n              parentSource = parentBinding;\n            }\n          }\n          if (!cycle) {\n            composeBindingRow(\n              hierarchyBinding,\n              currentCursor.row,\n              parentSource,\n              parentCursor.row,\n              scratch,\n              scratch.hierarchyChanged[currentCursor.bindingIndex] as Uint8Array,\n            );\n          }\n          if (states !== undefined && states[currentCursor.row] === 1) {\n            states[currentCursor.row] = 2;\n          }\n        }\n      }\n      stackChildren[top] = 0;\n      continue;\n    }\n\n    const childrenLength = world[worldRead].getArrayLength(current, Children, 'entities') ?? 0;\n    if (nextChild >= childrenLength) {\n      stackEntities.pop();\n      stackChildren.pop();\n      if (allowCompletedRoot) {\n        const completedCursor = scratch.hierarchyResidualCursor;\n        const completedBinding = findHierarchyLocation(writer, bindings, current, completedCursor);\n        const completedStates =\n          completedBinding === undefined\n            ? undefined\n            : scratch.hierarchyStates[completedCursor.bindingIndex];\n        if (completedStates !== undefined && completedStates[completedCursor.row] === 3) {\n          completedStates[completedCursor.row] = 4;\n        }\n      }\n      continue;\n    }\n    stackChildren[top] = nextChild + 1;\n    countPropagation('hierarchyEdgesVisited');\n    const childRaw = world[worldRead].getArrayElement(current, Children, 'entities', nextChild);\n    if (childRaw === undefined || childRaw === ENTITY_NULL_RAW) {\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          current,\n          current,\n          'Children.entities to contain live child handles',\n          'repair the Children mirror and retry TransformPropagation',\n        ),\n      );\n      continue;\n    }\n    const child = childRaw as EntityHandle;\n    const childBinding = findHierarchyLocation(writer, bindings, child, childCursor);\n    if (childBinding === undefined) {\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          child,\n          current,\n          'each Children entry to carry Transform, GlobalTransform, and ChildOf',\n          'repair the child component pair before retrying propagation',\n        ),\n      );\n      continue;\n    }\n    const childParent = (hierarchyColumns(childBinding).parent[childCursor.row] ??\n      ENTITY_NULL_RAW) as number;\n    const childState = scratch.hierarchyStates[childCursor.bindingIndex]?.[childCursor.row] ?? 0;\n    if (childParent !== (current as number)) {\n      // Leave an unvisited child for the residual row-state pass. That pass\n      // can classify the complete path (including a rootless cycle) without\n      // emitting a premature mirror error that would hide the cycle cause.\n      if (childState === 0) continue;\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          child,\n          current,\n          'Children and ChildOf to describe the same parent',\n          'repair the relationship mirror and retry TransformPropagation',\n        ),\n      );\n      continue;\n    }\n    if (childState === 1) {\n      handleActiveCycle(\n        child,\n        stackEntities,\n        stackChildren,\n        writer,\n        bindings,\n        scratch,\n        scratch.hierarchyChanged,\n        report,\n      );\n    } else if (childState === 0 || refresh) {\n      stackEntities.push(child);\n      stackChildren.push(-1);\n    }\n  }\n}\n\nfunction fallbackResidualPath(\n  world: World,\n  path: readonly EntityHandle[],\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  transformWriter: TransformWriter,\n  transformBindings: readonly TransformBinding[],\n  scratch: Scratch,\n  report: (error: SceneError) => void,\n): void {\n  // Root traversal owns the normal path.  A residual path is necessarily a\n  // malformed Children projection (or a rootless cycle); cut the complete\n  // path to local roots in one pass so no stale GlobalTransform survives the\n  // diagnostic.  Keeping the path as an explicit work list also makes this\n  // recovery O(path length), rather than repeatedly searching parent chains.\n  for (const entity of path) {\n    composeLocalHierarchyEntity(writer, bindings, entity, scratch, scratch.hierarchyChanged);\n  }\n  for (const entity of path) {\n    walkChildren(\n      world,\n      entity,\n      writer,\n      bindings,\n      transformWriter,\n      transformBindings,\n      scratch,\n      report,\n      true,\n    );\n  }\n}\n\nfunction resolveResidualPath(\n  world: World,\n  entity: EntityHandle,\n  writer: HierarchyWriter,\n  bindings: readonly HierarchyBinding[],\n  transformWriter: TransformWriter,\n  transformBindings: readonly TransformBinding[],\n  scratch: Scratch,\n  report: (error: SceneError) => void,\n): void {\n  const path = scratch.hierarchyProbeEntities;\n  path.length = 0;\n  const cursor = scratch.hierarchyResidualCursor;\n  const parentTransformCursor = scratch.hierarchyParentCursor;\n  const parentHierarchyCursor = scratch.hierarchyResidualParentCursor;\n  let current = entity;\n  while (true) {\n    countPropagation('hierarchyResidualParentProbes');\n    const binding = findHierarchyLocation(writer, bindings, current, cursor);\n    if (binding === undefined) break;\n    const states = scratch.hierarchyStates[cursor.bindingIndex];\n    const state = states?.[cursor.row] ?? 0;\n    if (state !== 0) {\n      const columns = hierarchyColumns(binding);\n      const parentRaw = (columns.parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n      report(\n        hierarchyError(\n          'hierarchy-cycle',\n          current,\n          parentRaw === ENTITY_NULL_RAW ? current : (parentRaw as EntityHandle),\n          'a parent-before-child Transform hierarchy',\n          'repair the ChildOf cycle and retry TransformPropagation',\n        ),\n      );\n      fallbackResidualPath(\n        world,\n        path,\n        writer,\n        bindings,\n        transformWriter,\n        transformBindings,\n        scratch,\n        report,\n      );\n      return;\n    }\n\n    if (states !== undefined) states[cursor.row] = 1;\n    path.push(current);\n    const parentRaw = (hierarchyColumns(binding).parent[cursor.row] ?? ENTITY_NULL_RAW) as number;\n    if (parentRaw === ENTITY_NULL_RAW) {\n      // Every null-parent row is enumerated as a root above.  Reaching one\n      // here means the materialized Children graph failed to expose the\n      // parent-first edge; preserve the explicit malformed-graph error.\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          current,\n          current,\n          'Children to enumerate every parent-before-child edge',\n          'repair the Children mirror and retry TransformPropagation',\n        ),\n      );\n      fallbackResidualPath(\n        world,\n        path,\n        writer,\n        bindings,\n        transformWriter,\n        transformBindings,\n        scratch,\n        report,\n      );\n      return;\n    }\n\n    const parent = parentRaw as EntityHandle;\n    const parentTransform = findTransformLocation(\n      transformWriter,\n      transformBindings,\n      parent,\n      parentTransformCursor,\n    );\n    const parentHierarchy = findHierarchyLocation(writer, bindings, parent, parentHierarchyCursor);\n    if (parentHierarchy === undefined) {\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          current,\n          parent,\n          parentTransform === undefined\n            ? 'each ChildOf parent to carry Transform and GlobalTransform'\n            : 'Children to enumerate every parent-before-child edge',\n          parentTransform === undefined\n            ? 'repair the missing parent pair before retrying propagation'\n            : 'repair the Children mirror and retry TransformPropagation',\n        ),\n      );\n      fallbackResidualPath(\n        world,\n        path,\n        writer,\n        bindings,\n        transformWriter,\n        transformBindings,\n        scratch,\n        report,\n      );\n      return;\n    }\n\n    const parentState =\n      scratch.hierarchyStates[parentHierarchyCursor.bindingIndex]?.[parentHierarchyCursor.row] ?? 0;\n    if (parentState === 0) {\n      current = parent;\n      continue;\n    }\n    if (parentState === 1) {\n      report(\n        hierarchyError(\n          'hierarchy-cycle',\n          parent,\n          current,\n          'a parent-before-child Transform hierarchy',\n          'repair the ChildOf cycle and retry TransformPropagation',\n        ),\n      );\n    } else {\n      report(\n        hierarchyError(\n          'hierarchy-broken',\n          current,\n          parent,\n          'Children to enumerate every parent-before-child edge',\n          'repair the Children mirror and retry TransformPropagation',\n        ),\n      );\n    }\n    fallbackResidualPath(\n      world,\n      path,\n      writer,\n      bindings,\n      transformWriter,\n      transformBindings,\n      scratch,\n      report,\n    );\n    return;\n  }\n}\n\n/**\n * A value write to ChildOf (reparent) is trusted for incremental propagation\n * only when the ECS-maintained Children mirror already lists the edge. Public\n * writes always satisfy this; a malformed edge falls back to the full pass so\n * its diagnostic is identical to a cold evaluation.\n */\nfunction parentEdgeMirrored(\n  world: World,\n  child: EntityHandle,\n  transformWriter: TransformWriter,\n  cursor: DerivedRangeCursor,\n): boolean {\n  const parentRaw = world[worldRead].getFieldValue(child, ChildOf, 'parent');\n  if (parentRaw === undefined || parentRaw === ENTITY_NULL_RAW) return true;\n  const parent = parentRaw as EntityHandle;\n  if (!transformWriter.locateEntity(parent, cursor)) return false;\n  const length = world[worldRead].getArrayLength(parent, Children, 'entities') ?? 0;\n  for (let index = 0; index < length; index += 1) {\n    if (world[worldRead].getArrayElement(parent, Children, 'entities', index) === child)\n      return true;\n  }\n  return false;\n}\n\n/**\n * Highest dirty entities: those with no dirty ancestor. The ancestor walk is\n * bounded by the hierarchy row count so a malformed parent loop cannot spin;\n * exceeding it returns undefined and the caller runs the full pass.\n */\nfunction highestDirtyEntities(\n  world: World,\n  dirty: ReadonlySet<EntityHandle>,\n  hierarchyRows: number,\n): EntityHandle[] | undefined {\n  const roots: EntityHandle[] = [];\n  for (const entity of dirty) {\n    let parent = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n    let covered = false;\n    let hops = 0;\n    while (parent !== undefined && parent !== ENTITY_NULL_RAW) {\n      if (dirty.has(parent as EntityHandle)) {\n        covered = true;\n        break;\n      }\n      hops += 1;\n      if (hops > hierarchyRows) return undefined;\n      parent = world[worldRead].getFieldValue(parent as EntityHandle, ChildOf, 'parent');\n    }\n    if (!covered) roots.push(entity);\n  }\n  return roots;\n}\n\ninterface StructuralCandidates {\n  /** Live Transform entities whose storage block changed membership. */\n  readonly entities: readonly EntityHandle[];\n  /** A candidate left the Transform pair while still holding a hierarchy edge. */\n  readonly relationLeftTransform: boolean;\n}\n\nconst NO_STRUCTURAL_CANDIDATES: StructuralCandidates = {\n  entities: [],\n  relationLeftTransform: false,\n};\n\n/**\n * Structural changes are discovered per 256-row storage block rather than by\n * rescanning every Transform row: the projection enqueues the previous and\n * current occupants of each block whose membership changed. Its first read\n * (and any read after invalidation) returns every Transform row, which is the\n * cold full pass.\n */\nfunction readStructuralCandidates(world: World, scratch: Scratch): StructuralCandidates {\n  const transformWriter = scratch.transformWriter;\n  scratch.structure ??= createStateProjection(world, [], [Transform]);\n  const projection = scratch.structure;\n  const batch = projection.read();\n  batch.accept();\n  if (!batch.membershipChanged || batch.indices.length === 0 || transformWriter === undefined) {\n    return NO_STRUCTURAL_CANDIDATES;\n  }\n  const entities: EntityHandle[] = [];\n  let relationLeftTransform = false;\n  const cursor = scratch.flatCursor;\n  for (const index of batch.indices) {\n    const entity = projection.entity(index);\n    if (entity === undefined) continue;\n    if (transformWriter.locateEntity(entity, cursor)) {\n      entities.push(entity);\n    } else if (\n      world[worldRead].getFieldValue(entity, ChildOf, 'parent') !== undefined ||\n      world[worldRead].getArrayLength(entity, Children, 'entities') !== undefined\n    ) {\n      relationLeftTransform = true;\n    }\n  }\n  return { entities, relationLeftTransform };\n}\n\nfunction propagateHierarchy(\n  world: World,\n  scratch: Scratch,\n  structural: StructuralCandidates,\n  globalEdited: readonly EntityHandle[],\n  flatRoots: readonly EntityHandle[],\n): Result<void, SceneError> {\n  const hierarchyWriter = scratch.hierarchyWriter;\n  const transformWriter = scratch.transformWriter;\n  if (hierarchyWriter === undefined || transformWriter === undefined) {\n    return err(\n      new SceneError({\n        code: 'hierarchy-broken',\n        expected: 'paired Transform and GlobalTransform derived bindings',\n        hint: 'register the scene components before running TransformPropagation',\n      }),\n    );\n  }\n  const hierarchyBindings = hierarchyWriter.bindings as readonly HierarchyBinding[];\n  const transformBindings = transformWriter.bindings as readonly TransformBinding[];\n  if (hierarchyBindings.length === 0) {\n    // Keep the flat-only lane independent: it must not allocate hierarchy\n    // markers or scan every Transform row merely to prove that no ChildOf\n    // archetype exists.\n    scratch.hierarchyBindingTables.length = 0;\n    scratch.hierarchyBindingRows.length = 0;\n    scratch.hierarchyStates.length = 0;\n    scratch.hierarchyChanged.length = 0;\n    scratch.hierarchyValid = true;\n    return ok(undefined);\n  }\n  const dirty = new Set<EntityHandle>();\n  for (const row of scratch.dirtyTransforms ?? []) dirty.add(row.entity);\n  let rebuild = !scratch.hierarchyValid || structural.relationLeftTransform;\n  const structuralSet = new Set(structural.entities);\n  const edgeCursor = scratch.hierarchyResidualParentCursor;\n  for (const row of scratch.dirtyParents ?? []) {\n    dirty.add(row.entity);\n    if (\n      !rebuild &&\n      !structuralSet.has(row.entity) &&\n      !parentEdgeMirrored(world, row.entity, transformWriter, edgeCursor)\n    ) {\n      rebuild = true;\n    }\n  }\n  for (const entity of structural.entities) {\n    if (world[worldRead].getFieldValue(entity, ChildOf, 'parent') !== undefined) dirty.add(entity);\n  }\n  for (const entity of globalEdited) dirty.add(entity);\n  for (const entity of flatRoots) dirty.add(entity);\n  if (!rebuild && dirty.size === 0) return ok(undefined);\n  ensureHierarchyBuffers(scratch, hierarchyBindings);\n  let dirtyRoots: EntityHandle[] | undefined;\n  if (!rebuild) {\n    let hierarchyRows = 0;\n    for (const binding of hierarchyBindings) hierarchyRows += binding.rowCapacity;\n    dirtyRoots = highestDirtyEntities(world, dirty, hierarchyRows);\n  }\n  if (dirtyRoots === undefined) {\n    resetHierarchyBuffers(scratch);\n  } else {\n    // Rows outside the dirty subtrees keep the worlds proven by the last\n    // successful pass; mark them complete so parent-first checks accept them.\n    for (const states of scratch.hierarchyStates) states.fill(2);\n    for (const changed of scratch.hierarchyChanged) changed.fill(0);\n  }\n  let firstError: SceneError | undefined;\n  const report = (error: SceneError): void => {\n    firstError = noteHierarchyError(firstError, error);\n  };\n\n  if (dirtyRoots !== undefined) {\n    for (const entity of dirtyRoots) {\n      walkChildren(\n        world,\n        entity,\n        hierarchyWriter,\n        hierarchyBindings,\n        transformWriter,\n        transformBindings,\n        scratch,\n        report,\n        false,\n        true,\n      );\n    }\n  } else {\n    // Start only at actual roots (flat Transform rows and null-parent\n    // ChildOf rows). Descendants are discovered exclusively through the ECS\n    // materialized Children lists, so every normal frame is parent-first and\n    // linear in rows plus relationship edges.\n    for (const binding of transformBindings) {\n      const entities = binding.entities;\n      for (let row = 0; row < binding.rowCapacity; row += 1) {\n        const entity = (entities[row] ?? 0) as EntityHandle;\n        const parentRaw = world[worldRead].getFieldValue(entity, ChildOf, 'parent');\n        if (parentRaw === undefined || parentRaw === ENTITY_NULL_RAW) {\n          walkChildren(\n            world,\n            entity,\n            hierarchyWriter,\n            hierarchyBindings,\n            transformWriter,\n            transformBindings,\n            scratch,\n            report,\n            false,\n          );\n        }\n      }\n    }\n\n    // Any remaining hierarchy row is either behind a malformed/missing mirror\n    // edge or belongs to a rootless cycle. Follow each residual parent chain\n    // once with the same row-state machine (not a per-node parent search), then\n    // cut that complete residual path to local space. This keeps malformed\n    // coverage linear in residual rows and edges while normal frames remain\n    // exclusively Children-driven.\n    for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n      const binding = hierarchyBindings[bindingIndex];\n      if (binding === undefined) continue;\n      const entities = binding.entities;\n      const states = scratch.hierarchyStates[bindingIndex];\n      for (let row = 0; row < binding.rowCapacity; row += 1) {\n        if ((states?.[row] ?? 0) !== 0) continue;\n        const entity = (entities[row] ?? 0) as EntityHandle;\n        resolveResidualPath(\n          world,\n          entity,\n          hierarchyWriter,\n          hierarchyBindings,\n          transformWriter,\n          transformBindings,\n          scratch,\n          report,\n        );\n      }\n    }\n  }\n\n  for (let bindingIndex = 0; bindingIndex < hierarchyBindings.length; bindingIndex += 1) {\n    const changed = scratch.hierarchyChanged[bindingIndex];\n    if (changed === undefined) continue;\n    countPublishedRows(changed);\n    const published = hierarchyWriter.publishChangedRows(bindingIndex, changed);\n    if (!published.ok) {\n      const cause = published.error as EcsError;\n      report(derivedWriteError(cause, bindingIndex));\n    }\n  }\n  scratch.hierarchyValid = firstError === undefined;\n  return firstError === undefined ? ok(undefined) : err(firstError);\n}\n\nexport function propagateTransforms(world: World): Result<void, SceneError> {\n  const scratch = scratchFor(world);\n  const pairs = validateTransformPairs(world, scratch);\n  if (!pairs.ok) return pairs;\n  const structural = readStructuralCandidates(world, scratch);\n  const globalEdited: EntityHandle[] = [];\n  for (const row of scratch.dirtyGlobals ?? []) globalEdited.push(row.entity);\n  const flat = propagateFlat(world, scratch, structural.entities, globalEdited);\n  if (!flat.ok) {\n    scratch.structure?.invalidate();\n    scratch.hierarchyValid = false;\n    return flat;\n  }\n  const hierarchy = propagateHierarchy(world, scratch, structural, globalEdited, flat.value);\n  // Consume our own derived publications, while preserving later external edits.\n  for (const _span of scratch.dirtyGlobals?.spans().unwrap() ?? []) {\n    /* observation only */\n  }\n  return hierarchy;\n}\n\nexport const PropagateTransforms: SystemHandle<readonly []> = defineSystem({\n  name: PROPAGATE_TRANSFORMS_SYSTEM,\n  queries: [],\n  fn: (world) => {\n    const result = propagateTransforms(world);\n    if (!result.ok) throw result.error;\n  },\n});\n\nexport const PropagateTransformsFixed: SystemHandle<readonly []> = defineSystem({\n  name: PROPAGATE_TRANSFORMS_FIXED_SYSTEM,\n  queries: [],\n  fn: PropagateTransforms.fn,\n});\n\nexport function registerPropagateTransforms(\n  world: World,\n  options: { beforeSystemName?: string } = {},\n): () => void {\n  const existing = REGISTRATION_LEASES.get(world);\n  if (existing !== undefined) {\n    existing.refs += 1;\n    let active = true;\n    return () => {\n      if (!active) return;\n      active = false;\n      existing.refs -= 1;\n      if (existing.refs === 0) {\n        world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n        world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n        REGISTRATION_LEASES.delete(world);\n        SCRATCH.delete(world);\n      }\n    };\n  }\n  if (options.beforeSystemName === undefined) {\n    world.addSystems(Update, TransformSet, [PropagateTransforms]).unwrap();\n  } else {\n    world\n      .addSystems(Update, TransformSet, [\n        {\n          name: PROPAGATE_TRANSFORMS_SYSTEM,\n          queries: [],\n          fn: PropagateTransforms.fn,\n          before: [options.beforeSystemName],\n        },\n      ])\n      .unwrap();\n  }\n  world.addSystems(FixedUpdate, TransformFixedSet, [PropagateTransformsFixed]).unwrap();\n  REGISTRATION_LEASES.set(world, { refs: 1 });\n  let active = true;\n  return () => {\n    if (!active) return;\n    active = false;\n    const lease = REGISTRATION_LEASES.get(world);\n    if (lease === undefined) return;\n    lease.refs -= 1;\n    if (lease.refs !== 0) return;\n    world.removeSystem(FixedUpdate, PROPAGATE_TRANSFORMS_FIXED_SYSTEM);\n    world.removeSystem(Update, PROPAGATE_TRANSFORMS_SYSTEM);\n    REGISTRATION_LEASES.delete(world);\n    SCRATCH.delete(world);\n  };\n}\n","import type { Component, World } from '@forgeax/engine-ecs';\nimport type { Plugin } from '@forgeax/engine-plugin';\nimport { ChildOf } from './components/child-of';\nimport { Children } from './components/children';\nimport { Mobility } from './components/mobility';\nimport { MorphWeights } from './components/morph-weights';\nimport { Name } from './components/name';\nimport { GlobalTransform, Transform } from './components/transform';\nimport { registerMobilityStaticMoved } from './systems/mobility-static-moved';\nimport { registerPropagateTransforms } from './systems/propagate-transforms';\n\nconst SCENE_COMPONENTS: readonly Component[] = [\n  ChildOf,\n  Children,\n  Mobility,\n  MorphWeights,\n  Name,\n  Transform,\n  GlobalTransform,\n];\n\nfunction registerSceneComponents(world: World): () => void {\n  const leases = SCENE_COMPONENTS.map((component) => world.components.register(component).unwrap());\n  return () => {\n    for (let index = leases.length - 1; index >= 0; index -= 1) leases[index]?.dispose();\n  };\n}\n\nexport function scenePlugin(): Plugin {\n  return {\n    name: 'scene',\n    inject: ['world'],\n    apply(ctx) {\n      ctx.effect(() => registerSceneComponents(ctx.world), 'scene/components');\n      ctx.effect(() => registerPropagateTransforms(ctx.world), 'scene/propagate-transforms');\n      ctx.effect(() => registerMobilityStaticMoved(ctx.world), 'scene/mobility-static-moved');\n    },\n  };\n}\n","import { Entity, type EntityHandle, type Query, type World } from '@forgeax/engine-ecs';\nimport { ChildOf } from '../components/child-of';\nimport type { SceneErrorCode, SceneErrorDetail } from '../errors';\n\nexport interface SceneHierarchyDiagnostic {\n  readonly code: SceneErrorCode;\n  readonly expected: string;\n  readonly hint: string;\n  readonly detail: SceneErrorDetail;\n}\n\nexport interface SceneHierarchySnapshot {\n  readonly parentOf: ReadonlyMap<EntityHandle, EntityHandle>;\n  readonly diagnostics: readonly SceneHierarchyDiagnostic[];\n  getParent(entity: EntityHandle): EntityHandle | undefined;\n}\n\ninterface HierarchyProjectionCacheEntry {\n  readonly structureEpoch: number;\n  readonly childOfChanges: Query;\n  readonly snapshot: SceneHierarchySnapshot;\n}\n\n// A World can be observed by the transform system, renderer visibility, and\n// editor projections in the same frame. Keep one World-local projection so\n// those consumers do not each rescan every archetype. Structure changes and\n// the ChildOf component's own mutation token are the invalidation keys; the\n// global mutation epoch is intentionally too broad because animation and\n// runtime-only component writes may advance it every frame. Direct table\n// writes are internal-only and must not mutate authored hierarchy state.\nconst HIERARCHY_PROJECTION_CACHE = new WeakMap<World, HierarchyProjectionCacheEntry>();\n\nfunction createChildOfChangeQuery(world: World): Query {\n  const result = world.query({ changed: [ChildOf] });\n  if (!result.ok) throw result.error;\n  return result.value;\n}\n\nfunction drainChanges(query: Query): boolean {\n  let changed = false;\n  for (const span of query.spans().unwrap()) changed ||= span.length > 0;\n  return changed;\n}\n\nfunction diagnostic(\n  code: SceneErrorCode,\n  entity: EntityHandle,\n  parent: EntityHandle,\n): SceneHierarchyDiagnostic {\n  if (code === 'hierarchy-cycle') {\n    return {\n      code,\n      expected: 'ChildOf parent edges form an acyclic live hierarchy',\n      hint: 'remove one ChildOf edge from the reported cycle, then re-run the extract',\n      detail: { entity, parent },\n    };\n  }\n  return {\n    code,\n    expected: 'ChildOf.parent references a live entity in the same World',\n    hint: 'remove the stale ChildOf component or restore the referenced parent in this World',\n    detail: { entity, parent },\n  };\n}\n\n/** Build the only World-local projection of ChildOf parent facts. */\nexport function projectHierarchy(world: World): SceneHierarchySnapshot {\n  const cached = HIERARCHY_PROJECTION_CACHE.get(world);\n  if (\n    cached !== undefined &&\n    cached.structureEpoch === world.getStructureEpoch() &&\n    !drainChanges(cached.childOfChanges)\n  ) {\n    return cached.snapshot;\n  }\n  const liveEntities = new Set<EntityHandle>();\n  const authoredParents = new Map<EntityHandle, EntityHandle>();\n\n  const query = world.query({ read: [Entity], optional: [ChildOf] });\n  if (query.ok) {\n    for (const row of query.value) {\n      liveEntities.add(row.entity);\n      const parent = row.get(ChildOf)?.parent;\n      if (parent !== undefined && parent !== null) authoredParents.set(row.entity, parent);\n    }\n  }\n\n  const parentOf = new Map<EntityHandle, EntityHandle>();\n  const diagnostics: SceneHierarchyDiagnostic[] = [];\n  for (const [entity, parent] of authoredParents) {\n    if (liveEntities.has(parent)) {\n      parentOf.set(entity, parent);\n    } else {\n      diagnostics.push(diagnostic('hierarchy-broken', entity, parent));\n    }\n  }\n\n  const state = new Map<EntityHandle, 0 | 1 | 2>();\n  const stack: EntityHandle[] = [];\n  const cycleMembers = new Set<EntityHandle>();\n  const visit = (entity: EntityHandle): void => {\n    const currentState = state.get(entity) ?? 0;\n    if (currentState === 2) return;\n    if (currentState === 1) {\n      const cycleStart = stack.indexOf(entity);\n      for (let index = cycleStart; index >= 0 && index < stack.length; index++) {\n        const member = stack[index];\n        if (member !== undefined) cycleMembers.add(member);\n      }\n      return;\n    }\n\n    state.set(entity, 1);\n    stack.push(entity);\n    const parent = parentOf.get(entity);\n    if (parent !== undefined) visit(parent);\n    stack.pop();\n    state.set(entity, 2);\n  };\n\n  for (const entity of liveEntities) visit(entity);\n  for (const entity of cycleMembers) {\n    const parent = authoredParents.get(entity);\n    if (parent !== undefined) diagnostics.push(diagnostic('hierarchy-cycle', entity, parent));\n    parentOf.delete(entity);\n  }\n\n  diagnostics.sort((left, right) => {\n    const entityDelta = (left.detail.entity as number) - (right.detail.entity as number);\n    if (entityDelta !== 0) return entityDelta;\n    return left.code.localeCompare(right.code);\n  });\n\n  const stableParentOf = new Map(parentOf);\n  const stableDiagnostics = Object.freeze(diagnostics.slice());\n  const snapshot: SceneHierarchySnapshot = {\n    parentOf: stableParentOf,\n    diagnostics: stableDiagnostics,\n    getParent(entity: EntityHandle): EntityHandle | undefined {\n      return stableParentOf.get(entity);\n    },\n  };\n  const childOfChanges = createChildOfChangeQuery(world);\n  drainChanges(childOfChanges);\n  HIERARCHY_PROJECTION_CACHE.set(world, {\n    structureEpoch: world.getStructureEpoch(),\n    childOfChanges,\n    snapshot,\n  });\n  return snapshot;\n}\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,EACA;AAAA,OAKK;;;ACHA,SAAS,kCACd,eACA,QACA,kBACyB;AACzB,QAAM,SAAS,EAAE,GAAG,OAAO;AAC3B,QAAM,UAAU,CAAC,UACf,OAAO,cAAc,KAAK,IAAK,kBAAkB,IAAI,KAAe,KAAK,OAAO,KAAK,IAAK;AAC5F,MAAI,kBAAkB,sBAAsB,OAAO,OAAO,QAAQ,eAAe,GAAG;AAClF,UAAM,SAAS,OAAO;AACtB,UAAM,eAAe,WAAW,IAAI,IAAI,WAAW,IAAI,IAAI,WAAW,IAAI,IAAI;AAC9E,QAAI,iBAAiB,UAAa,CAAC,OAAO,OAAO,QAAQ,cAAc,GAAG;AACxE,aAAO,OAAO;AACd,aAAO,eAAe;AAAA,IACxB;AAAA,EACF;AACA,MAAI,kBAAkB,aAAa,OAAO,cAAc,OAAO,MAAM,GAAG;AACtE,WAAO,SAAS,QAAQ,OAAO,MAAM;AAAA,EACvC;AACA,MAAI,kBAAkB,cAAc,MAAM,QAAQ,OAAO,QAAQ,GAAG;AAClE,WAAO,WAAW,OAAO,SAAS,IAAI,OAAO;AAAA,EAC/C;AACA,SAAO;AACT;AAkBO,SAAS,0BACd,OAC4C;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,YAAY;AAClB,MAAI,CAAC,MAAM,QAAQ,UAAU,QAAQ;AACnC,WAAO;AAET,QAAM,OAAO,UAAU;AACvB,QAAM,m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tC,UAAM,IAAI;AACV,UAAM,IAAI,QAAQ,CAAC;AAAA,EACrB;AAEA,aAAW,UAAU,aAAc,OAAM,MAAM;AAC/C,aAAW,UAAU,cAAc;AACjC,UAAM,SAAS,gBAAgB,IAAI,MAAM;AACzC,QAAI,WAAW,OAAW,aAAY,KAAK,WAAW,mBAAmB,QAAQ,MAAM,CAAC;AACxF,aAAS,OAAO,MAAM;AAAA,EACxB;AAEA,cAAY,KAAK,CAAC,MAAM,UAAU;AAChC,UAAM,cAAe,KAAK,OAAO,SAAqB,MAAM,OAAO;AACnE,QAAI,gBAAgB,EAAG,QAAO;AAC9B,WAAO,KAAK,KAAK,cAAc,MAAM,IAAI;AAAA,EAC3C,CAAC;AAED,QAAM,iBAAiB,IAAI,IAAI,QAAQ;AACvC,QAAM,oBAAoB,OAAO,OAAO,YAAY,MAAM,CAAC;AAC3D,QAAM,WAAmC;AAAA,IACvC,UAAU;AAAA,IACV,aAAa;AAAA,IACb,UAAU,QAAgD;AACxD,aAAO,eAAe,IAAI,MAAM;AAAA,IAClC;AAAA,EACF;AACA,QAAM,iBAAiB,yBAAyB,KAAK;AACrD,eAAa,cAAc;AAC3B,6BAA2B,IAAI,OAAO;AAAA,IACpC,gBAAgB,MAAM,kBAAkB;AAAA,IACxC;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO;AACT;","names":["defineComponent","defineComponent","defineComponent","err","ok","err","ok","err","ok","err","ok","err","parts","slot","ok","converted","classifyEntityField","remapEntityFieldValue","componentSchema","err","ok","PACK_ERROR_HINTS","componentSchema","err","ok","ok","err","PACK_ERROR_HINTS","classifyEntityField","componentSchema","remapEntityFieldValue","value","diagnostic","ENTITY_NULL_RAW","Update","err","ok","err","ok","world","ENTITY_NULL_RAW","parentRaw","active","Update"]}